{
  "version": 3,
  "sources": ["../../../../node_modules/.pnpm/encoding@0.1.13/node_modules/encoding/lib/encoding.js", "../../../../node_modules/.pnpm/node-fetch@2.6.13_encoding@0.1.13/node_modules/node-fetch/lib/index.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/tslib/tslib.es6.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/backends/backend.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/util_base.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/environment.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/global_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/kernel_names.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/log.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/kernel_registry.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/platforms/is_typed_array_browser.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/long/src/long.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/hash_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/profiler.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/tape.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/tensor_format.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/tensor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/types.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/tensor_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/engine.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/device_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/flags.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/tensor_util_env.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/operation.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/complex.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor_ops_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/types.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/composite_array_buffer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/globals.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/io_utils.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/router_registry.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/indexed_db.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/local_storage.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/model_management.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/platforms/platform_browser.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/platforms/platform_node.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/buffer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/cast.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/clone.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/print.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/base_side_effects.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/add.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/floorDiv.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/div.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/mul.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/abs.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/acos.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/acosh.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/add_n.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/all.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/any.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/arg_max.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/arg_min.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/asin.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/asinh.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/atan.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/atan2.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/atanh.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/reshape.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/avg_pool.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/avg_pool_3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/concat.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/mat_mul.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sigmoid.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/slice.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tanh.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/basic_lstm_cell.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/batch_to_space_nd.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/batchnorm_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/batchnorm.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/batchnorm2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/batchnorm3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/batchnorm4d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/bincount.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/bitwise_and.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/broadcast_args.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/broadcast_to.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ceil.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/fill.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/clip_by_value.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/concat_1d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/concat_2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/concat_3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/concat_4d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv1d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv2d_backprop_input.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv2d_transpose.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv3d_backprop_input.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv3d_transpose.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/cos.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/cosh.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/cumprod.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/cumsum.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/dense_bincount.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/depth_to_space.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/depthwise_conv2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/diag.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/dilation2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/broadcast_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/equal.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/where.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/zeros_like.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/div_no_nan.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/dot.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/einsum.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/elu.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ensure_shape.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/erf.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/axis_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/max.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/min.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/pow.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/scalar.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sqrt.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/square.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sum.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/norm.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/euclidean_norm.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/exp.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/expand_dims.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/expm1.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tile.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/eye.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/floor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/gather.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/greater.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/greater_equal.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/imag.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/is_finite.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/is_inf.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/is_nan.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/leaky_relu.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/less.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/less_equal.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/linspace.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/local_response_normalization.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/log.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/log1p.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/gradients.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/neg.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/softplus.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/log_sigmoid.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sub.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/log_softmax.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/log_sum_exp.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/logical_and.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/logical_not.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/logical_or.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/logical_xor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/search_sorted.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/lower_bound.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/max_pool.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/max_pool_3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/max_pool_with_argmax.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/maximum.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/mean.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/zeros.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ones.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/meshgrid.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/minimum.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/mirror_pad.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/mod.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/moments.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/multi_rnn_cell.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/multinomial.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/not_equal.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/one_hot.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ones_like.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/outer_product.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/pad.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/pad1d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/pad2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/pad3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/pad4d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/space_to_batch_nd.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/pool.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/prelu.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/prod.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ragged_gather.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ragged_range.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ragged_tensor_to_tensor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/rand.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/seedrandom/lib/alea.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/seedrandom/lib/xor128.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/seedrandom/lib/xorwow.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/seedrandom/lib/xorshift7.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/seedrandom/lib/xor4096.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/seedrandom/lib/tychei.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/seedrandom/seedrandom.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/node_modules/seedrandom/index.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/test_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/rand_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/random_gamma.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/random_normal.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/random_standard_normal.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/random_uniform.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/random_uniform_int.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/range.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/real.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/reciprocal.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/relu.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/relu6.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/reverse.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/reverse_1d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/reverse_2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/reverse_3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/reverse_4d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/round.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/rsqrt.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/selu.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/separable_conv2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/setdiff1d_async.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sign.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sin.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sinh.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/slice1d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/slice2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/slice3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/slice4d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/softmax.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/spectral/fft.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/spectral/ifft.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/spectral/irfft.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/split.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/spectral/rfft.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/squared_difference.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/squeeze.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/stack.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/step.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/strided_slice.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tan.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor1d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor3d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor4d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor5d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor6d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/scatter_nd_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/tensor_scatter_update.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/topk.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/truncated_normal.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/unique.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/unsorted_segment_sum.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/unstack.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/upper_bound.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/variable.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/backends/where_impl.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/where_async.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/boolean_mask.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/transpose.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/moving_average.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/scatter_nd.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse_to_dense_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse_to_dense.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/gather_nd.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/dropout_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/dropout.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/signal_ops_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/in_top_k.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/conv2d_backprop_filter.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/fused_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/fused/conv2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/depthwise_conv2d_native_backprop_filter.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/depthwise_conv2d_native_backprop_input.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/fused/depthwise_conv2d.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/fused/mat_mul.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/fused_ops.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/signal/hamming_window.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/signal/hann_window.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/signal/frame.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/signal/stft.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/crop_and_resize.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/flip_left_right.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/grayscale_to_rgb.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/rgb_to_grayscale.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/rotate_with_offset.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/nonmax_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/non_max_suppression.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/backends/non_max_suppression_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/backends/non_max_suppression_impl.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/non_max_suppression_async.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/non_max_suppression_with_score.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/non_max_suppression_with_score_async.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/non_max_suppression_padded.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/non_max_suppression_padded_async.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/resize_bilinear.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/resize_nearest_neighbor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/threshold.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/image/transform.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/linalg/band_part.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/linalg/gram_schmidt.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/linalg/qr.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/loss_ops_utils.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/compute_weighted_loss.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/absolute_difference.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/cosine_distance.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/hinge_loss.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/huber_loss.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/log_loss.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/mean_squared_error.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/sigmoid_cross_entropy.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/losses/softmax_cross_entropy.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse/sparse_fill_empty_rows.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse/sparse_reshape.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse/sparse_segment_mean.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse/sparse_segment_sum.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/string/string_n_grams.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/string/string_split.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/string/string_to_hash_bucket_fast.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/string/static_regex_replace.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ops.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/serialization.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/optimizer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/adadelta_optimizer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/adagrad_optimizer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/adam_optimizer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/adamax_optimizer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/sgd_optimizer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/momentum_optimizer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/rmsprop_optimizer.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/register_optimizers.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/browser_files.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/progress.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/weights_loader.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/http.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/passthrough.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/io/io.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/confusion_matrix.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/math.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/browser.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/gather_nd_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/slice_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/version.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/optimizers/optimizer_constructors.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/train.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/browser_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/concat_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/ragged_to_dense_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/reduce_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/rotate_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/array_ops_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/selu_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/erf_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/backends/complex_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/backends/einsum_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/split_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse/sparse_fill_empty_rows_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse/sparse_reshape_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/sparse/sparse_segment_reduction_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/ops/segment_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/backends/backend_util.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/backends/kernel_impls.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-core@4.22.0_encoding@0.1.13/tfjs-core/src/index.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/flags.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/tslib/tslib.es6.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/data/compiled_api.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/custom_op/register.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/utils.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/arithmetic.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/basic_math.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/control.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/convolution.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/creation.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/dynamic.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/evaluation.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/graph.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/hash_table.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/image.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/logical.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/matrices.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/normalization.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/reduction.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/slice_join.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/sparse.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/spectral.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/string.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/op_list/transformation.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/operation_mapper.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/custom_op/node_value_impl.ts", "../../../../node_modules/.pnpm/tfjs-core/src/backends/backend.ts", "../../../../node_modules/.pnpm/tfjs-core/src/util_base.ts", "../../../../node_modules/.pnpm/tfjs-core/src/environment.ts", "../../../../node_modules/.pnpm/tfjs-core/src/global_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/kernel_names.ts", "../../../../node_modules/.pnpm/tfjs-core/src/log.ts", "../../../../node_modules/.pnpm/tfjs-core/src/kernel_registry.ts", "../../../../node_modules/.pnpm/tfjs-core/src/platforms/is_typed_array_browser.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/long/src/long.js", "../../../../node_modules/.pnpm/tfjs-core/src/hash_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/profiler.ts", "../../../../node_modules/.pnpm/tfjs-core/src/tape.ts", "../../../../node_modules/.pnpm/tfjs-core/src/tensor_format.ts", "../../../../node_modules/.pnpm/tfjs-core/src/tensor.ts", "../../../../node_modules/.pnpm/tfjs-core/src/types.ts", "../../../../node_modules/.pnpm/tfjs-core/src/tensor_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/engine.ts", "../../../../node_modules/.pnpm/tfjs-core/src/tensor_util_env.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/operation.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/abs.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/acos.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/acosh.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/add.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/add_n.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/all.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/any.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/arg_max.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/arg_min.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/asin.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/asinh.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/atan.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/atan2.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/atanh.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/cast.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/reshape.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/avg_pool.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/avg_pool_3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/clone.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/concat.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/mat_mul.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/mul.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sigmoid.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/slice.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tanh.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/basic_lstm_cell.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/batch_to_space_nd.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/batchnorm_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/batchnorm.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/batchnorm2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/batchnorm3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/batchnorm4d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/bincount.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/bitwise_and.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/broadcast_args.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/broadcast_to.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/buffer.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ceil.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/fill.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/clip_by_value.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/complex.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/concat_1d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/concat_2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/concat_3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/concat_4d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv1d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv2d_backprop_input.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv2d_transpose.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv3d_backprop_input.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv3d_transpose.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/cos.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/cosh.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/cumprod.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/cumsum.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/dense_bincount.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/depth_to_space.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/depthwise_conv2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/diag.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/dilation2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/floorDiv.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/div.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/broadcast_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/equal.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/where.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/zeros_like.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/div_no_nan.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/dot.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/einsum.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/elu.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ensure_shape.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/erf.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/axis_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/max.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/min.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/pow.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor_ops_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/scalar.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sqrt.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/square.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sum.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/norm.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/euclidean_norm.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/exp.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/expand_dims.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/expm1.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tile.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/eye.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/floor.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/gather.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/greater.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/greater_equal.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/imag.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/is_finite.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/is_inf.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/is_nan.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/leaky_relu.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/less.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/less_equal.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/linspace.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/local_response_normalization.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/log.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/log1p.ts", "../../../../node_modules/.pnpm/tfjs-core/src/gradients.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/neg.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/softplus.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/log_sigmoid.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sub.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/log_softmax.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/log_sum_exp.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/logical_and.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/logical_not.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/logical_or.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/logical_xor.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/search_sorted.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/lower_bound.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/max_pool.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/max_pool_3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/max_pool_with_argmax.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/maximum.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/mean.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/zeros.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ones.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/meshgrid.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/minimum.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/mirror_pad.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/mod.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/moments.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/multi_rnn_cell.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/multinomial.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/not_equal.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/one_hot.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ones_like.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/outer_product.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/pad.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/pad1d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/pad2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/pad3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/pad4d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/space_to_batch_nd.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/pool.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/prelu.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/print.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/prod.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ragged_gather.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ragged_range.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ragged_tensor_to_tensor.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/rand.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/seedrandom/lib/alea.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/seedrandom/lib/xor128.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/seedrandom/lib/xorwow.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/seedrandom/lib/xorshift7.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/seedrandom/lib/xor4096.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/seedrandom/lib/tychei.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/seedrandom/seedrandom.js", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/node_modules/seedrandom/index.js", "../../../../node_modules/.pnpm/tfjs-core/src/ops/rand_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/random_gamma.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/random_normal.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/random_standard_normal.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/random_uniform.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/random_uniform_int.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/range.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/real.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/reciprocal.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/relu.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/relu6.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/reverse.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/reverse_1d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/reverse_2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/reverse_3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/reverse_4d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/round.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/rsqrt.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/selu.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/separable_conv2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/setdiff1d_async.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sign.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sin.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sinh.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/slice1d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/slice2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/slice3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/slice4d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/softmax.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/spectral/fft.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/spectral/ifft.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/spectral/irfft.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/split.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/spectral/rfft.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/squared_difference.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/squeeze.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/stack.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/step.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/strided_slice.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tan.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor1d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor3d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor4d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor5d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor6d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/scatter_nd_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/tensor_scatter_update.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/topk.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/truncated_normal.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/unique.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/unsorted_segment_sum.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/unstack.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/upper_bound.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/variable.ts", "../../../../node_modules/.pnpm/tfjs-core/src/backends/where_impl.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/where_async.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/boolean_mask.ts", "../../../../node_modules/.pnpm/tfjs-core/src/globals.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/transpose.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/moving_average.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/scatter_nd.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sparse_to_dense_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sparse_to_dense.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/gather_nd.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/dropout_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/dropout.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/signal_ops_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/in_top_k.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/conv2d_backprop_filter.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/fused_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/fused/conv2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/depthwise_conv2d_native_backprop_filter.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/depthwise_conv2d_native_backprop_input.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/fused/depthwise_conv2d.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/fused/mat_mul.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/fused_ops.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/signal/hamming_window.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/signal/hann_window.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/signal/frame.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/signal/stft.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/crop_and_resize.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/flip_left_right.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/grayscale_to_rgb.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/rgb_to_grayscale.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/rotate_with_offset.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/nonmax_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/non_max_suppression.ts", "../../../../node_modules/.pnpm/tfjs-core/src/backends/non_max_suppression_util.ts", "../../../../node_modules/.pnpm/tfjs-core/src/backends/non_max_suppression_impl.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/non_max_suppression_async.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/non_max_suppression_with_score.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/non_max_suppression_with_score_async.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/non_max_suppression_padded.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/non_max_suppression_padded_async.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/resize_bilinear.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/resize_nearest_neighbor.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/threshold.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/image/transform.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/linalg/band_part.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/linalg/gram_schmidt.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/linalg/qr.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/loss_ops_utils.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/compute_weighted_loss.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/absolute_difference.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/cosine_distance.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/hinge_loss.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/huber_loss.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/log_loss.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/mean_squared_error.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/sigmoid_cross_entropy.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/losses/softmax_cross_entropy.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sparse/sparse_fill_empty_rows.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sparse/sparse_reshape.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sparse/sparse_segment_mean.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/sparse/sparse_segment_sum.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/string/string_n_grams.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/string/string_split.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/string/string_to_hash_bucket_fast.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/string/static_regex_replace.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ops.ts", "../../../../node_modules/.pnpm/tfjs-core/src/ops/ops_for_converter.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/arithmetic_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/basic_math_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/tensor_utils.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/tensor_array.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/tensor_list.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/control_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/convolution_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/creation_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/dynamic_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/evaluation_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/graph_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/hash_table.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/hash_table_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/image_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/logical_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/matrices_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/normalization_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/ragged_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/reduction_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/slice_join_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/sparse_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/spectral_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/string_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/executors/transformation_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/operations/operation_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/execution_context.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/model_analysis.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/graph_executor.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/resource_manager.ts", "../../../../node_modules/.pnpm/tfjs-core/src/io/types.ts", "../../../../node_modules/.pnpm/tfjs-core/src/io/io_utils.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/executor/graph_model.ts", "../../../../node_modules/.pnpm/@tensorflow+tfjs-converter@4.22.0_@tensorflow+tfjs-core@4.22.0_encoding@0.1.13_/tfjs-converter/src/version.ts", "../../../../serving/lib/search.ts", "../../../../serving/lib/tfjs-embedder.ts", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/utils/generic.js", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/utils/core.js", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/utils/hub.js", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/env.js", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/utils/maths.js", "../../../../serving/lib/dummy-onnx.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/index.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/backend-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/version.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/env-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/env.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/tensor-conversion-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/tensor-factory-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/tensor-impl-type-mapping.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/tensor-utils-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/tensor-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/tensor.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/trace.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/inference-session-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-common/lib/inference-session.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/wasm-utils-env.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/wasm-utils-import.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/wasm-factory.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/wasm-utils.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/run-options.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/session-options.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/wasm-common.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/wasm-utils-load-file.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/wasm-core-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/proxy-wrapper.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/wasm/session-handler-inference.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/backend-wasm.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/index.ts", "../../../../node_modules/.pnpm/onnxruntime-web@1.22.0-dev.20250409-89f8206ba4/node_modules/onnxruntime-web/lib/version.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.25.1/node_modules/onnxruntime-common/lib/version.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.25.1/node_modules/onnxruntime-common/lib/env-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.25.1/node_modules/onnxruntime-common/lib/tensor-conversion-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.25.1/node_modules/onnxruntime-common/lib/tensor-factory-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.25.1/node_modules/onnxruntime-common/lib/tensor-impl-type-mapping.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.25.1/node_modules/onnxruntime-common/lib/tensor-utils-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.25.1/node_modules/onnxruntime-common/lib/tensor-impl.ts", "../../../../node_modules/.pnpm/onnxruntime-common@1.25.1/node_modules/onnxruntime-common/lib/tensor.ts", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/backends/onnx.js", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/utils/tensor.js", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/utils/data-structures.js", "../../../../node_modules/.pnpm/@huggingface+jinja@0.5.5/node_modules/@huggingface/jinja/dist/index.js", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/models/whisper/common_whisper.js", "../../../../node_modules/.pnpm/@huggingface+transformers@3.8.1/node_modules/@huggingface/transformers/src/tokenizers.js", "../../../../serving/lib/tfjs-kernels-precise.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/base.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/backend_cpu.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/cpu_util.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Add.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/utils/binary_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/utils/binary_utils.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Cast.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/utils/zeros_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Complex.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Identity.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Real.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/utils/unary_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/utils/unary_utils.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Concat_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Exp.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/GatherV2_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Max_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Maximum.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Minimum.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Multiply.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Prod.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Transpose.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Transpose_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Range_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Rsqrt.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Slice.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/SquaredDifference.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/StridedSlice_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Sub.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Tile_impl.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/GatherV2.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Reshape.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/ExpandDims.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/StridedSlice.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Pack.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Concat.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Imag.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Range.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Mean.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/RealDiv.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Sum.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/BatchMatMul.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Softmax.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Max.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Erf.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Tile.ts", "../../../../node_modules/.pnpm/tfjs-backend-cpu/src/kernels/Square.ts", "../../../../serving/lib/logger.ts", "../../../../constants.ts"],
  "sourcesContent": ["'use strict';\n\nvar iconvLite = require('iconv-lite');\n\n// Expose to the world\nmodule.exports.convert = convert;\n\n/**\n * Convert encoding of an UTF-8 string or a buffer\n *\n * @param {String|Buffer} str String to be converted\n * @param {String} to Encoding to be converted to\n * @param {String} [from='UTF-8'] Encoding to be converted from\n * @return {Buffer} Encoded string\n */\nfunction convert(str, to, from) {\n    from = checkEncoding(from || 'UTF-8');\n    to = checkEncoding(to || 'UTF-8');\n    str = str || '';\n\n    var result;\n\n    if (from !== 'UTF-8' && typeof str === 'string') {\n        str = Buffer.from(str, 'binary');\n    }\n\n    if (from === to) {\n        if (typeof str === 'string') {\n            result = Buffer.from(str);\n        } else {\n            result = str;\n        }\n    } else {\n        try {\n            result = convertIconvLite(str, to, from);\n        } catch (E) {\n            console.error(E);\n            result = str;\n        }\n    }\n\n    if (typeof result === 'string') {\n        result = Buffer.from(result, 'utf-8');\n    }\n\n    return result;\n}\n\n/**\n * Convert encoding of astring with iconv-lite\n *\n * @param {String|Buffer} str String to be converted\n * @param {String} to Encoding to be converted to\n * @param {String} [from='UTF-8'] Encoding to be converted from\n * @return {Buffer} Encoded string\n */\nfunction convertIconvLite(str, to, from) {\n    if (to === 'UTF-8') {\n        return iconvLite.decode(str, from);\n    } else if (from === 'UTF-8') {\n        return iconvLite.encode(str, to);\n    } else {\n        return iconvLite.encode(iconvLite.decode(str, from), to);\n    }\n}\n\n/**\n * Converts charset name if needed\n *\n * @param {String} name Character set\n * @return {String} Character set name\n */\nfunction checkEncoding(name) {\n    return (name || '')\n        .toString()\n        .trim()\n        .replace(/^latin[\\-_]?(\\d+)$/i, 'ISO-8859-$1')\n        .replace(/^win(?:dows)?[\\-_]?(\\d+)$/i, 'WINDOWS-$1')\n        .replace(/^utf[\\-_]?(\\d+)$/i, 'UTF-$1')\n        .replace(/^ks_c_5601\\-1987$/i, 'CP949')\n        .replace(/^us[\\-_]?ascii$/i, 'ASCII')\n        .toUpperCase();\n}\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar Stream = _interopDefault(require('stream'));\nvar http = _interopDefault(require('http'));\nvar Url = _interopDefault(require('url'));\nvar whatwgUrl = _interopDefault(require('whatwg-url'));\nvar https = _interopDefault(require('https'));\nvar zlib = _interopDefault(require('zlib'));\n\n// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js\n\n// fix for \"Readable\" isn't a named export issue\nconst Readable = Stream.Readable;\n\nconst BUFFER = Symbol('buffer');\nconst TYPE = Symbol('type');\n\nclass Blob {\n\tconstructor() {\n\t\tthis[TYPE] = '';\n\n\t\tconst blobParts = arguments[0];\n\t\tconst options = arguments[1];\n\n\t\tconst buffers = [];\n\t\tlet size = 0;\n\n\t\tif (blobParts) {\n\t\t\tconst a = blobParts;\n\t\t\tconst length = Number(a.length);\n\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\tconst element = a[i];\n\t\t\t\tlet buffer;\n\t\t\t\tif (element instanceof Buffer) {\n\t\t\t\t\tbuffer = element;\n\t\t\t\t} else if (ArrayBuffer.isView(element)) {\n\t\t\t\t\tbuffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);\n\t\t\t\t} else if (element instanceof ArrayBuffer) {\n\t\t\t\t\tbuffer = Buffer.from(element);\n\t\t\t\t} else if (element instanceof Blob) {\n\t\t\t\t\tbuffer = element[BUFFER];\n\t\t\t\t} else {\n\t\t\t\t\tbuffer = Buffer.from(typeof element === 'string' ? element : String(element));\n\t\t\t\t}\n\t\t\t\tsize += buffer.length;\n\t\t\t\tbuffers.push(buffer);\n\t\t\t}\n\t\t}\n\n\t\tthis[BUFFER] = Buffer.concat(buffers);\n\n\t\tlet type = options && options.type !== undefined && String(options.type).toLowerCase();\n\t\tif (type && !/[^\\u0020-\\u007E]/.test(type)) {\n\t\t\tthis[TYPE] = type;\n\t\t}\n\t}\n\tget size() {\n\t\treturn this[BUFFER].length;\n\t}\n\tget type() {\n\t\treturn this[TYPE];\n\t}\n\ttext() {\n\t\treturn Promise.resolve(this[BUFFER].toString());\n\t}\n\tarrayBuffer() {\n\t\tconst buf = this[BUFFER];\n\t\tconst ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n\t\treturn Promise.resolve(ab);\n\t}\n\tstream() {\n\t\tconst readable = new Readable();\n\t\treadable._read = function () {};\n\t\treadable.push(this[BUFFER]);\n\t\treadable.push(null);\n\t\treturn readable;\n\t}\n\ttoString() {\n\t\treturn '[object Blob]';\n\t}\n\tslice() {\n\t\tconst size = this.size;\n\n\t\tconst start = arguments[0];\n\t\tconst end = arguments[1];\n\t\tlet relativeStart, relativeEnd;\n\t\tif (start === undefined) {\n\t\t\trelativeStart = 0;\n\t\t} else if (start < 0) {\n\t\t\trelativeStart = Math.max(size + start, 0);\n\t\t} else {\n\t\t\trelativeStart = Math.min(start, size);\n\t\t}\n\t\tif (end === undefined) {\n\t\t\trelativeEnd = size;\n\t\t} else if (end < 0) {\n\t\t\trelativeEnd = Math.max(size + end, 0);\n\t\t} else {\n\t\t\trelativeEnd = Math.min(end, size);\n\t\t}\n\t\tconst span = Math.max(relativeEnd - relativeStart, 0);\n\n\t\tconst buffer = this[BUFFER];\n\t\tconst slicedBuffer = buffer.slice(relativeStart, relativeStart + span);\n\t\tconst blob = new Blob([], { type: arguments[2] });\n\t\tblob[BUFFER] = slicedBuffer;\n\t\treturn blob;\n\t}\n}\n\nObject.defineProperties(Blob.prototype, {\n\tsize: { enumerable: true },\n\ttype: { enumerable: true },\n\tslice: { enumerable: true }\n});\n\nObject.defineProperty(Blob.prototype, Symbol.toStringTag, {\n\tvalue: 'Blob',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\n/**\n * fetch-error.js\n *\n * FetchError interface for operational errors\n */\n\n/**\n * Create FetchError instance\n *\n * @param   String      message      Error message for human\n * @param   String      type         Error type for machine\n * @param   String      systemError  For Node.js system error\n * @return  FetchError\n */\nfunction FetchError(message, type, systemError) {\n  Error.call(this, message);\n\n  this.message = message;\n  this.type = type;\n\n  // when err.type is `system`, err.code contains system error code\n  if (systemError) {\n    this.code = this.errno = systemError.code;\n  }\n\n  // hide custom error implementation details from end-users\n  Error.captureStackTrace(this, this.constructor);\n}\n\nFetchError.prototype = Object.create(Error.prototype);\nFetchError.prototype.constructor = FetchError;\nFetchError.prototype.name = 'FetchError';\n\nlet convert;\ntry {\n\tconvert = require('encoding').convert;\n} catch (e) {}\n\nconst INTERNALS = Symbol('Body internals');\n\n// fix an issue where \"PassThrough\" isn't a named export for node <10\nconst PassThrough = Stream.PassThrough;\n\n/**\n * Body mixin\n *\n * Ref: https://fetch.spec.whatwg.org/#body\n *\n * @param   Stream  body  Readable stream\n * @param   Object  opts  Response options\n * @return  Void\n */\nfunction Body(body) {\n\tvar _this = this;\n\n\tvar _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},\n\t    _ref$size = _ref.size;\n\n\tlet size = _ref$size === undefined ? 0 : _ref$size;\n\tvar _ref$timeout = _ref.timeout;\n\tlet timeout = _ref$timeout === undefined ? 0 : _ref$timeout;\n\n\tif (body == null) {\n\t\t// body is undefined or null\n\t\tbody = null;\n\t} else if (isURLSearchParams(body)) {\n\t\t// body is a URLSearchParams\n\t\tbody = Buffer.from(body.toString());\n\t} else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {\n\t\t// body is ArrayBuffer\n\t\tbody = Buffer.from(body);\n\t} else if (ArrayBuffer.isView(body)) {\n\t\t// body is ArrayBufferView\n\t\tbody = Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n\t} else if (body instanceof Stream) ; else {\n\t\t// none of the above\n\t\t// coerce to string then buffer\n\t\tbody = Buffer.from(String(body));\n\t}\n\tthis[INTERNALS] = {\n\t\tbody,\n\t\tdisturbed: false,\n\t\terror: null\n\t};\n\tthis.size = size;\n\tthis.timeout = timeout;\n\n\tif (body instanceof Stream) {\n\t\tbody.on('error', function (err) {\n\t\t\tconst error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);\n\t\t\t_this[INTERNALS].error = error;\n\t\t});\n\t}\n}\n\nBody.prototype = {\n\tget body() {\n\t\treturn this[INTERNALS].body;\n\t},\n\n\tget bodyUsed() {\n\t\treturn this[INTERNALS].disturbed;\n\t},\n\n\t/**\n  * Decode response as ArrayBuffer\n  *\n  * @return  Promise\n  */\n\tarrayBuffer() {\n\t\treturn consumeBody.call(this).then(function (buf) {\n\t\t\treturn buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n\t\t});\n\t},\n\n\t/**\n  * Return raw response as Blob\n  *\n  * @return Promise\n  */\n\tblob() {\n\t\tlet ct = this.headers && this.headers.get('content-type') || '';\n\t\treturn consumeBody.call(this).then(function (buf) {\n\t\t\treturn Object.assign(\n\t\t\t// Prevent copying\n\t\t\tnew Blob([], {\n\t\t\t\ttype: ct.toLowerCase()\n\t\t\t}), {\n\t\t\t\t[BUFFER]: buf\n\t\t\t});\n\t\t});\n\t},\n\n\t/**\n  * Decode response as json\n  *\n  * @return  Promise\n  */\n\tjson() {\n\t\tvar _this2 = this;\n\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(buffer.toString());\n\t\t\t} catch (err) {\n\t\t\t\treturn Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));\n\t\t\t}\n\t\t});\n\t},\n\n\t/**\n  * Decode response as text\n  *\n  * @return  Promise\n  */\n\ttext() {\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\treturn buffer.toString();\n\t\t});\n\t},\n\n\t/**\n  * Decode response as buffer (non-spec api)\n  *\n  * @return  Promise\n  */\n\tbuffer() {\n\t\treturn consumeBody.call(this);\n\t},\n\n\t/**\n  * Decode response as text, while automatically detecting the encoding and\n  * trying to decode to UTF-8 (non-spec api)\n  *\n  * @return  Promise\n  */\n\ttextConverted() {\n\t\tvar _this3 = this;\n\n\t\treturn consumeBody.call(this).then(function (buffer) {\n\t\t\treturn convertBody(buffer, _this3.headers);\n\t\t});\n\t}\n};\n\n// In browsers, all properties are enumerable.\nObject.defineProperties(Body.prototype, {\n\tbody: { enumerable: true },\n\tbodyUsed: { enumerable: true },\n\tarrayBuffer: { enumerable: true },\n\tblob: { enumerable: true },\n\tjson: { enumerable: true },\n\ttext: { enumerable: true }\n});\n\nBody.mixIn = function (proto) {\n\tfor (const name of Object.getOwnPropertyNames(Body.prototype)) {\n\t\t// istanbul ignore else: future proof\n\t\tif (!(name in proto)) {\n\t\t\tconst desc = Object.getOwnPropertyDescriptor(Body.prototype, name);\n\t\t\tObject.defineProperty(proto, name, desc);\n\t\t}\n\t}\n};\n\n/**\n * Consume and convert an entire Body to a Buffer.\n *\n * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body\n *\n * @return  Promise\n */\nfunction consumeBody() {\n\tvar _this4 = this;\n\n\tif (this[INTERNALS].disturbed) {\n\t\treturn Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));\n\t}\n\n\tthis[INTERNALS].disturbed = true;\n\n\tif (this[INTERNALS].error) {\n\t\treturn Body.Promise.reject(this[INTERNALS].error);\n\t}\n\n\tlet body = this.body;\n\n\t// body is null\n\tif (body === null) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is blob\n\tif (isBlob(body)) {\n\t\tbody = body.stream();\n\t}\n\n\t// body is buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn Body.Promise.resolve(body);\n\t}\n\n\t// istanbul ignore if: should never happen\n\tif (!(body instanceof Stream)) {\n\t\treturn Body.Promise.resolve(Buffer.alloc(0));\n\t}\n\n\t// body is stream\n\t// get ready to actually consume the body\n\tlet accum = [];\n\tlet accumBytes = 0;\n\tlet abort = false;\n\n\treturn new Body.Promise(function (resolve, reject) {\n\t\tlet resTimeout;\n\n\t\t// allow timeout on slow response body\n\t\tif (_this4.timeout) {\n\t\t\tresTimeout = setTimeout(function () {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));\n\t\t\t}, _this4.timeout);\n\t\t}\n\n\t\t// handle stream errors\n\t\tbody.on('error', function (err) {\n\t\t\tif (err.name === 'AbortError') {\n\t\t\t\t// if the request was aborted, reject with this Error\n\t\t\t\tabort = true;\n\t\t\t\treject(err);\n\t\t\t} else {\n\t\t\t\t// other errors, such as incorrect content-encoding\n\t\t\t\treject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\n\t\tbody.on('data', function (chunk) {\n\t\t\tif (abort || chunk === null) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (_this4.size && accumBytes + chunk.length > _this4.size) {\n\t\t\t\tabort = true;\n\t\t\t\treject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t});\n\n\t\tbody.on('end', function () {\n\t\t\tif (abort) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tclearTimeout(resTimeout);\n\n\t\t\ttry {\n\t\t\t\tresolve(Buffer.concat(accum, accumBytes));\n\t\t\t} catch (err) {\n\t\t\t\t// handle streams that have accumulated too much data (issue #414)\n\t\t\t\treject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));\n\t\t\t}\n\t\t});\n\t});\n}\n\n/**\n * Detect buffer encoding and convert to target encoding\n * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding\n *\n * @param   Buffer  buffer    Incoming buffer\n * @param   String  encoding  Target encoding\n * @return  String\n */\nfunction convertBody(buffer, headers) {\n\tif (typeof convert !== 'function') {\n\t\tthrow new Error('The package `encoding` must be installed to use the textConverted() function');\n\t}\n\n\tconst ct = headers.get('content-type');\n\tlet charset = 'utf-8';\n\tlet res, str;\n\n\t// header\n\tif (ct) {\n\t\tres = /charset=([^;]*)/i.exec(ct);\n\t}\n\n\t// no charset in content type, peek at response body for at most 1024 bytes\n\tstr = buffer.slice(0, 1024).toString();\n\n\t// html5\n\tif (!res && str) {\n\t\tres = /<meta.+?charset=(['\"])(.+?)\\1/i.exec(str);\n\t}\n\n\t// html4\n\tif (!res && str) {\n\t\tres = /<meta[\\s]+?http-equiv=(['\"])content-type\\1[\\s]+?content=(['\"])(.+?)\\2/i.exec(str);\n\t\tif (!res) {\n\t\t\tres = /<meta[\\s]+?content=(['\"])(.+?)\\1[\\s]+?http-equiv=(['\"])content-type\\3/i.exec(str);\n\t\t\tif (res) {\n\t\t\t\tres.pop(); // drop last quote\n\t\t\t}\n\t\t}\n\n\t\tif (res) {\n\t\t\tres = /charset=(.*)/i.exec(res.pop());\n\t\t}\n\t}\n\n\t// xml\n\tif (!res && str) {\n\t\tres = /<\\?xml.+?encoding=(['\"])(.+?)\\1/i.exec(str);\n\t}\n\n\t// found charset\n\tif (res) {\n\t\tcharset = res.pop();\n\n\t\t// prevent decode issues when sites use incorrect encoding\n\t\t// ref: https://hsivonen.fi/encoding-menu/\n\t\tif (charset === 'gb2312' || charset === 'gbk') {\n\t\t\tcharset = 'gb18030';\n\t\t}\n\t}\n\n\t// turn raw buffers into a single utf-8 buffer\n\treturn convert(buffer, 'UTF-8', charset).toString();\n}\n\n/**\n * Detect a URLSearchParams object\n * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143\n *\n * @param   Object  obj     Object to detect by type or brand\n * @return  String\n */\nfunction isURLSearchParams(obj) {\n\t// Duck-typing as a necessary condition.\n\tif (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {\n\t\treturn false;\n\t}\n\n\t// Brand-checking and more duck-typing as optional condition.\n\treturn obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';\n}\n\n/**\n * Check if `obj` is a W3C `Blob` object (which `File` inherits from)\n * @param  {*} obj\n * @return {boolean}\n */\nfunction isBlob(obj) {\n\treturn typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);\n}\n\n/**\n * Clone body given Res/Req instance\n *\n * @param   Mixed  instance  Response or Request instance\n * @return  Mixed\n */\nfunction clone(instance) {\n\tlet p1, p2;\n\tlet body = instance.body;\n\n\t// don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif (body instanceof Stream && typeof body.getBoundary !== 'function') {\n\t\t// tee instance body\n\t\tp1 = new PassThrough();\n\t\tp2 = new PassThrough();\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].body = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n}\n\n/**\n * Performs the operation \"extract a `Content-Type` value from |object|\" as\n * specified in the specification:\n * https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n *\n * This function assumes that instance.body is present.\n *\n * @param   Mixed  instance  Any options.body input\n */\nfunction extractContentType(body) {\n\tif (body === null) {\n\t\t// body is null\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\t// body is string\n\t\treturn 'text/plain;charset=UTF-8';\n\t} else if (isURLSearchParams(body)) {\n\t\t// body is a URLSearchParams\n\t\treturn 'application/x-www-form-urlencoded;charset=UTF-8';\n\t} else if (isBlob(body)) {\n\t\t// body is blob\n\t\treturn body.type || null;\n\t} else if (Buffer.isBuffer(body)) {\n\t\t// body is buffer\n\t\treturn null;\n\t} else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {\n\t\t// body is ArrayBuffer\n\t\treturn null;\n\t} else if (ArrayBuffer.isView(body)) {\n\t\t// body is ArrayBufferView\n\t\treturn null;\n\t} else if (typeof body.getBoundary === 'function') {\n\t\t// detect form data input from form-data module\n\t\treturn `multipart/form-data;boundary=${body.getBoundary()}`;\n\t} else if (body instanceof Stream) {\n\t\t// body is stream\n\t\t// can't really do much about this\n\t\treturn null;\n\t} else {\n\t\t// Body constructor defaults other things to string\n\t\treturn 'text/plain;charset=UTF-8';\n\t}\n}\n\n/**\n * The Fetch Standard treats this as if \"total bytes\" is a property on the body.\n * For us, we have to explicitly get it with a function.\n *\n * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes\n *\n * @param   Body    instance   Instance of Body\n * @return  Number?            Number of bytes, or null if not possible\n */\nfunction getTotalBytes(instance) {\n\tconst body = instance.body;\n\n\n\tif (body === null) {\n\t\t// body is null\n\t\treturn 0;\n\t} else if (isBlob(body)) {\n\t\treturn body.size;\n\t} else if (Buffer.isBuffer(body)) {\n\t\t// body is buffer\n\t\treturn body.length;\n\t} else if (body && typeof body.getLengthSync === 'function') {\n\t\t// detect form data input from form-data module\n\t\tif (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x\n\t\tbody.hasKnownLength && body.hasKnownLength()) {\n\t\t\t// 2.x\n\t\t\treturn body.getLengthSync();\n\t\t}\n\t\treturn null;\n\t} else {\n\t\t// body is stream\n\t\treturn null;\n\t}\n}\n\n/**\n * Write a Body to a Node.js WritableStream (e.g. http.Request) object.\n *\n * @param   Body    instance   Instance of Body\n * @return  Void\n */\nfunction writeToStream(dest, instance) {\n\tconst body = instance.body;\n\n\n\tif (body === null) {\n\t\t// body is null\n\t\tdest.end();\n\t} else if (isBlob(body)) {\n\t\tbody.stream().pipe(dest);\n\t} else if (Buffer.isBuffer(body)) {\n\t\t// body is buffer\n\t\tdest.write(body);\n\t\tdest.end();\n\t} else {\n\t\t// body is stream\n\t\tbody.pipe(dest);\n\t}\n}\n\n// expose Promise\nBody.Promise = global.Promise;\n\n/**\n * headers.js\n *\n * Headers class offers convenient helpers\n */\n\nconst invalidTokenRegex = /[^\\^_`a-zA-Z\\-0-9!#$%&'*+.|~]/;\nconst invalidHeaderCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/;\n\nfunction validateName(name) {\n\tname = `${name}`;\n\tif (invalidTokenRegex.test(name) || name === '') {\n\t\tthrow new TypeError(`${name} is not a legal HTTP header name`);\n\t}\n}\n\nfunction validateValue(value) {\n\tvalue = `${value}`;\n\tif (invalidHeaderCharRegex.test(value)) {\n\t\tthrow new TypeError(`${value} is not a legal HTTP header value`);\n\t}\n}\n\n/**\n * Find the key in the map object given a header name.\n *\n * Returns undefined if not found.\n *\n * @param   String  name  Header name\n * @return  String|Undefined\n */\nfunction find(map, name) {\n\tname = name.toLowerCase();\n\tfor (const key in map) {\n\t\tif (key.toLowerCase() === name) {\n\t\t\treturn key;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nconst MAP = Symbol('map');\nclass Headers {\n\t/**\n  * Headers class\n  *\n  * @param   Object  headers  Response headers\n  * @return  Void\n  */\n\tconstructor() {\n\t\tlet init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;\n\n\t\tthis[MAP] = Object.create(null);\n\n\t\tif (init instanceof Headers) {\n\t\t\tconst rawHeaders = init.raw();\n\t\t\tconst headerNames = Object.keys(rawHeaders);\n\n\t\t\tfor (const headerName of headerNames) {\n\t\t\t\tfor (const value of rawHeaders[headerName]) {\n\t\t\t\t\tthis.append(headerName, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\t// We don't worry about converting prop to ByteString here as append()\n\t\t// will handle it.\n\t\tif (init == null) ; else if (typeof init === 'object') {\n\t\t\tconst method = init[Symbol.iterator];\n\t\t\tif (method != null) {\n\t\t\t\tif (typeof method !== 'function') {\n\t\t\t\t\tthrow new TypeError('Header pairs must be iterable');\n\t\t\t\t}\n\n\t\t\t\t// sequence<sequence<ByteString>>\n\t\t\t\t// Note: per spec we have to first exhaust the lists then process them\n\t\t\t\tconst pairs = [];\n\t\t\t\tfor (const pair of init) {\n\t\t\t\t\tif (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {\n\t\t\t\t\t\tthrow new TypeError('Each header pair must be iterable');\n\t\t\t\t\t}\n\t\t\t\t\tpairs.push(Array.from(pair));\n\t\t\t\t}\n\n\t\t\t\tfor (const pair of pairs) {\n\t\t\t\t\tif (pair.length !== 2) {\n\t\t\t\t\t\tthrow new TypeError('Each header pair must be a name/value tuple');\n\t\t\t\t\t}\n\t\t\t\t\tthis.append(pair[0], pair[1]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// record<ByteString, ByteString>\n\t\t\t\tfor (const key of Object.keys(init)) {\n\t\t\t\t\tconst value = init[key];\n\t\t\t\t\tthis.append(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new TypeError('Provided initializer must be an object');\n\t\t}\n\t}\n\n\t/**\n  * Return combined header value given name\n  *\n  * @param   String  name  Header name\n  * @return  Mixed\n  */\n\tget(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key === undefined) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this[MAP][key].join(', ');\n\t}\n\n\t/**\n  * Iterate over all headers\n  *\n  * @param   Function  callback  Executed for each item with parameters (value, name, thisArg)\n  * @param   Boolean   thisArg   `this` context for callback function\n  * @return  Void\n  */\n\tforEach(callback) {\n\t\tlet thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;\n\n\t\tlet pairs = getHeaders(this);\n\t\tlet i = 0;\n\t\twhile (i < pairs.length) {\n\t\t\tvar _pairs$i = pairs[i];\n\t\t\tconst name = _pairs$i[0],\n\t\t\t      value = _pairs$i[1];\n\n\t\t\tcallback.call(thisArg, value, name, this);\n\t\t\tpairs = getHeaders(this);\n\t\t\ti++;\n\t\t}\n\t}\n\n\t/**\n  * Overwrite header values given name\n  *\n  * @param   String  name   Header name\n  * @param   String  value  Header value\n  * @return  Void\n  */\n\tset(name, value) {\n\t\tname = `${name}`;\n\t\tvalue = `${value}`;\n\t\tvalidateName(name);\n\t\tvalidateValue(value);\n\t\tconst key = find(this[MAP], name);\n\t\tthis[MAP][key !== undefined ? key : name] = [value];\n\t}\n\n\t/**\n  * Append a value onto existing header\n  *\n  * @param   String  name   Header name\n  * @param   String  value  Header value\n  * @return  Void\n  */\n\tappend(name, value) {\n\t\tname = `${name}`;\n\t\tvalue = `${value}`;\n\t\tvalidateName(name);\n\t\tvalidateValue(value);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key !== undefined) {\n\t\t\tthis[MAP][key].push(value);\n\t\t} else {\n\t\t\tthis[MAP][name] = [value];\n\t\t}\n\t}\n\n\t/**\n  * Check for header name existence\n  *\n  * @param   String   name  Header name\n  * @return  Boolean\n  */\n\thas(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\treturn find(this[MAP], name) !== undefined;\n\t}\n\n\t/**\n  * Delete all header values given name\n  *\n  * @param   String  name  Header name\n  * @return  Void\n  */\n\tdelete(name) {\n\t\tname = `${name}`;\n\t\tvalidateName(name);\n\t\tconst key = find(this[MAP], name);\n\t\tif (key !== undefined) {\n\t\t\tdelete this[MAP][key];\n\t\t}\n\t}\n\n\t/**\n  * Return raw headers (non-spec api)\n  *\n  * @return  Object\n  */\n\traw() {\n\t\treturn this[MAP];\n\t}\n\n\t/**\n  * Get an iterator on keys.\n  *\n  * @return  Iterator\n  */\n\tkeys() {\n\t\treturn createHeadersIterator(this, 'key');\n\t}\n\n\t/**\n  * Get an iterator on values.\n  *\n  * @return  Iterator\n  */\n\tvalues() {\n\t\treturn createHeadersIterator(this, 'value');\n\t}\n\n\t/**\n  * Get an iterator on entries.\n  *\n  * This is the default iterator of the Headers object.\n  *\n  * @return  Iterator\n  */\n\t[Symbol.iterator]() {\n\t\treturn createHeadersIterator(this, 'key+value');\n\t}\n}\nHeaders.prototype.entries = Headers.prototype[Symbol.iterator];\n\nObject.defineProperty(Headers.prototype, Symbol.toStringTag, {\n\tvalue: 'Headers',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nObject.defineProperties(Headers.prototype, {\n\tget: { enumerable: true },\n\tforEach: { enumerable: true },\n\tset: { enumerable: true },\n\tappend: { enumerable: true },\n\thas: { enumerable: true },\n\tdelete: { enumerable: true },\n\tkeys: { enumerable: true },\n\tvalues: { enumerable: true },\n\tentries: { enumerable: true }\n});\n\nfunction getHeaders(headers) {\n\tlet kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';\n\n\tconst keys = Object.keys(headers[MAP]).sort();\n\treturn keys.map(kind === 'key' ? function (k) {\n\t\treturn k.toLowerCase();\n\t} : kind === 'value' ? function (k) {\n\t\treturn headers[MAP][k].join(', ');\n\t} : function (k) {\n\t\treturn [k.toLowerCase(), headers[MAP][k].join(', ')];\n\t});\n}\n\nconst INTERNAL = Symbol('internal');\n\nfunction createHeadersIterator(target, kind) {\n\tconst iterator = Object.create(HeadersIteratorPrototype);\n\titerator[INTERNAL] = {\n\t\ttarget,\n\t\tkind,\n\t\tindex: 0\n\t};\n\treturn iterator;\n}\n\nconst HeadersIteratorPrototype = Object.setPrototypeOf({\n\tnext() {\n\t\t// istanbul ignore if\n\t\tif (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {\n\t\t\tthrow new TypeError('Value of `this` is not a HeadersIterator');\n\t\t}\n\n\t\tvar _INTERNAL = this[INTERNAL];\n\t\tconst target = _INTERNAL.target,\n\t\t      kind = _INTERNAL.kind,\n\t\t      index = _INTERNAL.index;\n\n\t\tconst values = getHeaders(target, kind);\n\t\tconst len = values.length;\n\t\tif (index >= len) {\n\t\t\treturn {\n\t\t\t\tvalue: undefined,\n\t\t\t\tdone: true\n\t\t\t};\n\t\t}\n\n\t\tthis[INTERNAL].index = index + 1;\n\n\t\treturn {\n\t\t\tvalue: values[index],\n\t\t\tdone: false\n\t\t};\n\t}\n}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));\n\nObject.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {\n\tvalue: 'HeadersIterator',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\n/**\n * Export the Headers object in a form that Node.js can consume.\n *\n * @param   Headers  headers\n * @return  Object\n */\nfunction exportNodeCompatibleHeaders(headers) {\n\tconst obj = Object.assign({ __proto__: null }, headers[MAP]);\n\n\t// http.request() only supports string as Host header. This hack makes\n\t// specifying custom Host header possible.\n\tconst hostHeaderKey = find(headers[MAP], 'Host');\n\tif (hostHeaderKey !== undefined) {\n\t\tobj[hostHeaderKey] = obj[hostHeaderKey][0];\n\t}\n\n\treturn obj;\n}\n\n/**\n * Create a Headers object from an object of headers, ignoring those that do\n * not conform to HTTP grammar productions.\n *\n * @param   Object  obj  Object of headers\n * @return  Headers\n */\nfunction createHeadersLenient(obj) {\n\tconst headers = new Headers();\n\tfor (const name of Object.keys(obj)) {\n\t\tif (invalidTokenRegex.test(name)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (Array.isArray(obj[name])) {\n\t\t\tfor (const val of obj[name]) {\n\t\t\t\tif (invalidHeaderCharRegex.test(val)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (headers[MAP][name] === undefined) {\n\t\t\t\t\theaders[MAP][name] = [val];\n\t\t\t\t} else {\n\t\t\t\t\theaders[MAP][name].push(val);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (!invalidHeaderCharRegex.test(obj[name])) {\n\t\t\theaders[MAP][name] = [obj[name]];\n\t\t}\n\t}\n\treturn headers;\n}\n\nconst INTERNALS$1 = Symbol('Response internals');\n\n// fix an issue where \"STATUS_CODES\" aren't a named export for node <10\nconst STATUS_CODES = http.STATUS_CODES;\n\n/**\n * Response class\n *\n * @param   Stream  body  Readable stream\n * @param   Object  opts  Response options\n * @return  Void\n */\nclass Response {\n\tconstructor() {\n\t\tlet body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n\t\tlet opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n\t\tBody.call(this, body, opts);\n\n\t\tconst status = opts.status || 200;\n\t\tconst headers = new Headers(opts.headers);\n\n\t\tif (body != null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(body);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tthis[INTERNALS$1] = {\n\t\t\turl: opts.url,\n\t\t\tstatus,\n\t\t\tstatusText: opts.statusText || STATUS_CODES[status],\n\t\t\theaders,\n\t\t\tcounter: opts.counter\n\t\t};\n\t}\n\n\tget url() {\n\t\treturn this[INTERNALS$1].url || '';\n\t}\n\n\tget status() {\n\t\treturn this[INTERNALS$1].status;\n\t}\n\n\t/**\n  * Convenience property representing if the request ended normally\n  */\n\tget ok() {\n\t\treturn this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;\n\t}\n\n\tget redirected() {\n\t\treturn this[INTERNALS$1].counter > 0;\n\t}\n\n\tget statusText() {\n\t\treturn this[INTERNALS$1].statusText;\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS$1].headers;\n\t}\n\n\t/**\n  * Clone this response\n  *\n  * @return  Response\n  */\n\tclone() {\n\t\treturn new Response(clone(this), {\n\t\t\turl: this.url,\n\t\t\tstatus: this.status,\n\t\t\tstatusText: this.statusText,\n\t\t\theaders: this.headers,\n\t\t\tok: this.ok,\n\t\t\tredirected: this.redirected\n\t\t});\n\t}\n}\n\nBody.mixIn(Response.prototype);\n\nObject.defineProperties(Response.prototype, {\n\turl: { enumerable: true },\n\tstatus: { enumerable: true },\n\tok: { enumerable: true },\n\tredirected: { enumerable: true },\n\tstatusText: { enumerable: true },\n\theaders: { enumerable: true },\n\tclone: { enumerable: true }\n});\n\nObject.defineProperty(Response.prototype, Symbol.toStringTag, {\n\tvalue: 'Response',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nconst INTERNALS$2 = Symbol('Request internals');\nconst URL = Url.URL || whatwgUrl.URL;\n\n// fix an issue where \"format\", \"parse\" aren't a named export for node <10\nconst parse_url = Url.parse;\nconst format_url = Url.format;\n\n/**\n * Wrapper around `new URL` to handle arbitrary URLs\n *\n * @param  {string} urlStr\n * @return {void}\n */\nfunction parseURL(urlStr) {\n\t/*\n \tCheck whether the URL is absolute or not\n \t\tScheme: https://tools.ietf.org/html/rfc3986#section-3.1\n \tAbsolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\n */\n\tif (/^[a-zA-Z][a-zA-Z\\d+\\-.]*:/.exec(urlStr)) {\n\t\turlStr = new URL(urlStr).toString();\n\t}\n\n\t// Fallback to old implementation for arbitrary URLs\n\treturn parse_url(urlStr);\n}\n\nconst streamDestructionSupported = 'destroy' in Stream.Readable.prototype;\n\n/**\n * Check if a value is an instance of Request.\n *\n * @param   Mixed   input\n * @return  Boolean\n */\nfunction isRequest(input) {\n\treturn typeof input === 'object' && typeof input[INTERNALS$2] === 'object';\n}\n\nfunction isAbortSignal(signal) {\n\tconst proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);\n\treturn !!(proto && proto.constructor.name === 'AbortSignal');\n}\n\n/**\n * Request class\n *\n * @param   Mixed   input  Url or Request instance\n * @param   Object  init   Custom options\n * @return  Void\n */\nclass Request {\n\tconstructor(input) {\n\t\tlet init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n\t\tlet parsedURL;\n\n\t\t// normalize input\n\t\tif (!isRequest(input)) {\n\t\t\tif (input && input.href) {\n\t\t\t\t// in order to support Node.js' Url objects; though WHATWG's URL objects\n\t\t\t\t// will fall into this branch also (since their `toString()` will return\n\t\t\t\t// `href` property anyway)\n\t\t\t\tparsedURL = parseURL(input.href);\n\t\t\t} else {\n\t\t\t\t// coerce input to a string before attempting to parse\n\t\t\t\tparsedURL = parseURL(`${input}`);\n\t\t\t}\n\t\t\tinput = {};\n\t\t} else {\n\t\t\tparsedURL = parseURL(input.url);\n\t\t}\n\n\t\tlet method = init.method || input.method || 'GET';\n\t\tmethod = method.toUpperCase();\n\n\t\tif ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {\n\t\t\tthrow new TypeError('Request with GET/HEAD method cannot have body');\n\t\t}\n\n\t\tlet inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;\n\n\t\tBody.call(this, inputBody, {\n\t\t\ttimeout: init.timeout || input.timeout || 0,\n\t\t\tsize: init.size || input.size || 0\n\t\t});\n\n\t\tconst headers = new Headers(init.headers || input.headers || {});\n\n\t\tif (inputBody != null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(inputBody);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tlet signal = isRequest(input) ? input.signal : null;\n\t\tif ('signal' in init) signal = init.signal;\n\n\t\tif (signal != null && !isAbortSignal(signal)) {\n\t\t\tthrow new TypeError('Expected signal to be an instanceof AbortSignal');\n\t\t}\n\n\t\tthis[INTERNALS$2] = {\n\t\t\tmethod,\n\t\t\tredirect: init.redirect || input.redirect || 'follow',\n\t\t\theaders,\n\t\t\tparsedURL,\n\t\t\tsignal\n\t\t};\n\n\t\t// node-fetch-only options\n\t\tthis.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;\n\t\tthis.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;\n\t\tthis.counter = init.counter || input.counter || 0;\n\t\tthis.agent = init.agent || input.agent;\n\t}\n\n\tget method() {\n\t\treturn this[INTERNALS$2].method;\n\t}\n\n\tget url() {\n\t\treturn format_url(this[INTERNALS$2].parsedURL);\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS$2].headers;\n\t}\n\n\tget redirect() {\n\t\treturn this[INTERNALS$2].redirect;\n\t}\n\n\tget signal() {\n\t\treturn this[INTERNALS$2].signal;\n\t}\n\n\t/**\n  * Clone this request\n  *\n  * @return  Request\n  */\n\tclone() {\n\t\treturn new Request(this);\n\t}\n}\n\nBody.mixIn(Request.prototype);\n\nObject.defineProperty(Request.prototype, Symbol.toStringTag, {\n\tvalue: 'Request',\n\twritable: false,\n\tenumerable: false,\n\tconfigurable: true\n});\n\nObject.defineProperties(Request.prototype, {\n\tmethod: { enumerable: true },\n\turl: { enumerable: true },\n\theaders: { enumerable: true },\n\tredirect: { enumerable: true },\n\tclone: { enumerable: true },\n\tsignal: { enumerable: true }\n});\n\n/**\n * Convert a Request to Node.js http request options.\n *\n * @param   Request  A Request instance\n * @return  Object   The options object to be passed to http.request\n */\nfunction getNodeRequestOptions(request) {\n\tconst parsedURL = request[INTERNALS$2].parsedURL;\n\tconst headers = new Headers(request[INTERNALS$2].headers);\n\n\t// fetch step 1.3\n\tif (!headers.has('Accept')) {\n\t\theaders.set('Accept', '*/*');\n\t}\n\n\t// Basic fetch\n\tif (!parsedURL.protocol || !parsedURL.hostname) {\n\t\tthrow new TypeError('Only absolute URLs are supported');\n\t}\n\n\tif (!/^https?:$/.test(parsedURL.protocol)) {\n\t\tthrow new TypeError('Only HTTP(S) protocols are supported');\n\t}\n\n\tif (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {\n\t\tthrow new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');\n\t}\n\n\t// HTTP-network-or-cache fetch steps 2.4-2.7\n\tlet contentLengthValue = null;\n\tif (request.body == null && /^(POST|PUT)$/i.test(request.method)) {\n\t\tcontentLengthValue = '0';\n\t}\n\tif (request.body != null) {\n\t\tconst totalBytes = getTotalBytes(request);\n\t\tif (typeof totalBytes === 'number') {\n\t\t\tcontentLengthValue = String(totalBytes);\n\t\t}\n\t}\n\tif (contentLengthValue) {\n\t\theaders.set('Content-Length', contentLengthValue);\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.11\n\tif (!headers.has('User-Agent')) {\n\t\theaders.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.15\n\tif (request.compress && !headers.has('Accept-Encoding')) {\n\t\theaders.set('Accept-Encoding', 'gzip,deflate');\n\t}\n\n\tlet agent = request.agent;\n\tif (typeof agent === 'function') {\n\t\tagent = agent(parsedURL);\n\t}\n\n\t// HTTP-network fetch step 4.2\n\t// chunked encoding is handled by Node.js\n\n\treturn Object.assign({}, parsedURL, {\n\t\tmethod: request.method,\n\t\theaders: exportNodeCompatibleHeaders(headers),\n\t\tagent\n\t});\n}\n\n/**\n * abort-error.js\n *\n * AbortError interface for cancelled requests\n */\n\n/**\n * Create AbortError instance\n *\n * @param   String      message      Error message for human\n * @return  AbortError\n */\nfunction AbortError(message) {\n  Error.call(this, message);\n\n  this.type = 'aborted';\n  this.message = message;\n\n  // hide custom error implementation details from end-users\n  Error.captureStackTrace(this, this.constructor);\n}\n\nAbortError.prototype = Object.create(Error.prototype);\nAbortError.prototype.constructor = AbortError;\nAbortError.prototype.name = 'AbortError';\n\nconst URL$1 = Url.URL || whatwgUrl.URL;\n\n// fix an issue where \"PassThrough\", \"resolve\" aren't a named export for node <10\nconst PassThrough$1 = Stream.PassThrough;\n\nconst isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {\n\tconst orig = new URL$1(original).hostname;\n\tconst dest = new URL$1(destination).hostname;\n\n\treturn orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);\n};\n\n/**\n * isSameProtocol reports whether the two provided URLs use the same protocol.\n *\n * Both domains must already be in canonical form.\n * @param {string|URL} original\n * @param {string|URL} destination\n */\nconst isSameProtocol = function isSameProtocol(destination, original) {\n\tconst orig = new URL$1(original).protocol;\n\tconst dest = new URL$1(destination).protocol;\n\n\treturn orig === dest;\n};\n\n/**\n * Fetch function\n *\n * @param   Mixed    url   Absolute url or Request instance\n * @param   Object   opts  Fetch options\n * @return  Promise\n */\nfunction fetch(url, opts) {\n\n\t// allow custom promise\n\tif (!fetch.Promise) {\n\t\tthrow new Error('native promise missing, set fetch.Promise to your favorite alternative');\n\t}\n\n\tBody.Promise = fetch.Promise;\n\n\t// wrap http.request into fetch\n\treturn new fetch.Promise(function (resolve, reject) {\n\t\t// build request object\n\t\tconst request = new Request(url, opts);\n\t\tconst options = getNodeRequestOptions(request);\n\n\t\tconst send = (options.protocol === 'https:' ? https : http).request;\n\t\tconst signal = request.signal;\n\n\t\tlet response = null;\n\n\t\tconst abort = function abort() {\n\t\t\tlet error = new AbortError('The user aborted a request.');\n\t\t\treject(error);\n\t\t\tif (request.body && request.body instanceof Stream.Readable) {\n\t\t\t\tdestroyStream(request.body, error);\n\t\t\t}\n\t\t\tif (!response || !response.body) return;\n\t\t\tresponse.body.emit('error', error);\n\t\t};\n\n\t\tif (signal && signal.aborted) {\n\t\t\tabort();\n\t\t\treturn;\n\t\t}\n\n\t\tconst abortAndFinalize = function abortAndFinalize() {\n\t\t\tabort();\n\t\t\tfinalize();\n\t\t};\n\n\t\t// send request\n\t\tconst req = send(options);\n\t\tlet reqTimeout;\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', abortAndFinalize);\n\t\t}\n\n\t\tfunction finalize() {\n\t\t\treq.abort();\n\t\t\tif (signal) signal.removeEventListener('abort', abortAndFinalize);\n\t\t\tclearTimeout(reqTimeout);\n\t\t}\n\n\t\tif (request.timeout) {\n\t\t\treq.once('socket', function (socket) {\n\t\t\t\treqTimeout = setTimeout(function () {\n\t\t\t\t\treject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));\n\t\t\t\t\tfinalize();\n\t\t\t\t}, request.timeout);\n\t\t\t});\n\t\t}\n\n\t\treq.on('error', function (err) {\n\t\t\treject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));\n\n\t\t\tif (response && response.body) {\n\t\t\t\tdestroyStream(response.body, err);\n\t\t\t}\n\n\t\t\tfinalize();\n\t\t});\n\n\t\tfixResponseChunkedTransferBadEnding(req, function (err) {\n\t\t\tif (signal && signal.aborted) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (response && response.body) {\n\t\t\t\tdestroyStream(response.body, err);\n\t\t\t}\n\t\t});\n\n\t\t/* c8 ignore next 18 */\n\t\tif (parseInt(process.version.substring(1)) < 14) {\n\t\t\t// Before Node.js 14, pipeline() does not fully support async iterators and does not always\n\t\t\t// properly handle when the socket close/end events are out of order.\n\t\t\treq.on('socket', function (s) {\n\t\t\t\ts.addListener('close', function (hadError) {\n\t\t\t\t\t// if a data listener is still present we didn't end cleanly\n\t\t\t\t\tconst hasDataListener = s.listenerCount('data') > 0;\n\n\t\t\t\t\t// if end happened before close but the socket didn't emit an error, do it now\n\t\t\t\t\tif (response && hasDataListener && !hadError && !(signal && signal.aborted)) {\n\t\t\t\t\t\tconst err = new Error('Premature close');\n\t\t\t\t\t\terr.code = 'ERR_STREAM_PREMATURE_CLOSE';\n\t\t\t\t\t\tresponse.body.emit('error', err);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\treq.on('response', function (res) {\n\t\t\tclearTimeout(reqTimeout);\n\n\t\t\tconst headers = createHeadersLenient(res.headers);\n\n\t\t\t// HTTP fetch step 5\n\t\t\tif (fetch.isRedirect(res.statusCode)) {\n\t\t\t\t// HTTP fetch step 5.2\n\t\t\t\tconst location = headers.get('Location');\n\n\t\t\t\t// HTTP fetch step 5.3\n\t\t\t\tlet locationURL = null;\n\t\t\t\ttry {\n\t\t\t\t\tlocationURL = location === null ? null : new URL$1(location, request.url).toString();\n\t\t\t\t} catch (err) {\n\t\t\t\t\t// error here can only be invalid URL in Location: header\n\t\t\t\t\t// do not throw when options.redirect == manual\n\t\t\t\t\t// let the user extract the errorneous redirect URL\n\t\t\t\t\tif (request.redirect !== 'manual') {\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// HTTP fetch step 5.5\n\t\t\t\tswitch (request.redirect) {\n\t\t\t\t\tcase 'error':\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase 'manual':\n\t\t\t\t\t\t// node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.\n\t\t\t\t\t\tif (locationURL !== null) {\n\t\t\t\t\t\t\t// handle corrupted header\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\theaders.set('Location', locationURL);\n\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t// istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request\n\t\t\t\t\t\t\t\treject(err);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'follow':\n\t\t\t\t\t\t// HTTP-redirect fetch step 2\n\t\t\t\t\t\tif (locationURL === null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 5\n\t\t\t\t\t\tif (request.counter >= request.follow) {\n\t\t\t\t\t\t\treject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 6 (counter increment)\n\t\t\t\t\t\t// Create a new Request object.\n\t\t\t\t\t\tconst requestOpts = {\n\t\t\t\t\t\t\theaders: new Headers(request.headers),\n\t\t\t\t\t\t\tfollow: request.follow,\n\t\t\t\t\t\t\tcounter: request.counter + 1,\n\t\t\t\t\t\t\tagent: request.agent,\n\t\t\t\t\t\t\tcompress: request.compress,\n\t\t\t\t\t\t\tmethod: request.method,\n\t\t\t\t\t\t\tbody: request.body,\n\t\t\t\t\t\t\tsignal: request.signal,\n\t\t\t\t\t\t\ttimeout: request.timeout,\n\t\t\t\t\t\t\tsize: request.size\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tif (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {\n\t\t\t\t\t\t\tfor (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {\n\t\t\t\t\t\t\t\trequestOpts.headers.delete(name);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 9\n\t\t\t\t\t\tif (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {\n\t\t\t\t\t\t\treject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 11\n\t\t\t\t\t\tif (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {\n\t\t\t\t\t\t\trequestOpts.method = 'GET';\n\t\t\t\t\t\t\trequestOpts.body = undefined;\n\t\t\t\t\t\t\trequestOpts.headers.delete('content-length');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 15\n\t\t\t\t\t\tresolve(fetch(new Request(locationURL, requestOpts)));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// prepare response\n\t\t\tres.once('end', function () {\n\t\t\t\tif (signal) signal.removeEventListener('abort', abortAndFinalize);\n\t\t\t});\n\t\t\tlet body = res.pipe(new PassThrough$1());\n\n\t\t\tconst response_options = {\n\t\t\t\turl: request.url,\n\t\t\t\tstatus: res.statusCode,\n\t\t\t\tstatusText: res.statusMessage,\n\t\t\t\theaders: headers,\n\t\t\t\tsize: request.size,\n\t\t\t\ttimeout: request.timeout,\n\t\t\t\tcounter: request.counter\n\t\t\t};\n\n\t\t\t// HTTP-network fetch step 12.1.1.3\n\t\t\tconst codings = headers.get('Content-Encoding');\n\n\t\t\t// HTTP-network fetch step 12.1.1.4: handle content codings\n\n\t\t\t// in following scenarios we ignore compression support\n\t\t\t// 1. compression support is disabled\n\t\t\t// 2. HEAD request\n\t\t\t// 3. no Content-Encoding header\n\t\t\t// 4. no content response (204)\n\t\t\t// 5. content not modified response (304)\n\t\t\tif (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For Node v6+\n\t\t\t// Be less strict when decoding compressed responses, since sometimes\n\t\t\t// servers send slightly invalid responses that are still accepted\n\t\t\t// by common browsers.\n\t\t\t// Always using Z_SYNC_FLUSH is what cURL does.\n\t\t\tconst zlibOptions = {\n\t\t\t\tflush: zlib.Z_SYNC_FLUSH,\n\t\t\t\tfinishFlush: zlib.Z_SYNC_FLUSH\n\t\t\t};\n\n\t\t\t// for gzip\n\t\t\tif (codings == 'gzip' || codings == 'x-gzip') {\n\t\t\t\tbody = body.pipe(zlib.createGunzip(zlibOptions));\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// for deflate\n\t\t\tif (codings == 'deflate' || codings == 'x-deflate') {\n\t\t\t\t// handle the infamous raw deflate response from old servers\n\t\t\t\t// a hack for old IIS and Apache servers\n\t\t\t\tconst raw = res.pipe(new PassThrough$1());\n\t\t\t\traw.once('data', function (chunk) {\n\t\t\t\t\t// see http://stackoverflow.com/questions/37519828\n\t\t\t\t\tif ((chunk[0] & 0x0F) === 0x08) {\n\t\t\t\t\t\tbody = body.pipe(zlib.createInflate());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbody = body.pipe(zlib.createInflateRaw());\n\t\t\t\t\t}\n\t\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\t\tresolve(response);\n\t\t\t\t});\n\t\t\t\traw.on('end', function () {\n\t\t\t\t\t// some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted.\n\t\t\t\t\tif (!response) {\n\t\t\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\t\t\tresolve(response);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// for br\n\t\t\tif (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {\n\t\t\t\tbody = body.pipe(zlib.createBrotliDecompress());\n\t\t\t\tresponse = new Response(body, response_options);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// otherwise, use response as-is\n\t\t\tresponse = new Response(body, response_options);\n\t\t\tresolve(response);\n\t\t});\n\n\t\twriteToStream(req, request);\n\t});\n}\nfunction fixResponseChunkedTransferBadEnding(request, errorCallback) {\n\tlet socket;\n\n\trequest.on('socket', function (s) {\n\t\tsocket = s;\n\t});\n\n\trequest.on('response', function (response) {\n\t\tconst headers = response.headers;\n\n\t\tif (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {\n\t\t\tresponse.once('close', function (hadError) {\n\t\t\t\t// tests for socket presence, as in some situations the\n\t\t\t\t// the 'socket' event is not triggered for the request\n\t\t\t\t// (happens in deno), avoids `TypeError`\n\t\t\t\t// if a data listener is still present we didn't end cleanly\n\t\t\t\tconst hasDataListener = socket && socket.listenerCount('data') > 0;\n\n\t\t\t\tif (hasDataListener && !hadError) {\n\t\t\t\t\tconst err = new Error('Premature close');\n\t\t\t\t\terr.code = 'ERR_STREAM_PREMATURE_CLOSE';\n\t\t\t\t\terrorCallback(err);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}\n\nfunction destroyStream(stream, err) {\n\tif (stream.destroy) {\n\t\tstream.destroy(err);\n\t} else {\n\t\t// node < 8\n\t\tstream.emit('error', err);\n\t\tstream.end();\n\t}\n}\n\n/**\n * Redirect code matching\n *\n * @param   Number   code  Status code\n * @return  Boolean\n */\nfetch.isRedirect = function (code) {\n\treturn code === 301 || code === 302 || code === 303 || code === 307 || code === 308;\n};\n\n// expose Promise\nfetch.Promise = global.Promise;\n\nmodule.exports = exports = fetch;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = exports;\nexports.Headers = Headers;\nexports.Request = Request;\nexports.Response = Response;\nexports.FetchError = FetchError;\n", "/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n    extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n    return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n    if (typeof b !== \"function\" && b !== null)\r\n        throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n    extendStatics(d, b);\r\n    function __() { this.constructor = d; }\r\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n    __assign = Object.assign || function __assign(t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    }\r\n    return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        t[p] = s[p];\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                t[p[i]] = s[p[i]];\r\n        }\r\n    return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n    return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n    if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n    return new (P || (P = Promise))(function (resolve, reject) {\r\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n    });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n    function verb(n) { return function (v) { return step([n, v]); }; }\r\n    function step(op) {\r\n        if (f) throw new TypeError(\"Generator is already executing.\");\r\n        while (_) try {\r\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n            if (y = 0, t) op = [op[0] & 2, t.value];\r\n            switch (op[0]) {\r\n                case 0: case 1: t = op; break;\r\n                case 4: _.label++; return { value: op[1], done: false };\r\n                case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                default:\r\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                    if (t[2]) _.ops.pop();\r\n                    _.trys.pop(); continue;\r\n            }\r\n            op = body.call(thisArg, _);\r\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n    }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    var desc = Object.getOwnPropertyDescriptor(m, k);\r\n    if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n        desc = { enumerable: true, get: function() { return m[k]; } };\r\n    }\r\n    Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n    var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n    if (m) return m.call(o);\r\n    if (o && typeof o.length === \"number\") return {\r\n        next: function () {\r\n            if (o && i >= o.length) o = void 0;\r\n            return { value: o && o[i++], done: !o };\r\n        }\r\n    };\r\n    throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n    if (!m) return o;\r\n    var i = m.call(o), r, ar = [], e;\r\n    try {\r\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n    }\r\n    catch (error) { e = { error: error }; }\r\n    finally {\r\n        try {\r\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n        }\r\n        finally { if (e) throw e.error; }\r\n    }\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n    for (var ar = [], i = 0; i < arguments.length; i++)\r\n        ar = ar.concat(__read(arguments[i]));\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n    for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n            r[k] = a[j];\r\n    return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n        if (ar || !(i in from)) {\r\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n            ar[i] = from[i];\r\n        }\r\n    }\r\n    return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n    return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n    return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n    function fulfill(value) { resume(\"next\", value); }\r\n    function reject(value) { resume(\"throw\", value); }\r\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n    var i, p;\r\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var m = o[Symbol.asyncIterator], i;\r\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n    if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n    return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n    o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n    if (mod && mod.__esModule) return mod;\r\n    var result = {};\r\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n    __setModuleDefault(result, mod);\r\n    return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n    return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n    if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n    return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Backend, DataToGPUOptions, GPUData, Tensor} from '../tensor';\nimport {DataId} from '../tensor_info';\nimport {BackendValues, DataType, WebGLData, WebGPUData} from '../types';\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\n// Required information for all backends.\nexport interface BackendTimingInfo {\n  kernelMs: number|{error: string};\n  getExtraProfileInfo?(): string;  // a field for additional timing information\n                                   // e.g. packing / unpacking for WebGL backend\n}\n\nexport interface TensorStorage {\n  read(dataId: DataId): Promise<BackendValues>;\n  readSync(dataId: DataId): BackendValues;\n  disposeData(dataId: DataId, force?: boolean): boolean;\n  write(values: BackendValues, shape: number[], dtype: DataType): DataId;\n  move(\n      dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n      refCount: number): void;\n  memory(): {unreliable: boolean;};  // Backend-specific information.\n  /** Returns number of data ids currently in the storage. */\n  numDataIds(): number;\n  refCount(dataId: DataId): number;\n}\n\n/** Convenient class for storing tensor-related data. */\nexport class DataStorage<T> {\n  private data = new WeakMap<DataId, T>();\n  private dataIdsCount = 0;\n\n  constructor(private backend: KernelBackend, private dataMover: DataMover) {}\n\n  get(dataId: DataId) {\n    if (!this.data.has(dataId)) {\n      this.dataMover.moveData(this.backend, dataId);\n    }\n    return this.data.get(dataId);\n  }\n\n  set(dataId: DataId, value: T): void {\n    this.dataIdsCount++;\n    this.data.set(dataId, value);\n  }\n\n  has(dataId: DataId): boolean {\n    return this.data.has(dataId);\n  }\n\n  delete(dataId: DataId): boolean {\n    this.dataIdsCount--;\n    return this.data.delete(dataId);\n  }\n\n  numDataIds(): number {\n    return this.dataIdsCount;\n  }\n}\n\nexport interface DataMover {\n  /**\n   * To be called by backends whenever they see a dataId that they don't own.\n   * Upon calling this method, the mover will fetch the tensor from another\n   * backend and register it with the current active backend.\n   */\n  moveData(backend: KernelBackend, dataId: DataId): void;\n}\n\nexport interface BackendTimer {\n  // check if backend timer is available\n  timerAvailable(): boolean;\n  time(f: () => void): Promise<BackendTimingInfo>;\n}\n\n/**\n * The interface that defines the kernels that should be implemented when\n * adding a new backend. New backends don't need to implement every one of the\n * methods, this can be done gradually (throw an error for unimplemented\n * methods).\n */\nexport class KernelBackend implements TensorStorage, Backend, BackendTimer {\n  refCount(dataId: DataId): number {\n    return notYetImplemented('refCount');\n  }\n  incRef(dataId: DataId): void {\n    return notYetImplemented('incRef');\n  }\n  timerAvailable(): boolean {\n    return true;\n  }\n  time(f: () => void): Promise<BackendTimingInfo> {\n    return notYetImplemented('time');\n  }\n  read(dataId: object): Promise<BackendValues> {\n    return notYetImplemented('read');\n  }\n  readSync(dataId: object): BackendValues {\n    return notYetImplemented('readSync');\n  }\n  readToGPU(dataId: object, options?: DataToGPUOptions): GPUData {\n    return notYetImplemented('readToGPU');\n  }\n  numDataIds(): number {\n    return notYetImplemented('numDataIds');\n  }\n  disposeData(dataId: object, force?: boolean): boolean {\n    return notYetImplemented('disposeData');\n  }\n  write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n    return notYetImplemented('write');\n  }\n  move(\n      dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n      refCount: number): void {\n    return notYetImplemented('move');\n  }\n\n  createTensorFromGPUData(\n      values: WebGLData|WebGPUData, shape: number[], dtype: DataType): Tensor {\n    return notYetImplemented('createTensorFromGPUData');\n  }\n\n  memory(): {unreliable: boolean; reasons?: string[]} {\n    return notYetImplemented('memory');\n  }\n  /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n  floatPrecision(): 16|32 {\n    return notYetImplemented('floatPrecision');\n  }\n  /** Returns the smallest representable number.  */\n  epsilon(): number {\n    return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n  }\n  dispose(): void {\n    return notYetImplemented('dispose');\n  }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n  throw new Error(\n      `'${kernelName}' not yet implemented or not found in the registry. ` +\n      `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendValues, DataType, DataTypeMap, FlatVector, NumericDataType, TensorLike, TypedArray, WebGLData, WebGPUData} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n                        Float32Array): void {\n  let counter = array.length;\n  let index = 0;\n  // While there are elements in the array\n  while (counter > 0) {\n    // Pick a random index\n    index = (Math.random() * counter) | 0;\n    // Decrease counter by 1\n    counter--;\n    // And swap the last element with it\n    swap(array, counter, index);\n  }\n}\n\n/**\n * Shuffles two arrays in-place the same way using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1,2,3,4,5];\n * const b = [11,22,33,44,55];\n * tf.util.shuffleCombo(a, b);\n * console.log(a, b);\n * ```\n *\n * @param array The first array to shuffle in-place.\n * @param array2 The second array to shuffle in-place with the same permutation\n *     as the first array.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function shuffleCombo(\n    // tslint:disable-next-line:no-any\n    array: any[]|Uint32Array|Int32Array|Float32Array,\n    // tslint:disable-next-line:no-any\n    array2: any[]|Uint32Array|Int32Array|Float32Array): void {\n  if (array.length !== array2.length) {\n    throw new Error(\n        `Array sizes must match to be shuffled together ` +\n        `First array length was ${array.length}` +\n        `Second array length was ${array2.length}`);\n  }\n  let counter = array.length;\n  let index = 0;\n  // While there are elements in the array\n  while (counter > 0) {\n    // Pick a random index\n    index = (Math.random() * counter) | 0;\n    // Decrease counter by 1\n    counter--;\n    // And swap the last element of each array with it\n    swap(array, counter, index);\n    swap(array2, counter, index);\n  }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n  return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n  return val % 2 === 0 ? val : val + 1;\n}\n\nexport function swap<T>(\n    object: {[index: number]: T}, left: number, right: number) {\n  const temp = object[left];\n  object[left] = object[right];\n  object[right] = temp;\n}\n\nexport function sum(arr: number[]): number {\n  let sum = 0;\n  for (let i = 0; i < arr.length; i++) {\n    sum += arr[i];\n  }\n  return sum;\n}\n\n/**\n * Returns a sample from a uniform [a, b) distribution.\n *\n * @param a The minimum support (inclusive).\n * @param b The maximum support (exclusive).\n * @return A pseudorandom number on the half-open interval [a,b).\n */\nexport function randUniform(a: number, b: number) {\n  const r = Math.random();\n  return (b * r) + (1 - r) * a;\n}\n\n/** Returns the squared Euclidean distance between two vectors. */\nexport function distSquared(a: FlatVector, b: FlatVector): number {\n  let result = 0;\n  for (let i = 0; i < a.length; i++) {\n    const diff = Number(a[i]) - Number(b[i]);\n    result += diff * diff;\n  }\n  return result;\n}\n\n/**\n * Asserts that the expression is true. Otherwise throws an error with the\n * provided message.\n *\n * ```js\n * const x = 2;\n * tf.util.assert(x === 2, 'x is not 2');\n * ```\n *\n * @param expr The expression to assert (as a boolean).\n * @param msg A function that returns the message to report when throwing an\n *     error. We use a function for performance reasons.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function assert(expr: boolean, msg: () => string) {\n  if (!expr) {\n    throw new Error(typeof msg === 'string' ? msg : msg());\n  }\n}\n\nexport function assertShapesMatch(\n    shapeA: number[], shapeB: number[], errorMessagePrefix = ''): void {\n  assert(\n      arraysEqual(shapeA, shapeB),\n      () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n}\n\nexport function assertNonNull(a: TensorLike): void {\n  assert(\n      a != null,\n      () => `The input to the tensor constructor must be a non-null value.`);\n}\n\n/**\n * Returns the size (number of elements) of the tensor given its shape.\n *\n * ```js\n * const shape = [3, 4, 2];\n * const size = tf.util.sizeFromShape(shape);\n * console.log(size);\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function sizeFromShape(shape: number[]): number {\n  if (shape.length === 0) {\n    // Scalar.\n    return 1;\n  }\n  let size = shape[0];\n  for (let i = 1; i < shape.length; i++) {\n    size *= shape[i];\n  }\n  return size;\n}\n\nexport function isScalarShape(shape: number[]): boolean {\n  return shape.length === 0;\n}\n\nexport function arraysEqualWithNull(n1: number[], n2: number[]) {\n  if (n1 === n2) {\n    return true;\n  }\n\n  if (n1 == null || n2 == null) {\n    return false;\n  }\n\n  if (n1.length !== n2.length) {\n    return false;\n  }\n\n  for (let i = 0; i < n1.length; i++) {\n    if (n1[i] !== null && n2[i] !== null && n1[i] !== n2[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function arraysEqual(n1: FlatVector, n2: FlatVector) {\n  if (n1 === n2) {\n    return true;\n  }\n  if (n1 == null || n2 == null) {\n    return false;\n  }\n\n  if (n1.length !== n2.length) {\n    return false;\n  }\n  for (let i = 0; i < n1.length; i++) {\n    if (n1[i] !== n2[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function isInt(a: number): boolean {\n  return a % 1 === 0;\n}\n\nexport function tanh(x: number): number {\n  // tslint:disable-next-line:no-any\n  if ((Math as any).tanh != null) {\n    // tslint:disable-next-line:no-any\n    return (Math as any).tanh(x);\n  }\n  if (x === Infinity) {\n    return 1;\n  } else if (x === -Infinity) {\n    return -1;\n  } else {\n    const e2x = Math.exp(2 * x);\n    return (e2x - 1) / (e2x + 1);\n  }\n}\n\nexport function sizeToSquarishShape(size: number): [number, number] {\n  const width = Math.ceil(Math.sqrt(size));\n  return [width, Math.ceil(size / width)];\n}\n\n/**\n * Creates a new array with randomized indices to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indices to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n  const shuffledIndices = new Uint32Array(n);\n  for (let i = 0; i < n; ++i) {\n    shuffledIndices[i] = i;\n  }\n  shuffle(shuffledIndices);\n  return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n  if (size <= a.length) {\n    return a;\n  }\n  return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n    checkFn: () => boolean, delayFn = (counter: number) => 0,\n    maxCounter?: number,\n    scheduleFn?: (functionRef: Function, delay: number) =>\n        void): Promise<void> {\n  return new Promise<void>((resolve, reject) => {\n    let tryCount = 0;\n\n    const tryFn = () => {\n      if (checkFn()) {\n        resolve();\n        return;\n      }\n\n      tryCount++;\n\n      const nextBackoff = delayFn(tryCount);\n\n      if (maxCounter != null && tryCount >= maxCounter) {\n        reject();\n        return;\n      }\n\n      if (scheduleFn != null) {\n        scheduleFn(tryFn, nextBackoff);\n      } else {\n        // google3 does not allow assigning another variable to setTimeout.\n        // Don't refactor this so scheduleFn has a default value of setTimeout.\n        setTimeout(tryFn, nextBackoff);\n      }\n    };\n\n    tryFn();\n  });\n}\n\n/**\n * Given the full size of the array and a shape that may contain -1 as the\n * implicit dimension, returns the inferred shape where -1 is replaced.\n * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].\n *\n * @param shape The shape, which may contain -1 in some dimension.\n * @param size The full size (number of elements) of the array.\n * @return The inferred shape where -1 is replaced with the inferred size.\n */\nexport function inferFromImplicitShape(\n    shape: number[], size: number): number[] {\n  let shapeProd = 1;\n  let implicitIdx = -1;\n\n  for (let i = 0; i < shape.length; ++i) {\n    if (shape[i] >= 0) {\n      shapeProd *= shape[i];\n    } else if (shape[i] === -1) {\n      if (implicitIdx !== -1) {\n        throw Error(\n            `Shapes can only have 1 implicit size. ` +\n            `Found -1 at dim ${implicitIdx} and dim ${i}`);\n      }\n      implicitIdx = i;\n    } else if (shape[i] < 0) {\n      throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);\n    }\n  }\n\n  if (implicitIdx === -1) {\n    if (size > 0 && size !== shapeProd) {\n      throw Error(`Size(${size}) must match the product of shape ${shape}`);\n    }\n    return shape;\n  }\n\n  if (shapeProd === 0) {\n    throw Error(\n        `Cannot infer the missing size in [${shape}] when ` +\n        `there are 0 elements`);\n  }\n  if (size % shapeProd !== 0) {\n    throw Error(\n        `The implicit shape can't be a fractional number. ` +\n        `Got ${size} / ${shapeProd}`);\n  }\n\n  const newShape = shape.slice();\n  newShape[implicitIdx] = size / shapeProd;\n  return newShape;\n}\n\nexport function parseAxisParam(\n    axis: number|number[], shape: number[]): number[] {\n  const rank = shape.length;\n\n  // Normalize input\n  axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);\n\n  // Check for valid range\n  assert(\n      axis.every(ax => ax >= -rank && ax < rank),\n      () =>\n          `All values in axis param must be in range [-${rank}, ${rank}) but ` +\n          `got axis ${axis}`);\n\n  // Check for only integers\n  assert(\n      axis.every(ax => isInt(ax)),\n      () => `All values in axis param must be integers but ` +\n          `got axis ${axis}`);\n\n  // Handle negative axis.\n  return axis.map(a => a < 0 ? rank + a : a);\n}\n\n/** Reduces the shape by removing all dimensions of shape 1. */\nexport function squeezeShape(shape: number[], axis?: number[]):\n    {newShape: number[], keptDims: number[]} {\n  const newShape: number[] = [];\n  const keptDims: number[] = [];\n  const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;\n  const axes = (axis == null || isEmptyArray) ?\n      null :\n      parseAxisParam(axis, shape).sort();\n  let j = 0;\n  for (let i = 0; i < shape.length; ++i) {\n    if (axes != null) {\n      if (axes[j] === i && shape[i] !== 1) {\n        throw new Error(\n            `Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);\n      }\n      if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {\n        newShape.push(shape[i]);\n        keptDims.push(i);\n      }\n      if (axes[j] <= i) {\n        j++;\n      }\n    }\n    if (shape[i] !== 1) {\n      newShape.push(shape[i]);\n      keptDims.push(i);\n    }\n  }\n  return {newShape, keptDims};\n}\n\nexport function getTypedArrayFromDType<D extends NumericDataType>(\n    dtype: D, size: number): DataTypeMap[D] {\n  return getArrayFromDType<D>(dtype, size);\n}\n\nexport function getArrayFromDType<D extends DataType>(\n    dtype: D, size: number): DataTypeMap[D] {\n  let values = null;\n  if (dtype == null || dtype === 'float32') {\n    values = new Float32Array(size);\n  } else if (dtype === 'int32') {\n    values = new Int32Array(size);\n  } else if (dtype === 'bool') {\n    values = new Uint8Array(size);\n  } else if (dtype === 'string') {\n    values = new Array<string>(size);\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n  return values as DataTypeMap[D];\n}\n\nexport function checkConversionForErrors<D extends DataType>(\n    vals: DataTypeMap[D]|number[], dtype: D): void {\n  for (let i = 0; i < vals.length; i++) {\n    const num = vals[i] as number;\n    if (isNaN(num) || !isFinite(num)) {\n      throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);\n    }\n  }\n}\n\n/** Returns true if the dtype is valid. */\nexport function isValidDtype(dtype: DataType): boolean {\n  return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||\n      dtype === 'int32' || dtype === 'string';\n}\n\n/**\n * Returns true if the new type can't encode the old type without loss of\n * precision.\n */\nexport function hasEncodingLoss(oldType: DataType, newType: DataType): boolean {\n  if (newType === 'complex64') {\n    return false;\n  }\n  if (newType === 'float32' && oldType !== 'complex64') {\n    return false;\n  }\n  if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {\n    return false;\n  }\n  if (newType === 'bool' && oldType === 'bool') {\n    return false;\n  }\n  return true;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n  if (dtype === 'float32' || dtype === 'int32') {\n    return 4;\n  } else if (dtype === 'complex64') {\n    return 8;\n  } else if (dtype === 'bool') {\n    return 1;\n  } else {\n    throw new Error(`Unknown dtype ${dtype}`);\n  }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS\n * is not possible since it depends on the encoding of the html page that\n * serves the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n  if (arr == null) {\n    return 0;\n  }\n  let bytes = 0;\n  arr.forEach(x => bytes += x.length);\n  return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n  return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n  return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n  return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike|WebGLData|WebGPUData): DataType {\n  if (Array.isArray(values)) {\n    return inferDtype(values[0]);\n  }\n  if (values instanceof Float32Array) {\n    return 'float32';\n  } else if (\n      values instanceof Int32Array || values instanceof Uint8Array ||\n      values instanceof Uint8ClampedArray) {\n    return 'int32';\n  } else if (isNumber(values)) {\n    return 'float32';\n  } else if (isString(values)) {\n    return 'string';\n  } else if (isBoolean(values)) {\n    return 'bool';\n  }\n  return 'float32';\n}\n\nexport function isFunction(f: Function) {\n  return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n  for (let i = start; i < size; ++i) {\n    if (size % i === 0) {\n      return i;\n    }\n  }\n  return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n  const rank = shape.length;\n  if (rank < 2) {\n    return [];\n  }\n\n  // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n  // strides.\n  const strides = new Array(rank - 1);\n  strides[rank - 2] = shape[rank - 1];\n  for (let i = rank - 3; i >= 0; --i) {\n    strides[i] = strides[i + 1] * shape[i + 1];\n  }\n  return strides;\n}\n\nfunction createNestedArray(\n    offset: number, shape: number[], a: TypedArray, isComplex = false) {\n  const ret = new Array();\n  if (shape.length === 1) {\n    const d = shape[0] * (isComplex ? 2 : 1);\n    for (let i = 0; i < d; i++) {\n      ret[i] = a[offset + i];\n    }\n  } else {\n    const d = shape[0];\n    const rest = shape.slice(1);\n    const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n    for (let i = 0; i < d; i++) {\n      ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);\n    }\n  }\n  return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(\n    shape: number[], a: TypedArray, isComplex = false) {\n  if (shape.length === 0) {\n    // Scalar type should return a single number.\n    return a[0];\n  }\n  const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n  if (size === 0) {\n    // A tensor with shape zero should be turned into empty list.\n    return [];\n  }\n  if (size !== a.length) {\n    throw new Error(`[${shape}] does not match the input size ${a.length}${\n        isComplex ? ' for a complex tensor' : ''}.`);\n  }\n\n  return createNestedArray(0, shape, a, isComplex);\n}\n\nexport function convertBackendValuesAndArrayBuffer(\n    data: BackendValues|ArrayBuffer, dtype: DataType) {\n  // If is type Uint8Array[], return it directly.\n  if (Array.isArray(data)) {\n    return data;\n  }\n  if (dtype === 'float32') {\n    return data instanceof Float32Array ? data : new Float32Array(data);\n  } else if (dtype === 'int32') {\n    return data instanceof Int32Array ? data : new Int32Array(data);\n  } else if (dtype === 'bool' || dtype === 'string') {\n    return Uint8Array.from(new Int32Array(data));\n  } else {\n    throw new Error(`Unknown dtype ${dtype}`);\n  }\n}\n\nexport function makeOnesTypedArray<D extends DataType>(\n    size: number, dtype: D): DataTypeMap[D] {\n  const array = makeZerosTypedArray(size, dtype);\n  for (let i = 0; i < array.length; i++) {\n    array[i] = 1;\n  }\n  return array;\n}\n\nexport function makeZerosTypedArray<D extends DataType>(\n    size: number, dtype: D): DataTypeMap[D] {\n  if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n    return new Float32Array(size) as DataTypeMap[D];\n  } else if (dtype === 'int32') {\n    return new Int32Array(size) as DataTypeMap[D];\n  } else if (dtype === 'bool') {\n    return new Uint8Array(size) as DataTypeMap[D];\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n}\n\n/**\n * Make nested `TypedArray` filled with zeros.\n * @param shape The shape information for the nested array.\n * @param dtype dtype of the array element.\n */\nexport function makeZerosNestedTypedArray<D extends DataType>(\n    shape: number[], dtype: D) {\n  const size = shape.reduce((prev, curr) => prev * curr, 1);\n  if (dtype == null || dtype === 'float32') {\n    return toNestedArray(shape, new Float32Array(size));\n  } else if (dtype === 'int32') {\n    return toNestedArray(shape, new Int32Array(size));\n  } else if (dtype === 'bool') {\n    return toNestedArray(shape, new Uint8Array(size));\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n  shape.forEach(dimSize => {\n    assert(\n        Number.isInteger(dimSize) && dimSize >= 0,\n        () =>\n            `Tensor must have a shape comprised of positive integers but got ` +\n            `shape [${shape}].`);\n  });\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n    locs: number[], rank: number, strides: number[]): number {\n  if (rank === 0) {\n    return 0;\n  } else if (rank === 1) {\n    return locs[0];\n  }\n  let index = locs[locs.length - 1];\n  for (let i = 0; i < locs.length - 1; ++i) {\n    index += strides[i] * locs[i];\n  }\n  return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a\n * tensor/multidimentional array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n    index: number, rank: number, strides: number[]): number[] {\n  if (rank === 0) {\n    return [];\n  } else if (rank === 1) {\n    return [index];\n  }\n  const locs: number[] = new Array(rank);\n  for (let i = 0; i < locs.length - 1; ++i) {\n    locs[i] = Math.floor(index / strides[i]);\n    index -= locs[i] * strides[i];\n  }\n  locs[locs.length - 1] = index;\n  return locs;\n}\n\n/**\n * This method asserts whether an object is a Promise instance.\n * @param object\n */\n// tslint:disable-next-line: no-any\nexport function isPromise(object: any): object is Promise<unknown> {\n  //  We chose to not use 'obj instanceOf Promise' for two reasons:\n  //  1. It only reliably works for es6 Promise, not other Promise\n  //  implementations.\n  //  2. It doesn't work with framework that uses zone.js. zone.js monkey\n  //  patch the async calls, so it is possible the obj (patched) is\n  //  comparing to a pre-patched Promise.\n  return object && object.then && typeof object.then === 'function';\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\nimport {isPromise} from './util_base';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean|string;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise<FlagValue>);\nexport type Flags = {\n  [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n  evaluationFn: FlagEvaluationFn;\n  setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n  private flags: Flags = {};\n  private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n  private urlFlags: Flags = {};\n\n  platformName: string;\n  platform: Platform;\n\n  // Jasmine spies on this in 'environment_test.ts'\n  getQueryParams = getQueryParams;\n\n  // tslint:disable-next-line: no-any\n  constructor(public global: any) {\n    this.populateURLFlags();\n  }\n\n  setPlatform(platformName: string, platform: Platform) {\n    if (this.platform != null) {\n      if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n        console.warn(\n            `Platform ${this.platformName} has already been set. ` +\n            `Overwriting the platform with ${platformName}.`);\n      }\n    }\n    this.platformName = platformName;\n    this.platform = platform;\n  }\n\n  registerFlag(\n      flagName: string, evaluationFn: FlagEvaluationFn,\n      setHook?: (value: FlagValue) => void) {\n    this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n    // Override the flag value from the URL. This has to happen here because\n    // the environment is initialized before flags get registered.\n    if (this.urlFlags[flagName] != null) {\n      const flagValue = this.urlFlags[flagName];\n      if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n        console.warn(\n            `Setting feature override from URL ${flagName}: ${flagValue}.`);\n      }\n      this.set(flagName, flagValue);\n    }\n  }\n\n  async getAsync(flagName: string): Promise<FlagValue> {\n    if (flagName in this.flags) {\n      return this.flags[flagName];\n    }\n\n    this.flags[flagName] = await this.evaluateFlag(flagName);\n    return this.flags[flagName];\n  }\n\n  get(flagName: string): FlagValue {\n    if (flagName in this.flags) {\n      return this.flags[flagName];\n    }\n\n    const flagValue = this.evaluateFlag(flagName);\n    if (isPromise(flagValue)) {\n      throw new Error(\n          `Flag ${flagName} cannot be synchronously evaluated. ` +\n          `Please use getAsync() instead.`);\n    }\n\n    this.flags[flagName] = flagValue;\n    return this.flags[flagName];\n  }\n\n  getNumber(flagName: string): number {\n    return this.get(flagName) as number;\n  }\n\n  getBool(flagName: string): boolean {\n    return this.get(flagName) as boolean;\n  }\n\n  getString(flagName: string): string {\n    return this.get(flagName) as string;\n  }\n\n  getFlags(): Flags {\n    return this.flags;\n  }\n  // For backwards compatibility.\n  get features(): Flags {\n    return this.flags;\n  }\n\n  set(flagName: string, value: FlagValue): void {\n    if (this.flagRegistry[flagName] == null) {\n      throw new Error(\n          `Cannot set flag ${flagName} as it has not been registered.`);\n    }\n    this.flags[flagName] = value;\n    if (this.flagRegistry[flagName].setHook != null) {\n      this.flagRegistry[flagName].setHook(value);\n    }\n  }\n\n  private evaluateFlag(flagName: string): FlagValue|Promise<FlagValue> {\n    if (this.flagRegistry[flagName] == null) {\n      throw new Error(\n          `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n    }\n    return this.flagRegistry[flagName].evaluationFn();\n  }\n\n  setFlags(flags: Flags) {\n    this.flags = Object.assign({}, flags);\n  }\n\n  reset() {\n    this.flags = {};\n    this.urlFlags = {};\n    this.populateURLFlags();\n  }\n\n  private populateURLFlags(): void {\n    if (typeof this.global === 'undefined' ||\n        typeof this.global.location === 'undefined' ||\n        typeof this.global.location.search === 'undefined') {\n      return;\n    }\n\n    const urlParams = this.getQueryParams(this.global.location.search);\n    if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n      const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n      keyValues.forEach(keyValue => {\n        const [key, value] = keyValue.split(':') as [string, string];\n        this.urlFlags[key] = parseValue(key, value);\n      });\n    }\n  }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n  const params = {};\n  queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n    decodeParam(params, t[0], t[1]);\n    return t.join('=');\n  });\n  return params;\n}\n\nfunction decodeParam(\n    params: {[key: string]: string}, name: string, value?: string) {\n  params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n  const lowerCaseValue = value.toLowerCase();\n  if (lowerCaseValue === 'true' || lowerCaseValue === 'false') {\n    return lowerCaseValue === 'true';\n  } else if (`${+ lowerCaseValue}` === lowerCaseValue) {\n    return +lowerCaseValue;\n  } else {\n    return value;\n  }\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n  return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n  ENV = environment;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map<string, any>};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map<string, any>} {\n  if (globalNameSpace == null) {\n    // tslint:disable-next-line:no-any\n    let ns: any;\n    if (typeof (window) !== 'undefined') {\n      ns = window;\n    } else if (typeof (global) !== 'undefined') {\n      ns = global;\n    } else if (typeof (process) !== 'undefined') {\n      ns = process;\n    } else if (typeof (self) !== 'undefined') {\n      ns = self;\n    } else {\n      throw new Error('Could not find a global object');\n    }\n    globalNameSpace = ns;\n  }\n  return globalNameSpace;\n}\n\n// tslint:disable-next-line:no-any\nfunction getGlobalMap(): Map<string, any> {\n  const ns = getGlobalNamespace();\n  if (ns._tfGlobals == null) {\n    ns._tfGlobals = new Map();\n  }\n  return ns._tfGlobals;\n}\n\n/**\n * Returns a globally accessible 'singleton' object.\n *\n * @param key the name of the object\n * @param init a function to initialize to initialize this object\n *             the first time it is fetched.\n */\nexport function getGlobal<T>(key: string, init: () => T): T {\n  const globalMap = getGlobalMap();\n  if (globalMap.has(key)) {\n    return globalMap.get(key);\n  } else {\n    const singleton = init();\n    globalMap.set(key, singleton);\n    return globalMap.get(key);\n  }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {TensorInfo} from './tensor_info';\nimport {DataType, DrawOptions, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AllAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AnyAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ArgMaxAttrs {\n  axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ArgMinAttrs {\n  axis: number;\n}\n\nexport const Asin = 'Asin';\nexport type AsinInputs = UnaryInputs;\n\nexport const Asinh = 'Asinh';\nexport type AsinhInputs = UnaryInputs;\n\nexport const Atan = 'Atan';\nexport type AtanInputs = UnaryInputs;\n\nexport const Atanh = 'Atanh';\nexport type AtanhInputs = UnaryInputs;\n\nexport const Atan2 = 'Atan2';\nexport type Atan2Inputs = BinaryInputs;\n\nexport const AvgPool = 'AvgPool';\nexport type AvgPoolInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AvgPoolAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const AvgPoolGrad = 'AvgPoolGrad';\nexport type AvgPoolGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'>;\nexport interface AvgPoolGradAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n}\n\nexport const AvgPool3D = 'AvgPool3D';\nexport type AvgPool3DInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AvgPool3DAttrs {\n  filterSize: [number, number, number]|number;\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same'|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  dataFormat: 'NDHWC'|'NCDHW';\n}\n\nexport const AvgPool3DGrad = 'AvgPool3DGrad';\nexport type AvgPool3DGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'>;\nexport interface AvgPool3DGradAttrs {\n  filterSize: [number, number, number]|number;\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same'|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const BatchMatMul = 'BatchMatMul';\nexport type BatchMatMulInputs = Pick<NamedTensorInfoMap, 'a'|'b'>;\nexport interface BatchMatMulAttrs {\n  transposeA: boolean;\n  transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BatchToSpaceNDAttrs {\n  blockShape: number[];\n  crops: number[][];\n}\n\nexport type BinaryInputs = Pick<NamedTensorInfoMap, 'a'|'b'>;\n\nexport const Bincount = 'Bincount';\nexport type BincountInputs = Pick<NamedTensorInfoMap, 'x'|'weights'>;\nexport interface BincountAttrs {\n  size: number;\n}\n\nexport const BitwiseAnd = 'BitwiseAnd';\nexport type BitwiseAndInputs = BinaryInputs;\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BroadCastToAttrs {\n  shape: number[];\n  inputShape: number[];  // for gradient\n}\n\nexport const BroadcastArgs = 'BroadcastArgs';\nexport type BroadcastArgsInputs = Pick<NamedTensorInfoMap, 's0'|'s1'>;\n\nexport const Cast = 'Cast';\nexport type CastInputs = UnaryInputs;\nexport interface CastAttrs {\n  dtype: DataType;\n}\n\nexport const Ceil = 'Ceil';\nexport type CeilInputs = UnaryInputs;\n\nexport const ClipByValue = 'ClipByValue';\nexport type ClipByValueInputs = UnaryInputs;\nexport interface ClipByValueAttrs {\n  clipValueMin: number;\n  clipValueMax: number;\n}\n\nexport const Complex = 'Complex';\nexport type ComplexInputs = Pick<NamedTensorInfoMap, 'real'|'imag'>;\n\nexport const ComplexAbs = 'ComplexAbs';\nexport type ComplexAbsInputs = UnaryInputs;\n\nexport const Concat = 'Concat';\nexport type ConcatInputs = TensorInfo[];\nexport interface ConcatAttrs {\n  axis: number;\n}\n\nexport const Conv2D = 'Conv2D';\nexport type Conv2DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Conv2DAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dilations: [number, number]|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropFilter = 'Conv2DBackpropFilter';\nexport type Conv2DBackpropFilterInputs = Pick<NamedTensorInfoMap, 'x'|'dy'>;\nexport interface Conv2DBackpropFilterAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  filterShape: [number, number, number, number];\n}\n\nexport const Conv2DBackpropInput = 'Conv2DBackpropInput';\nexport type Conv2DBackpropInputInputs = Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface Conv2DBackpropInputAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  inputShape: [number, number, number, number];\n}\n\nexport const Conv3D = 'Conv3D';\nexport type Conv3DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Conv3DAttrs {\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same';\n  dataFormat: 'NDHWC'|'NCDHW';\n  dilations: [number, number, number]|number;\n}\n\nexport const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';\nexport type Conv3DBackpropFilterV2Inputs = Pick<NamedTensorInfoMap, 'x'|'dy'>;\n\nexport interface Conv3DBackpropFilterV2Attrs {\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same';\n  filterShape: [number, number, number, number, number];\n}\n\nexport const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';\nexport type Conv3DBackpropInputV2Inputs =\n    Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface Conv3DBackpropInputV2Attrs {\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same';\n  inputShape: [number, number, number, number, number];\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumprod = 'Cumprod';\nexport type CumprodInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface CumprodAttrs {\n  axis: number;\n  exclusive: boolean;\n  reverse: boolean;\n}\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface CumsumAttrs {\n  axis: number;\n  exclusive: boolean;\n  reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n    Pick<NamedTensorInfoMap, 'image'|'boxes'|'boxInd'>;\nexport interface CropAndResizeAttrs {\n  cropSize: [number, number];\n  method: 'bilinear'|'nearest';\n  extrapolationValue: number;\n}\n\nexport const DenseBincount = 'DenseBincount';\nexport type DenseBincountInputs = Pick<NamedTensorInfoMap, 'x'|'weights'>;\nexport interface DenseBincountAttrs {\n  size: number;\n  binaryOutput?: boolean;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface DepthToSpaceAttrs {\n  blockSize: number;\n  dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n    Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface DepthwiseConv2dNativeAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dilations: [number, number]|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const DepthwiseConv2dNativeBackpropFilter =\n    'DepthwiseConv2dNativeBackpropFilter';\nexport type DepthwiseConv2dNativeBackpropFilterInputs =\n    Pick<NamedTensorInfoMap, 'x'|'dy'>;\nexport interface DepthwiseConv2dNativeBackpropFilterAttrs {\n  strides: [number, number]|number;\n  dilations: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  filterShape: [number, number, number, number];\n}\n\nexport const DepthwiseConv2dNativeBackpropInput =\n    'DepthwiseConv2dNativeBackpropInput';\nexport type DepthwiseConv2dNativeBackpropInputInputs =\n    Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface DepthwiseConv2dNativeBackpropInputAttrs {\n  strides: [number, number]|number;\n  dilations: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  inputShape: [number, number, number, number];\n}\n\nexport const Diag = 'Diag';\nexport type DiagInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Dilation2DAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number;\n  dilations: [number, number]|number;\n}\n\nexport const Dilation2DBackpropInput = 'Dilation2DBackpropInput';\nexport type Dilation2DBackpropInputInputs =\n    Pick<NamedTensorInfoMap, 'x'|'filter'|'dy'>;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n    Pick<NamedTensorInfoMap, 'x'|'filter'|'dy'>;\n\nexport const Draw = 'Draw';\nexport type DrawInputs = Pick<NamedTensorInfoMap, 'image'>;\nexport interface DrawAttrs {\n  canvas: HTMLCanvasElement;\n  options?: DrawOptions;\n}\n\nexport const RealDiv = 'RealDiv';\nexport type RealDivInputs = BinaryInputs;\n\nexport const Einsum = 'Einsum';\nexport type EinsumInputs = TensorInfo[];\nexport interface EinsumAttrs {\n  equation: string;\n}\n\nexport const Elu = 'Elu';\nexport type EluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick<NamedTensorInfoMap, 'dy'|'y'>;\n\nexport const Erf = 'Erf';\nexport type ErfInputs = UnaryInputs;\n\nexport const Equal = 'Equal';\nexport type EqualInputs = BinaryInputs;\n\nexport const Exp = 'Exp';\nexport type ExpInputs = UnaryInputs;\n\nexport const ExpandDims = 'ExpandDims';\nexport type ExpandDimsInputs = Pick<NamedTensorInfoMap, 'input'>;\nexport interface ExpandDimsAttrs {\n  dim: number;\n}\n\nexport const Expm1 = 'Expm1';\nexport type Expm1Inputs = UnaryInputs;\n\nexport const FFT = 'FFT';\nexport type FFTInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Fill = 'Fill';\nexport interface FillAttrs {\n  shape: number[];\n  value: number|string;\n  dtype: DataType;\n}\n\nexport const FlipLeftRight = 'FlipLeftRight';\nexport type FlipLeftRightInputs = Pick<NamedTensorInfoMap, 'image'>;\n\nexport const Floor = 'Floor';\nexport type FloorInputs = UnaryInputs;\n\nexport const FloorDiv = 'FloorDiv';\nexport type FloorDivInputs = BinaryInputs;\n\nexport const FusedBatchNorm = 'FusedBatchNorm';\nexport type FusedBatchNormInputs =\n    Pick<NamedTensorInfoMap, 'x'|'scale'|'offset'|'mean'|'variance'>;\nexport interface FusedBatchNormAttrs {\n  varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick<NamedTensorInfoMap, 'x'|'indices'>;\nexport interface GatherV2Attrs {\n  axis: number;\n  batchDims: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick<NamedTensorInfoMap, 'params'|'indices'>;\n\nexport const Greater = 'Greater';\nexport type GreaterInputs = BinaryInputs;\n\nexport const GreaterEqual = 'GreaterEqual';\nexport type GreaterEqualInputs = BinaryInputs;\n\nexport const Identity = 'Identity';\nexport type IdentityInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const IsFinite = 'IsFinite';\nexport type IsFiniteInputs = UnaryInputs;\n\nexport const IsInf = 'IsInf';\nexport type IsInfInputs = UnaryInputs;\n\nexport const IsNan = 'IsNan';\nexport type IsNanInputs = UnaryInputs;\n\nexport const LeakyRelu = 'LeakyRelu';\nexport type LeakyReluInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface LeakyReluAttrs {\n  alpha: number;\n}\n\nexport const Less = 'Less';\nexport type LessInputs = BinaryInputs;\n\nexport const LessEqual = 'LessEqual';\nexport type LessEqualInputs = BinaryInputs;\n\nexport const LinSpace = 'LinSpace';\nexport interface LinSpaceAttrs {\n  start: number;\n  stop: number;\n  num: number;\n}\nexport const Log = 'Log';\nexport type LogInputs = UnaryInputs;\n\nexport const Log1p = 'Log1p';\nexport type Log1pInputs = UnaryInputs;\n\nexport const LogicalAnd = 'LogicalAnd';\nexport type LogicalAndInputs = BinaryInputs;\n\nexport const LogicalNot = 'LogicalNot';\nexport type LogicalNotInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogicalXor = 'LogicalXor';\nexport type LogicalXorInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface LogSoftmaxAttrs {\n  axis: number;\n}\n\nexport const LowerBound = 'LowerBound';\nexport type LowerBoundInputs =\n    Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface LRNAttrs {\n  depthRadius: number;\n  bias: number;\n  alpha: number;\n  beta: number;\n}\n\nexport const LRNGrad = 'LRNGrad';\nexport type LRNGradInputs = Pick<NamedTensorInfoMap, 'x'|'y'|'dy'>;\nexport interface LRNGradAttrs {\n  depthRadius: number;\n  bias: number;\n  alpha: number;\n  beta: number;\n}\n\nexport const MatrixBandPart = 'MatrixBandPart';\nexport type MatrixBandPartInputs =\n    Pick<NamedTensorInfoMap, 'input'|'numLower'|'numUpper'>;\nexport interface MatrixBandPartAttrs {}\n\nexport const Max = 'Max';\nexport type MaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxAttrs {\n  reductionIndices: number|number[];\n  keepDims: boolean;\n}\n\nexport const Maximum = 'Maximum';\nexport type MaximumInputs = BinaryInputs;\n\nexport const MaxPool = 'MaxPool';\nexport type MaxPoolInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPoolAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolGrad = 'MaxPoolGrad';\nexport type MaxPoolGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'|'output'>;\nexport interface MaxPoolGradAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3D = 'MaxPool3D';\nexport type MaxPool3DInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPool3DAttrs {\n  filterSize: [number, number, number]|number;\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same'|number;\n  dataFormat: 'NDHWC'|'NCDHW';\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3DGrad = 'MaxPool3DGrad';\nexport type MaxPool3DGradInputs =\n    Pick<NamedTensorInfoMap, 'dy'|'input'|'output'>;\nexport interface MaxPool3DGradAttrs {\n  filterSize: [number, number, number]|number;\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same'|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolWithArgmax = 'MaxPoolWithArgmax';\nexport type MaxPoolWithArgmaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPoolWithArgmaxAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number;\n  includeBatchInIndex: boolean;\n}\n\nexport const Mean = 'Mean';\nexport type MeanInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MeanAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MinAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const Minimum = 'Minimum';\nexport type MinimumInputs = BinaryInputs;\n\nexport const MirrorPad = 'MirrorPad';\nexport type MirrorPadInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MirrorPadAttrs {\n  paddings: Array<[number, number]>;\n  mode: 'reflect'|'symmetric';\n}\n\nexport const Mod = 'Mod';\nexport type ModInputs = BinaryInputs;\n\nexport const Multinomial = 'Multinomial';\nexport type MultinomialInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface MultinomialAttrs {\n  numSamples: number;\n  seed: number;\n  normalized: boolean;\n}\n\nexport const Multiply = 'Multiply';\nexport type MultiplyInputs = BinaryInputs;\n\nexport const Neg = 'Neg';\nexport type NegInputs = UnaryInputs;\n\nexport const NotEqual = 'NotEqual';\nexport type NotEqualInputs = BinaryInputs;\n\nexport const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';\nexport type NonMaxSuppressionV3Inputs =\n    Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV3Attrs {\n  maxOutputSize: number;\n  iouThreshold: number;\n  scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n    Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV4Attrs {\n  maxOutputSize: number;\n  iouThreshold: number;\n  scoreThreshold: number;\n  padToMaxOutputSize: boolean;\n}\n\nexport const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';\nexport type NonMaxSuppressionV5Inputs =\n    Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV5Attrs {\n  maxOutputSize: number;\n  iouThreshold: number;\n  scoreThreshold: number;\n  softNmsSigma: number;\n}\n\nexport const OnesLike = 'OnesLike';\nexport type OnesLikeInputs = UnaryInputs;\n\nexport const OneHot = 'OneHot';\nexport type OneHotInputs = Pick<NamedTensorInfoMap, 'indices'>;\nexport interface OneHotAttrs {\n  depth: number;\n  onValue: number;\n  offValue: number;\n  dtype: DataType;\n}\n\nexport const Pack = 'Pack';\nexport type PackInputs = TensorInfo[];\nexport interface PackAttrs {\n  axis: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface PadV2Attrs {\n  paddings: Array<[number, number]>;\n  constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick<NamedTensorInfoMap, 'x'|'alpha'>;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ProdAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const RaggedGather = 'RaggedGather';\nexport type RaggedGatherInputs = {\n  paramsNestedSplits: TensorInfo[]\n}&Pick<NamedTensorInfoMap, 'paramsDenseValues'|'indices'>;\nexport interface RaggedGatherAttrs {\n  outputRaggedRank: number;\n}\n\nexport const RaggedRange = 'RaggedRange';\nexport type RaggedRangeInputs =\n    Pick<NamedTensorInfoMap, 'starts'|'limits'|'deltas'>;\n\nexport const RaggedTensorToTensor = 'RaggedTensorToTensor';\nexport type RaggedTensorToTensorInputs =\n    Pick<NamedTensorInfoMap, 'shape'|'values'|'defaultValue'>&\n    {rowPartitionTensors: TensorInfo[]};\nexport interface RaggedTensorToTensorAttrs {\n  rowPartitionTypes: string[];\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n  start: number;\n  stop: number;\n  step: number;\n  dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ReshapeAttrs {\n  shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick<NamedTensorInfoMap, 'images'>;\nexport interface ResizeNearestNeighborAttrs {\n  alignCorners: boolean;\n  halfPixelCenters: boolean;\n  size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n    Pick<NamedTensorInfoMap, 'images'|'dy'>;\nexport type ResizeNearestNeighborGradAttrs = ResizeNearestNeighborAttrs;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick<NamedTensorInfoMap, 'images'>;\nexport interface ResizeBilinearAttrs {\n  alignCorners: boolean;\n  halfPixelCenters: boolean;\n  size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick<NamedTensorInfoMap, 'images'|'dy'>;\nexport type ResizeBilinearGradAttrs = ResizeBilinearAttrs;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ReverseAttrs {\n  dims: number|number[];\n}\n\nexport const Round = 'Round';\nexport type RoundInputs = UnaryInputs;\n\nexport const Rsqrt = 'Rsqrt';\nexport type RsqrtInputs = UnaryInputs;\n\nexport const ScatterNd = 'ScatterNd';\nexport type ScatterNdInputs = Pick<NamedTensorInfoMap, 'indices'|'updates'>;\nexport interface ScatterNdAttrs {\n  shape: number[];\n}\n\nexport const TensorScatterUpdate = 'TensorScatterUpdate';\nexport type TensorScatterUpdateInputs =\n    Pick<NamedTensorInfoMap, 'tensor'|'indices'|'updates'>;\nexport interface TensorScatterUpdateAttrs {}\n\nexport const SearchSorted = 'SearchSorted';\nexport type SearchSortedInputs =\n    Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\nexport interface SearchSortedAttrs {\n  side: 'left'|'right';\n}\n\nexport const Select = 'Select';\nexport type SelectInputs = Pick<NamedTensorInfoMap, 'condition'|'t'|'e'>;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SliceAttrs {\n  begin: number|number[];\n  size: number|number[];\n}\nexport const Sin = 'Sin';\nexport type SinInputs = UnaryInputs;\n\nexport const Sinh = 'Sinh';\nexport type SinhInputs = UnaryInputs;\n\nexport const Sign = 'Sign';\nexport type SignInputs = UnaryInputs;\n\nexport const Sigmoid = 'Sigmoid';\nexport type SigmoidInputs = UnaryInputs;\n\nexport const Softplus = 'Softplus';\nexport type SoftplusInputs = UnaryInputs;\n\nexport const Sqrt = 'Sqrt';\nexport type SqrtInputs = UnaryInputs;\n\nexport const Sum = 'Sum';\nexport type SumInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SumAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SpaceToBatchNDAttrs {\n  blockShape: number[];\n  paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SplitVAttrs {\n  numOrSizeSplits: number[]|number;\n  axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface SoftmaxAttrs {\n  dim: number;\n}\n\nexport const SparseFillEmptyRows = 'SparseFillEmptyRows';\nexport type SparseFillEmptyRowsInputs =\n    Pick<NamedTensorInfoMap, 'indices'|'values'|'denseShape'|'defaultValue'>;\n\nexport const SparseReshape = 'SparseReshape';\nexport type SparseReshapeInputs =\n    Pick<NamedTensorInfoMap, 'inputIndices'|'inputShape'|'newShape'>;\n\nexport const SparseSegmentMean = 'SparseSegmentMean';\nexport type SparseSegmentMeanInputs =\n    Pick<NamedTensorInfoMap, 'data'|'indices'|'segmentIds'>;\n\nexport const SparseSegmentSum = 'SparseSegmentSum';\nexport type SparseSegmentSumInputs =\n    Pick<NamedTensorInfoMap, 'data'|'indices'|'segmentIds'>;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n    Pick<NamedTensorInfoMap, 'sparseIndices'|'sparseValues'|'defaultValue'>;\nexport interface SparseToDenseAttrs {\n  outputShape: number[];\n}\n\nexport const SquaredDifference = 'SquaredDifference';\nexport type SquaredDifferenceInputs = BinaryInputs;\n\nexport const Square = 'Square';\nexport type SquareInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const StaticRegexReplace = 'StaticRegexReplace';\nexport type StaticRegexReplaceInputs = UnaryInputs;\nexport interface StaticRegexReplaceAttrs {\n  pattern: string;\n  rewrite: string;\n  replaceGlobal: boolean;\n}\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface StridedSliceAttrs {\n  begin: number[];\n  end: number[];\n  strides: number[];\n  beginMask: number;\n  endMask: number;\n  ellipsisMask: number;\n  newAxisMask: number;\n  shrinkAxisMask: number;\n}\n\nexport const StringNGrams = 'StringNGrams';\nexport type StringNGramsInputs = Pick<NamedTensorInfoMap, 'data'|'dataSplits'>;\nexport interface StringNGramsAttrs {\n  separator: string;\n  nGramWidths: number[];\n  leftPad: string;\n  rightPad: string;\n  padWidth: number;\n  preserveShortSequences: boolean;\n}\n\nexport const StringSplit = 'StringSplit';\nexport type StringSplitInputs = Pick<NamedTensorInfoMap, 'input'|'delimiter'>;\nexport interface StringSplitAttrs {\n  skipEmpty: boolean;\n}\n\nexport const StringToHashBucketFast = 'StringToHashBucketFast';\nexport type StringToHashBucketFastInputs = Pick<NamedTensorInfoMap, 'input'>;\nexport interface StringToHashBucketFastAttrs {\n  numBuckets: number;\n}\n\nexport const Sub = 'Sub';\nexport type SubInputs = BinaryInputs;\n\nexport const Tan = 'Tan';\nexport type TanInputs = UnaryInputs;\n\nexport const Tanh = 'Tanh';\nexport type TanhInputs = UnaryInputs;\n\nexport const Tile = 'Tile';\nexport type TileInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TileAttrs {\n  reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TopKAttrs {\n  k: number;\n  sorted: boolean;\n}\n\nexport const Transform = 'Transform';\nexport type TransformInputs = Pick<NamedTensorInfoMap, 'image'|'transforms'>;\nexport interface TransformAttrs {\n  interpolation: 'nearest'|'bilinear';\n  fillMode: 'constant'|'reflect'|'wrap'|'nearest';\n  fillValue: number;\n  outputShape?: [number, number];\n}\n\nexport const Transpose = 'Transpose';\nexport type TransposeInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TransposeAttrs {\n  perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface UniqueAttrs {\n  axis: number;\n}\n\nexport type UnaryInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick<NamedTensorInfoMap, 'value'>;\nexport interface UnpackAttrs {\n  axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n    Pick<NamedTensorInfoMap, 'x'|'segmentIds'>;\nexport interface UnsortedSegmentSumAttrs {\n  numSegments: number;\n}\n\nexport const UpperBound = 'UpperBound';\nexport type UpperBoundInputs =\n    Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\n\nexport const ZerosLike = 'ZerosLike';\nexport type ZerosLikeInputs = UnaryInputs;\n\n/**\n * TensorFlow.js-only kernels\n */\nexport const Step = 'Step';\nexport type StepInputs = UnaryInputs;\nexport interface StepAttrs {\n  alpha: number;\n}\n\nexport const FromPixels = 'FromPixels';\nexport interface FromPixelsInputs {\n  pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n      HTMLVideoElement|ImageBitmap;\n}\nexport interface FromPixelsAttrs {\n  numChannels: number;\n}\n\nexport const RotateWithOffset = 'RotateWithOffset';\nexport type RotateWithOffsetInputs = Pick<NamedTensorInfoMap, 'image'>;\nexport interface RotateWithOffsetAttrs {\n  radians: number;\n  fillValue: number|[number, number, number];\n  center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n  a: TensorInfo;\n  b: TensorInfo;\n  bias?: TensorInfo;\n  preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n  transposeA: boolean;\n  transposeB: boolean;\n  activation: Activation;\n  leakyreluAlpha?: number;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n  x: TensorInfo;\n  filter: TensorInfo;\n  bias?: TensorInfo;\n  preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dilations: [number, number]|number;\n  dimRoundingMode: 'floor'|'round'|'ceil';\n  activation: Activation;\n  leakyreluAlpha?: number;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n  x: TensorInfo;\n  filter: TensorInfo;\n  bias?: TensorInfo;\n  preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dilations: [number, number]|number;\n  dimRoundingMode: 'floor'|'round'|'ceil';\n  activation: Activation;\n  leakyreluAlpha?: number;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\n\nexport function warn(...msg: Array<{}>): void {\n  if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n    console.warn(...msg);\n  }\n}\n\nexport function log(...msg: Array<{}>): void {\n  if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n    console.log(...msg);\n  }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\nimport {getGlobal} from './global_util';\nimport * as log from './log';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {TensorInfo} from './tensor_info';\nimport {RecursiveArray} from './types';\n\nconst kernelRegistry =\n  getGlobal('kernelRegistry', () => new Map<`${string}_${string}`,\n    KernelConfig>());\nconst gradRegistry =\n  getGlobal('gradRegistry', () => new Map<string, GradConfig>());\n\ntype AttributeValue =\n  number | number[] | boolean | boolean[] | string | string[] | NamedAttrMap;\n\n/** These are extra non-tensor/primitive params passed to kernel functions. */\nexport type Attribute = AttributeValue | RecursiveArray<AttributeValue>;\n\n/** Specifies the code to run when executing a kernel. */\nexport type KernelFunc = (params: {\n  inputs: NamedTensorInfoMap,\n  backend: {},\n  attrs?: NamedAttrMap,\n}) => TensorInfo | TensorInfo[];\n\n/** The function to run when computing a gradient during backprop. */\nexport type GradFunc =\n  (dy: Tensor | Tensor[], saved: Tensor[], attrs: NamedAttrMap) =>\n    NamedGradientMap;\n\n/** Function that gets called after the backend initializes. */\nexport type KernelSetupFunc = (backend: {}) => void;\n/** Function that gets called right before the backend is disposed. */\nexport type KernelDisposeFunc = KernelSetupFunc;\n\n/** Config object for registering a kernel in the global registry. */\nexport interface KernelConfig {\n  kernelName: string;\n  backendName: string;\n  kernelFunc: KernelFunc;\n  setupFunc?: KernelSetupFunc;\n  disposeFunc?: KernelDisposeFunc;\n}\n\n/** Config object for registering a gradient in the global registry. */\nexport interface GradConfig {\n  kernelName: string;\n  inputsToSave?: string[];\n  // When saveAllInputs is true, all inputs will be saved. Only use this flag\n  // if inputs is an array of Tensors.\n  saveAllInputs?: boolean;\n  outputsToSave?: boolean[];\n  gradFunc: GradFunc;\n}\n\nexport interface NamedTensorInfoMap {\n  [name: string]: TensorInfo|undefined;\n}\n\nexport interface NamedAttrMap {\n  [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n    kernelName: string, backendName: string): KernelConfig {\n  const key = makeKey(kernelName, backendName);\n  return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n  return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n  const it = kernelRegistry.entries();\n  const result: KernelConfig[] = [];\n\n  while (true) {\n    const {done, value} = it.next();\n    if (done) {\n      break;\n    }\n    const [key, config] = value;\n    const [backend, ] = key.split('_');\n    if (backend === backendName) {\n      result.push(config);\n    }\n  }\n  return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n  const {kernelName, backendName} = config;\n  const key = makeKey(kernelName, backendName);\n  if (kernelRegistry.has(key)) {\n    log.warn(\n        `The kernel '${kernelName}' for backend ` +\n        `'${backendName}' is already registered`);\n  }\n  kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n  const {kernelName} = config;\n\n  if (gradRegistry.has(kernelName)) {\n    // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n    // to debug mode.\n    if (env().getBool('DEBUG')) {\n      log.warn(`Overriding the gradient for '${kernelName}'`);\n    }\n  }\n  gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n    kernelName: string, backendName: string): void {\n  const key = makeKey(kernelName, backendName);\n  if (!kernelRegistry.has(key)) {\n    throw new Error(\n        `The kernel '${kernelName}' for backend ` +\n        `'${backendName}' is not registered`);\n  }\n  kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n  if (!gradRegistry.has(kernelName)) {\n    throw new Error(\n        `The gradient '${kernelName}' for backend is not registered`);\n  }\n  gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n    registeredBackendName: string, newBackendName: string): void {\n  const kernels = getKernelsForBackend(registeredBackendName);\n  kernels.forEach(kernelConfig => {\n    const newKernelConfig =\n        Object.assign({}, kernelConfig, {backendName: newBackendName});\n    registerKernel(newKernelConfig);\n  });\n}\n\nfunction makeKey(kernelName: string,\n                 backendName: string): `${string}_${string}` {\n  return `${backendName}_${kernelName}`;\n}\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport function isTypedArrayBrowser(a: unknown): a is Uint8Array\n  | Float32Array | Int32Array | Uint8ClampedArray {\n  return a instanceof Float32Array || a instanceof Int32Array ||\n    a instanceof Uint8Array || a instanceof Uint8ClampedArray;\n}\n", "module.exports = Long;\r\n\r\n/**\r\n * wasm optimizations, to do native i64 multiplication and divide\r\n */\r\nvar wasm = null;\r\n\r\ntry {\r\n  wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([\r\n    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\r\n  ])), {}).exports;\r\n} catch (e) {\r\n  // no wasm support :(\r\n}\r\n\r\n/**\r\n * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.\r\n *  See the from* functions below for more convenient ways of constructing Longs.\r\n * @exports Long\r\n * @class A Long class for representing a 64 bit two's-complement integer value.\r\n * @param {number} low The low (signed) 32 bits of the long\r\n * @param {number} high The high (signed) 32 bits of the long\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @constructor\r\n */\r\nfunction Long(low, high, unsigned) {\r\n\r\n    /**\r\n     * The low 32 bits as a signed value.\r\n     * @type {number}\r\n     */\r\n    this.low = low | 0;\r\n\r\n    /**\r\n     * The high 32 bits as a signed value.\r\n     * @type {number}\r\n     */\r\n    this.high = high | 0;\r\n\r\n    /**\r\n     * Whether unsigned or not.\r\n     * @type {boolean}\r\n     */\r\n    this.unsigned = !!unsigned;\r\n}\r\n\r\n// The internal representation of a long is the two given signed, 32-bit values.\r\n// We use 32-bit pieces because these are the size of integers on which\r\n// Javascript performs bit-operations.  For operations like addition and\r\n// multiplication, we split each number into 16 bit pieces, which can easily be\r\n// multiplied within Javascript's floating-point representation without overflow\r\n// or change in sign.\r\n//\r\n// In the algorithms below, we frequently reduce the negative case to the\r\n// positive case by negating the input(s) and then post-processing the result.\r\n// Note that we must ALWAYS check specially whether those values are MIN_VALUE\r\n// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as\r\n// a positive number, it overflows back into a negative).  Not handling this\r\n// case would often result in infinite recursion.\r\n//\r\n// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*\r\n// methods on which they depend.\r\n\r\n/**\r\n * An indicator used to reliably determine if an object is a Long or not.\r\n * @type {boolean}\r\n * @const\r\n * @private\r\n */\r\nLong.prototype.__isLong__;\r\n\r\nObject.defineProperty(Long.prototype, \"__isLong__\", { value: true });\r\n\r\n/**\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n * @inner\r\n */\r\nfunction isLong(obj) {\r\n    return (obj && obj[\"__isLong__\"]) === true;\r\n}\r\n\r\n/**\r\n * Tests if the specified object is a Long.\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n */\r\nLong.isLong = isLong;\r\n\r\n/**\r\n * A cache of the Long representations of small integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar INT_CACHE = {};\r\n\r\n/**\r\n * A cache of the Long representations of small unsigned integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar UINT_CACHE = {};\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromInt(value, unsigned) {\r\n    var obj, cachedObj, cache;\r\n    if (unsigned) {\r\n        value >>>= 0;\r\n        if (cache = (0 <= value && value < 256)) {\r\n            cachedObj = UINT_CACHE[value];\r\n            if (cachedObj)\r\n                return cachedObj;\r\n        }\r\n        obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);\r\n        if (cache)\r\n            UINT_CACHE[value] = obj;\r\n        return obj;\r\n    } else {\r\n        value |= 0;\r\n        if (cache = (-128 <= value && value < 128)) {\r\n            cachedObj = INT_CACHE[value];\r\n            if (cachedObj)\r\n                return cachedObj;\r\n        }\r\n        obj = fromBits(value, value < 0 ? -1 : 0, false);\r\n        if (cache)\r\n            INT_CACHE[value] = obj;\r\n        return obj;\r\n    }\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given 32 bit integer value.\r\n * @function\r\n * @param {number} value The 32 bit integer in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromInt = fromInt;\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromNumber(value, unsigned) {\r\n    if (isNaN(value))\r\n        return unsigned ? UZERO : ZERO;\r\n    if (unsigned) {\r\n        if (value < 0)\r\n            return UZERO;\r\n        if (value >= TWO_PWR_64_DBL)\r\n            return MAX_UNSIGNED_VALUE;\r\n    } else {\r\n        if (value <= -TWO_PWR_63_DBL)\r\n            return MIN_VALUE;\r\n        if (value + 1 >= TWO_PWR_63_DBL)\r\n            return MAX_VALUE;\r\n    }\r\n    if (value < 0)\r\n        return fromNumber(-value, unsigned).neg();\r\n    return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.\r\n * @function\r\n * @param {number} value The number in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromNumber = fromNumber;\r\n\r\n/**\r\n * @param {number} lowBits\r\n * @param {number} highBits\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromBits(lowBits, highBits, unsigned) {\r\n    return new Long(lowBits, highBits, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is\r\n *  assumed to use 32 bits.\r\n * @function\r\n * @param {number} lowBits The low 32 bits\r\n * @param {number} highBits The high 32 bits\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromBits = fromBits;\r\n\r\n/**\r\n * @function\r\n * @param {number} base\r\n * @param {number} exponent\r\n * @returns {number}\r\n * @inner\r\n */\r\nvar pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)\r\n\r\n/**\r\n * @param {string} str\r\n * @param {(boolean|number)=} unsigned\r\n * @param {number=} radix\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromString(str, unsigned, radix) {\r\n    if (str.length === 0)\r\n        throw Error('empty string');\r\n    if (str === \"NaN\" || str === \"Infinity\" || str === \"+Infinity\" || str === \"-Infinity\")\r\n        return ZERO;\r\n    if (typeof unsigned === 'number') {\r\n        // For goog.math.long compatibility\r\n        radix = unsigned,\r\n        unsigned = false;\r\n    } else {\r\n        unsigned = !! unsigned;\r\n    }\r\n    radix = radix || 10;\r\n    if (radix < 2 || 36 < radix)\r\n        throw RangeError('radix');\r\n\r\n    var p;\r\n    if ((p = str.indexOf('-')) > 0)\r\n        throw Error('interior hyphen');\r\n    else if (p === 0) {\r\n        return fromString(str.substring(1), unsigned, radix).neg();\r\n    }\r\n\r\n    // Do several (8) digits each time through the loop, so as to\r\n    // minimize the calls to the very expensive emulated div.\r\n    var radixToPower = fromNumber(pow_dbl(radix, 8));\r\n\r\n    var result = ZERO;\r\n    for (var i = 0; i < str.length; i += 8) {\r\n        var size = Math.min(8, str.length - i),\r\n            value = parseInt(str.substring(i, i + size), radix);\r\n        if (size < 8) {\r\n            var power = fromNumber(pow_dbl(radix, size));\r\n            result = result.mul(power).add(fromNumber(value));\r\n        } else {\r\n            result = result.mul(radixToPower);\r\n            result = result.add(fromNumber(value));\r\n        }\r\n    }\r\n    result.unsigned = unsigned;\r\n    return result;\r\n}\r\n\r\n/**\r\n * Returns a Long representation of the given string, written using the specified radix.\r\n * @function\r\n * @param {string} str The textual representation of the Long\r\n * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {number=} radix The radix in which the text is written (2-36), defaults to 10\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromString = fromString;\r\n\r\n/**\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromValue(val, unsigned) {\r\n    if (typeof val === 'number')\r\n        return fromNumber(val, unsigned);\r\n    if (typeof val === 'string')\r\n        return fromString(val, unsigned);\r\n    // Throws for non-objects, converts non-instanceof Long:\r\n    return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);\r\n}\r\n\r\n/**\r\n * Converts the specified value to a Long using the appropriate from* function for its type.\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long}\r\n */\r\nLong.fromValue = fromValue;\r\n\r\n// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be\r\n// no runtime penalty for these.\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_16_DBL = 1 << 16;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24_DBL = 1 << 24;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;\r\n\r\n/**\r\n * @type {!Long}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ZERO = fromInt(0);\r\n\r\n/**\r\n * Signed zero.\r\n * @type {!Long}\r\n */\r\nLong.ZERO = ZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UZERO = fromInt(0, true);\r\n\r\n/**\r\n * Unsigned zero.\r\n * @type {!Long}\r\n */\r\nLong.UZERO = UZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ONE = fromInt(1);\r\n\r\n/**\r\n * Signed one.\r\n * @type {!Long}\r\n */\r\nLong.ONE = ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UONE = fromInt(1, true);\r\n\r\n/**\r\n * Unsigned one.\r\n * @type {!Long}\r\n */\r\nLong.UONE = UONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar NEG_ONE = fromInt(-1);\r\n\r\n/**\r\n * Signed negative one.\r\n * @type {!Long}\r\n */\r\nLong.NEG_ONE = NEG_ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);\r\n\r\n/**\r\n * Maximum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_VALUE = MAX_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);\r\n\r\n/**\r\n * Maximum unsigned value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MIN_VALUE = fromBits(0, 0x80000000|0, false);\r\n\r\n/**\r\n * Minimum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MIN_VALUE = MIN_VALUE;\r\n\r\n/**\r\n * @alias Long.prototype\r\n * @inner\r\n */\r\nvar LongPrototype = Long.prototype;\r\n\r\n/**\r\n * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.\r\n * @returns {number}\r\n */\r\nLongPrototype.toInt = function toInt() {\r\n    return this.unsigned ? this.low >>> 0 : this.low;\r\n};\r\n\r\n/**\r\n * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).\r\n * @returns {number}\r\n */\r\nLongPrototype.toNumber = function toNumber() {\r\n    if (this.unsigned)\r\n        return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);\r\n    return this.high * TWO_PWR_32_DBL + (this.low >>> 0);\r\n};\r\n\r\n/**\r\n * Converts the Long to a string written in the specified radix.\r\n * @param {number=} radix Radix (2-36), defaults to 10\r\n * @returns {string}\r\n * @override\r\n * @throws {RangeError} If `radix` is out of range\r\n */\r\nLongPrototype.toString = function toString(radix) {\r\n    radix = radix || 10;\r\n    if (radix < 2 || 36 < radix)\r\n        throw RangeError('radix');\r\n    if (this.isZero())\r\n        return '0';\r\n    if (this.isNegative()) { // Unsigned Longs are never negative\r\n        if (this.eq(MIN_VALUE)) {\r\n            // We need to change the Long value before it can be negated, so we remove\r\n            // the bottom-most digit in this base and then recurse to do the rest.\r\n            var radixLong = fromNumber(radix),\r\n                div = this.div(radixLong),\r\n                rem1 = div.mul(radixLong).sub(this);\r\n            return div.toString(radix) + rem1.toInt().toString(radix);\r\n        } else\r\n            return '-' + this.neg().toString(radix);\r\n    }\r\n\r\n    // Do several (6) digits each time through the loop, so as to\r\n    // minimize the calls to the very expensive emulated div.\r\n    var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),\r\n        rem = this;\r\n    var result = '';\r\n    while (true) {\r\n        var remDiv = rem.div(radixToPower),\r\n            intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,\r\n            digits = intval.toString(radix);\r\n        rem = remDiv;\r\n        if (rem.isZero())\r\n            return digits + result;\r\n        else {\r\n            while (digits.length < 6)\r\n                digits = '0' + digits;\r\n            result = '' + digits + result;\r\n        }\r\n    }\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as a signed integer.\r\n * @returns {number} Signed high bits\r\n */\r\nLongPrototype.getHighBits = function getHighBits() {\r\n    return this.high;\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned high bits\r\n */\r\nLongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {\r\n    return this.high >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as a signed integer.\r\n * @returns {number} Signed low bits\r\n */\r\nLongPrototype.getLowBits = function getLowBits() {\r\n    return this.low;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned low bits\r\n */\r\nLongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {\r\n    return this.low >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the number of bits needed to represent the absolute value of this Long.\r\n * @returns {number}\r\n */\r\nLongPrototype.getNumBitsAbs = function getNumBitsAbs() {\r\n    if (this.isNegative()) // Unsigned Longs are never negative\r\n        return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();\r\n    var val = this.high != 0 ? this.high : this.low;\r\n    for (var bit = 31; bit > 0; bit--)\r\n        if ((val & (1 << bit)) != 0)\r\n            break;\r\n    return this.high != 0 ? bit + 33 : bit + 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isZero = function isZero() {\r\n    return this.high === 0 && this.low === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eqz = LongPrototype.isZero;\r\n\r\n/**\r\n * Tests if this Long's value is negative.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isNegative = function isNegative() {\r\n    return !this.unsigned && this.high < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is positive.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isPositive = function isPositive() {\r\n    return this.unsigned || this.high >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is odd.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isOdd = function isOdd() {\r\n    return (this.low & 1) === 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is even.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isEven = function isEven() {\r\n    return (this.low & 1) === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.equals = function equals(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)\r\n        return false;\r\n    return this.high === other.high && this.low === other.low;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eq = LongPrototype.equals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.notEquals = function notEquals(other) {\r\n    return !this.eq(/* validates */ other);\r\n};\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.neq = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ne = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThan = function lessThan(other) {\r\n    return this.comp(/* validates */ other) < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lt = LongPrototype.lessThan;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {\r\n    return this.comp(/* validates */ other) <= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lte = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.le = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThan = function greaterThan(other) {\r\n    return this.comp(/* validates */ other) > 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gt = LongPrototype.greaterThan;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {\r\n    return this.comp(/* validates */ other) >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gte = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ge = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Compares this Long's value with the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n *  if the given one is greater\r\n */\r\nLongPrototype.compare = function compare(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    if (this.eq(other))\r\n        return 0;\r\n    var thisNeg = this.isNegative(),\r\n        otherNeg = other.isNegative();\r\n    if (thisNeg && !otherNeg)\r\n        return -1;\r\n    if (!thisNeg && otherNeg)\r\n        return 1;\r\n    // At this point the sign bits are the same\r\n    if (!this.unsigned)\r\n        return this.sub(other).isNegative() ? -1 : 1;\r\n    // Both are positive if at least one is unsigned\r\n    return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;\r\n};\r\n\r\n/**\r\n * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n *  if the given one is greater\r\n */\r\nLongPrototype.comp = LongPrototype.compare;\r\n\r\n/**\r\n * Negates this Long's value.\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.negate = function negate() {\r\n    if (!this.unsigned && this.eq(MIN_VALUE))\r\n        return MIN_VALUE;\r\n    return this.not().add(ONE);\r\n};\r\n\r\n/**\r\n * Negates this Long's value. This is an alias of {@link Long#negate}.\r\n * @function\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.neg = LongPrototype.negate;\r\n\r\n/**\r\n * Returns the sum of this and the specified Long.\r\n * @param {!Long|number|string} addend Addend\r\n * @returns {!Long} Sum\r\n */\r\nLongPrototype.add = function add(addend) {\r\n    if (!isLong(addend))\r\n        addend = fromValue(addend);\r\n\r\n    // Divide each number into 4 chunks of 16 bits, and then sum the chunks.\r\n\r\n    var a48 = this.high >>> 16;\r\n    var a32 = this.high & 0xFFFF;\r\n    var a16 = this.low >>> 16;\r\n    var a00 = this.low & 0xFFFF;\r\n\r\n    var b48 = addend.high >>> 16;\r\n    var b32 = addend.high & 0xFFFF;\r\n    var b16 = addend.low >>> 16;\r\n    var b00 = addend.low & 0xFFFF;\r\n\r\n    var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n    c00 += a00 + b00;\r\n    c16 += c00 >>> 16;\r\n    c00 &= 0xFFFF;\r\n    c16 += a16 + b16;\r\n    c32 += c16 >>> 16;\r\n    c16 &= 0xFFFF;\r\n    c32 += a32 + b32;\r\n    c48 += c32 >>> 16;\r\n    c32 &= 0xFFFF;\r\n    c48 += a48 + b48;\r\n    c48 &= 0xFFFF;\r\n    return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long.\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.subtract = function subtract(subtrahend) {\r\n    if (!isLong(subtrahend))\r\n        subtrahend = fromValue(subtrahend);\r\n    return this.add(subtrahend.neg());\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.\r\n * @function\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.sub = LongPrototype.subtract;\r\n\r\n/**\r\n * Returns the product of this and the specified Long.\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.multiply = function multiply(multiplier) {\r\n    if (this.isZero())\r\n        return ZERO;\r\n    if (!isLong(multiplier))\r\n        multiplier = fromValue(multiplier);\r\n\r\n    // use wasm support if present\r\n    if (wasm) {\r\n        var low = wasm.mul(this.low,\r\n                           this.high,\r\n                           multiplier.low,\r\n                           multiplier.high);\r\n        return fromBits(low, wasm.get_high(), this.unsigned);\r\n    }\r\n\r\n    if (multiplier.isZero())\r\n        return ZERO;\r\n    if (this.eq(MIN_VALUE))\r\n        return multiplier.isOdd() ? MIN_VALUE : ZERO;\r\n    if (multiplier.eq(MIN_VALUE))\r\n        return this.isOdd() ? MIN_VALUE : ZERO;\r\n\r\n    if (this.isNegative()) {\r\n        if (multiplier.isNegative())\r\n            return this.neg().mul(multiplier.neg());\r\n        else\r\n            return this.neg().mul(multiplier).neg();\r\n    } else if (multiplier.isNegative())\r\n        return this.mul(multiplier.neg()).neg();\r\n\r\n    // If both longs are small, use float multiplication\r\n    if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))\r\n        return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);\r\n\r\n    // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.\r\n    // We can skip products that would overflow.\r\n\r\n    var a48 = this.high >>> 16;\r\n    var a32 = this.high & 0xFFFF;\r\n    var a16 = this.low >>> 16;\r\n    var a00 = this.low & 0xFFFF;\r\n\r\n    var b48 = multiplier.high >>> 16;\r\n    var b32 = multiplier.high & 0xFFFF;\r\n    var b16 = multiplier.low >>> 16;\r\n    var b00 = multiplier.low & 0xFFFF;\r\n\r\n    var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n    c00 += a00 * b00;\r\n    c16 += c00 >>> 16;\r\n    c00 &= 0xFFFF;\r\n    c16 += a16 * b00;\r\n    c32 += c16 >>> 16;\r\n    c16 &= 0xFFFF;\r\n    c16 += a00 * b16;\r\n    c32 += c16 >>> 16;\r\n    c16 &= 0xFFFF;\r\n    c32 += a32 * b00;\r\n    c48 += c32 >>> 16;\r\n    c32 &= 0xFFFF;\r\n    c32 += a16 * b16;\r\n    c48 += c32 >>> 16;\r\n    c32 &= 0xFFFF;\r\n    c32 += a00 * b32;\r\n    c48 += c32 >>> 16;\r\n    c32 &= 0xFFFF;\r\n    c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;\r\n    c48 &= 0xFFFF;\r\n    return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.\r\n * @function\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.mul = LongPrototype.multiply;\r\n\r\n/**\r\n * Returns this Long divided by the specified. The result is signed if this Long is signed or\r\n *  unsigned if this Long is unsigned.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.divide = function divide(divisor) {\r\n    if (!isLong(divisor))\r\n        divisor = fromValue(divisor);\r\n    if (divisor.isZero())\r\n        throw Error('division by zero');\r\n\r\n    // use wasm support if present\r\n    if (wasm) {\r\n        // guard against signed division overflow: the largest\r\n        // negative number / -1 would be 1 larger than the largest\r\n        // positive number, due to two's complement.\r\n        if (!this.unsigned &&\r\n            this.high === -0x80000000 &&\r\n            divisor.low === -1 && divisor.high === -1) {\r\n            // be consistent with non-wasm code path\r\n            return this;\r\n        }\r\n        var low = (this.unsigned ? wasm.div_u : wasm.div_s)(\r\n            this.low,\r\n            this.high,\r\n            divisor.low,\r\n            divisor.high\r\n        );\r\n        return fromBits(low, wasm.get_high(), this.unsigned);\r\n    }\r\n\r\n    if (this.isZero())\r\n        return this.unsigned ? UZERO : ZERO;\r\n    var approx, rem, res;\r\n    if (!this.unsigned) {\r\n        // This section is only relevant for signed longs and is derived from the\r\n        // closure library as a whole.\r\n        if (this.eq(MIN_VALUE)) {\r\n            if (divisor.eq(ONE) || divisor.eq(NEG_ONE))\r\n                return MIN_VALUE;  // recall that -MIN_VALUE == MIN_VALUE\r\n            else if (divisor.eq(MIN_VALUE))\r\n                return ONE;\r\n            else {\r\n                // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.\r\n                var halfThis = this.shr(1);\r\n                approx = halfThis.div(divisor).shl(1);\r\n                if (approx.eq(ZERO)) {\r\n                    return divisor.isNegative() ? ONE : NEG_ONE;\r\n                } else {\r\n                    rem = this.sub(divisor.mul(approx));\r\n                    res = approx.add(rem.div(divisor));\r\n                    return res;\r\n                }\r\n            }\r\n        } else if (divisor.eq(MIN_VALUE))\r\n            return this.unsigned ? UZERO : ZERO;\r\n        if (this.isNegative()) {\r\n            if (divisor.isNegative())\r\n                return this.neg().div(divisor.neg());\r\n            return this.neg().div(divisor).neg();\r\n        } else if (divisor.isNegative())\r\n            return this.div(divisor.neg()).neg();\r\n        res = ZERO;\r\n    } else {\r\n        // The algorithm below has not been made for unsigned longs. It's therefore\r\n        // required to take special care of the MSB prior to running it.\r\n        if (!divisor.unsigned)\r\n            divisor = divisor.toUnsigned();\r\n        if (divisor.gt(this))\r\n            return UZERO;\r\n        if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true\r\n            return UONE;\r\n        res = UZERO;\r\n    }\r\n\r\n    // Repeat the following until the remainder is less than other:  find a\r\n    // floating-point that approximates remainder / other *from below*, add this\r\n    // into the result, and subtract it from the remainder.  It is critical that\r\n    // the approximate value is less than or equal to the real value so that the\r\n    // remainder never becomes negative.\r\n    rem = this;\r\n    while (rem.gte(divisor)) {\r\n        // Approximate the result of division. This may be a little greater or\r\n        // smaller than the actual value.\r\n        approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));\r\n\r\n        // We will tweak the approximate result by changing it in the 48-th digit or\r\n        // the smallest non-fractional digit, whichever is larger.\r\n        var log2 = Math.ceil(Math.log(approx) / Math.LN2),\r\n            delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),\r\n\r\n        // Decrease the approximation until it is smaller than the remainder.  Note\r\n        // that if it is too large, the product overflows and is negative.\r\n            approxRes = fromNumber(approx),\r\n            approxRem = approxRes.mul(divisor);\r\n        while (approxRem.isNegative() || approxRem.gt(rem)) {\r\n            approx -= delta;\r\n            approxRes = fromNumber(approx, this.unsigned);\r\n            approxRem = approxRes.mul(divisor);\r\n        }\r\n\r\n        // We know the answer can't be zero... and actually, zero would cause\r\n        // infinite recursion since we would make no progress.\r\n        if (approxRes.isZero())\r\n            approxRes = ONE;\r\n\r\n        res = res.add(approxRes);\r\n        rem = rem.sub(approxRem);\r\n    }\r\n    return res;\r\n};\r\n\r\n/**\r\n * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.div = LongPrototype.divide;\r\n\r\n/**\r\n * Returns this Long modulo the specified.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.modulo = function modulo(divisor) {\r\n    if (!isLong(divisor))\r\n        divisor = fromValue(divisor);\r\n\r\n    // use wasm support if present\r\n    if (wasm) {\r\n        var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(\r\n            this.low,\r\n            this.high,\r\n            divisor.low,\r\n            divisor.high\r\n        );\r\n        return fromBits(low, wasm.get_high(), this.unsigned);\r\n    }\r\n\r\n    return this.sub(this.div(divisor).mul(divisor));\r\n};\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.mod = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.rem = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns the bitwise NOT of this Long.\r\n * @returns {!Long}\r\n */\r\nLongPrototype.not = function not() {\r\n    return fromBits(~this.low, ~this.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise AND of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.and = function and(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    return fromBits(this.low & other.low, this.high & other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise OR of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.or = function or(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    return fromBits(this.low | other.low, this.high | other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise XOR of this Long and the given one.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.xor = function xor(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftLeft = function shiftLeft(numBits) {\r\n    if (isLong(numBits))\r\n        numBits = numBits.toInt();\r\n    if ((numBits &= 63) === 0)\r\n        return this;\r\n    else if (numBits < 32)\r\n        return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);\r\n    else\r\n        return fromBits(0, this.low << (numBits - 32), this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shl = LongPrototype.shiftLeft;\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRight = function shiftRight(numBits) {\r\n    if (isLong(numBits))\r\n        numBits = numBits.toInt();\r\n    if ((numBits &= 63) === 0)\r\n        return this;\r\n    else if (numBits < 32)\r\n        return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);\r\n    else\r\n        return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr = LongPrototype.shiftRight;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {\r\n    if (isLong(numBits))\r\n        numBits = numBits.toInt();\r\n    numBits &= 63;\r\n    if (numBits === 0)\r\n        return this;\r\n    else {\r\n        var high = this.high;\r\n        if (numBits < 32) {\r\n            var low = this.low;\r\n            return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);\r\n        } else if (numBits === 32)\r\n            return fromBits(high, 0, this.unsigned);\r\n        else\r\n            return fromBits(high >>> (numBits - 32), 0, this.unsigned);\r\n    }\r\n};\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shru = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr_u = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Converts this Long to signed.\r\n * @returns {!Long} Signed long\r\n */\r\nLongPrototype.toSigned = function toSigned() {\r\n    if (!this.unsigned)\r\n        return this;\r\n    return fromBits(this.low, this.high, false);\r\n};\r\n\r\n/**\r\n * Converts this Long to unsigned.\r\n * @returns {!Long} Unsigned long\r\n */\r\nLongPrototype.toUnsigned = function toUnsigned() {\r\n    if (this.unsigned)\r\n        return this;\r\n    return fromBits(this.low, this.high, true);\r\n};\r\n\r\n/**\r\n * Converts this Long to its byte representation.\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {!Array.<number>} Byte representation\r\n */\r\nLongPrototype.toBytes = function toBytes(le) {\r\n    return le ? this.toBytesLE() : this.toBytesBE();\r\n};\r\n\r\n/**\r\n * Converts this Long to its little endian byte representation.\r\n * @returns {!Array.<number>} Little endian byte representation\r\n */\r\nLongPrototype.toBytesLE = function toBytesLE() {\r\n    var hi = this.high,\r\n        lo = this.low;\r\n    return [\r\n        lo        & 0xff,\r\n        lo >>>  8 & 0xff,\r\n        lo >>> 16 & 0xff,\r\n        lo >>> 24       ,\r\n        hi        & 0xff,\r\n        hi >>>  8 & 0xff,\r\n        hi >>> 16 & 0xff,\r\n        hi >>> 24\r\n    ];\r\n};\r\n\r\n/**\r\n * Converts this Long to its big endian byte representation.\r\n * @returns {!Array.<number>} Big endian byte representation\r\n */\r\nLongPrototype.toBytesBE = function toBytesBE() {\r\n    var hi = this.high,\r\n        lo = this.low;\r\n    return [\r\n        hi >>> 24       ,\r\n        hi >>> 16 & 0xff,\r\n        hi >>>  8 & 0xff,\r\n        hi        & 0xff,\r\n        lo >>> 24       ,\r\n        lo >>> 16 & 0xff,\r\n        lo >>>  8 & 0xff,\r\n        lo        & 0xff\r\n    ];\r\n};\r\n\r\n/**\r\n * Creates a Long from its byte representation.\r\n * @param {!Array.<number>} bytes Byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytes = function fromBytes(bytes, unsigned, le) {\r\n    return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);\r\n};\r\n\r\n/**\r\n * Creates a Long from its little endian byte representation.\r\n * @param {!Array.<number>} bytes Little endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesLE = function fromBytesLE(bytes, unsigned) {\r\n    return new Long(\r\n        bytes[0]       |\r\n        bytes[1] <<  8 |\r\n        bytes[2] << 16 |\r\n        bytes[3] << 24,\r\n        bytes[4]       |\r\n        bytes[5] <<  8 |\r\n        bytes[6] << 16 |\r\n        bytes[7] << 24,\r\n        unsigned\r\n    );\r\n};\r\n\r\n/**\r\n * Creates a Long from its big endian byte representation.\r\n * @param {!Array.<number>} bytes Big endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesBE = function fromBytesBE(bytes, unsigned) {\r\n    return new Long(\r\n        bytes[4] << 24 |\r\n        bytes[5] << 16 |\r\n        bytes[6] <<  8 |\r\n        bytes[7],\r\n        bytes[0] << 24 |\r\n        bytes[1] << 16 |\r\n        bytes[2] <<  8 |\r\n        bytes[3],\r\n        unsigned\r\n    );\r\n};\r\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Workaround for allowing cjs module to be included in bundle created by\n// rollup.\nimport * as LongExports from 'long';\n// tslint:disable-next-line\nconst Long: LongExports.LongConstructor =\n    // tslint:disable-next-line\n    (LongExports as any).default || LongExports;\n\nexport function hexToLong(hex: string): Long {\n  return Long.fromString(hex, true, 16);\n}\n\n// Some primes between 2^63 and 2^64 for various uses.\n// Hex 0xc3a5c85c97cb3127\nconst k0: Long = hexToLong('c3a5c85c97cb3127');\n// Hex 0xb492b66fbe98f273\nconst k1: Long = hexToLong('b492b66fbe98f273');\n// Hex 0x9ae16a3b2f90404f\nconst k2: Long = hexToLong('9ae16a3b2f90404f');\n\nfunction shiftMix(val: Long): Long {\n  return val.xor(val.shru(47));\n}\n\nfunction fetch(s: Uint8Array, offset: number, numBytes: number): Long {\n  const bytes = s.slice(offset, offset + numBytes);\n  return Long.fromBytes(Array.from(bytes), true, true);\n}\n\nfunction fetch64(s: Uint8Array, offset: number): Long {\n  return fetch(s, offset, 8);\n}\n\nfunction fetch32(s: Uint8Array, offset: number): Long {\n  return fetch(s, offset, 4);\n}\n\nfunction rotate64(val: Long, shift: number): Long {\n  // Avoid shifting by 64: doing so yields an undefined result.\n  return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));\n}\n\nfunction hashLen16(u: Long, v: Long, mul = hexToLong('9ddfea08eb382d69')) {\n  // Murmur-inspired hashing.\n  let a = u.xor(v).mul(mul);\n  a = a.xor(a.shru(47));\n  let b = v.xor(a).mul(mul);\n  b = b.xor(b.shru(47));\n  b = b.mul(mul);\n  return b;\n}\n\n// Return a 16-byte hash for 48 bytes.  Quick and dirty.\n// Callers do best to use \"random-looking\" values for a and b.\nfunction weakHashLen32WithSeeds(\n    w: Long, x: Long, y: Long, z: Long, a: Long, b: Long) {\n  a = a.add(w);\n  b = rotate64(b.add(a).add(z), 21);\n  const c = a;\n  a = a.add(x);\n  a = a.add(y);\n  b = b.add(rotate64(a, 44));\n  return [a.add(z), b.add(c)];\n}\n\nfunction weakHashLen32WithSeedsStr(\n    s: Uint8Array, offset: number, a: Long, b: Long) {\n  return weakHashLen32WithSeeds(\n      fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16),\n      fetch64(s, offset + 24), a, b);\n}\n\nfunction hashLen0to16(s: Uint8Array, len = s.length): Long {\n  if (len >= 8) {\n    const mul = k2.add(len * 2);\n    const a = fetch64(s, 0).add(k2);\n    const b = fetch64(s, len - 8);\n    const c = rotate64(b, 37).mul(mul).add(a);\n    const d = rotate64(a, 25).add(b).mul(mul);\n    return hashLen16(c, d, mul);\n  }\n  if (len >= 4) {\n    const mul = k2.add(len * 2);\n    const a = fetch32(s, 0);\n    return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul);\n  }\n  if (len > 0) {\n    const a = s[0];\n    const b = s[len >> 1];\n    const c = s[len - 1];\n    const y = a + (b << 8);\n    const z = len + (c << 2);\n    return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);\n  }\n  return k2;\n}\n\nfunction hashLen17to32(s: Uint8Array, len = s.length): Long {\n  const mul = k2.add(len * 2);\n  const a = fetch64(s, 0).mul(k1);\n  const b = fetch64(s, 8);\n  const c = fetch64(s, len - 8).mul(mul);\n  const d = fetch64(s, len - 16).mul(k2);\n  return hashLen16(\n      rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d),\n      a.add(rotate64(b.add(k2), 18)).add(c), mul);\n}\n\nfunction hashLen33to64(s: Uint8Array, len = s.length): Long {\n  const mul = k2.add(len * 2);\n  const a = fetch64(s, 0).mul(k2);\n  const b = fetch64(s, 8);\n  const c = fetch64(s, len - 8).mul(mul);\n  const d = fetch64(s, len - 16).mul(k2);\n  const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);\n  const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul);\n  const e = fetch64(s, 16).mul(mul);\n  const f = fetch64(s, 24);\n  const g = y.add(fetch64(s, len - 32)).mul(mul);\n  const h = z.add(fetch64(s, len - 24)).mul(mul);\n  return hashLen16(\n      rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h),\n      e.add(rotate64(f.add(a), 18)).add(g), mul);\n}\n\nexport function fingerPrint64(s: Uint8Array, len = s.length): Long {\n  const seed: Long = Long.fromNumber(81, true);\n  if (len <= 32) {\n    if (len <= 16) {\n      return hashLen0to16(s, len);\n    } else {\n      return hashLen17to32(s, len);\n    }\n  } else if (len <= 64) {\n    return hashLen33to64(s, len);\n  }\n\n  // For strings over 64 bytes we loop.  Internal state consists of\n  // 56 bytes: v, w, x, y, and z.\n  let x = seed;\n  let y = seed.mul(k1).add(113);\n\n  let z = shiftMix(y.mul(k2).add(113)).mul(k2);\n  let v = [Long.UZERO, Long.UZERO];\n  let w = [Long.UZERO, Long.UZERO];\n  x = x.mul(k2).add(fetch64(s, 0));\n\n  let offset = 0;\n  // Set end so that after the loop we have 1 to 64 bytes left to process.\n  const end = ((len - 1) >> 6) * 64;\n  const last64 = end + ((len - 1) & 63) - 63;\n\n  do {\n    x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);\n    y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);\n    x = x.xor(w[1]);\n    y = y.add(v[0]).add(fetch64(s, offset + 40));\n    z = rotate64(z.add(w[0]), 33).mul(k1);\n    v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));\n    w = weakHashLen32WithSeedsStr(\n        s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n    [z, x] = [x, z];\n    offset += 64;\n  } while (offset !== end);\n  const mul = k1.add(z.and(0xff).shl(1));\n  // Point to the last 64 bytes of input.\n  offset = last64;\n\n  w[0] = w[0].add((len - 1) & 63);\n  v[0] = v[0].add(w[0]);\n  w[0] = w[0].add(v[0]);\n\n  x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul);\n  y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul);\n  x = x.xor(w[1].mul(9));\n  y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));\n  z = rotate64(z.add(w[0]), 33).mul(mul);\n  v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul), x.add(w[0]));\n  w = weakHashLen32WithSeedsStr(\n      s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n  [z, x] = [x, z];\n\n  return hashLen16(\n      hashLen16(v[0], w[0], mul).add(shiftMix(y).mul(k0)).add(z),\n      hashLen16(v[1], w[1], mul).add(x), mul);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {isTypedArrayBrowser} from './platforms/is_typed_array_browser';\nimport {BackendValues, DataType, RecursiveArray, TensorLike, TypedArray} from './types';\nimport * as base from './util_base';\nexport * from './util_base';\nexport * from './hash_util';\n\n/**\n * Create typed array for scalar value. Used for storing in `DataStorage`.\n */\nexport function createScalarValue(\n    value: DataType, dtype: DataType): BackendValues {\n  if (dtype === 'string') {\n    return encodeString(value);\n  }\n\n  return toTypedArray([value], dtype);\n}\n\nfunction noConversionNeeded(a: TensorLike, dtype: DataType): boolean {\n  return (a instanceof Float32Array && dtype === 'float32') ||\n      (a instanceof Int32Array && dtype === 'int32') ||\n      (a instanceof Uint8Array && dtype === 'bool');\n}\n\nexport function toTypedArray(a: TensorLike, dtype: DataType): TypedArray {\n  if (dtype === 'string') {\n    throw new Error('Cannot convert a string[] to a TypedArray');\n  }\n  if (Array.isArray(a)) {\n    a = flatten(a);\n  }\n\n  if (env().getBool('DEBUG')) {\n    base.checkConversionForErrors(a as number[], dtype);\n  }\n  if (noConversionNeeded(a, dtype)) {\n    return a as TypedArray;\n  }\n  if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n    return new Float32Array(a as number[]);\n  } else if (dtype === 'int32') {\n    return new Int32Array(a as number[]);\n  } else if (dtype === 'bool') {\n    const bool = new Uint8Array((a as number[]).length);\n    for (let i = 0; i < bool.length; ++i) {\n      if (Math.round((a as number[])[i]) !== 0) {\n        bool[i] = 1;\n      }\n    }\n    return bool;\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n}\n\n/**\n * Returns the current high-resolution time in milliseconds relative to an\n * arbitrary time in the past. It works across different platforms (node.js,\n * browsers).\n *\n * ```js\n * console.log(tf.util.now());\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function now(): number {\n  return env().platform.now();\n}\n\n/**\n * Returns a platform-specific implementation of\n * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * If `fetch` is defined on the global object (`window`, `process`, etc.),\n * `tf.util.fetch` returns that function.\n *\n * If not, `tf.util.fetch` returns a platform-specific solution.\n *\n * ```js\n * const resource = await tf.util.fetch('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs');\n * // handle response\n * ```\n *\n * @doc {heading: 'Util'}\n */\nexport function fetch(\n    path: string, requestInits?: RequestInit): Promise<Response> {\n  return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n  encoding = encoding || 'utf-8';\n  return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n  encoding = encoding || 'utf-8';\n  return env().platform.decode(bytes, encoding);\n}\n\nexport function isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array|\n    Uint8ClampedArray {\n  // TODO(mattsoulanille): Remove this fallback in 5.0.0\n  if (env().platform.isTypedArray != null) {\n    return env().platform.isTypedArray(a);\n  } else {\n    return isTypedArrayBrowser(a);\n  }\n}\n\n// NOTE: We explicitly type out what T extends instead of any so that\n// util.flatten on a nested array of number doesn't try to infer T as a\n// number[][], causing us to explicitly type util.flatten<number>().\n/**\n *  Flattens an arbitrarily nested array.\n *\n * ```js\n * const a = [[1, 2], [3, 4], [5, [6, [7]]]];\n * const flat = tf.util.flatten(a);\n * console.log(flat);\n * ```\n *\n *  @param arr The nested array to flatten.\n *  @param result The destination array which holds the elements.\n *  @param skipTypedArray If true, avoids flattening the typed arrays. Defaults\n *      to false.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function\nflatten<T extends number|boolean|string|Promise<number>|TypedArray>(\n    arr: T|RecursiveArray<T>, result: T[] = [], skipTypedArray = false): T[] {\n  if (result == null) {\n    result = [];\n  }\n  if (typeof arr === 'boolean' || typeof arr === 'number' ||\n    typeof arr === 'string' || base.isPromise(arr) || arr == null ||\n      isTypedArray(arr) && skipTypedArray) {\n    result.push(arr as T);\n  } else if (Array.isArray(arr) || isTypedArray(arr)) {\n    for (let i = 0; i < arr.length; ++i) {\n      flatten(arr[i], result, skipTypedArray);\n    }\n  } else {\n    let maxIndex = -1;\n    for (const key of Object.keys(arr)) {\n      // 0 or positive integer.\n      if (/^([1-9]+[0-9]*|0)$/.test(key)) {\n        maxIndex = Math.max(maxIndex, Number(key));\n      }\n    }\n    for (let i = 0; i <= maxIndex; i++) {\n      // tslint:disable-next-line: no-unnecessary-type-assertion\n      flatten((arr as RecursiveArray<T>)[i], result, skipTypedArray);\n    }\n  }\n  return result;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimer, BackendTimingInfo} from './backends/backend';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {DataType, DataTypeMap, TypedArray} from './types';\nimport * as util from './util';\n\nexport type KernelProfile = {\n  kernelName: string,\n  outputs: Tensor[],\n  inputs: NamedTensorMap,\n  timeMs: Promise<number|{error: string}>,\n  extraInfo: Promise<string>\n};\n\nexport class Profiler {\n  constructor(private backendTimer: BackendTimer, private logger?: Logger) {\n    if (logger == null) {\n      this.logger = new Logger();\n    }\n  }\n\n  profileKernel(kernelName: string, inputs: NamedTensorMap, f: () => Tensor[]):\n      KernelProfile {\n    let outputs: Tensor[];\n    const holdResultWrapperFn = () => {\n      outputs = f();\n    };\n    let timer: Promise<BackendTimingInfo>;\n    const start = util.now();\n    if (this.backendTimer.timerAvailable()) {\n      timer = this.backendTimer.time(holdResultWrapperFn);\n    } else {\n      holdResultWrapperFn();\n      for (const output of outputs) {\n        output.dataSync();\n      }\n      timer = Promise.resolve({kernelMs: util.now() - start});\n    }\n    if (env().getBool('CHECK_COMPUTATION_FOR_ERRORS')) {\n      for (let i = 0; i < outputs.length; i++) {\n        const output = outputs[i];\n        // Dangling promise here because we don't want to propagate up\n        // asynchronicity.\n        output.data().then(tensorVals => {\n          checkComputationForErrors(tensorVals, output.dtype, kernelName);\n        });\n      }\n    }\n\n    const kernelProfile = {\n      kernelName,\n      outputs,\n      inputs,\n      timeMs: timer.then(timing => timing.kernelMs),\n      extraInfo: timer.then(\n          timing => timing.getExtraProfileInfo != null ?\n              timing.getExtraProfileInfo() :\n              '')\n    };\n    return kernelProfile;\n  }\n\n  logKernelProfile(kernelProfile: KernelProfile): void {\n    const {kernelName, outputs, timeMs, inputs, extraInfo} = kernelProfile;\n\n    outputs.forEach(result => {\n      Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {\n        this.logger.logKernelProfile(\n            kernelName, result, valueContainer[0], valueContainer[1], inputs,\n            valueContainer[2]);\n      });\n    });\n  }\n}\n\nexport function checkComputationForErrors<D extends DataType>(\n    vals: DataTypeMap[D], dtype: D, kernelName: string): boolean {\n  if (dtype !== 'float32') {\n    // Only floating point computations will generate NaN values\n    return false;\n  }\n  for (let i = 0; i < vals.length; i++) {\n    const num = vals[i] as number;\n    if (isNaN(num) || !isFinite(num)) {\n      // Throwing custom exception so behavior is testable.\n      console.warn(`Found ${num} in the result of '${kernelName}'`);\n      return true;\n    }\n  }\n  return false;\n}\n\nexport class Logger {\n  logKernelProfile(\n      name: string, result: Tensor, vals: TypedArray,\n      timeMs: number|{error: string}, inputs: NamedTensorMap,\n      extraInfo?: string) {\n    const time = typeof timeMs === 'number' ? util.rightPad(`${timeMs}ms`, 9) :\n                                              timeMs['error'];\n    const paddedName = util.rightPad(name, 25);\n    const rank = result.rank;\n    const size = result.size;\n    const shape = util.rightPad(result.shape.toString(), 14);\n    let inputShapesDescription = '';\n\n    for (const name in inputs) {\n      const input = inputs[name];\n      if (input != null) {\n        // The input might be a non-tensor (e.g HTMLImageElement), in which case\n        // we claim the output shape as input shape.\n        const inputShape = input.shape || result.shape;\n        const inputRank = inputShape.length;\n        inputShapesDescription +=\n            `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;\n      }\n    }\n\n    console.log(\n        `%c${paddedName}\\t%c${time}\\t%c${rank}D ${shape}\\t%c${size}\\t%c${\n            inputShapesDescription}\\t%c${extraInfo}`,\n        'font-weight:bold', 'color:red', 'color:blue', 'color: orange',\n        'color: green', 'color: steelblue');\n  }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport * as util from './util';\n\nexport interface TapeNode {\n  id: number;\n  kernelName: string;\n  outputs: Tensor[];\n  inputs: NamedTensorMap;\n  // Optional params, defined only for ops with gradient impl.\n  gradient?: (dys: Tensor[]) => NamedGradientMap;\n  saved?: Tensor[];\n}\n\nexport type NamedGradientMap = {\n  [inputName: string]: () => Tensor;\n};\n\n/**\n * Computes a list of TapeNodes that connect x to y, filtering everything else\n * out and preserving the order of the original tape elements.\n *\n * @param tape The tape elements to filter.\n * @param xs The input Tensors.\n * @param y The output Tensor.\n */\nexport function getFilteredNodesXToY(\n    tape: TapeNode[], xs: Tensor[], y: Tensor): TapeNode[] {\n  // Forward pass to compute all the nodes and Tensors that are transitively a\n  // function of x.\n  const tensorsFromX: {[tensorId: number]: boolean} = {};\n  const nodesFromX: {[nodeId: number]: boolean} = {};\n  for (let i = 0; i < xs.length; i++) {\n    tensorsFromX[xs[i].id] = true;\n  }\n\n  for (let i = 0; i < tape.length; i++) {\n    const node = tape[i];\n    const nodeInputs = node.inputs;\n    for (const inputName in nodeInputs) {\n      const input = nodeInputs[inputName];\n\n      let anyInputFromX = false;\n      for (let j = 0; j < xs.length; j++) {\n        if (tensorsFromX[input.id]) {\n          node.outputs.forEach(output => tensorsFromX[output.id] = true);\n          anyInputFromX = true;\n          nodesFromX[node.id] = true;\n          break;\n        }\n      }\n\n      if (anyInputFromX) {\n        break;\n      }\n    }\n  }\n\n  // Backward pass to find all of the nodes and Tensors that lead to y.\n  const tensorsLeadToY: {[tensorId: number]: boolean} = {};\n  tensorsLeadToY[y.id] = true;\n  const nodesToY: {[nodeId: number]: boolean} = {};\n\n  for (let i = tape.length - 1; i >= 0; i--) {\n    const node = tape[i];\n    const nodeInputs = node.inputs;\n\n    // If any of the outputs lead to y, mark all of the inputs as leading to y.\n    for (let j = 0; j < node.outputs.length; j++) {\n      if (tensorsLeadToY[node.outputs[j].id]) {\n        for (const inputName in nodeInputs) {\n          tensorsLeadToY[nodeInputs[inputName].id] = true;\n          nodesToY[node.id] = true;\n        }\n        break;\n      }\n    }\n  }\n\n  // Return the paths that come from x and lead to y.\n  const filteredTape: TapeNode[] = [];\n  for (let i = 0; i < tape.length; i++) {\n    const node = tape[i];\n\n    if (nodesFromX[node.id] && nodesToY[node.id]) {\n      // Prune the inputs from the node that aren't a function of x.\n      const prunedInputs: {[inputName: string]: Tensor} = {};\n      for (const inputName in node.inputs) {\n        const nodeInput = node.inputs[inputName];\n        if (tensorsFromX[nodeInput.id]) {\n          prunedInputs[inputName] = nodeInput;\n        }\n      }\n\n      // Copy the node and overwrite inputsAndArgs to the pruned version.\n      const prunedNode = Object.assign({}, node);\n      prunedNode.inputs = prunedInputs;\n      prunedNode.outputs = node.outputs;\n\n      filteredTape.push(prunedNode);\n    }\n  }\n\n  return filteredTape;\n}\n\n/**\n * Backpropagate gradients through the filtered TapeNodes.\n *\n * @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map\n * is mutated by this method.\n * @param filteredTape The filtered TapeNodes to backprop through.\n */\nexport function backpropagateGradients(\n    tensorAccumulatedGradientMap: {[tensorId: number]: Tensor},\n    filteredTape: TapeNode[], tidy: (f: Function) => Tensor,\n    add: (a: Tensor, b: Tensor) => Tensor) {\n  // Walk the tape backward and keep a map of Tensor to its gradient.\n  for (let i = filteredTape.length - 1; i >= 0; i--) {\n    const node = filteredTape[i];\n\n    const dys: Tensor[] = [];\n    node.outputs.forEach(o => {\n      const gradTensor = tensorAccumulatedGradientMap[o.id];\n      if (gradTensor != null) {\n        dys.push(gradTensor);\n      } else {\n        // This particular output is not in the back-propagation subgraph, so it\n        // does not affect the final output, thus we put null for its dy.\n        dys.push(null);\n      }\n    });\n\n    if (node.gradient == null) {\n      throw new Error(\n          `Cannot compute gradient: gradient function not found ` +\n          `for ${node.kernelName}.`);\n    }\n\n    // Backprop dy through this node and accumulate gradients over the inputs.\n    const inputGradients = node.gradient(dys);\n\n    for (const inputName in node.inputs) {\n      if (!(inputName in inputGradients)) {\n        throw new Error(\n            `Cannot backprop through input ${inputName}. ` +\n            `Available gradients found: ${Object.keys(inputGradients)}.`);\n      }\n\n      // Call the gradient function.\n      const dx = tidy(() => inputGradients[inputName]());\n      if (dx.dtype !== 'float32') {\n        throw new Error(\n            `Error in gradient for op ${\n                node.kernelName}. The gradient of input ` +\n            `${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);\n      }\n      const x = node.inputs[inputName];\n      if (!util.arraysEqual(dx.shape, x.shape)) {\n        throw new Error(\n            `Error in gradient for op ${\n                node.kernelName}. The gradient of input ` +\n            `'${inputName}' has shape '${dx.shape}', which does not match ` +\n            `the shape of the input '${x.shape}'`);\n      }\n\n      if (tensorAccumulatedGradientMap[x.id] == null) {\n        tensorAccumulatedGradientMap[x.id] = dx;\n      } else {\n        const curGradient = tensorAccumulatedGradientMap[x.id];\n        tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);\n        curGradient.dispose();\n      }\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray} from './types';\nimport {computeStrides, isString, rightPad, sizeFromShape} from './util';\n\n// Maximum number of values before we decide to show ellipsis.\nconst FORMAT_LIMIT_NUM_VALS = 20;\n// Number of first and last values to show when displaying a, b,...,y, z.\nconst FORMAT_NUM_FIRST_LAST_VALS = 3;\n// Number of significant digits to show.\nconst FORMAT_NUM_SIG_DIGITS = 7;\n\nexport function tensorToString(\n    vals: TypedArray|string[], shape: number[], dtype: DataType,\n    verbose: boolean) {\n  const strides = computeStrides(shape);\n  const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);\n  const rank = shape.length;\n  const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);\n  const lines = ['Tensor'];\n  if (verbose) {\n    lines.push(`  dtype: ${dtype}`);\n    lines.push(`  rank: ${rank}`);\n    lines.push(`  shape: [${shape}]`);\n    lines.push(`  values:`);\n  }\n  lines.push(valsLines.map(l => '    ' + l).join('\\n'));\n  return lines.join('\\n');\n}\n\nfunction computeMaxSizePerColumn(\n    vals: TypedArray|string[], shape: number[], dtype: DataType,\n    strides: number[]): number[] {\n  const n = sizeFromShape(shape);\n  const numCols = strides[strides.length - 1];\n  const padPerCol = new Array(numCols).fill(0);\n  const rank = shape.length;\n  const valuesOrTuples =\n      dtype === 'complex64' ? createComplexTuples(vals) : vals;\n\n  if (rank > 1) {\n    for (let row = 0; row < n / numCols; row++) {\n      const offset = row * numCols;\n      for (let j = 0; j < numCols; j++) {\n        padPerCol[j] = Math.max(\n            padPerCol[j],\n            valToString(valuesOrTuples[offset + j], 0, dtype).length);\n      }\n    }\n  }\n  return padPerCol;\n}\n\nfunction valToString(\n    val: number|string|[number, number], pad: number, dtype: DataType) {\n  let valStr: string;\n  if (Array.isArray(val)) {\n    valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +\n        `${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;\n  } else if (isString(val)) {\n    valStr = `'${val}'`;\n  } else if (dtype === 'bool') {\n    valStr = boolNumToString(val);\n  } else {\n    valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();\n  }\n\n  return rightPad(valStr, pad);\n}\n\nfunction boolNumToString(v: number): string {\n  return v === 0 ? 'false' : 'true';\n}\n\nfunction subTensorToString(\n    vals: TypedArray|string[], shape: number[], dtype: DataType,\n    strides: number[], padPerCol: number[], isLast = true): string[] {\n  const storagePerElement = dtype === 'complex64' ? 2 : 1;\n\n  const size = shape[0];\n  const rank = shape.length;\n  if (rank === 0) {\n    if (dtype === 'complex64') {\n      const complexTuple = createComplexTuples(vals);\n      return [valToString(complexTuple[0], 0, dtype)];\n    }\n    if (dtype === 'bool') {\n      return [boolNumToString(vals[0] as number)];\n    }\n    return [vals[0].toString()];\n  }\n\n  if (rank === 1) {\n    if (size > FORMAT_LIMIT_NUM_VALS) {\n      const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;\n\n      let firstVals = Array.from<number|string|[number, number]>(\n          vals.slice(0, firstValsSize));\n      let lastVals = Array.from<number|string|[number, number]>(vals.slice(\n          (size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement,\n          size * storagePerElement));\n      if (dtype === 'complex64') {\n        firstVals = createComplexTuples(firstVals);\n        lastVals = createComplexTuples(lastVals);\n      }\n      return [\n        '[' +\n        firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n            .join(', ') +\n        ', ..., ' +\n        lastVals\n            .map(\n                (x, i) => valToString(\n                    x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))\n            .join(', ') +\n        ']'\n      ];\n    }\n    const displayVals: Array<number|string|[number, number]> =\n        dtype === 'complex64' ? createComplexTuples(vals) :\n                                Array.from<number|string>(vals);\n\n    return [\n      '[' +\n      displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n          .join(', ') +\n      ']'\n    ];\n  }\n\n  // The array is rank 2 or more.\n  const subshape = shape.slice(1);\n  const substrides = strides.slice(1);\n  const stride = strides[0] * storagePerElement;\n  const lines: string[] = [];\n  if (size > FORMAT_LIMIT_NUM_VALS) {\n    for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {\n      const start = i * stride;\n      const end = start + stride;\n      lines.push(...subTensorToString(\n          vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n          false /* isLast */));\n    }\n    lines.push('...');\n    for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {\n      const start = i * stride;\n      const end = start + stride;\n      lines.push(...subTensorToString(\n          vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n          i === size - 1 /* isLast */));\n    }\n  } else {\n    for (let i = 0; i < size; i++) {\n      const start = i * stride;\n      const end = start + stride;\n      lines.push(...subTensorToString(\n          vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n          i === size - 1 /* isLast */));\n    }\n  }\n  const sep = rank === 2 ? ',' : '';\n  lines[0] = '[' + (size > 0 ? lines[0] + sep : '');\n  for (let i = 1; i < lines.length - 1; i++) {\n    lines[i] = ' ' + lines[i] + sep;\n  }\n  let newLineSep = ',\\n';\n  for (let i = 2; i < rank; i++) {\n    newLineSep += '\\n';\n  }\n  lines[lines.length - 1] =\n      ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);\n  return lines;\n}\n\nfunction createComplexTuples(vals: Array<{}>|\n                             TypedArray): Array<[number, number]> {\n  const complexTuples: Array<[number, number]> = [];\n  for (let i = 0; i < vals.length; i += 2) {\n    complexTuples.push([vals[i], vals[i + 1]] as [number, number]);\n  }\n  return complexTuples;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265\n/// <reference types=\"@webgpu/types/dist\" />\n\nimport {getGlobal} from './global_util';\nimport {tensorToString} from './tensor_format';\nimport {DataId, TensorInfo} from './tensor_info';\nimport {ArrayMap, BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, Rank, ShapeMap, SingleValueMap, TypedArray} from './types';\nimport * as util from './util';\nimport {computeStrides, toNestedArray} from './util';\n\nexport interface TensorData<D extends DataType> {\n  dataId?: DataId;\n  values?: DataTypeMap[D];\n}\n\n// This interface mimics KernelBackend (in backend.ts), which would create a\n// circular dependency if imported.\nexport interface Backend {}\n\n/**\n * A mutable object, similar to `tf.Tensor`, that allows users to set values\n * at locations before converting to an immutable `tf.Tensor`.\n *\n * See `tf.buffer` for creating a tensor buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class TensorBuffer<R extends Rank, D extends DataType = 'float32'> {\n  size: number;\n  shape: ShapeMap[R];\n  strides: number[];\n  values: DataTypeMap[D];\n\n  constructor(shape: ShapeMap[R], public dtype: D, values?: DataTypeMap[D]) {\n    this.shape = shape.slice() as ShapeMap[R];\n    this.size = util.sizeFromShape(shape);\n\n    if (values != null) {\n      const n = values.length;\n      util.assert(\n          n === this.size,\n          () => `Length of values '${n}' does not match the size ` +\n              `inferred by the shape '${this.size}'.`);\n    }\n    if (dtype === 'complex64') {\n      throw new Error(\n          `complex64 dtype TensorBuffers are not supported. Please create ` +\n          `a TensorBuffer for the real and imaginary parts separately and ` +\n          `call tf.complex(real, imag).`);\n    }\n    this.values = values || util.getArrayFromDType(dtype, this.size);\n    this.strides = computeStrides(shape);\n  }\n\n  /**\n   * Sets a value in the buffer at a given location.\n   *\n   * @param value The value to set.\n   * @param locs  The location indices.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Creation'}\n   */\n  set(value: SingleValueMap[D], ...locs: number[]): void {\n    if (locs.length === 0) {\n      locs = [0];\n    }\n    util.assert(\n        locs.length === this.rank,\n        () => `The number of provided coordinates (${locs.length}) must ` +\n            `match the rank (${this.rank})`);\n\n    const index = this.locToIndex(locs);\n    this.values[index] = value as number;\n  }\n\n  /**\n   * Returns the value in the buffer at the provided location.\n   *\n   * @param locs The location indices.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Creation'}\n   */\n  get(...locs: number[]): SingleValueMap[D] {\n    if (locs.length === 0) {\n      locs = [0];\n    }\n    let i = 0;\n    for (const loc of locs) {\n      if (loc < 0 || loc >= this.shape[i]) {\n        const msg = `Requested out of range element at ${locs}. ` +\n            `  Buffer shape=${this.shape}`;\n        throw new Error(msg);\n      }\n      i++;\n    }\n    let index = locs[locs.length - 1];\n    for (let i = 0; i < locs.length - 1; ++i) {\n      index += this.strides[i] * locs[i];\n    }\n    return this.values[index] as SingleValueMap[D];\n  }\n\n  locToIndex(locs: number[]): number {\n    if (this.rank === 0) {\n      return 0;\n    } else if (this.rank === 1) {\n      return locs[0];\n    }\n    let index = locs[locs.length - 1];\n    for (let i = 0; i < locs.length - 1; ++i) {\n      index += this.strides[i] * locs[i];\n    }\n    return index;\n  }\n\n  indexToLoc(index: number): number[] {\n    if (this.rank === 0) {\n      return [];\n    } else if (this.rank === 1) {\n      return [index];\n    }\n    const locs: number[] = new Array(this.shape.length);\n    for (let i = 0; i < locs.length - 1; ++i) {\n      locs[i] = Math.floor(index / this.strides[i]);\n      index -= locs[i] * this.strides[i];\n    }\n    locs[locs.length - 1] = index;\n    return locs;\n  }\n\n  get rank() {\n    return this.shape.length;\n  }\n\n  /**\n   * Creates an immutable `tf.Tensor` object from the buffer.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Creation'}\n   */\n  toTensor(): Tensor<R> {\n    return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n        Tensor<R>;\n  }\n}\n\nexport interface DataToGPUWebGLOption {\n  customTexShape?: [number, number];\n}\n\nexport type DataToGPUOptions = DataToGPUWebGLOption;\n\nexport interface GPUData {\n  tensorRef: Tensor;\n  texture?: WebGLTexture;\n  buffer?: GPUBuffer;\n  texShape?: [number, number];\n}\n\nexport interface TensorTracker {\n  makeTensor(\n      values: DataValues, shape: number[], dtype: DataType,\n      backend?: Backend): Tensor;\n  makeVariable(\n      initialValue: Tensor, trainable?: boolean, name?: string,\n      dtype?: DataType): Variable;\n  incRef(a: Tensor, backend: Backend): void;\n  disposeTensor(t: Tensor): void;\n  disposeVariable(v: Variable): void;\n  read(dataId: DataId): Promise<BackendValues>;\n  readSync(dataId: DataId): BackendValues;\n  readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n  cast<T extends Tensor>(x: T, dtype: DataType): T;\n  buffer<R extends Rank, D extends DataType>(\n      shape: ShapeMap[R], dtype: D,\n      values?: DataTypeMap[D]): TensorBuffer<R, D>;\n  print<T extends Tensor>(x: T, verbose: boolean): void;\n  clone<T extends Tensor>(x: T): T;\n  // TODO(yassogba) bring reshape back?\n}\n\n// For tracking tensor creation and disposal.\nlet trackerFn: () => TensorTracker = null;\n// Used by chaining methods to call into ops.\nlet opHandler: OpHandler = null;\n// Used to warn about deprecated methods.\nlet deprecationWarningFn: (msg: string) => void = null;\n// This here so that we can use this method on dev branches and keep the\n// functionality at master.\n// tslint:disable-next-line:no-unused-expression\n[deprecationWarningFn];\n\n/**\n * An external consumer can register itself as the tensor tracker. This way\n * the Tensor class can notify the tracker for every tensor created and\n * disposed.\n */\nexport function setTensorTracker(fn: () => TensorTracker) {\n  trackerFn = fn;\n}\n\n/**\n * An external consumer can register itself as the op handler. This way the\n * Tensor class can have chaining methods that call into ops via the op\n * handler.\n */\nexport function setOpHandler(handler: OpHandler) {\n  opHandler = handler;\n}\n\n/**\n * Sets the deprecation warning function to be used by this file. This way the\n * Tensor class can be a leaf but still use the environment.\n */\nexport function setDeprecationWarningFn(fn: (msg: string) => void) {\n  deprecationWarningFn = fn;\n}\n\n// Declare this namespace to make Tensor class augmentation work in google3.\nexport declare namespace Tensor {}\n/**\n * A `tf.Tensor` object represents an immutable, multidimensional array of\n * numbers that has a shape and a data type.\n *\n * For performance reasons, functions that create tensors do not necessarily\n * perform a copy of the data passed to them (e.g. if the data is passed as a\n * `Float32Array`), and changes to the data will change the tensor. This is not\n * a feature and is not supported. To avoid this behavior, use the tensor before\n * changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.\n *\n * See `tf.tensor` for details on how to create a `tf.Tensor`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Tensor<R extends Rank = Rank> implements TensorInfo {\n  /** Unique id of this tensor. */\n  readonly id: number;\n  /**\n   * Id of the bucket holding the data for this tensor. Multiple arrays can\n   * point to the same bucket (e.g. when calling array.reshape()).\n   */\n  dataId: DataId;\n  /** The shape of the tensor. */\n  readonly shape: ShapeMap[R];\n  /** Number of elements in the tensor. */\n  readonly size: number;\n  /** The data type for the array. */\n  readonly dtype: DataType;\n  /** The rank type for the array (see `Rank` enum). */\n  readonly rankType: R;\n\n  /** Whether this tensor has been globally kept. */\n  kept = false;\n  /** The id of the scope this tensor is being tracked in. */\n  scopeId: number;\n  /** The keras mask that some keras layers attach to the tensor */\n  kerasMask?: Tensor;\n\n  /**\n   * Number of elements to skip in each dimension when indexing. See\n   * https://docs.scipy.org/doc/numpy/reference/generated/\\\n   * numpy.ndarray.strides.html\n   */\n  readonly strides: number[];\n\n  constructor(shape: ShapeMap[R], dtype: DataType, dataId: DataId, id: number) {\n    this.shape = shape.slice() as ShapeMap[R];\n    this.dtype = dtype || 'float32';\n    this.size = util.sizeFromShape(shape);\n    this.strides = computeStrides(shape);\n    this.dataId = dataId;\n    this.id = id;\n    this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher') as R;\n  }\n\n  get rank(): number {\n    return this.shape.length;\n  }\n\n  /**\n   * Returns a promise of `tf.TensorBuffer` that holds the underlying data.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  async buffer<D extends DataType = 'float32'>(): Promise<TensorBuffer<R, D>> {\n    const vals = await this.data<D>();\n    return opHandler.buffer(this.shape, this.dtype as D, vals);\n  }\n\n  /**\n   * Returns a `tf.TensorBuffer` that holds the underlying data.\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  bufferSync<D extends DataType = 'float32'>(): TensorBuffer<R, D> {\n    return opHandler.buffer(this.shape, this.dtype as D, this.dataSync());\n  }\n\n  /**\n   * Returns the tensor data as a nested array. The transfer of data is done\n   * asynchronously.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  async array(): Promise<ArrayMap[R]> {\n    const vals = await this.data();\n    return toNestedArray(this.shape, vals, this.dtype === 'complex64') as\n        ArrayMap[R];\n  }\n\n  /**\n   * Returns the tensor data as a nested array. The transfer of data is done\n   * synchronously.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  arraySync(): ArrayMap[R] {\n    return toNestedArray(\n               this.shape, this.dataSync(), this.dtype === 'complex64') as\n        ArrayMap[R];\n  }\n\n  /**\n   * Asynchronously downloads the values from the `tf.Tensor`. Returns a\n   * promise of `TypedArray` that resolves when the computation has finished.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  async data<D extends DataType = NumericDataType>(): Promise<DataTypeMap[D]> {\n    this.throwIfDisposed();\n    const data = trackerFn().read(this.dataId);\n    if (this.dtype === 'string') {\n      const bytes = await data as Uint8Array[];\n      try {\n        return bytes.map(b => util.decodeString(b)) as DataTypeMap[D];\n      } catch {\n        throw new Error(\n            'Failed to decode the string bytes into utf-8. ' +\n            'To get the original bytes, call tensor.bytes().');\n      }\n    }\n    return data as Promise<DataTypeMap[D]>;\n  }\n\n  /**\n   * Copy the tensor's data to a new GPU resource. Comparing to the `dataSync()`\n   * and `data()`, this method prevents data from being downloaded to CPU.\n   *\n   * For WebGL backend, the data will be stored on a densely packed texture.\n   * This means that the texture will use the RGBA channels to store value.\n   *\n   * For WebGPU backend, the data will be stored on a buffer. There is no\n   * parameter, so can not use a user-defined size to create the buffer.\n   *\n   * @param options:\n   *     For WebGL,\n   *         - customTexShape: Optional. If set, will use the user defined\n   *     texture shape to create the texture.\n   *\n   * @returns For WebGL backend, a GPUData contains the new texture and\n   *     its information.\n   *     {\n   *        tensorRef: The tensor that is associated with this texture,\n   *        texture: WebGLTexture,\n   *        texShape: [number, number] // [height, width]\n   *     }\n   *\n   *     For WebGPU backend, a GPUData contains the new buffer.\n   *     {\n   *        tensorRef: The tensor that is associated with this buffer,\n   *        buffer: GPUBuffer,\n   *     }\n   *\n   *     Remember to dispose the GPUData after it is used by\n   *     `res.tensorRef.dispose()`.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  dataToGPU(options?: DataToGPUOptions): GPUData {\n    this.throwIfDisposed();\n    return trackerFn().readToGPU(this.dataId, options);\n  }\n\n  /**\n   * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n   * UI thread until the values are ready, which can cause performance issues.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  dataSync<D extends DataType = NumericDataType>(): DataTypeMap[D] {\n    this.throwIfDisposed();\n    const data = trackerFn().readSync(this.dataId);\n    if (this.dtype === 'string') {\n      try {\n        return (data as Uint8Array[]).map(b => util.decodeString(b)) as\n            DataTypeMap[D];\n      } catch {\n        throw new Error(\n            'Failed to decode the string bytes into utf-8. ' +\n            'To get the original bytes, call tensor.bytes().');\n      }\n    }\n    return data as DataTypeMap[D];\n  }\n\n  /** Returns the underlying bytes of the tensor's data. */\n  async bytes(): Promise<Uint8Array[]|Uint8Array> {\n    this.throwIfDisposed();\n    const data = await trackerFn().read(this.dataId);\n    if (this.dtype === 'string') {\n      return data as Uint8Array[];\n    } else {\n      return new Uint8Array((data as TypedArray).buffer);\n    }\n  }\n\n  /**\n   * Disposes `tf.Tensor` from memory.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  dispose(): void {\n    if (this.isDisposed) {\n      return;\n    }\n    if (this.kerasMask) {\n      this.kerasMask.dispose();\n    }\n    trackerFn().disposeTensor(this);\n    this.isDisposedInternal = true;\n  }\n\n  protected isDisposedInternal = false;\n  get isDisposed(): boolean {\n    return this.isDisposedInternal;\n  }\n\n  throwIfDisposed() {\n    if (this.isDisposed) {\n      throw new Error(`Tensor is disposed.`);\n    }\n  }\n\n  /**\n   * Prints the `tf.Tensor`. See `tf.print` for details.\n   *\n   * @param verbose Whether to print verbose information about the tensor,\n   *    including dtype and size.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  print(verbose = false): void {\n    return opHandler.print(this, verbose);\n  }\n\n  /**\n   * Returns a copy of the tensor. See `tf.clone` for details.\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  clone<T extends Tensor>(this: T): T {\n    this.throwIfDisposed();\n    return opHandler.clone(this);\n  }\n\n  /**\n   * Returns a human-readable description of the tensor. Useful for logging.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  toString(verbose = false): string {\n    const vals = this.dataSync();\n    return tensorToString(vals, this.shape, this.dtype, verbose);\n  }\n\n  cast<T extends this>(dtype: DataType): T {\n    this.throwIfDisposed();\n    return opHandler.cast(this as T, dtype);\n  }\n  variable(trainable = true, name?: string, dtype?: DataType): Variable<R> {\n    this.throwIfDisposed();\n    return trackerFn().makeVariable(this, trainable, name, dtype) as\n        Variable<R>;\n  }\n}\n\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n  value: (instance: Tensor) => {\n    // Implementation note: we should use properties of the object that will be\n    // defined before the constructor body has finished executing (methods).\n    // This is because when this code is transpiled by babel, babel will call\n    // classCallCheck before the constructor body is run.\n    // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n    return !!instance && instance.data != null && instance.dataSync != null &&\n        instance.throwIfDisposed != null;\n  }\n});\n\nexport function getGlobalTensorClass() {\n  // Use getGlobal so that we can augment the Tensor class across package\n  // boundaries because the node resolution alg may result in different modules\n  // being returned for this file depending on the path they are loaded from.\n  return getGlobal('Tensor', () => {\n    return Tensor;\n  });\n}\n\n// Global side effect. Cache global reference to Tensor class\ngetGlobalTensorClass();\n\nexport interface NumericTensor<R extends Rank = Rank> extends Tensor<R> {\n  dtype: NumericDataType;\n  dataSync<D extends DataType = NumericDataType>(): DataTypeMap[D];\n  data<D extends DataType = NumericDataType>(): Promise<DataTypeMap[D]>;\n  dataToGPU(options?: DataToGPUOptions): GPUData;\n}\n\nexport interface StringTensor<R extends Rank = Rank> extends Tensor<R> {\n  dtype: 'string';\n  dataSync<D extends DataType = 'string'>(): DataTypeMap[D];\n  data<D extends DataType = 'string'>(): Promise<DataTypeMap[D]>;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor<Rank.R0>;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor<Rank.R1>;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor<Rank.R2>;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor<Rank.R3>;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor<Rank.R4>;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor<Rank.R5>;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor<Rank.R6>;\n\n/**\n * A mutable `tf.Tensor`, useful for persisting state, e.g. for training.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Variable<R extends Rank = Rank> extends Tensor<R> {\n  name: string;\n\n  constructor(\n      initialValue: Tensor<R>, public trainable: boolean, name: string,\n      tensorId: number) {\n    super(\n        initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);\n    this.name = name;\n  }\n\n  /**\n   * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have\n   * the same shape and dtype as the old `tf.Tensor`.\n   *\n   * @param newValue New tensor to be assigned to this variable.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  assign(newValue: Tensor<R>): void {\n    if (newValue.dtype !== this.dtype) {\n      throw new Error(\n          `dtype of the new value (${newValue.dtype}) and ` +\n          `previous value (${this.dtype}) must match`);\n    }\n    if (!util.arraysEqual(newValue.shape, this.shape)) {\n      throw new Error(\n          `shape of the new value (${newValue.shape}) and ` +\n          `previous value (${this.shape}) must match`);\n    }\n    trackerFn().disposeTensor(this);\n    this.dataId = newValue.dataId;\n    trackerFn().incRef(this, null /* backend */);\n  }\n\n  override dispose(): void {\n    trackerFn().disposeVariable(this);\n    this.isDisposedInternal = true;\n  }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n  value: (instance: Variable) => {\n    return instance instanceof Tensor && instance.assign != null &&\n        instance.assign instanceof Function;\n  }\n});\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** @docalias number[] */\nexport interface ShapeMap {\n  R0: number[];\n  R1: [number];\n  R2: [number, number];\n  R3: [number, number, number];\n  R4: [number, number, number, number];\n  R5: [number, number, number, number, number];\n  R6: [number, number, number, number, number, number];\n}\n\n/** @docalias number[] */\nexport interface ArrayMap {\n  R0: number;\n  R1: number[];\n  R2: number[][];\n  R3: number[][][];\n  R4: number[][][][];\n  R5: number[][][][][];\n  R6: number[][][][][][];\n}\n\nexport interface DataTypeMap {\n  float32: Float32Array;\n  int32: Int32Array;\n  bool: Uint8Array;\n  complex64: Float32Array;\n  string: string[];\n}\n\nexport interface SingleValueMap {\n  bool: boolean;\n  int32: number;\n  float32: number;\n  complex64: number;\n  string: string;\n}\n\n/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */\nexport type DataType = keyof DataTypeMap;\nexport type NumericDataType = 'float32'|'int32'|'bool'|'complex64';\n\nexport type DataTypeFor<T extends number|string|boolean> =\n    T extends number|boolean ? NumericDataType : T extends string ? 'string' :\n                                                                    never;\n\nexport type TypedArray = Float32Array|Int32Array|Uint8Array;\n/** Tensor data used in tensor creation and user-facing API. */\nexport type DataValues = DataTypeMap[DataType];\n/** The underlying tensor data that gets stored in a backend. */\nexport type BackendValues = Float32Array|Int32Array|Uint8Array|Uint8Array[];\n\nexport enum Rank {\n  R0 = 'R0',\n  R1 = 'R1',\n  R2 = 'R2',\n  R3 = 'R3',\n  R4 = 'R4',\n  R5 = 'R5',\n  R6 = 'R6'\n}\n\nexport type FlatVector = boolean[]|number[]|TypedArray;\nexport type RegularArray<T> =\n    T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray<T extends any> {\n  [index: number]: T|RecursiveArray<T>;\n}\n\n// Looks for upcasting types. Used, for example, in operations with mixed dtype\n// inputs.\nenum UpcastInt32AndMap {\n  'float32' = 'float32',\n  'int32' = 'int32',\n  'bool' = 'int32',\n  'complex64' = 'complex64'\n}\n\nenum UpcastBoolAndMap {\n  'float32' = 'float32',\n  'int32' = 'int32',\n  'bool' = 'bool',\n  'complex64' = 'complex64'\n}\n\nenum UpcastFloat32AndMap {\n  'float32' = 'float32',\n  'int32' = 'float32',\n  'bool' = 'float32',\n  'complex64' = 'complex64'\n}\n\nenum UpcastComplex64AndMap {\n  'float32' = 'complex64',\n  'int32' = 'complex64',\n  'bool' = 'complex64',\n  'complex64' = 'complex64'\n}\n\nconst upcastTypeMap = {\n  'float32': UpcastFloat32AndMap,\n  'int32': UpcastInt32AndMap,\n  'bool': UpcastBoolAndMap,\n  'complex64': UpcastComplex64AndMap\n};\n\nexport function upcastType(typeA: DataType, typeB: DataType): DataType {\n  if (typeA === 'string' || typeB === 'string') {\n    if (typeA === 'string' && typeB === 'string') {\n      return 'string';\n    }\n    throw new Error(`Can not upcast ${typeA} with ${typeB}`);\n  }\n  return upcastTypeMap[typeA][typeB];\n}\n\n/** Returns the output type after summation. */\nexport function sumOutType(type: DataType): DataType {\n  return upcastType(type, 'int32');\n}\n\n/** @docalias TypedArray|Array */\nexport type TensorLike =\n    TypedArray|number|boolean|string|RecursiveArray<number|number[]|TypedArray>|\n    RecursiveArray<boolean>|RecursiveArray<string>|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n    string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n    boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n    boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n    TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n    string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n    TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n    string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image data in Uint8Array type. */\nexport interface PixelData {\n  width: number;\n  height: number;\n  data: Uint8Array;\n}\n\n/**\n * Type for representing all permutations and combinations of 'RGBA' channels.\n */\nexport type WebGLChannels = 'A'|'B'|'G'|'R'|'AB'|'AG'|'AR'|'BA'|'BG'|'BR'|'GA'|\n    'GB'|'GR'|'RA'|'RB'|'RG'|'ABG'|'ABR'|'AGB'|'AGR'|'ARB'|'ARG'|'BAG'|'BAR'|\n    'BGA'|'BGR'|'BRA'|'BRG'|'GAB'|'GAR'|'GBA'|'GBR'|'GRA'|'GRB'|'RAB'|'RAG'|\n    'RBA'|'RBG'|'RGA'|'RGB'|'ABGR'|'ABRG'|'AGBR'|'AGRB'|'ARBG'|'ARGB'|'BAGR'|\n    'BARG'|'BGAR'|'BGRA'|'BRAG'|'BRGA'|'GABR'|'GARB'|'GBAR'|'GBRA'|'GRAB'|\n    'GRBA'|'RABG'|'RAGB'|'RBAG'|'RBGA'|'RGAB'|'RGBA';\n\n/** Type for representing a texture data to create a tensor. */\nexport interface WebGLData {\n  texture: WebGLTexture;\n  height: number;\n  width: number;\n  channels: WebGLChannels;\n}\n\n/**\n * Type for representing a buffer data to create a tensor. Buffer usage should\n * at least support GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC. When\n * zeroCopy is false or undefined (default), this GPUBuffer will be copied to\n * the tensor's resource buffer. When zeroCopy is true, tensor will use this\n * GPUBuffer as tensor's resource buffer, user should not destroy this GPUBuffer\n * until all access is done. If not specified at creating a tensor, tensor type\n * is float32.\n */\nexport interface WebGPUData {\n  buffer: GPUBuffer;\n  zeroCopy?: boolean;\n}\n\nexport function isWebGLData(values: unknown): values is WebGLData {\n  return values != null && typeof values === 'object' && 'texture' in values &&\n      values.texture instanceof WebGLTexture;\n}\nexport function isWebGPUData(values: unknown): values is WebGPUData {\n  return typeof GPUBuffer !== 'undefined' && values != null &&\n      typeof values === 'object' && 'buffer' in values &&\n      values.buffer instanceof GPUBuffer;\n}\n\nexport interface ImageOptions {\n  /**\n   * Optional. A number in range [0-1]. If the image is a 2D tensor or a 3D\n   * tensor with 1 or 3 channels, the alpha channels would set as its value;\n   * otherwise, it would not make effects.\n   */\n  alpha?: number;\n}\n\nexport interface ContextOptions {\n  /**\n   * Optional.  If the canvas has created a context, it would not make effects.\n   * If it is not set, it would be variable based on the current backend.\n   */\n  contextType?: string;\n  /**\n   * Optional. A WebGLContextAttributes configuration. If the canvas has created\n   * a context, it would not make effects.\n   */\n  contextAttributes?: WebGLContextAttributes;\n}\n\nexport interface DrawOptions {\n  /**\n   * Optional. An object of options to customize the values of image tensor.\n   */\n  imageOptions?: ImageOptions;\n  /**\n   * Optional. An object to configure the context of the canvas to draw to.\n   */\n  contextOptions?: ContextOptions;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch<T extends Tensor>(a: T, b: T): [T, T] {\n  if (a.dtype === b.dtype) {\n    return [a, b];\n  }\n  const dtype = upcastType(a.dtype, b.dtype);\n  return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n  assert(\n      a.dtype === b.dtype,\n      () => `The dtypes of the first(${a.dtype}) and` +\n          ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n  return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n *   `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n *   is safe to pass any object here, except that `Promise`s are not\n *   supported.\n * @returns An array of `Tensors` found within the passed object. If the\n *   argument is simply a `Tensor', a list containing that `Tensor` is\n *   returned. If the object is not a `Tensor` or does not\n *   contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n  const list: Tensor[] = [];\n  const seen = new Set<{}|void>();\n  walkTensorContainer(result, list, seen);\n  return list;\n}\n\nfunction walkTensorContainer(\n    container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n  if (container == null) {\n    return;\n  }\n  if (container instanceof Tensor) {\n    list.push(container);\n    return;\n  }\n  if (!isIterable(container)) {\n    return;\n  }\n  // Iteration over keys works also for arrays.\n  const iterable = container as TensorContainerArray;\n  for (const k in iterable) {\n    const val = iterable[k];\n    if (!seen.has(val)) {\n      seen.add(val);\n      walkTensorContainer(val, list, seen);\n    }\n  }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n  return Array.isArray(obj) || typeof obj === 'object';\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast, Identity} from './kernel_names';\nimport { getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap } from './kernel_registry';\nimport { TensorInfo } from './tensor_info';\nimport * as log from './log';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataToGPUOptions, GPUData, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\nimport {DataId} from './tensor_info';\nimport {GradSaveFunc, NamedTensorMap, NamedVariableMap, TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\nimport {BackendValues, DataType, DataValues} from './types';\nimport * as util from './util';\nimport {bytesFromStringArray, makeOnesTypedArray, now, sizeFromShape} from './util';\n\n/**\n * A function that computes an output. The save function is for saving tensors\n * computed in the forward pass, that we need in the backward pass.\n */\nexport type ForwardFunc<T> = (backend: KernelBackend, save?: GradSaveFunc) => T;\n\n/**\n * @docalias (a: Tensor, b: Tensor,..., save?: Function) => {\n *   value: Tensor,\n *   gradFunc: (dy: Tensor, saved?: NamedTensorMap) => Tensor | Tensor[]\n * }\n */\nexport type CustomGradientFunc<T extends Tensor> =\n    (...inputs: Array<Tensor|GradSaveFunc>) => {\n      value: T;\n      gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[];\n    };\n\nexport type MemoryInfo = {\n  numTensors: number; numDataBuffers: number; numBytes: number;\n  unreliable?: boolean; reasons: string[];\n};\n\ntype KernelInfo = {\n  name: string; bytesAdded: number; totalBytesSnapshot: number;\n  tensorsAdded: number;\n  totalTensorsSnapshot: number;\n  inputShapes: number[][];\n  outputShapes: number[][];\n  kernelTimeMs: number | {error: string} | Promise<number|{error: string}>;\n  extraInfo: string | Promise<string>;\n};\n\nexport type ProfileInfo = {\n  newBytes: number; newTensors: number; peakBytes: number;\n  kernels: KernelInfo[];\n  result: TensorContainer;\n  kernelNames: string[];\n};\n\nexport interface TimingInfo extends BackendTimingInfo {\n  wallMs: number;\n}\n\n/** @docalias Function */\nexport type ScopeFn<T extends TensorContainer> = () => T;\n\ninterface ScopeState {\n  track: Tensor[];\n  name: string;\n  id: number;\n}\n\ninterface RegisteredKernelInvocation<I extends NamedTensorMap> {\n  kernelName: string;\n  inputs: I;\n  attrs?: NamedAttrMap;\n}\n\ninterface CustomGradKernelInvocation<T extends Tensor|Tensor[],\n                                               I extends NamedTensorMap> {\n  forwardFunc: ForwardFunc<T>;\n  backwardsFunc: (dy: T, saved: Tensor[]) => {\n    [P in keyof I]: () => I[P]\n  };\n  inputs: I;\n  attrs?: NamedAttrMap;\n}\n\nfunction isRegisteredKernelInvocation<T extends Tensor|Tensor[],\n                                                I extends NamedTensorMap>(\n    kernelInvocation: RegisteredKernelInvocation<I>|\n    CustomGradKernelInvocation<T, I>):\n    kernelInvocation is RegisteredKernelInvocation<I> {\n  return (kernelInvocation as RegisteredKernelInvocation<I>).kernelName != null;\n}\n\nclass EngineState {\n  // Public since optimizers will use it.\n  registeredVariables: NamedVariableMap = {};\n\n  nextTapeNodeId = 0;\n  numBytes = 0;\n  numTensors = 0;\n  numStringTensors = 0;\n  numDataBuffers = 0;\n\n  activeTape: TapeNode[];\n  // Number of nested tf.grad() statements when computing higher-order\n  // gradients. E.g. `1` for first-order gradients and `2` for second-order\n  // gradients. Used to track if the tape should be removed after a backprop.\n  gradientDepth = 0;\n  // Number of nested kernel calls. When kernel depth is greater than 1, we turn\n  // off the tape.\n  kernelDepth = 0;\n\n  // Keep Tensors that parallel the tapes.\n  activeScope: ScopeState;\n  scopeStack: ScopeState[] = [];\n  /**\n   * Keeps track of the number of data moves during a kernel execution. We\n   * maintain a stack since kernels can call other kernels, recursively.\n   */\n  numDataMovesStack: number[] = [];\n  nextScopeId = 0;\n\n  tensorInfo = new WeakMap<DataId, {\n    backend: KernelBackend,\n    bytes: number,\n    dtype: DataType,\n    shape: number[]\n  }>();\n\n  profiling = false;\n  activeProfile: ProfileInfo = {\n    newBytes: 0,\n    newTensors: 0,\n    peakBytes: 0,\n    kernels: [],\n    result: null,\n    get kernelNames():\n        string[] {\n          return Array.from(new Set(this.kernels.map(k => k.name)));\n        }\n  };\n\n  dispose() {\n    for (const variableName in this.registeredVariables) {\n      this.registeredVariables[variableName].dispose();\n    }\n  }\n}\n\nexport class Engine implements TensorTracker, DataMover {\n  state: EngineState;\n  backendName: string;\n  registry: {[id: string]: KernelBackend} = {};\n  registryFactory: {\n    [id: string]: {\n      factory: () => KernelBackend | Promise<KernelBackend>,\n      priority: number\n    }\n  } = {};\n\n  private profiler: Profiler;\n  private backendInstance: KernelBackend;\n  private pendingBackendInit: Promise<boolean>;\n  private pendingBackendInitId = 0;\n\n  constructor(public ENV: Environment) {\n    this.state = new EngineState();\n  }\n\n  async ready(): Promise<void> {\n    if (this.pendingBackendInit != null) {\n      return this.pendingBackendInit.then(() => {});\n    }\n    if (this.backendInstance != null) {\n      return;\n    }\n    const sortedBackends = this.getSortedBackends();\n\n    for (let i = 0; i < sortedBackends.length; i++) {\n      const backendName = sortedBackends[i];\n      const success = await this.initializeBackend(backendName).success;\n      if (success) {\n        await this.setBackend(backendName);\n        return;\n      }\n    }\n\n    throw new Error(\n        `Could not initialize any backends, all backend initializations ` +\n        `failed.`);\n  }\n\n  get backend(): KernelBackend {\n    if (this.pendingBackendInit != null) {\n      throw new Error(\n          `Backend '${this.backendName}' has not yet been initialized. Make ` +\n          `sure to await tf.ready() or await tf.setBackend() before calling ` +\n          `other methods`);\n    }\n    if (this.backendInstance == null) {\n      const {name, asyncInit} = this.initializeBackendsAndReturnBest();\n      if (asyncInit) {\n        throw new Error(\n            `The highest priority backend '${name}' has not yet been ` +\n            `initialized. Make sure to await tf.ready() or ` +\n            `await tf.setBackend() before calling other methods`);\n      }\n      this.setBackend(name);\n    }\n    return this.backendInstance;\n  }\n\n  backendNames(): string[] {\n    return Object.keys(this.registryFactory);\n  }\n\n  findBackend(backendName: string): KernelBackend {\n    if (!(backendName in this.registry)) {\n      // If the backend hasn't been initialized but we have a registry entry for\n      // it, initialize it and return it.\n      if (backendName in this.registryFactory) {\n        const {asyncInit} = this.initializeBackend(backendName);\n        if (asyncInit) {\n          // Backend is not ready yet.\n          return null;\n        }\n      } else {\n        return null;\n      }\n    }\n    return this.registry[backendName];\n  }\n\n  findBackendFactory(backendName: string):\n      () => KernelBackend | Promise<KernelBackend> {\n    if (!(backendName in this.registryFactory)) {\n      return null;\n    }\n    return this.registryFactory[backendName].factory;\n  }\n\n  registerBackend(\n      backendName: string,\n      factory: () => KernelBackend | Promise<KernelBackend>,\n      priority = 1): boolean {\n    if (backendName in this.registryFactory) {\n      log.warn(\n          `${backendName} backend was already registered. ` +\n          `Reusing existing backend factory.`);\n      return false;\n    }\n    this.registryFactory[backendName] = {factory, priority};\n    return true;\n  }\n\n  async setBackend(backendName: string): Promise<boolean> {\n    if (this.registryFactory[backendName] == null) {\n      throw new Error(`Backend name '${backendName}' not found in registry`);\n    }\n    this.backendName = backendName;\n    if (this.registry[backendName] == null) {\n      this.backendInstance = null;\n      const {success, asyncInit} = this.initializeBackend(backendName);\n      const result = asyncInit ? await success : success;\n      if (!result) {\n        return false;\n      }\n    }\n    this.backendInstance = this.registry[backendName];\n    this.setupRegisteredKernels();\n    // Reset the profiler.\n    this.profiler = new Profiler(this.backendInstance);\n\n    return true;\n  }\n\n  private setupRegisteredKernels(): void {\n    const kernels = getKernelsForBackend(this.backendName);\n    kernels.forEach(kernel => {\n      if (kernel.setupFunc != null) {\n        kernel.setupFunc(this.backendInstance);\n      }\n    });\n  }\n\n  private disposeRegisteredKernels(backendName: string): void {\n    const kernels = getKernelsForBackend(backendName);\n    kernels.forEach(kernel => {\n      if (kernel.disposeFunc != null) {\n        kernel.disposeFunc(this.registry[backendName]);\n      }\n    });\n  }\n\n  /**\n   * Initializes a backend by looking up the backend name in the factory\n   * registry and calling the factory method. Returns a boolean representing\n   * whether the initialization of the backend succeeded. Throws an error if\n   * there is no backend in the factory registry.\n   */\n  private initializeBackend(backendName: string):\n      {success: boolean|Promise<boolean>, asyncInit: boolean} {\n    const registryFactoryEntry = this.registryFactory[backendName];\n    if (registryFactoryEntry == null) {\n      throw new Error(\n          `Cannot initialize backend ${backendName}, no registration found.`);\n    }\n\n    try {\n      const backend = registryFactoryEntry.factory();\n      /* Test if the factory returns a promise.\n      Done in a more liberal way than\n      previous 'Promise.resolve(backend)===backend'\n      as we needed to account for custom Promise\n      implementations (e.g. Angular) */\n      if (backend && !(backend instanceof KernelBackend) &&\n          typeof backend.then === 'function') {\n        const promiseId = ++this.pendingBackendInitId;\n        const success =\n            backend\n                .then(backendInstance => {\n                  // Outdated promise. Another backend was set in the meantime.\n                  if (promiseId < this.pendingBackendInitId) {\n                    return false;\n                  }\n                  this.registry[backendName] = backendInstance;\n                  this.pendingBackendInit = null;\n                  return true;\n                })\n                .catch(err => {\n                  // Outdated promise. Another backend was set in the meantime.\n                  if (promiseId < this.pendingBackendInitId) {\n                    return false;\n                  }\n                  this.pendingBackendInit = null;\n                  log.warn(`Initialization of backend ${backendName} failed`);\n                  log.warn(err.stack || err.message);\n                  return false;\n                });\n        this.pendingBackendInit = success;\n        return {success, asyncInit: true};\n      } else {\n        this.registry[backendName] = backend as KernelBackend;\n        return {success: true, asyncInit: false};\n      }\n    } catch (err) {\n      log.warn(`Initialization of backend ${backendName} failed`);\n      log.warn(err.stack || err.message);\n      return {success: false, asyncInit: false};\n    }\n  }\n\n  removeBackend(backendName: string): void {\n    if (!(backendName in this.registryFactory)) {\n      throw new Error(`${backendName} backend not found in registry`);\n    }\n    if (this.backendName === backendName && this.pendingBackendInit != null) {\n      // There is a pending promise of the backend we want to remove. Make it\n      // obsolete.\n      this.pendingBackendInitId++;\n    }\n\n    if (backendName in this.registry) {\n      this.disposeRegisteredKernels(backendName);\n      this.registry[backendName].dispose();\n      delete this.registry[backendName];\n    }\n\n    delete this.registryFactory[backendName];\n\n    // Unset the backend if it is active.\n    if (this.backendName === backendName) {\n      this.pendingBackendInit = null;\n      this.backendName = null;\n      this.backendInstance = null;\n    }\n  }\n\n  private getSortedBackends(): string[] {\n    if (Object.keys(this.registryFactory).length === 0) {\n      throw new Error('No backend found in registry.');\n    }\n    return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n      // Highest priority comes first.\n      return this.registryFactory[b].priority -\n          this.registryFactory[a].priority;\n    });\n  }\n\n  private initializeBackendsAndReturnBest():\n      {name: string, asyncInit: boolean} {\n    const sortedBackends = this.getSortedBackends();\n\n    for (let i = 0; i < sortedBackends.length; i++) {\n      const backendName = sortedBackends[i];\n      const {success, asyncInit} = this.initializeBackend(backendName);\n      if (asyncInit || success) {\n        return {name: backendName, asyncInit};\n      }\n    }\n    throw new Error(\n        `Could not initialize any backends, all backend initializations ` +\n        `failed.`);\n  }\n\n  moveData(backend: KernelBackend, dataId: DataId) {\n    const info = this.state.tensorInfo.get(dataId);\n    const srcBackend = info.backend;\n    const values = this.readSync(dataId);\n    const refCount = srcBackend.refCount(dataId);\n    // Delete the tensor from the old backend and move it to the new\n    // backend.\n    srcBackend.disposeData(dataId, true);\n    info.backend = backend;\n    backend.move(dataId, values, info.shape, info.dtype, refCount);\n    if (this.shouldCheckForMemLeaks()) {\n      // Track the number of moves during a kernel execution to correctly\n      // detect memory leaks.\n      this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n    }\n  }\n\n  tidy<T extends TensorContainer>(nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>):\n      T {\n    let name: string = null;\n    if (fn == null) {\n      // Called with only 1 argument.\n      if (typeof nameOrFn !== 'function') {\n        throw new Error('Please provide a function to tidy()');\n      }\n      fn = nameOrFn;\n    } else {\n      // Called with 2 arguments.\n      if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {\n        throw new Error(\n            'When calling with two arguments, the first argument ' +\n            'to tidy() must be a string');\n      }\n      if (typeof fn !== 'function') {\n        throw new Error(\n            'When calling with two arguments, the 2nd argument ' +\n            'to tidy() must be a function');\n      }\n      name = nameOrFn as string;\n      // TODO(nsthorat,smilkov): Do operation logging and performance\n      // profiling.\n    }\n    let result: T;\n    return this.scopedRun(\n        () => this.startScope(name), () => this.endScope(result), () => {\n          result = fn();\n          if (result instanceof Promise) {\n            console.error('Cannot return a Promise inside of tidy.');\n          }\n          return result;\n        });\n  }\n\n  private scopedRun<T>(start: () => void, end: () => void, f: () => T): T {\n    start();\n    try {\n      const res = f();\n      end();\n      return res;\n    } catch (ex) {\n      end();\n      throw ex;\n    }\n  }\n\n  private static nextTensorId = 0;\n  private nextTensorId(): number {\n    return Engine.nextTensorId++;\n  }\n\n  private static nextVariableId = 0;\n  private nextVariableId(): number {\n    return Engine.nextVariableId++;\n  }\n\n  /**\n   * This method is called instead of the public-facing tensor.clone() when\n   * saving a tensor for backwards pass. It makes sure to add the clone\n   * operation to the tape regardless of being called inside a kernel\n   * execution.\n   */\n  private clone(x: Tensor): Tensor {\n    const y: Tensor = ENGINE.runKernel(Identity,\n                                       {x} as unknown as NamedTensorMap);\n    const inputs = {x};\n    const grad = (dy: Tensor) => ({\n      x: () => {\n        const dtype = 'float32';\n        const gradInputs = {x: dy};\n        const attrs = {dtype};\n\n        return ENGINE.runKernel(\n                   Cast, gradInputs as unknown as NamedTensorMap,\n                   // tslint:disable-next-line: no-unnecessary-type-assertion\n                   attrs as unknown as NamedAttrMap) as Tensor;\n      }\n    });\n    const saved: Tensor[] = [];\n    this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});\n    return y;\n  }\n\n  /**\n   * Execute a kernel with the given name and return the output tensor.\n   *\n   * @param kernelName The name of the kernel to execute.\n   * @param inputs A map of input names to tensors.\n   * @param attrs A map of attribute names to their values. An attribute is a\n   *     primitive (non-tensor) input to the kernel.\n   * @param inputsToSave A list of tensors, inputs to save for the backprop\n   *     computation.\n   * @param outputsToSave A list of booleans, specifying which output to save\n   *     for the backprop computation. These are booleans since the output\n   * tensors are not visible to the user.\n   */\n  runKernel<T extends Tensor|Tensor[]>(\n      kernelName: string, inputs: NamedTensorMap, attrs?: NamedAttrMap): T {\n    if (this.backendName == null) {\n      // backend has not been initialized yet (backend initialization is lazy\n      // can be deferred until an op/ kernel is run).\n      // The below getter has side effects that will try to initialize the\n      // backend and set properties like this.backendName\n      // tslint:disable-next-line: no-unused-expression\n      this.backend;\n    }\n    const hasKernel = getKernel(kernelName, this.backendName) != null;\n    if (!hasKernel) {\n      throw new Error(`Kernel '${kernelName}' not registered for backend '${\n          this.backendName}'`);\n    }\n    return this.runKernelFunc({kernelName, inputs, attrs});\n  }\n\n  private shouldCheckForMemLeaks(): boolean {\n    return this.ENV.getBool('IS_TEST');\n  }\n\n  private checkKernelForMemLeak(\n      kernelName: string, numDataIdsBefore: number,\n      outInfos: TensorInfo[]): void {\n    const numDataIdsAfter = this.backend.numDataIds();\n\n    // Count the number of data ids associated with the result of the kernel.\n    let numOutputDataIds = 0;\n    outInfos.forEach(info => {\n      // Complex numbers allocate 3 data ids, one for 'real', one for\n      // 'imaginary', and one for the container that holds the former two.\n      numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);\n    });\n\n    // Account for the number of moves during kernel execution. A \"data move\"\n    // can happen in the middle of a kernel execution, placing a new (key,value)\n    // pair in the data storage. Since data moves have net zero effect (we\n    // always remove the data from the old backend), we have to cancel them out\n    // when detecting memory leaks.\n    const numMoves =\n        this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];\n    const dataIdsLeaked =\n        numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;\n    if (dataIdsLeaked > 0) {\n      throw new Error(\n          `Backend '${this.backendName}' has an internal memory leak ` +\n          `(${dataIdsLeaked} data ids) after running '${kernelName}'`);\n    }\n  }\n\n  /**\n   * Internal helper method to execute a kernel Func\n   *\n   * Use `runKernel` to execute kernels from outside of engine.\n   */\n  private runKernelFunc<T extends Tensor|Tensor[], I extends NamedTensorMap>(\n      kernelParams: RegisteredKernelInvocation<I>|\n      CustomGradKernelInvocation<T, I>): T {\n    let outputs: Tensor[];\n    let saved: Tensor[] = [];\n    const isTapeOn = this.isTapeOn();\n\n    const startingBytecount = this.state.numBytes;\n    const startingNumTensors = this.state.numTensors;\n\n    if (this.shouldCheckForMemLeaks()) {\n      this.state.numDataMovesStack.push(0);\n    }\n\n    let kernelFunc: () => Tensor[];\n    if (this.backendName == null) {\n      // backend has not been initialized yet (backend initialization is lazy\n      // can be deferred until an op/ kernel is run).\n      // The below getter has side effects that will try to initialize the\n      // backend and set properties like this.backendName\n      // tslint:disable-next-line: no-unused-expression\n      this.backend;\n    }\n\n    let out: TensorInfo|TensorInfo[];\n\n    const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?\n        kernelParams.kernelName :\n        this.state.activeScope != null ? this.state.activeScope.name : '';\n\n    // Create the kernelFunc from either a registered kernel OR passed in\n    // forward/backward functions (used by custom grad). In this context a\n    // kernelFunc wraps a kernel implementation with some bookkeeping.\n\n    if (isRegisteredKernelInvocation(kernelParams)) {\n      const {kernelName, inputs, attrs} = kernelParams;\n      if (this.backendName == null) {\n        // backend has not been initialized yet (backend initialization is lazy\n        // can be deferred until an op/ kernel is run).\n        // The below getter has side effects that will try to initialize the\n        // backend and set properties like this.backendName\n        // tslint:disable-next-line: no-unused-expression\n        this.backend;\n      }\n      const kernel = getKernel(kernelName, this.backendName);\n      util.assert(\n          kernel != null,\n          () => `Cannot find registered kernel '${kernelName}' for backend '${\n              this.backendName}'`);\n\n      kernelFunc = () => {\n        const numDataIdsBefore = this.backend.numDataIds();\n        out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n        const outInfos = Array.isArray(out) ? out : [out];\n        if (this.shouldCheckForMemLeaks()) {\n          this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n        }\n\n        const outTensors = outInfos.map((outInfo: TensorInfo|Tensor) => {\n          // todo (yassogba) remove this option (Tensor) when node backend\n          // methods have been modularized and they all return tensorInfo.\n          // TensorInfos do not have a rank attribute.\n          if ((outInfo as Tensor).rank != null) {\n            return outInfo as Tensor;\n          }\n          return this.makeTensorFromTensorInfo(outInfo);\n        });\n\n        // Save any required inputs and outputs.\n\n        // Do not save unless we are recording to the tape. Otherwise it would\n        // cause a mem leak since there would be no backprop for these tensors\n        // (which would otherwise dispose them).\n        if (isTapeOn) {\n          const tensorsToSave =\n              this.getTensorsForGradient(kernelName, inputs, outTensors);\n          saved = this.saveTensorsForBackwardMode(tensorsToSave);\n        }\n        return outTensors;\n      };\n    } else {\n      const {forwardFunc} = kernelParams;\n      // Running a customGrad op.\n      const saveFunc: GradSaveFunc = (tensors) => {\n        // Do not save unless we are recording to the tape. Otherwise it would\n        // cause a mem leak since we would never run backprop, which disposes\n        // the kept tensors.\n        if (!isTapeOn) {\n          return;\n        }\n        saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n      };\n\n      kernelFunc = () => {\n        const numDataIdsBefore = this.backend.numDataIds();\n        out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n        const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n        if (this.shouldCheckForMemLeaks()) {\n          // Scope name is used to print a more helpful error message if needed.\n          this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);\n        }\n        return outs;\n      };\n    }\n\n    //\n    // Run the kernelFunc. Optionally profiling it.\n    //\n    const {inputs, attrs} = kernelParams;\n    const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?\n        null :\n        kernelParams.backwardsFunc;\n\n    let kernelProfile: KernelProfile;\n    this.scopedRun(\n        // Stop recording to a tape when running a kernel.\n        () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n          if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n            outputs = kernelFunc();\n          } else {\n            kernelProfile = this.profiler.profileKernel(\n                kernelOrScopeName, inputs, () => kernelFunc());\n            if (this.ENV.getBool('DEBUG')) {\n              this.profiler.logKernelProfile(kernelProfile);\n            }\n            outputs = kernelProfile.outputs;\n          }\n        });\n\n    if (isTapeOn) {\n      this.addTapeNode(\n          kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);\n    }\n\n    if (this.state.profiling) {\n      this.state.activeProfile.kernels.push({\n        name: kernelOrScopeName,\n        bytesAdded: this.state.numBytes - startingBytecount,\n        totalBytesSnapshot: this.state.numBytes,\n        tensorsAdded: this.state.numTensors - startingNumTensors,\n        totalTensorsSnapshot: this.state.numTensors,\n        inputShapes: Object.keys(inputs).map(\n            key => inputs[key] != null ? inputs[key].shape : null),\n        outputShapes: outputs.map(item => item.shape),\n        kernelTimeMs: kernelProfile.timeMs,\n        extraInfo: kernelProfile.extraInfo\n      });\n    }\n    return (Array.isArray(out) ? outputs : outputs[0]) as T;\n  }\n\n  /**\n   * Saves tensors used in forward mode for use in backward mode.\n   *\n   * @param tensors the list of tensors to save.\n   */\n  private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n    const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n    return saved;\n  }\n\n  /**\n   * Returns a list of tensors to save for a given gradient calculation.\n   *\n   * @param kernelName name of kernel to look up gradient for.\n   * @param inputs a map of input tensors.\n   * @param outputs an array of output tensors from forward mode of kernel.\n   */\n  private getTensorsForGradient(\n      kernelName: string, inputs: NamedTensorMap,\n      outputs: Tensor[]): Tensor[]|null {\n    const gradConfig = getGradient(kernelName);\n    if (gradConfig != null) {\n      const inputsToSave: string[] = gradConfig.inputsToSave || [];\n      const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n      // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n      // specified in inputsToSave will be saved.\n      let inputTensorsToSave: Tensor[];\n      if (gradConfig.saveAllInputs) {\n        util.assert(\n            Array.isArray(inputs),\n            () => 'saveAllInputs is true, expected inputs to be an array.');\n\n        inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n      } else {\n        inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n      }\n\n      const outputTensorsToSave: Tensor[] =\n          outputs.filter((_, i) => outputsToSave[i]);\n\n      return inputTensorsToSave.concat(outputTensorsToSave);\n    }\n    // We return an empty list rather than throw an error because the kernel we\n    // are looking up may not actually be relevant to backproping through the\n    // overall function\n    //\n    // See 'does not error if irrelevant (pruned) ops are missing grads' test\n    // in gradients_test.ts for an example.\n    return [];\n  }\n\n  /**\n   * Internal method used by public APIs for tensor creation. Makes a new\n   * tensor with the provided shape, dtype and values. It always\n   * creates a new data id and writes the values to the underlying backend.\n   */\n  makeTensor(\n      values: DataValues, shape: number[], dtype: DataType,\n      backend?: KernelBackend): Tensor {\n    if (values == null) {\n      throw new Error('Values passed to engine.makeTensor() are null');\n    }\n    dtype = dtype || 'float32';\n    backend = backend || this.backend;\n    let backendVals = values as BackendValues;\n    if (dtype === 'string' && util.isString(values[0])) {\n      backendVals = (values as string[]).map(d => util.encodeString(d));\n    }\n    const dataId = backend.write(backendVals, shape, dtype);\n    const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n    this.trackTensor(t, backend);\n\n    // Count bytes for string tensors.\n    if (dtype === 'string') {\n      const info = this.state.tensorInfo.get(dataId);\n      const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n      this.state.numBytes += newBytes - info.bytes;\n      info.bytes = newBytes;\n    }\n    return t;\n  }\n\n  /**\n   * Internal method used by backends. Makes a new tensor\n   * that is a wrapper around an existing data id. It doesn't create\n   * a new data id, only increments the ref count used in memory tracking.\n   * @deprecated\n   */\n  makeTensorFromDataId(\n    dataId: DataId, shape: number[], dtype: DataType,\n    backend?: KernelBackend): Tensor {\n    dtype = dtype || 'float32';\n    const tensorInfo: TensorInfo = {dataId, shape, dtype};\n    return this.makeTensorFromTensorInfo(tensorInfo, backend);\n  }\n\n  /**\n   * Internal method used by backends. Makes a new tensor that is a wrapper\n   * around an existing data id in TensorInfo. It doesn't create a new data id,\n   * only increments the ref count used in memory tracking.\n   */\n  makeTensorFromTensorInfo(tensorInfo: TensorInfo, backend?: KernelBackend):\n      Tensor {\n    const {dataId, shape, dtype} = tensorInfo;\n    const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n    this.trackTensor(t, backend);\n    return t;\n  }\n\n  makeVariable(\n      initialValue: Tensor, trainable = true, name?: string,\n      dtype?: DataType): Variable {\n    name = name || this.nextVariableId().toString();\n    if (dtype != null && dtype !== initialValue.dtype) {\n      initialValue = initialValue.cast(dtype);\n    }\n    const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n    if (this.state.registeredVariables[v.name] != null) {\n      throw new Error(`Variable with name ${v.name} was already registered`);\n    }\n    this.state.registeredVariables[v.name] = v;\n    this.incRef(v, this.backend);\n    return v;\n  }\n\n  trackTensor(a: Tensor, backend: KernelBackend): void {\n    this.state.numTensors++;\n    if (a.dtype === 'string') {\n      this.state.numStringTensors++;\n    }\n    // Bytes for complex numbers are counted by their components. Bytes for\n    // string tensors are counted when writing values.\n    let bytes = 0;\n    if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n      bytes = a.size * util.bytesPerElement(a.dtype);\n    }\n    this.state.numBytes += bytes;\n\n    if (!this.state.tensorInfo.has(a.dataId)) {\n      this.state.numDataBuffers++;\n      this.state.tensorInfo.set(a.dataId, {\n        backend: backend || this.backend,\n        dtype: a.dtype,\n        shape: a.shape,\n        bytes\n      });\n    }\n\n    if (!(a instanceof Variable)) {\n      this.track(a);\n    }\n  }\n\n  // Track the tensor by dataId and increase the refCount for the dataId in the\n  // backend.\n  // TODO(pyu10055): This is currently used by makeVariable method, to increase\n  // refCount on the backend for the dataId. It can potentially be replaced with\n  // Identity op indead of calling backend directly.\n  incRef(a: Tensor, backend: KernelBackend): void {\n    this.trackTensor(a, backend);\n    this.backend.incRef(a.dataId);\n  }\n\n  removeDataId(dataId: DataId, backend: KernelBackend) {\n    if (this.state.tensorInfo.has(dataId) &&\n        this.state.tensorInfo.get(dataId).backend === backend) {\n      this.state.tensorInfo.delete(dataId);\n      this.state.numDataBuffers--;\n    }\n  }\n  disposeTensor(a: Tensor): void {\n    if (!this.state.tensorInfo.has(a.dataId)) {\n      return;\n    }\n    const info = this.state.tensorInfo.get(a.dataId);\n\n    this.state.numTensors--;\n    if (a.dtype === 'string') {\n      this.state.numStringTensors--;\n      this.state.numBytes -= info.bytes;\n    }\n    // Don't count bytes for complex numbers as they are counted by their\n    // components.\n    if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n      const bytes = a.size * util.bytesPerElement(a.dtype);\n      this.state.numBytes -= bytes;\n    }\n\n    // Remove the reference to dataId if backend dispose the data successfully\n    if (info.backend.disposeData(a.dataId)) {\n      this.removeDataId(a.dataId, info.backend);\n    }\n\n    // TODO(nsthorat): Construct an error and save the stack trace for\n    // debugging when in debug mode. Creating a stack trace is too expensive\n    // to do unconditionally.\n  }\n\n  disposeVariables(): void {\n    for (const varName in this.state.registeredVariables) {\n      const v = this.state.registeredVariables[varName];\n      this.disposeVariable(v);\n    }\n  }\n\n  disposeVariable(v: Variable): void {\n    this.disposeTensor(v);\n    if (this.state.registeredVariables[v.name] != null) {\n      delete this.state.registeredVariables[v.name];\n    }\n  }\n\n  memory(): MemoryInfo {\n    const info = this.backend.memory() as MemoryInfo;\n    info.numTensors = this.state.numTensors;\n    info.numDataBuffers = this.state.numDataBuffers;\n    info.numBytes = this.state.numBytes;\n    if (this.state.numStringTensors > 0) {\n      info.unreliable = true;\n      if (info.reasons == null) {\n        info.reasons = [];\n      }\n      info.reasons.push(\n          'Memory usage by string tensors is approximate ' +\n          '(2 bytes per character)');\n    }\n    return info;\n  }\n\n  async profile(query: () => (TensorContainer | Promise<TensorContainer>)):\n      Promise<ProfileInfo> {\n    this.state.profiling = true;\n\n    const startBytes = this.state.numBytes;\n    const startNumTensors = this.state.numTensors;\n\n    this.state.activeProfile.kernels = [];\n    this.state.activeProfile.result = await query();\n\n    this.state.profiling = false;\n\n    this.state.activeProfile.peakBytes = Math.max(\n        ...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));\n    this.state.activeProfile.newBytes = this.state.numBytes - startBytes;\n    this.state.activeProfile.newTensors =\n        this.state.numTensors - startNumTensors;\n    for (const kernel of this.state.activeProfile.kernels) {\n      kernel.kernelTimeMs = await kernel.kernelTimeMs;\n      kernel.extraInfo = await kernel.extraInfo;\n    }\n    return this.state.activeProfile;\n  }\n\n  isTapeOn(): boolean {\n    return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;\n  }\n\n  private addTapeNode(\n      kernelName: string, inputs: NamedTensorMap, outputs: Tensor[],\n      gradientsFunc: GradFunc, saved: Tensor[], attrs: NamedAttrMap): void {\n    const tapeNode: TapeNode =\n        {id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved};\n\n    const gradConfig = getGradient(kernelName);\n    if (gradConfig != null) {\n      gradientsFunc = gradConfig.gradFunc;\n    }\n    if (gradientsFunc != null) {\n      tapeNode.gradient = (dys: Tensor[]) => {\n        // TODO(smilkov): To optimize back-prop, pass dys that are not used in\n        // the backprop graph to the user as null instead of zeros\n        dys = dys.map((dy, i) => {\n          if (dy == null) {\n            const output = outputs[i];\n            const vals = util.makeZerosTypedArray(output.size, output.dtype);\n            return this.makeTensor(vals, output.shape, output.dtype);\n          }\n          return dy;\n        });\n        // Grad functions of ops with single outputs expect a dy, while ops\n        // with multiple outputs expect dys (array of dy).\n        return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);\n      };\n    }\n    this.state.activeTape.push(tapeNode);\n  }\n\n  keep<T extends Tensor>(result: T): T {\n    result.kept = true;\n    return result;\n  }\n\n  private startTape() {\n    if (this.state.gradientDepth === 0) {\n      this.state.activeTape = [];\n    }\n    this.state.gradientDepth++;\n  }\n\n  private endTape() {\n    this.state.gradientDepth--;\n  }\n\n  /**\n   * Start a scope. Use this with endScope() to achieve the same functionality\n   * as scope() without the need for a function closure.\n   */\n  startScope(name?: string) {\n    const scopeInfo: ScopeState = {\n      track: [],\n      name: 'unnamed scope',\n      id: this.state.nextScopeId++\n    };\n    if (name) {\n      scopeInfo.name = name;\n    }\n    this.state.scopeStack.push(scopeInfo);\n    this.state.activeScope = scopeInfo;\n  }\n\n  /**\n   * End a scope. Use this with startScope() to achieve the same functionality\n   * as scope() without the need for a function closure.\n   */\n  endScope(result?: TensorContainer) {\n    const tensorsToTrackInParent = getTensorsInContainer(result);\n    const tensorsToTrackInParentSet =\n        new Set(tensorsToTrackInParent.map(t => t.id));\n\n    // Dispose the arrays tracked in this scope.\n    for (let i = 0; i < this.state.activeScope.track.length; i++) {\n      const tensor = this.state.activeScope.track[i];\n      if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {\n        tensor.dispose();\n      }\n    }\n\n    const oldScope = this.state.scopeStack.pop();\n    this.state.activeScope = this.state.scopeStack.length === 0 ?\n        null :\n        this.state.scopeStack[this.state.scopeStack.length - 1];\n\n    // Track the current result in the parent scope.\n    tensorsToTrackInParent.forEach(tensor => {\n      // Only track the tensor if was allocated in the inner scope and is not\n      // globally kept.\n      if (!tensor.kept && tensor.scopeId === oldScope.id) {\n        this.track(tensor);\n      }\n    });\n  }\n\n  /**\n   * Returns gradients of `f` with respect to each of the `xs`. The gradients\n   * returned are of the same length as `xs`, but some might be null if `f`\n   * was not a function of that `x`. It also takes optional dy to multiply the\n   * gradient, which defaults to `1`.\n   */\n  gradients<T extends Tensor>(\n      f: () => T, xs: Tensor[], dy?: T,\n      allowNoGradients = false): {value: T, grads: Tensor[]} {\n    util.assert(\n        xs.length > 0, () => 'gradients() received an empty list of xs.');\n    if (dy != null && dy.dtype !== 'float32') {\n      throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);\n    }\n\n    const y = this.scopedRun(\n        () => this.startTape(), () => this.endTape(),\n        () => this.tidy('forward', f));\n\n    util.assert(\n        y instanceof Tensor,\n        () => 'The result y returned by f() must be a tensor.');\n    // Filter out the nodes that don't connect x => y.\n    const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);\n    if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {\n      throw new Error(\n          'Cannot compute gradient of y=f(x) with respect to x. Make sure ' +\n          'that the f you passed encloses all operations that lead from x ' +\n          'to y.');\n    }\n\n    return this.tidy('backward', () => {\n      const accumulatedGradientMap: {[tensorId: number]: Tensor} = {};\n      accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;\n\n      // Backprop gradients through the filtered nodes.\n      backpropagateGradients(\n          accumulatedGradientMap, filteredTape,\n          // Pass the tidy function to avoid circular dep with `tape.ts`.\n          f => this.tidy(f as ScopeFn<Tensor>),\n          // Pass an add function to avoide a circular dep with `tape.ts`.\n          add);\n      const grads = xs.map(x => accumulatedGradientMap[x.id]);\n\n      if (this.state.gradientDepth === 0) {\n        // This means that we are not computing higher-order gradients\n        // and can clean up the tape.\n        this.state.activeTape.forEach(node => {\n          for (const tensor of node.saved) {\n            tensor.dispose();\n          }\n        });\n        this.state.activeTape = null;\n      }\n      return {value: y, grads};\n    });\n  }\n\n  customGrad<T extends Tensor>(f: CustomGradientFunc<T>):\n      (...args: Array<Tensor|GradSaveFunc>) => T {\n    util.assert(\n        util.isFunction(f),\n        () => 'The f passed in customGrad(f) must be a function.');\n    return (...inputs: Tensor[]): T => {\n      util.assert(\n          inputs.every(t => t instanceof Tensor),\n          () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +\n              'tensors');\n\n      let res: {\n        value: T,\n        gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[],\n      };\n      const inputMap: NamedTensorMap = {};\n      inputs.forEach((input, i) => {\n        inputMap[i] = input;\n      });\n\n      const forwardFunc: ForwardFunc<T> = (_, save) => {\n        res = f(...[...inputs, save]);\n        util.assert(\n            res.value instanceof Tensor,\n            () => 'The function f passed in customGrad(f) must return an ' +\n                'object where `obj.value` is a tensor');\n        util.assert(\n            util.isFunction(res.gradFunc),\n            () => 'The function f passed in customGrad(f) must return an ' +\n                'object where `obj.gradFunc` is a function.');\n        return res.value;\n      };\n\n      const backwardsFunc = (dy: T, saved: Tensor[]) => {\n        const gradRes = res.gradFunc(dy, saved);\n        const grads: Tensor[] = Array.isArray(gradRes) ? gradRes : [gradRes];\n        util.assert(\n            grads.length === inputs.length,\n            () => 'The function f passed in customGrad(f) must return an ' +\n                'object where `obj.gradFunc` is a function that returns ' +\n                'the same number of tensors as inputs passed to f(...).');\n        util.assert(\n            grads.every(t => t instanceof Tensor),\n            () => 'The function f passed in customGrad(f) must return an ' +\n                'object where `obj.gradFunc` is a function that returns ' +\n                'a list of only tensors.');\n        const gradMap: {[key: string]: () => Tensor} = {};\n        grads.forEach((grad, i) => {\n          gradMap[i] = () => grad;\n        });\n        return gradMap;\n      };\n\n      return this.runKernelFunc({\n        forwardFunc,\n        backwardsFunc,\n        inputs: inputMap,\n      });\n    };\n  }\n\n  readSync(dataId: DataId): BackendValues {\n    // Route the read to the correct backend.\n    const info = this.state.tensorInfo.get(dataId);\n    return info.backend.readSync(dataId);\n  }\n  read(dataId: DataId): Promise<BackendValues> {\n    // Route the read to the correct backend.\n    const info = this.state.tensorInfo.get(dataId);\n    return info.backend.read(dataId);\n  }\n\n  readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData {\n    // Route the read to the correct backend.\n    const info = this.state.tensorInfo.get(dataId);\n    return info.backend.readToGPU(dataId, options);\n  }\n\n  async time(query: () => void): Promise<TimingInfo> {\n    const start = now();\n    const timingInfo = await this.backend.time(query) as TimingInfo;\n    timingInfo.wallMs = now() - start;\n    return timingInfo;\n  }\n\n  /**\n   * Tracks a Tensor in the current scope to be automatically cleaned up\n   * when the current scope ends, and returns the value.\n   *\n   * @param result The Tensor to track in the current scope.\n   */\n  private track<T extends Tensor>(result: T): T {\n    if (this.state.activeScope != null) {\n      result.scopeId = this.state.activeScope.id;\n      this.state.activeScope.track.push(result);\n    }\n\n    return result;\n  }\n\n  get registeredVariables(): NamedVariableMap {\n    return this.state.registeredVariables;\n  }\n\n  /**\n   * Resets the engine state. Removes all backends but does not remove\n   * registered backend factories.\n   */\n  reset(): void {\n    // Make any pending promise obsolete.\n    this.pendingBackendInitId++;\n\n    this.state.dispose();\n    this.ENV.reset();\n    this.state = new EngineState();\n\n    for (const backendName in this.registry) {\n      this.disposeRegisteredKernels(backendName);\n      this.registry[backendName].dispose();\n      delete this.registry[backendName];\n    }\n    this.backendName = null;\n    this.backendInstance = null;\n    this.pendingBackendInit = null;\n  }\n}\n\nfunction ones(shape: number[]): Tensor {\n  const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n  return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n  const ns = getGlobalNamespace() as unknown as {_tfengine: Engine};\n  if (ns._tfengine == null) {\n    const environment = new Environment(ns);\n    ns._tfengine = new Engine(environment);\n  }\n  setEnvironmentGlobal(ns._tfengine.ENV);\n\n  // Tell the current tensor interface that the global engine is responsible\n  // for tracking.\n  setTensorTracker(() => ns._tfengine);\n  return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n  // We duplicate Add here to avoid a circular dependency with add.ts.\n  const inputs = {a, b};\n  return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// tslint:disable-next-line:no-any\nfunction _isNavigatorDefined(): boolean {\n  return typeof navigator !== 'undefined' && navigator != null;\n}\n\nlet isMobileMockValue: boolean|undefined;\n\nexport function mockIsMobile(value: boolean|undefined) {\n  isMobileMockValue = value;\n}\n\nexport function isMobile(nav?: Navigator): boolean {\n  if (isMobileMockValue !== undefined) {\n    return isMobileMockValue;\n  }\n  if (nav || _isNavigatorDefined()) {\n    if (!nav) {\n      nav = navigator;\n    }\n    if (nav.product === 'ReactNative') {\n      return true;\n    }\n\n    const a = nav.userAgent || nav.vendor ||\n        // tslint:disable-next-line:no-any\n        (typeof window !== 'undefined' ? (window as any).opera : '');\n    // Use `navigator.userAgentData.mobile` as fallback.\n    if (!a) {\n      // tslint:disable-next-line:no-any\n      const navAny = nav as any;\n      return navAny.userAgentData && navAny.userAgentData.mobile;\n    }\n    // tslint:disable-next-line:max-line-length\n    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\n               .test(a) ||\n        // tslint:disable-next-line:max-line-length\n        /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\n            .test(a.substr(0, 4));\n  }\n  return false;\n}\n\nexport function isBrowser(): boolean {\n  return (typeof window !== 'undefined' && window.document != null) ||\n      //@ts-ignore\n      (typeof WorkerGlobalScope !== 'undefined');\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport './engine';\n\nimport * as device_util from './device_util';\nimport {env} from './environment';\n\nconst ENV = env();\n\n/**\n * This file contains environment-related flag registrations.\n */\n\n/** Whether to enable debug mode. */\nENV.registerFlag('DEBUG', () => false, debugValue => {\n  if (debugValue) {\n    console.warn(\n        'Debugging mode is ON. The output of every math call will ' +\n        'be downloaded to CPU and checked for NaNs. ' +\n        'This significantly impacts performance.');\n  }\n});\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag('IS_BROWSER', () => device_util.isBrowser());\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag(\n    'IS_NODE',\n    () => (typeof process !== 'undefined') &&\n        (typeof process.versions !== 'undefined') &&\n        (typeof process.versions.node !== 'undefined'));\n\n/** Whether this browser is Chrome. */\nENV.registerFlag(\n    'IS_CHROME',\n    () => typeof navigator !== 'undefined' && navigator != null &&\n        navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&\n        /Google Inc/.test(navigator.vendor));\n\n/** Whether this browser is Safari. */\nENV.registerFlag(\n    'IS_SAFARI',\n    () => typeof navigator !== 'undefined' && navigator != null &&\n        navigator.userAgent != null && /Safari/.test(navigator.userAgent) &&\n        /Apple/.test(navigator.vendor));\n/**\n * True when the environment is \"production\" where we disable safety checks\n * to gain performance.\n */\nENV.registerFlag('PROD', () => false);\n\n/**\n * Whether to do sanity checks when inferring a shape from user-provided\n * values, used when creating a new tensor.\n */\nENV.registerFlag(\n    'TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));\n\n/** Whether deprecation warnings are enabled. */\nENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);\n\n/** True if running unit tests. */\nENV.registerFlag('IS_TEST', () => false);\n\n/** Whether to check computation result for errors. */\nENV.registerFlag('CHECK_COMPUTATION_FOR_ERRORS', () => ENV.getBool('DEBUG'));\n\n/** Whether the backend needs to wrap input to imageBitmap. */\nENV.registerFlag('WRAP_TO_IMAGEBITMAP', () => false);\n\n/** Whether to enable canvas2d willReadFrequently for GPU backends */\nENV.registerFlag('CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU', () => false);\n\n/** Whether to use setTimeoutCustom */\nENV.registerFlag('USE_SETTIMEOUTCUSTOM', () => false);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {getGlobalTensorClass, Tensor} from './tensor';\nimport {DataType, isWebGLData, isWebGPUData, TensorLike, WebGLData, WebGPUData} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\nimport {bytesPerElement} from './util_base';\n\nexport function inferShape(\n    val: TensorLike|WebGLData|WebGPUData, dtype?: DataType): number[] {\n  let firstElem: typeof val = val;\n\n  if (isTypedArray(val)) {\n    return dtype === 'string' ? [] : [val.length];\n  }\n\n  if (isWebGLData(val)) {\n    const usedChannels = val.channels || 'RGBA';\n    return [val.height, val.width * usedChannels.length];\n  } else if (isWebGPUData(val)) {\n    return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];\n  }\n  if (!Array.isArray(val)) {\n    return [];  // Scalar.\n  }\n  const shape: number[] = [];\n\n  while (Array.isArray(firstElem) ||\n         isTypedArray(firstElem) && dtype !== 'string') {\n    shape.push(firstElem.length);\n    firstElem = firstElem[0];\n  }\n  if (Array.isArray(val) &&\n      env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {\n    deepAssertShapeConsistency(val, shape, []);\n  }\n\n  return shape;\n}\n\nfunction deepAssertShapeConsistency(\n    val: TensorLike, shape: number[], indices: number[]) {\n  indices = indices || [];\n  if (!(Array.isArray(val)) && !isTypedArray(val)) {\n    assert(\n        shape.length === 0,\n        () => `Element arr[${indices.join('][')}] is a primitive, ` +\n            `but should be an array/TypedArray of ${shape[0]} elements`);\n    return;\n  }\n  assert(\n      shape.length > 0,\n      () => `Element arr[${indices.join('][')}] should be a primitive, ` +\n          `but is an array of ${val.length} elements`);\n  assert(\n      val.length === shape[0],\n      () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +\n          `elements, but has ${val.length} elements`);\n  const subShape = shape.slice(1);\n  for (let i = 0; i < val.length; ++i) {\n    deepAssertShapeConsistency(val[i], subShape, indices.concat(i));\n  }\n}\n\nfunction assertDtype(\n    expectedDtype: DataType|'numeric'|'string_or_numeric',\n    actualDType: DataType, argName: string, functionName: string) {\n  if (expectedDtype === 'string_or_numeric') {\n    return;\n  }\n  if (expectedDtype == null) {\n    throw new Error(`Expected dtype cannot be null.`);\n  }\n  if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||\n      expectedDtype === 'numeric' && actualDType === 'string') {\n    throw new Error(\n        `Argument '${argName}' passed to '${functionName}' must ` +\n        `be ${expectedDtype} tensor, but got ${actualDType} tensor`);\n  }\n}\n\nexport function convertToTensor<T extends Tensor>(\n    x: T|TensorLike, argName: string, functionName: string,\n    parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T {\n  if (x instanceof getGlobalTensorClass()) {\n    assertDtype(parseAsDtype, x.dtype, argName, functionName);\n    return x;\n  }\n  let inferredDtype = inferDtype(x);\n  // If the user expects a bool/int/float, use that info to update the\n  // inferredDtype when it is not a string.\n  if (inferredDtype !== 'string' &&\n      ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {\n    inferredDtype = parseAsDtype as DataType;\n  }\n  assertDtype(parseAsDtype, inferredDtype, argName, functionName);\n\n  if ((x == null) ||\n      (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&\n       typeof x !== 'boolean' && typeof x !== 'string')) {\n    const type = x == null ? 'null' : (x as {}).constructor.name;\n    throw new Error(\n        `Argument '${argName}' passed to '${functionName}' must be a ` +\n        `Tensor or TensorLike, but got '${type}'`);\n  }\n  const inferredShape = inferShape(x, inferredDtype);\n  if (!isTypedArray(x) && !Array.isArray(x)) {\n    x = [x] as number[];\n  }\n  const skipTypedArray = true;\n  const values = inferredDtype !== 'string' ?\n      toTypedArray(x, inferredDtype as DataType) :\n      flatten(x as string[], [], skipTypedArray) as string[];\n  return ENGINE.makeTensor(values, inferredShape, inferredDtype) as T;\n}\n\nexport function convertToTensorArray<T extends Tensor>(\n    arg: Array<T|TensorLike>, argName: string, functionName: string,\n    parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T[] {\n  if (!Array.isArray(arg)) {\n    throw new Error(\n        `Argument ${argName} passed to ${functionName} must be a ` +\n        '`Tensor[]` or `TensorLike[]`');\n  }\n  const tensors = arg as T[];\n  return tensors.map(\n      (t, i) =>\n          convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {isPromise} from '../util';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op<T extends Function>(f: {[name: string]: T}): T {\n  const keys = Object.keys(f);\n  if (keys.length !== 1) {\n    throw new Error(\n        `Please provide an object with a single key ` +\n        `(operation name) mapping to a function. Got an object with ` +\n        `${keys.length} keys.`);\n  }\n\n  let opName = keys[0];\n  const fn = f[opName];\n\n  // Strip the underscore from the end of the function name.\n  if (opName.endsWith('_')) {\n    opName = opName.substring(0, opName.length - 1);\n  }\n\n  // add an __op suffix to distinguish ops from kernels in tf.profile\n  opName = opName + OP_SCOPE_SUFFIX;\n\n  // tslint:disable-next-line:no-any\n  const f2 = (...args: any[]) => {\n    ENGINE.startScope(opName);\n    try {\n      const result = fn(...args);\n      if (isPromise(result)) {\n        console.error('Cannot return a Promise inside of tidy.');\n      }\n      ENGINE.endScope(result);\n      return result;\n    } catch (ex) {\n      ENGINE.endScope(null);\n      throw ex;\n    }\n  };\n  Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n  // tslint:disable-next-line:no-any\n  return f2 as any as T;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Complex, ComplexInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Converts two real numbers to a complex number.\n *\n * Given a tensor `real` representing the real part of a complex number, and a\n * tensor `imag` representing the imaginary part of a complex number, this\n * operation returns complex numbers elementwise of the form [r0, i0, r1, i1],\n * where r represents the real part and i represents the imag part.\n *\n * The input tensors real and imag must have the same shape.\n *\n * ```js\n * const real = tf.tensor1d([2.25, 3.25]);\n * const imag = tf.tensor1d([4.75, 5.75]);\n * const complex = tf.complex(real, imag);\n *\n * complex.print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction complex_<T extends Tensor>(real: T|TensorLike, imag: T|TensorLike): T {\n  const $real = convertToTensor(real, 'real', 'complex');\n  const $imag = convertToTensor(imag, 'imag', 'complex');\n  util.assertShapesMatch(\n      $real.shape, $imag.shape,\n      `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +\n          `must match in call to tf.complex().`);\n\n  const inputs: ComplexInputs = {real: $real, imag: $imag};\n  return ENGINE.runKernel(Complex, inputs as unknown as NamedTensorMap);\n}\n\nexport const complex = /* @__PURE__ */ op({complex_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {isWebGLData, isWebGPUData, TensorLike, TypedArray, WebGLData, WebGPUData} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n    values: TensorLike|WebGLData|WebGPUData, shape: number[],\n    inferredShape: number[], dtype?: DataType): Tensor {\n  if (dtype == null) {\n    dtype = inferDtype(values);\n  } else if (dtype === 'complex64') {\n    throw new Error(\n        `Cannot construct a complex64 tensor directly. ` +\n        `Please use tf.complex(real, imag).`);\n  }\n\n  if (isWebGPUData(values) || isWebGLData(values)) {\n    if (dtype !== 'float32' && dtype !== 'int32') {\n      throw new Error(\n          `Creating tensor from GPU data only supports ` +\n          `'float32'|'int32' dtype, while the dtype is ${dtype}.`);\n    }\n    return ENGINE.backend.createTensorFromGPUData(\n        values, shape || inferredShape, dtype);\n  }\n\n  if (!isTypedArray(values) && !Array.isArray(values) &&\n      typeof values !== 'number' && typeof values !== 'boolean' &&\n      typeof values !== 'string') {\n    throw new Error(\n        'values passed to tensor(values) must be a number/boolean/string or ' +\n        'an array of numbers/booleans/strings, or a TypedArray');\n  }\n  // Verify that the shape matches the inferred shape.\n  if (shape != null) {\n    assertNonNegativeIntegerDimensions(shape);\n\n    const providedSize = sizeFromShape(shape);\n    const inferredSize = sizeFromShape(inferredShape);\n    assert(\n        providedSize === inferredSize,\n        () =>\n            `Based on the provided shape, [${shape}], the tensor should have ` +\n            `${providedSize} values but has ${inferredSize}`);\n\n    for (let i = 0; i < inferredShape.length; ++i) {\n      const inferred = inferredShape[i];\n      const flatDimsDontMatch = i === inferredShape.length - 1 ?\n          inferred !== sizeFromShape(shape.slice(i)) :\n          true;\n      assert(\n          inferredShape[i] === shape[i] || !flatDimsDontMatch,\n          () => `Error creating a new Tensor. Inferred shape ` +\n              `(${inferredShape}) does not match the provided ` +\n              `shape (${shape}). `);\n    }\n  }\n\n  if (!isTypedArray(values) && !Array.isArray(values)) {\n    values = [values] as number[];\n  }\n\n  shape = shape || inferredShape;\n  values = dtype !== 'string' ?\n      toTypedArray(values, dtype) :\n      flatten(values as string[], [], true) as string[];\n  return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {DataType, Rank, ShapeMap, WebGLData, WebGPUData} from '../types';\n\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates a `tf.Tensor` with the provided values, shape and dtype.\n *\n * ```js\n * // Pass an array of values to create a vector.\n * tf.tensor([1, 2, 3, 4]).print();\n * ```\n *\n * ```js\n * // Pass a nested array of values to make a matrix or a higher\n * // dimensional tensor.\n * tf.tensor([[1, 2], [3, 4]]).print();\n * ```\n *\n * ```js\n * // Pass a flat array and specify a shape yourself.\n * tf.tensor([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * ```js\n * // Pass a `WebGLData` object and specify a shape yourself.\n *\n * // This makes it possible for TF.js applications to avoid GPU / CPU sync.\n * // For example, if your application includes a preprocessing step on the GPU,\n * // you could upload the GPU output directly to TF.js, rather than first\n * // downloading the values.\n *\n * // Example for WebGL2:\n * if (tf.findBackend('custom-webgl') == null) {\n *   const customCanvas = document.createElement('canvas');\n *   const customBackend = new tf.MathBackendWebGL(customCanvas);\n *   tf.registerBackend('custom-webgl', () => customBackend);\n * }\n * const savedBackend = tf.getBackend();\n * await tf.setBackend('custom-webgl');\n * const gl = tf.backend().gpgpu.gl;\n * const texture = gl.createTexture();\n * const tex2d = gl.TEXTURE_2D;\n * const width = 2;\n * const height = 2;\n *\n * gl.bindTexture(tex2d, texture);\n * gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n * gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n * gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n * gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n * gl.texImage2D(\n *   tex2d, 0, gl.RGBA32F, // internalFormat\n *   width, height, 0,\n *   gl.RGBA, // textureFormat\n *   gl.FLOAT, // textureType\n *   new Float32Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])\n * );\n *\n * // Currently, the `texture` has 4 pixels:\n * // Pixel0 is {R:0, G:1, B:2, A:3}\n * // Pixel1 is {R:4, G:5, B:6, A:7}\n * // Pixel2 is {R:8, G:9, B:10, A:11}\n * // Pixel3 is {R:12, G:13, B:14, A:15}\n *\n * const logicalShape = [height * width * 2];\n * const a = tf.tensor({texture, height, width, channels: 'BR'}, logicalShape);\n * a.print();\n * // Tensor value will be [2, 0, 6, 4, 10, 8, 14, 12], since [2, 0] is the\n * // values of 'B' and 'R' channels of Pixel0, [6, 4] is the values of 'B' and\n * 'R'\n * // channels of Pixel1...\n *\n * // For postprocessing on the GPU, it's possible to retrieve the texture\n * // backing any tensor by calling the tensor's `dataToGPU` method like\n * // so:\n *\n * const tex = a.dataToGPU();\n * await tf.setBackend(savedBackend);\n * ```\n *\n * ```js\n * // Pass a `WebGPUData` object and specify a shape yourself.\n *\n * // This makes it possible for TF.js applications to avoid GPU / CPU sync.\n * // For example, if your application includes a preprocessing step on the GPU,\n * // you could upload the GPU output directly to TF.js, rather than first\n * // downloading the values. Unlike WebGL, this optionally supports zero copy\n * // by WebGPUData.zeroCopy. When zeroCopy is false or undefined(default), this\n * // passing GPUBuffer can be destroyed after tensor is created. When zeroCopy\n * // is true, this GPUBuffer is bound directly by the tensor, so do not destroy\n * // this GPUBuffer until all access is done.\n *\n * // Example for WebGPU:\n * function createGPUBufferFromData(device, data, dtype) {\n *   const bytesPerElement = 4;\n *   const sizeInBytes = data.length * bytesPerElement;\n *\n *   const gpuWriteBuffer = device.createBuffer({\n *     mappedAtCreation: true,\n *     size: sizeInBytes,\n *     usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC\n *   });\n *   const arrayBuffer = gpuWriteBuffer.getMappedRange();\n *   if (dtype === 'float32') {\n *     new Float32Array(arrayBuffer).set(data);\n *   } else if (dtype === 'int32') {\n *     new Int32Array(arrayBuffer).set(data);\n *   } else {\n *     throw new Error(\n *         `Creating tensor from GPUBuffer only supports` +\n *         `'float32'|'int32' dtype, while the dtype is ${dtype}.`);\n *   }\n *   gpuWriteBuffer.unmap();\n *\n *   const gpuReadBuffer = device.createBuffer({\n *     mappedAtCreation: false,\n *     size: sizeInBytes,\n *     usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE |\n *         GPUBufferUsage.COPY_SRC\n *   });\n *\n *   const copyEncoder = device.createCommandEncoder();\n *   copyEncoder.copyBufferToBuffer(\n *       gpuWriteBuffer, 0, gpuReadBuffer, 0, sizeInBytes);\n *   const copyCommands = copyEncoder.finish();\n *   device.queue.submit([copyCommands]);\n *   gpuWriteBuffer.destroy();\n *   return gpuReadBuffer;\n * }\n *\n * const savedBackend = tf.getBackend();\n * await tf.setBackend('webgpu').catch(\n *     () => {throw new Error(\n *         'Failed to use WebGPU backend. Please use Chrome Canary to run.')});\n * const dtype = 'float32';\n * const device = tf.backend().device;\n * const aData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];\n * const bData = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4];\n * const expected = [2, 4, 6, 8, 6, 8, 10, 12, 10, 12, 14, 16, 14, 16, 18, 20];\n * const aBuffer = createGPUBufferFromData(device, aData, dtype);\n * const shape = [aData.length];\n * // To use zeroCopy, use {buffer: aBuffer, zeroCopy: true} instead and destroy\n * // aBuffer untill all access is done.\n * const a = tf.tensor({buffer: aBuffer}, shape, dtype);\n * const b = tf.tensor(bData, shape, dtype);\n * const result = tf.add(a, b);\n * result.print();\n * a.dispose();\n * b.dispose();\n * result.dispose();\n * aBuffer.destroy();\n * await tf.setBackend(savedBackend);\n * ```\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`(At the moment it supports Uint8Array,\n * Uint8ClampedArray, Int32Array, Float32Array) data types, or a `WebGLData`\n * object, or a `WebGPUData` object. If the values are strings, they will be\n * encoded as utf-8 and kept as `Uint8Array[]`. If the values is a `WebGLData`\n * object, the dtype could only be 'float32' or 'int32' and the object has to\n * have: 1. texture, a `WebGLTexture`, the texture must share the same\n * `WebGLRenderingContext` with TFJS's WebGL backend (you could create a custom\n * WebGL backend from your texture's canvas) and the internal texture format\n * for the input texture must be floating point or normalized integer; 2.\n * height, the height of the texture; 3. width, the width of the texture; 4.\n * channels, a non-empty subset of 'RGBA', indicating the values of which\n * channels will be passed to the tensor, such as 'R' or 'BR' (The order of the \n * channels affect the order of tensor values. ). (If the values passed from \n * texture is less than the tensor size, zeros will be padded at the rear.). If \n * the values is a `WebGPUData` object, the dtype could only be 'float32' or\n * 'int32 and the object has to have: buffer, a `GPUBuffer`. The buffer must:\n * 1. share the same `GPUDevice` with TFJS's WebGPU backend; 2. buffer.usage\n * should at least support GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC; 3.\n * buffer.size should not be smaller than the byte size of tensor shape.\n * WebGPUData optionally supports zero copy by flag zeroCopy. When zeroCopy is\n * false or undefined(default),this passing GPUBuffer can be destroyed after\n * tensor is created. When zeroCopy is true, this GPUBuffer is bound directly\n * by the tensor, so do not destroy this GPUBuffer until all access is done.\n * @param shape The shape of the tensor. Optional. If not provided,\n *   it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor<R extends Rank>(\n    values: TensorLike|WebGLData|WebGPUData, shape?: ShapeMap[R],\n    dtype?: DataType): Tensor<R> {\n  const inferredShape = inferShape(values, dtype);\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor<R>;\n}", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/* Type definitions for exporting and importing of models. */\n\n/**\n * A map from Tensor dtype to number of bytes per element of the Tensor.\n */\nexport const DTYPE_VALUE_SIZE_MAP: {[dtype: string]: number} = {\n  'float32': 4,\n  'float16': 2,\n  'int32': 4,\n  'uint16': 2,\n  'uint8': 1,\n  'bool': 1,\n  'complex64': 8\n};\n\n/**\n * A weight manifest.\n *\n * The weight manifest consists of an ordered list of weight-manifest groups.\n * Each weight-manifest group (\"group\" for short hereafter) consists of a\n * number of weight values stored in a number of paths.\n * See the documentation of `WeightManifestGroupConfig` below for more details.\n */\nexport declare type WeightsManifestConfig = WeightsManifestGroupConfig[];\n\n/**\n * A weight-manifest group.\n *\n * Consists of an ordered list of weight values encoded in binary format,\n * stored in an ordered list of paths.\n */\nexport declare interface WeightsManifestGroupConfig {\n  /**\n   * An ordered list of paths.\n   *\n   * Paths are intentionally abstract in order to be general. For example, they\n   * can be relative URL paths or relative paths on the file system.\n   */\n  paths: string[];\n\n  /**\n   * Specifications of the weights stored in the paths.\n   */\n  weights: WeightsManifestEntry[];\n}\n\n/**\n * Group to which the weight belongs.\n *\n * - 'optimizer': Weight from a stateful optimizer.\n */\nexport type WeightGroup = 'model'|'optimizer';\n\n/**\n * An entry in the weight manifest.\n *\n * The entry contains specification of a weight.\n */\nexport declare interface WeightsManifestEntry {\n  /**\n   * Name of the weight, e.g., 'Dense_1/bias'\n   */\n  name: string;\n\n  /**\n   * Shape of the weight.\n   */\n  shape: number[];\n\n  /**\n   * Data type of the weight.\n   */\n  dtype: 'float32'|'int32'|'bool'|'string'|'complex64';\n\n  /**\n   * Type of the weight.\n   *\n   * Optional.\n   *\n   * The value 'optimizer' indicates the weight belongs to an optimizer\n   * (i.e., used only during model training and not during inference).\n   */\n  group?: WeightGroup;\n\n  /**\n   * Information for dequantization of the weight.\n   */\n  quantization?: {\n    scale?: number,  // The scaling constant to multiply by.\n    min?: number,    // The (possibly nudged) minimum weight to add.\n       dtype: 'uint16'|'uint8'|'float16'  // The dtype of the quantized weights.\n  };\n}\n\n/**\n * Options for saving a model.\n * @innamespace io\n */\nexport interface SaveConfig {\n  /**\n   * Whether to save only the trainable weights of the model, ignoring the\n   * non-trainable ones.\n   */\n  trainableOnly?: boolean;\n\n  /**\n   * Whether the optimizer will be saved (if exists).\n   *\n   * Default: `false`.\n   */\n  includeOptimizer?: boolean;\n}\n\n/**\n * Result of a saving operation.\n */\nexport interface SaveResult {\n  /**\n   * Information about the model artifacts saved.\n   */\n  modelArtifactsInfo: ModelArtifactsInfo;\n\n  /**\n   * HTTP responses from the server that handled the model-saving request (if\n   * any). This is applicable only to server-based saving routes.\n   */\n  responses?: Response[];\n\n  /**\n   * Error messages and related data (if any).\n   */\n  errors?: Array<{}|string>;\n}\n\nexport declare interface ModelArtifactsInfo {\n  /**\n   * Timestamp for when the model is saved.\n   */\n  dateSaved: Date;\n\n  /**\n   * TODO (cais,yassogba) consider removing GraphDef as GraphDefs now\n   * come in a JSON format and none of our IOHandlers support a non json\n   * format. We could conder replacing this with 'Binary' if we want to\n   * allow future handlers to save to non json formats (though they will\n   * probably want more information than 'Binary').\n   * Type of the model topology\n   *\n   * Type of the model topology\n   *\n   * Possible values:\n   *   - JSON: JSON config (human-readable, e.g., Keras JSON).\n   *   - GraphDef: TensorFlow\n   *     [GraphDef](https://www.tensorflow.org/extend/tool_developers/#graphdef)\n   *     protocol buffer (binary).\n   */\n  modelTopologyType: 'JSON'|'GraphDef';\n\n  /**\n   * Size of model topology (Keras JSON or GraphDef), in bytes.\n   */\n  modelTopologyBytes?: number;\n\n  /**\n   * Size of weight specification or manifest, in bytes.\n   */\n  weightSpecsBytes?: number;\n\n  /**\n   * Size of weight value data, in bytes.\n   */\n  weightDataBytes?: number;\n}\n\n/** Model training configuration. */\nexport declare interface TrainingConfig {\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  // See\n  // tslint:disable-next-line:max-line-length\n  // https://github.com/tensorflow/tfjs-layers/blob/master/src/keras_format/training_config.ts\n  /** Optimizer used for the model training. */\n  optimizer_config: {};\n\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  /** Loss function(s) for the model's output(s). */\n  loss: string|string[]|{[key: string]: string};\n\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  /** Metric function(s) for the model's output(s). */\n  metrics?: string[]|{[key: string]: string};\n\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  weighted_metrics?: string[];\n\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  sample_weight_mode?: string;\n\n  loss_weights?: number[]|{[key: string]: number};\n}\n\nexport type WeightData = ArrayBuffer | ArrayBuffer[];\n\n/**\n * The serialized artifacts of a model, including topology and weights.\n *\n * The `modelTopology`, `trainingConfig`, `weightSpecs` and `weightData` fields\n * of this interface are optional, in order to support topology- or weights-only\n * saving and loading.\n *\n * Note this interface is used internally in IOHandlers.  For the file format\n * written to disk as `model.json`, see `ModelJSON`.\n */\nexport declare interface ModelArtifacts {\n  /**\n   * Model topology.\n   *\n   * For Keras-style `tf.Model`s, this is a JSON object.\n   * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n   * encoding of the `GraphDef` protocol buffer.\n   */\n  modelTopology?: {}|ArrayBuffer;\n\n  /**\n   * Serialized configuration for the model's training.\n   */\n  trainingConfig?: TrainingConfig;\n\n  /**\n   * Weight specifications.\n   *\n   * This corresponds to the weightsData below.\n   */\n  weightSpecs?: WeightsManifestEntry[];\n\n  /**\n   * Binary buffer(s) for all weight values in the order specified by\n   * `weightSpecs`. This may be a single ArrayBuffer of all the weights\n   * concatenated together or an Array of ArrayBuffers containing the weights\n   * (weights may be sharded across multiple ArrayBuffers).\n   */\n  weightData?: WeightData;\n\n  /**\n   * Returns a stream of the weights. Some models are too large to fit in\n   * V8's memory heap, and `getWeightStream` loads their weights without storing\n   * them all in memory at the same time.\n   */\n  getWeightStream?: () => ReadableStream<ArrayBuffer>;\n\n  /**\n   * Hard-coded format name for models saved from TensorFlow.js or converted\n   * by TensorFlow.js Converter.\n   */\n  format?: string;\n\n  /**\n   * What library is responsible for originally generating this artifact.\n   *\n   * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n   */\n  generatedBy?: string;\n\n  /**\n   * What library or tool is responsible for converting the original model\n   * to this format, applicable only if the model is output by a converter.\n   *\n   * Used for debugging purposes.  E.g., 'TensorFlow.js Converter v1.0.0'.\n   *\n   * A value of `null` means the model artifacts are generated without any\n   * conversion process (e.g., saved directly from a TensorFlow.js\n   * `tf.LayersModel` instance.)\n   */\n  convertedBy?: string|null;\n\n  /**\n   * Inputs and outputs signature for saved model.\n   */\n  signature?: {};\n\n  /**\n   * User-defined metadata about the model.\n   */\n  userDefinedMetadata?: {[key: string]: {}};\n\n  /**\n   * Initializer for the model.\n   */\n  modelInitializer?: {};\n\n  /**\n   * Inputs and outputs signature for model initializer.\n   */\n  initializerSignature?: {};\n}\n\n/**\n * The on-disk format of the `model.json` file.\n *\n * TF.js 1.0 always populates the optional fields when writing model.json.\n * Prior versions did not provide those fields.\n */\nexport declare interface ModelJSON {\n  /**\n   * Model topology.\n   *\n   * For Keras-style `tf.Model`s, this is a JSON object.\n   * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n   * encoding of the `GraphDef` protocol buffer.\n   */\n  modelTopology: {};\n\n  /** Model training configuration. */\n  trainingConfig?: TrainingConfig;\n\n  /**\n   * Weights manifest.\n   *\n   * The weights manifest consists of an ordered list of weight-manifest\n   * groups. Each weight-manifest group consists of a number of weight values\n   * stored in a number of paths. See the documentation of\n   * `WeightsManifestConfig` for more details.\n   */\n  weightsManifest: WeightsManifestConfig;\n\n  /**\n   * Hard-coded format name for models saved from TensorFlow.js or converted\n   * by TensorFlow.js Converter.\n   */\n  format?: string;\n\n  /**\n   * What library is responsible for originally generating this artifact.\n   *\n   * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n   */\n  generatedBy?: string;\n\n  /**\n   * What library or tool is responsible for converting the original model\n   * to this format, applicable only if the model is output by a converter.\n   *\n   * Used for debugging purposes.  E.g., 'TensorFlow.js Converter v1.0.0'.\n   *\n   * A value of `null` means the model artifacts are generated without any\n   * conversion process (e.g., saved directly from a TensorFlow.js\n   * `tf.LayersModel` instance.)\n   */\n  convertedBy?: string|null;\n\n  /**\n   * Inputs and outputs signature for saved model.\n   */\n  signature?: {};\n\n  /**\n   * User-defined metadata about the model.\n   */\n  userDefinedMetadata?: {[key: string]: {}};\n\n  /**\n   * Initializer for the model.\n   */\n  modelInitializer?: {};\n\n  /**\n   * Inputs and outputs signature for model initializer.\n   */\n  initializerSignature?: {};\n}\n\n/**\n * Type definition for handlers of loading operations.\n */\nexport type LoadHandler = () => Promise<ModelArtifacts>;\n\n/**\n * Type definition for handlers of saving operations.\n */\nexport type SaveHandler = (modelArtifact: ModelArtifacts) =>\n    Promise<SaveResult>;\n\n/**\n * Interface for a model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport interface IOHandler {\n  save?: SaveHandler;\n  load?: LoadHandler;\n}\n\n/**\n * Type definition for handlers of synchronous loading operations.\n */\nexport type LoadHandlerSync = () => ModelArtifacts;\n\n/**\n * Type definition for handlers of synchronous saving operations.\n */\nexport type SaveHandlerSync = (modelArtifact: ModelArtifacts) => SaveResult;\n\n/**\n * Interface for a synchronous model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport type IOHandlerSync = {\n  save?: SaveHandlerSync;\n  load?: LoadHandlerSync;\n};\n\n/**\n * An interface for the manager of a model store.\n *\n * A model store is defined as a storage medium on which multiple models can\n * be stored. Each stored model has a unique `path` as its identifier.\n * A `ModelStoreManager` for the store allows actions including\n *\n * - Listing the models stored in the store.\n * - Deleting a model from the store.\n */\nexport interface ModelStoreManager {\n  /**\n   * List all models in the model store.\n   *\n   * @returns A dictionary mapping paths of existing models to their\n   *   model artifacts info. Model artifacts info include type of the model's\n   *   topology, byte sizes of the topology, weights, etc.\n   */\n  listModels(): Promise<{[path: string]: ModelArtifactsInfo}>;\n\n  /**\n   * Remove a model specified by `path`.\n   *\n   * @param path\n   * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n   *   is successful).\n   * @throws Error if deletion fails, e.g., if no model exists at `path`.\n   */\n  removeModel(path: string): Promise<ModelArtifactsInfo>;\n}\n\n/**\n * Callback for the progress of a long-running action such as an HTTP\n * request for a large binary object.\n *\n * `fraction` should be a number in the [0, 1] interval, indicating how\n * much of the action has completed.\n */\nexport type OnProgressCallback = (fraction: number) => void;\n\n/** @innamespace io */\nexport interface LoadOptions {\n  /**\n   * RequestInit (options) for HTTP requests.\n   *\n   * For detailed information on the supported fields, see\n   * [https://developer.mozilla.org/en-US/docs/Web/API/Request/Request](\n   *     https://developer.mozilla.org/en-US/docs/Web/API/Request/Request)\n   */\n  requestInit?: RequestInit;\n\n  /**\n   * Progress callback.\n   */\n  onProgress?: OnProgressCallback;\n\n  /**\n   * A function used to override the `window.fetch` function.\n   */\n  fetchFunc?: typeof fetch;\n\n  /**\n   * Strict loading model: whether extraneous weights or missing\n   * weights should trigger an `Error`.\n   *\n   * If `true`, require that the provided weights exactly match those\n   * required by the layers. `false` means that both extra weights\n   * and missing weights will be silently ignored.\n   *\n   * Default: `true`.\n   */\n  strict?: boolean;\n\n  /**\n   * Path prefix for weight files, by default this is calculated from the\n   * path of the model JSON file.\n   *\n   * For instance, if the path to the model JSON file is\n   * `http://localhost/foo/model.json`, then the default path prefix will be\n   * `http://localhost/foo/`. If a weight file has the path value\n   * `group1-shard1of2` in the weight manifest, then the weight file will be\n   * loaded from `http://localhost/foo/group1-shard1of2` by default. However,\n   * if you provide a `weightPathPrefix` value of\n   * `http://localhost/foo/alt-weights`, then the weight file will be loaded\n   * from the path `http://localhost/foo/alt-weights/group1-shard1of2` instead.\n   */\n  weightPathPrefix?: string;\n\n  /**\n   * Whether the module or model is to be loaded from TF Hub.\n   *\n   * Setting this to `true` allows passing a TF-Hub module URL, omitting the\n   * standard model file name and the query parameters.\n   *\n   * Default: `false`.\n   */\n  fromTFHub?: boolean;\n\n  /**\n   * An async function to convert weight file name to URL. The weight file\n   * names are stored in model.json's weightsManifest.paths field. By default we\n   * consider weight files are colocated with the model.json file. For example:\n   *     model.json URL: https://www.google.com/models/1/model.json\n   *     group1-shard1of1.bin url:\n   *        https://www.google.com/models/1/group1-shard1of1.bin\n   *\n   * With this func you can convert the weight file name to any URL.\n   */\n  weightUrlConverter?: (weightFileName: string) => Promise<string>;\n\n  /**\n   * Whether to stream the model directly to the backend or cache all its\n   * weights on CPU first. Useful for large models.\n   */\n  streamWeights?: boolean;\n}\n\n/**\n * Additional options for Platform.fetch\n */\nexport interface RequestDetails {\n  /**\n   * Is this request for a binary file (as opposed to a json file)\n   */\n  isBinary?: boolean;\n}\n", "/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {TypedArray} from '../types';\nimport * as util from '../util';\n\ntype BufferShard = {\n  start: number,\n  end: number,\n  buffer: ArrayBuffer,\n};\n\n/**\n * Wraps a list of ArrayBuffers into a `slice()`-able object without allocating\n * a large ArrayBuffer.\n *\n * Allocating large ArrayBuffers (~2GB) can be unstable on Chrome. TFJS loads\n * its weights as a list of (usually) 4MB ArrayBuffers and then slices the\n * weight tensors out of them. For small models, it's safe to concatenate all\n * the weight buffers into a single ArrayBuffer and then slice the weight\n * tensors out of it, but for large models, a different approach is needed.\n */\n\nexport class CompositeArrayBuffer {\n  private shards: BufferShard[] = [];\n  private previousShardIndex = 0;\n  private bufferUniformSize?: number;\n  public readonly byteLength: number;\n\n  /**\n   * Concatenate a number of ArrayBuffers into one.\n   *\n   * @param buffers An array of ArrayBuffers to concatenate, or a single\n   *     ArrayBuffer.\n   * @returns Result of concatenating `buffers` in order.\n   */\n  static join(buffers?: ArrayBuffer[] | ArrayBuffer) {\n    return new CompositeArrayBuffer(buffers).slice();\n  }\n\n  constructor(buffers?: ArrayBuffer | ArrayBuffer[] | TypedArray |\n    TypedArray[]) {\n    if (buffers == null) {\n      return;\n    }\n    // Normalize the `buffers` input to be `ArrayBuffer[]`.\n    if (!(buffers instanceof Array)) {\n      buffers = [buffers];\n    }\n    buffers = buffers.map((bufferOrTypedArray) => {\n      if (util.isTypedArray(bufferOrTypedArray)) {\n        return bufferOrTypedArray.buffer;\n      }\n      return bufferOrTypedArray;\n    });\n\n    // Skip setting up shards if there are no buffers.\n    if (buffers.length === 0) {\n      return;\n    }\n\n    this.bufferUniformSize = buffers[0].byteLength;\n    let start = 0;\n\n    for (let i = 0; i < buffers.length; i++) {\n      const buffer = buffers[i];\n      // Check that all buffers except the last one have the same length.\n      if (i !== buffers.length - 1 &&\n        buffer.byteLength !== this.bufferUniformSize) {\n        // Unset the buffer uniform size, since the buffer sizes are not\n        // uniform.\n        this.bufferUniformSize = undefined;\n      }\n\n      // Create the shards, including their start and end points.\n      const end = start + buffer.byteLength;\n      this.shards.push({ buffer, start, end });\n      start = end;\n    }\n\n    // Set the byteLength\n    if (this.shards.length === 0) {\n      this.byteLength = 0;\n    }\n    this.byteLength = this.shards[this.shards.length - 1].end;\n  }\n\n  slice(start = 0, end = this.byteLength): ArrayBuffer {\n    // If there are no shards, then the CompositeArrayBuffer was initialized\n    // with no data.\n    if (this.shards.length === 0) {\n      return new ArrayBuffer(0);\n    }\n\n    // NaN is treated as zero for slicing. This matches ArrayBuffer's behavior.\n    start = isNaN(Number(start)) ? 0 : start;\n    end = isNaN(Number(end)) ? 0 : end;\n\n    // Fix the bounds to within the array.\n    start = Math.max(0, start);\n    end = Math.min(this.byteLength, end);\n    if (end <= start) {\n      return new ArrayBuffer(0);\n    }\n\n    const startShardIndex = this.findShardForByte(start);\n    if (startShardIndex === -1) {\n      // This should not happen since the start and end indices are always\n      // within 0 and the composite array's length.\n      throw new Error(`Could not find start shard for byte ${start}`);\n    }\n\n    const size = end - start;\n    const outputBuffer = new ArrayBuffer(size);\n    const outputArray = new Uint8Array(outputBuffer);\n    let sliced = 0;\n    for (let i = startShardIndex; i < this.shards.length; i++) {\n      const shard = this.shards[i];\n\n      const globalStart = start + sliced;\n      const localStart = globalStart - shard.start;\n      const outputStart = sliced;\n\n      const globalEnd = Math.min(end, shard.end);\n      const localEnd = globalEnd - shard.start;\n\n      const outputSlice = new Uint8Array(shard.buffer, localStart,\n                                         localEnd - localStart);\n      outputArray.set(outputSlice, outputStart);\n      sliced += outputSlice.length;\n\n      if (end < shard.end) {\n        break;\n      }\n    }\n    return outputBuffer;\n  }\n\n  /**\n   * Get the index of the shard that contains the byte at `byteIndex`.\n   */\n  private findShardForByte(byteIndex: number): number {\n    if (this.shards.length === 0 || byteIndex < 0 ||\n      byteIndex >= this.byteLength) {\n      return -1;\n    }\n\n    // If the buffers have a uniform size, compute the shard directly.\n    if (this.bufferUniformSize != null) {\n      this.previousShardIndex = Math.floor(byteIndex / this.bufferUniformSize);\n      return this.previousShardIndex;\n    }\n\n    // If the buffers don't have a uniform size, we need to search for the\n    // shard. That means we need a function to check where the byteIndex lies\n    // relative to a given shard.\n    function check(shard: BufferShard) {\n      if (byteIndex < shard.start) {\n        return -1;\n      }\n      if (byteIndex >= shard.end) {\n        return 1;\n      }\n      return 0;\n    }\n\n    // For efficiency, try the previous shard first.\n    if (check(this.shards[this.previousShardIndex]) === 0) {\n      return this.previousShardIndex;\n    }\n\n    // Otherwise, use a generic search function.\n    // This should almost never end up being used in practice since the weight\n    // entries should always be in order.\n    const index = search(this.shards, check);\n    if (index === -1) {\n      return -1;\n    }\n\n    this.previousShardIndex = index;\n    return this.previousShardIndex;\n  }\n}\n\n/**\n * Search for an element of a sorted array.\n *\n * @param sortedArray The sorted array to search\n * @param compare A function to compare the current value against the searched\n *     value. Return 0 on a match, negative if the searched value is less than\n *     the value passed to the function, and positive if the searched value is\n *     greater than the value passed to the function.\n * @returns The index of the element, or -1 if it's not in the array.\n */\nexport function search<T>(sortedArray: T[], compare: (t: T) => number): number {\n  // Binary search\n  let min = 0;\n  let max = sortedArray.length;\n\n  while (min <= max) {\n    const middle = Math.floor((max - min) / 2) + min;\n    const side = compare(sortedArray[middle]);\n\n    if (side === 0) {\n      return middle;\n    } else if (side < 0) {\n      max = middle;\n    } else {\n      min = middle + 1;\n    }\n  }\n  return -1;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelBackend} from './backends/backend';\nimport {ENGINE, Engine, MemoryInfo, ProfileInfo, ScopeFn, TimingInfo} from './engine';\nimport {env} from './environment';\n\nimport {Platform} from './platforms/platform';\nimport {setDeprecationWarningFn, Tensor} from './tensor';\nimport {TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\n\n/**\n * Enables production mode which disables correctness checks in favor of\n * performance.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableProdMode(): void {\n  env().set('PROD', true);\n}\n\n/**\n * Enables debug mode which will log information about all executed kernels:\n * the elapsed time of the kernel execution, as well as the rank, shape, and\n * size of the output tensor.\n *\n * Debug mode will significantly slow down your application as it will\n * download the result of every operation to the CPU. This should not be used in\n * production. Debug mode does not affect the timing information of the kernel\n * execution as we do not measure download time in the kernel execution time.\n *\n * See also: `tf.profile`, `tf.memory`.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableDebugMode(): void {\n  env().set('DEBUG', true);\n}\n\n/** Globally disables deprecation warnings */\nexport function disableDeprecationWarnings(): void {\n  env().set('DEPRECATION_WARNINGS_ENABLED', false);\n  console.warn(`TensorFlow.js deprecation warnings have been disabled.`);\n}\n\n/** Warn users about deprecated functionality. */\nexport function deprecationWarn(msg: string) {\n  if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {\n    console.warn(\n        msg + ' You can disable deprecation warnings with ' +\n        'tf.disableDeprecationWarnings().');\n  }\n}\nsetDeprecationWarningFn(deprecationWarn);\n\n/**\n * Dispose all variables kept in backend engine.\n *\n * @doc {heading: 'Environment'}\n */\nexport function disposeVariables(): void {\n  ENGINE.disposeVariables();\n}\n\n/**\n * It returns the global engine that keeps track of all tensors and backends.\n *\n * @doc {heading: 'Environment'}\n */\nexport function engine(): Engine {\n  return ENGINE;\n}\n\n/**\n * Returns memory info at the current time in the program. The result is an\n * object with the following properties:\n *\n * - `numBytes`: Number of bytes allocated (undisposed) at this time.\n * - `numTensors`: Number of unique tensors allocated.\n * - `numDataBuffers`: Number of unique data buffers allocated\n *   (undisposed) at this time, which is ≤ the number of tensors\n *   (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same\n *   data buffer with `a`).\n * - `unreliable`: True if the memory usage is unreliable. See `reasons` when\n *    `unreliable` is true.\n * - `reasons`: `string[]`, reasons why the memory is unreliable, present if\n *    `unreliable` is true.\n *\n * WebGL Properties:\n * - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at\n *     this time.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function memory(): MemoryInfo {\n  return ENGINE.memory();\n}\n\n/**\n * Executes the provided function `f()` and returns a promise that resolves\n * with information about the function's memory use:\n * - `newBytes`: the number of new bytes allocated\n * - `newTensors`: the number of new tensors created\n * - `peakBytes`: the peak number of bytes allocated\n * - `kernels`: an array of objects for each kernel involved that reports\n * their input and output shapes, number of bytes used, and number of new\n * tensors created.\n * - `kernelNames`: an array of unique strings with just the names of the\n * kernels in the `kernels` array.\n *\n * ```js\n * const profile = await tf.profile(() => {\n *   const x = tf.tensor1d([1, 2, 3]);\n *   let x2 = x.square();\n *   x2.dispose();\n *   x2 = x.square();\n *   x2.dispose();\n *   return x;\n * });\n *\n * console.log(`newBytes: ${profile.newBytes}`);\n * console.log(`newTensors: ${profile.newTensors}`);\n * console.log(`byte usage over all kernels: ${profile.kernels.map(k =>\n * k.totalBytesSnapshot)}`);\n * ```\n *\n *\n * @doc {heading: 'Performance', subheading: 'Profile'}\n */\nexport function profile(f: () => (TensorContainer | Promise<TensorContainer>)):\n    Promise<ProfileInfo> {\n  return ENGINE.profile(f);\n}\n\n/**\n * Executes the provided function `fn` and after it is executed, cleans up all\n * intermediate tensors allocated by `fn` except those returned by `fn`.\n * `fn` must not return a Promise (async functions not allowed). The returned\n * result can be a complex object.\n *\n * Using this method helps avoid memory leaks. In general, wrap calls to\n * operations in `tf.tidy` for automatic memory cleanup.\n *\n * NOTE: Variables do *not* get cleaned up when inside a tidy(). If you want to\n * dispose variables, please use `tf.disposeVariables` or call dispose()\n * directly on variables.\n *\n * ```js\n * // y = 2 ^ 2 + 1\n * const y = tf.tidy(() => {\n *   // a, b, and one will be cleaned up when the tidy ends.\n *   const one = tf.scalar(1);\n *   const a = tf.scalar(2);\n *   const b = a.square();\n *\n *   console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n *   // The value returned inside the tidy function will return\n *   // through the tidy, in this case to the variable y.\n *   return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * y.print();\n * ```\n *\n * @param nameOrFn The name of the closure, or the function to execute.\n *     If a name is provided, the 2nd argument should be the function.\n *     If debug mode is on, the timing and the memory usage of the function\n *     will be tracked and displayed on the console using the provided name.\n * @param fn The function to execute.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function tidy<T extends TensorContainer>(\n    nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>): T {\n  return ENGINE.tidy(nameOrFn, fn);\n}\n\n/**\n * Disposes any `tf.Tensor`s found within the provided object.\n *\n * @param container an object that may be a `tf.Tensor` or may directly\n *     contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If\n *     the object is not a `tf.Tensor` or does not contain `Tensors`, nothing\n *     happens. In general it is safe to pass any object here, except that\n *     `Promise`s are not supported.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function dispose(container: TensorContainer) {\n  const tensors = getTensorsInContainer(container);\n  tensors.forEach(tensor => tensor.dispose());\n}\n\n/**\n * Keeps a `tf.Tensor` generated inside a `tf.tidy` from being disposed\n * automatically.\n *\n * ```js\n * let b;\n * const y = tf.tidy(() => {\n *   const one = tf.scalar(1);\n *   const a = tf.scalar(2);\n *\n *   // b will not be cleaned up by the tidy. a and one will be cleaned up\n *   // when the tidy ends.\n *   b = tf.keep(a.square());\n *\n *   console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n *   // The value returned inside the tidy function will return\n *   // through the tidy, in this case to the variable y.\n *   return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * console.log('y:');\n * y.print();\n * console.log('b:');\n * b.print();\n * ```\n *\n * @param result The tensor to keep from being disposed.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function keep<T extends Tensor>(result: T): T {\n  return ENGINE.keep(result);\n}\n\n/**\n * Executes `f()` and returns a promise that resolves with timing\n * information.\n *\n * The result is an object with the following properties:\n *\n * - `wallMs`: Wall execution time.\n * - `kernelMs`: Kernel execution time, ignoring data transfer. If using the\n * WebGL backend and the query timer extension is not available, this will\n * return an error object.\n * - On `WebGL` The following additional properties exist:\n *   - `uploadWaitMs`: CPU blocking time on texture uploads.\n *   - `downloadWaitMs`: CPU blocking time on texture downloads (readPixels).\n *\n * ```js\n * const x = tf.randomNormal([20, 20]);\n * const time = await tf.time(() => x.matMul(x));\n *\n * console.log(`kernelMs: ${time.kernelMs}, wallTimeMs: ${time.wallMs}`);\n * ```\n *\n * @param f The function to execute and time.\n *\n * @doc {heading: 'Performance', subheading: 'Timing'}\n */\nexport function time(f: () => void): Promise<TimingInfo> {\n  return ENGINE.time(f);\n}\n\n/**\n * Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and\n * executing operations on those tensors. Returns a promise that resolves\n * to a boolean if the backend initialization was successful.\n *\n * Note this disposes the current backend, if any, as well as any tensors\n * associated with it. A new backend is initialized, even if it is of the\n * same type as the previous one.\n *\n * @param backendName The name of the backend. Currently supports\n *     `'webgl'|'cpu'` in the browser, `'tensorflow'` under node.js\n *     (requires tfjs-node), and `'wasm'` (requires tfjs-backend-wasm).\n *\n * @doc {heading: 'Backends'}\n */\nexport function setBackend(backendName: string): Promise<boolean> {\n  return ENGINE.setBackend(backendName);\n}\n\n/**\n * Returns a promise that resolves when the currently selected backend (or the\n * highest priority one) has initialized. Await this promise when you are using\n * a backend that has async initialization.\n *\n * @doc {heading: 'Backends'}\n */\nexport function ready(): Promise<void> {\n  return ENGINE.ready();\n}\n\n/**\n * Returns the current backend name (cpu, webgl, etc). The backend is\n * responsible for creating tensors and executing operations on those tensors.\n *\n * @doc {heading: 'Backends'}\n */\nexport function getBackend(): string {\n  return ENGINE.backendName;\n}\n\n/**\n * Removes a backend and the registered factory.\n *\n * @doc {heading: 'Backends'}\n */\nexport function removeBackend(name: string): void {\n  ENGINE.removeBackend(name);\n}\n\n/**\n * Finds the backend registered under the provided name. Returns null if the\n * name is not in the registry, or the registration hasn't finished yet.\n */\nexport function findBackend(name: string): KernelBackend {\n  return ENGINE.findBackend(name);\n}\n\n/**\n * Finds the backend factory registered under the provided name. Returns a\n * function that produces a new backend when called. Returns null if the name\n * is not in the registry.\n */\nexport function findBackendFactory(name: string): () =>\n    KernelBackend | Promise<KernelBackend> {\n  return ENGINE.findBackendFactory(name);\n}\n\n/**\n * Registers a global backend. The registration should happen when importing\n * a module file (e.g. when importing `backend_webgl.ts`), and is used for\n * modular builds (e.g. custom tfjs bundle with only webgl support).\n *\n * @param factory The backend factory function. When called, it should\n * return a backend instance, or a promise of an instance.\n * @param priority The priority of the backend (higher = more important).\n *     In case multiple backends are registered, the priority is used to find\n *     the best backend. Defaults to 1.\n * @return False if there is already a registered backend under this name, true\n *     if not.\n *\n * @doc {heading: 'Backends'}\n */\nexport function registerBackend(\n    name: string, factory: () => KernelBackend | Promise<KernelBackend>,\n    priority = 1): boolean {\n  return ENGINE.registerBackend(name, factory, priority);\n}\n\n/**\n * Gets the current backend. If no backends have been initialized, this will\n * attempt to initialize the best backend. Will throw an error if the highest\n * priority backend has async initialization, in which case you should call\n * 'await tf.ready()' before running other code.\n *\n * @doc {heading: 'Backends'}\n */\nexport function backend(): KernelBackend {\n  return ENGINE.backend;\n}\n\n/**\n * Sets the global platform.\n *\n * @param platformName The name of this platform.\n * @param platform A platform implementation.\n */\nexport function setPlatform(platformName: string, platform: Platform) {\n  env().setPlatform(platformName, platform);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, ModelJSON, WeightData, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {Tensor} from '../tensor';\nimport {backend} from '../globals';\nimport {DataId} from '../tensor_info';\nimport {env} from '../environment';\nimport {getBackend} from '../globals';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n *   - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n *     concatenated.\n *   - An `Array` of `WeightManifestEntry`s, carrying information including\n *     tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n    tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n    Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n  // TODO(adarob, cais): Support quantization.\n  const specs: WeightsManifestEntry[] = [];\n  const dataPromises: Array<Promise<TypedArray>> = [];\n\n  const names: string[] = Array.isArray(tensors) ?\n      tensors.map(tensor => tensor.name) :\n      Object.keys(tensors);\n\n  for (let i = 0; i < names.length; ++i) {\n    const name = names[i];\n    const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name];\n    if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool' &&\n        t.dtype !== 'string' && t.dtype !== 'complex64') {\n      throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`);\n    }\n    const spec: WeightsManifestEntry = {name, shape: t.shape, dtype: t.dtype};\n    if (t.dtype === 'string') {\n      const utf8bytes = new Promise<TypedArray>(async resolve => {\n        const vals = await t.bytes() as Uint8Array[];\n        const totalNumBytes = vals.reduce((p, c) => p + c.length, 0) +\n            NUM_BYTES_STRING_LENGTH * vals.length;\n        const bytes = new Uint8Array(totalNumBytes);\n        let offset = 0;\n        for (let i = 0; i < vals.length; i++) {\n          const val = vals[i];\n          const bytesOfLength =\n              new Uint8Array(new Uint32Array([val.length]).buffer);\n          bytes.set(bytesOfLength, offset);\n          offset += NUM_BYTES_STRING_LENGTH;\n          bytes.set(val, offset);\n          offset += val.length;\n        }\n        resolve(bytes);\n      });\n      dataPromises.push(utf8bytes);\n    } else {\n      dataPromises.push(t.data());\n    }\n    if (group != null) {\n      spec.group = group;\n    }\n    specs.push(spec);\n  }\n\n  const tensorValues = await Promise.all(dataPromises);\n  return {data: concatenateTypedArrays(tensorValues), specs};\n}\n\n/**\n * Decode flat ArrayBuffer as weights.\n *\n * This function does not handle sharding.\n *\n * This function is the reverse of `encodeWeights`.\n *\n * @param weightData A flat ArrayBuffer or an array of ArrayBuffers carrying the\n *   binary values of the tensors concatenated in the order specified in\n *   `specs`.\n * @param specs Specifications of the names, dtypes and shapes of the tensors\n *   whose value are encoded by `buffer`.\n * @return A map from tensor name to tensor value, with the names corresponding\n *   to names in `specs`.\n * @throws Error, if any of the tensors has unsupported dtype.\n */\nexport function decodeWeights(\n    weightData: WeightData,\n    specs: WeightsManifestEntry[]): NamedTensorMap {\n  // TODO(adarob, cais): Support quantization.\n  const compositeBuffer = new CompositeArrayBuffer(weightData);\n  const out: NamedTensorMap = {};\n  let offset = 0;\n  for (const spec of specs) {\n    const byteLength = getWeightBytelength(spec, (start, end) => {\n      return compositeBuffer.slice(offset + start, offset + end);\n    });\n    out[spec.name] = decodeWeight(spec, compositeBuffer\n      .slice(offset, offset + byteLength));\n    offset += byteLength;\n  }\n  return out;\n}\n\nfunction getWeightBytelength(spec: WeightsManifestEntry,\n  slice: (start: number, end: number) => ArrayBuffer): number {\n\n  const size = sizeFromShape(spec.shape);\n  let bytesPerValue: number;\n  if ('quantization' in spec) {\n    const quantization = spec.quantization;\n    bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n  } else if (spec.dtype === 'string') {\n    // Can not statically determine string length.\n    let byteLength = 0;\n    for (let i = 0; i < size; i++) {\n      byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(\n        slice(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];\n    }\n    return byteLength;\n  } else {\n    bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];\n  }\n\n  return size * bytesPerValue;\n}\n\nasync function getWeightBytelengthAsync(\n  spec: WeightsManifestEntry,\n  slice: (start: number, end: number) => Promise<ArrayBuffer>\n): Promise<number> {\n\n  const size = sizeFromShape(spec.shape);\n  let bytesPerValue: number;\n  if ('quantization' in spec) {\n    const quantization = spec.quantization;\n    bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n  } else if (spec.dtype === 'string') {\n    // Can not statically determine string length.\n    let byteLength = 0;\n    for (let i = 0; i < size; i++) {\n      byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(\n        await slice(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];\n    }\n    return byteLength;\n  } else {\n    bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];\n  }\n\n  return size * bytesPerValue;\n}\n\nfunction decodeWeight(\n  spec: WeightsManifestEntry,\n  byteBuffer: ArrayBuffer): Tensor {\n\n  const name = spec.name;\n  const dtype = spec.dtype;\n  const shape = spec.shape;\n  const size = sizeFromShape(shape);\n  let values: TypedArray | string[] | Uint8Array[];\n  let offset = 0;\n\n  if ('quantization' in spec) {\n    const quantization = spec.quantization;\n    if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n      if (!('min' in quantization && 'scale' in quantization)) {\n        throw new Error(\n            `Weight ${spec.name} with quantization ${quantization.dtype} ` +\n            `doesn't have corresponding metadata min and scale.`);\n      }\n    } else if (quantization.dtype === 'float16') {\n      if (dtype !== 'float32') {\n        throw new Error(\n            `Weight ${spec.name} is quantized with ${quantization.dtype} ` +\n            `which only supports weights of type float32 not ${dtype}.`);\n      }\n    } else {\n      throw new Error(\n          `Weight ${spec.name} has unknown ` +\n          `quantization dtype ${quantization.dtype}. ` +\n          `Supported quantization dtypes are: ` +\n          `'uint8', 'uint16', and 'float16'.`);\n    }\n    const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n    const quantizedArray = (quantization.dtype === 'uint8') ?\n      new Uint8Array(byteBuffer) :\n      new Uint16Array(byteBuffer);\n    if (dtype === 'float32') {\n      if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n        values = new Float32Array(quantizedArray.length);\n        for (let i = 0; i < quantizedArray.length; i++) {\n          const v = quantizedArray[i];\n          values[i] = v * quantization.scale + quantization.min;\n        }\n      } else if (quantization.dtype === 'float16') {\n        // TODO: This is inefficient. Make getFloat16Decoder efficient.\n        const float16Decode = getFloat16Decoder();\n        values = float16Decode(quantizedArray as Uint16Array);\n      } else {\n        throw new Error(\n          `Unsupported quantization type ${quantization.dtype} ` +\n          `for weight type float32.`);\n      }\n    } else if (dtype === 'int32') {\n      if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {\n        throw new Error(\n          `Unsupported quantization type ${quantization.dtype} ` +\n          `for weight type int32.`);\n      }\n      values = new Int32Array(quantizedArray.length);\n      for (let i = 0; i < quantizedArray.length; i++) {\n        const v = quantizedArray[i];\n        values[i] = Math.round(v * quantization.scale + quantization.min);\n      }\n    } else {\n      throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n    }\n    offset += size * quantizationSizeFactor;\n  } else if (dtype === 'string') {\n    const size = sizeFromShape(spec.shape);\n    values = [];\n    for (let i = 0; i < size; i++) {\n      const byteLength = new Uint32Array(\n        byteBuffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n      offset += NUM_BYTES_STRING_LENGTH;\n      const bytes = new Uint8Array(\n        byteBuffer.slice(offset, offset + byteLength));\n      (values as Uint8Array[]).push(bytes);\n      offset += byteLength;\n    }\n  } else {\n    const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];\n    if (dtype === 'float32') {\n      values = new Float32Array(byteBuffer);\n    } else if (dtype === 'int32') {\n      values = new Int32Array(byteBuffer);\n    } else if (dtype === 'bool') {\n      values = new Uint8Array(byteBuffer);\n    } else if (dtype === 'complex64') {\n      values = new Float32Array(byteBuffer);\n      const real = new Float32Array(values.length / 2);\n      const image = new Float32Array(values.length / 2);\n      for (let i = 0; i < real.length; i++) {\n        real[i] = values[i * 2];\n        image[i] = values[i * 2 + 1];\n      }\n      const realTensor = tensor(real, shape, 'float32');\n      const imageTensor = tensor(image, shape, 'float32');\n      const complexTensor = complex(realTensor, imageTensor);\n      realTensor.dispose();\n      imageTensor.dispose();\n      return complexTensor;\n    } else {\n      throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n    }\n    offset += size * dtypeFactor;\n  }\n  return tensor(values, shape, dtype);\n}\n\nasync function readToLength(reader: ReadableStreamDefaultReader<ArrayBuffer>,\n                            initialData: ArrayBuffer,\n                            length: number): Promise<ArrayBuffer> {\n  let data = new Uint8Array(initialData);\n\n  while (data.byteLength < length) {\n    const {done, value} = await reader.read();\n    if (done && value == null) {\n      const missing  = length - data.byteLength;\n      throw new Error(`Reader is done but ${missing} bytes are still expected`);\n    }\n\n    // TODO: Don't create a new array every loop.\n    const newData = new Uint8Array(data.length + value.byteLength);\n    newData.set(data, 0);\n    newData.set(new Uint8Array(value), data.length);\n    data = newData;\n  }\n\n  return data.buffer;\n}\n\nexport async function decodeWeightsStream(\n  weightStream: ReadableStream<ArrayBuffer>,\n  specs: WeightsManifestEntry[]): Promise<NamedTensorMap> {\n\n  const tensors: NamedTensorMap = {};\n  const reader = weightStream.getReader();\n  let data = new ArrayBuffer(0);\n\n  for (const spec of specs) {\n    const byteLength = await getWeightBytelengthAsync(spec,\n                                                      async (start, end) => {\n      data = await readToLength(reader, data, end);\n      return data.slice(start, end);\n    });\n    data = await readToLength(reader, data, byteLength);\n\n    // Slice the tensor out\n    const tensorData = data.slice(0, byteLength);\n    data = data.slice(byteLength);\n\n    const weightTensor = decodeWeight(spec, tensorData);\n    tensors[spec.name] = weightTensor;\n\n    // TODO(mattsoulanille): Better way to call uploadToGPU.\n    // TODO(mattsoulanille): Make this work for webgl too.\n    if (getBackend() === 'webgpu') {\n      const b = backend();\n\n      if ('uploadToGPU' in b &&\n        sizeFromShape(weightTensor.shape) >= (env()\n          .get('WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD') as number)) {\n        (b.uploadToGPU as (dataId: DataId) => void)(weightTensor.dataId);\n      }\n    }\n  }\n\n  return tensors;\n}\n\n/**\n * Concatenate TypedArrays into an ArrayBuffer.\n */\nexport function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {\n  // TODO(adarob, cais): Support quantization.\n  if (xs === null) {\n    throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);\n  }\n\n  let totalByteLength = 0;\n\n  // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'\n  // can have a different byte length from that of the `TypedArray` itself,\n  // for example, when the `TypedArray` is created from an offset in an\n  // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match\n  // the `TypedArray` in byte length. If an element of `xs` does not show\n  // this property, a new `TypedArray` that satisfy this property will be\n  // constructed and pushed into `normalizedXs`.\n  const normalizedXs: TypedArray[] = [];\n  xs.forEach((x: TypedArray) => {\n    totalByteLength += x.byteLength;\n    // tslint:disable:no-any\n    normalizedXs.push(\n        x.byteLength === x.buffer.byteLength ? x :\n                                               new (x.constructor as any)(x));\n    if (!(x as any instanceof Float32Array || x as any instanceof Int32Array ||\n          x as any instanceof Uint8Array)) {\n      throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);\n    }\n    // tslint:enable:no-any\n  });\n\n  const y = new Uint8Array(totalByteLength);\n  let offset = 0;\n  normalizedXs.forEach((x: TypedArray) => {\n    y.set(new Uint8Array(x.buffer), offset);\n    offset += x.byteLength;\n  });\n\n  return y.buffer;\n}\n\n// Use Buffer on Node.js instead of Blob/atob/btoa\nconst useNodeBuffer = typeof Buffer !== 'undefined' &&\n    (typeof Blob === 'undefined' || typeof atob === 'undefined' ||\n     typeof btoa === 'undefined');\n\n/**\n * Calculate the byte length of a JavaScript string.\n *\n * Note that a JavaScript string can contain wide characters, therefore the\n * length of the string is not necessarily equal to the byte length.\n *\n * @param str Input string.\n * @returns Byte length.\n */\nexport function stringByteLength(str: string): number {\n  if (useNodeBuffer) {\n    return Buffer.byteLength(str, 'utf8');\n  }\n  return new Blob([str]).size;\n}\n\n/**\n * Encode an ArrayBuffer as a base64 encoded string.\n *\n * @param buffer `ArrayBuffer` to be converted.\n * @returns A string that base64-encodes `buffer`.\n */\nexport function arrayBufferToBase64String(buffer: ArrayBuffer): string {\n  if (useNodeBuffer) {\n    return Buffer.from(buffer).toString('base64');\n  }\n  const buf = new Uint8Array(buffer);\n  let s = '';\n  for (let i = 0, l = buf.length; i < l; i++) {\n    s += String.fromCharCode(buf[i]);\n  }\n  return btoa(s);\n}\n\n/**\n * Decode a base64 string as an ArrayBuffer.\n *\n * @param str Base64 string.\n * @returns Decoded `ArrayBuffer`.\n */\nexport function base64StringToArrayBuffer(str: string): ArrayBuffer {\n  if (useNodeBuffer) {\n    const buf = Buffer.from(str, 'base64');\n    return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n  }\n  const s = atob(str);\n  const buffer = new Uint8Array(s.length);\n  for (let i = 0; i < s.length; ++i) {\n    buffer.set([s.charCodeAt(i)], i);\n  }\n  return buffer.buffer;\n}\n\n/**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers An array of ArrayBuffers to concatenate, or a single\n *     ArrayBuffer.\n * @returns Result of concatenating `buffers` in order.\n *\n * @deprecated Use tf.io.CompositeArrayBuffer.join() instead.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]\n      | ArrayBuffer): ArrayBuffer {\n  return CompositeArrayBuffer.join(buffers);\n}\n\n/**\n * Get the basename of a path.\n *\n * Behaves in a way analogous to Linux's basename command.\n *\n * @param path\n */\nexport function basename(path: string): string {\n  const SEPARATOR = '/';\n  path = path.trim();\n  while (path.endsWith(SEPARATOR)) {\n    path = path.slice(0, path.length - 1);\n  }\n  const items = path.split(SEPARATOR);\n  return items[items.length - 1];\n}\n\n/**\n * Create `ModelJSON` from `ModelArtifacts`.\n *\n * @param artifacts Model artifacts, describing the model and its weights.\n * @param manifest Weight manifest, describing where the weights of the\n *     `ModelArtifacts` are stored, and some metadata about them.\n * @returns Object representing the `model.json` file describing the model\n *     artifacts and weights\n */\nexport function getModelJSONForModelArtifacts(\n    artifacts: ModelArtifacts, manifest: WeightsManifestConfig): ModelJSON {\n  const result: ModelJSON = {\n    modelTopology: artifacts.modelTopology,\n    format: artifacts.format,\n    generatedBy: artifacts.generatedBy,\n    convertedBy: artifacts.convertedBy,\n    weightsManifest: manifest\n  };\n  if (artifacts.signature != null) {\n    result.signature = artifacts.signature;\n  }\n  if (artifacts.userDefinedMetadata != null) {\n    result.userDefinedMetadata = artifacts.userDefinedMetadata;\n  }\n  if (artifacts.modelInitializer != null) {\n    result.modelInitializer = artifacts.modelInitializer;\n  }\n  if (artifacts.initializerSignature != null) {\n    result.initializerSignature = artifacts.initializerSignature;\n  }\n  if (artifacts.trainingConfig != null) {\n    result.trainingConfig = artifacts.trainingConfig;\n  }\n  return result;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file and weights.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param weightSpecs The list of WeightsManifestEntry for the model. Must be\n *     passed if the modelJSON has a weightsManifest.\n * @param weightData An ArrayBuffer or array of ArrayBuffers of weight data for\n *     the model corresponding to the weights in weightSpecs. Must be passed if\n *     the modelJSON has a weightsManifest.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport function getModelArtifactsForJSONSync(\n    modelJSON: ModelJSON, weightSpecs?: WeightsManifestEntry[],\n    weightData?: WeightData): ModelArtifacts {\n\n  const modelArtifacts: ModelArtifacts = {\n    modelTopology: modelJSON.modelTopology,\n    format: modelJSON.format,\n    generatedBy: modelJSON.generatedBy,\n    convertedBy: modelJSON.convertedBy\n  };\n\n  if (modelJSON.trainingConfig != null) {\n    modelArtifacts.trainingConfig = modelJSON.trainingConfig;\n  }\n  if (modelJSON.weightsManifest != null) {\n    if (!weightSpecs) {\n      throw new Error('modelJSON has weightsManifest but weightSpecs is null');\n    }\n    if (!weightData) {\n      throw new Error('modelJSON has weightsManifest but weightData is null');\n    }\n    modelArtifacts.weightSpecs = weightSpecs;\n    modelArtifacts.weightData = weightData;\n  }\n  if (modelJSON.signature != null) {\n    modelArtifacts.signature = modelJSON.signature;\n  }\n  if (modelJSON.userDefinedMetadata != null) {\n    modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;\n  }\n  if (modelJSON.modelInitializer != null) {\n    modelArtifacts.modelInitializer = modelJSON.modelInitializer;\n  }\n  if (modelJSON.initializerSignature != null) {\n    modelArtifacts.initializerSignature = modelJSON.initializerSignature;\n  }\n\n  return modelArtifacts;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param loadWeights Function that takes the JSON file's weights manifest,\n *     reads weights from the listed path(s), and returns a Promise of the\n *     weight manifest entries along with the weights data.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport async function getModelArtifactsForJSON(\n    modelJSON: ModelJSON,\n    loadWeights: (weightsManifest: WeightsManifestConfig) => Promise<[\n      /* weightSpecs */ WeightsManifestEntry[], WeightData,\n    ]>): Promise<ModelArtifacts> {\n  let weightSpecs: WeightsManifestEntry[] | undefined;\n  let weightData: WeightData | undefined;\n\n  if (modelJSON.weightsManifest != null) {\n    [weightSpecs, weightData] = await loadWeights(modelJSON.weightsManifest);\n  }\n\n  return getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData);\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n    ModelArtifactsInfo {\n  if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n    throw new Error('Expected JSON model topology, received ArrayBuffer.');\n  }\n\n  return {\n    dateSaved: new Date(),\n    modelTopologyType: 'JSON',\n    modelTopologyBytes: modelArtifacts.modelTopology == null ?\n        0 :\n        stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n    weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n        0 :\n        stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n    weightDataBytes: modelArtifacts.weightData == null ?\n        0 :\n        new CompositeArrayBuffer(modelArtifacts.weightData).byteLength,\n  };\n}\n\n/**\n * Concatenate the weights stored in a WeightsManifestConfig into a list of\n * WeightsManifestEntry\n *\n * @param weightsManifest The WeightsManifestConfig to extract weights from.\n * @returns A list of WeightsManifestEntry of the weights in the weightsManifest\n */\nexport function getWeightSpecs(weightsManifest: WeightsManifestConfig):\n    WeightsManifestEntry[] {\n  const weightSpecs: WeightsManifestEntry[] = [];\n  for (const entry of weightsManifest) {\n    weightSpecs.push(...entry.weights);\n  }\n  return weightSpecs;\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n  const convertMantissa = (i: number): number => {\n    let m = i << 13;\n    let e = 0;\n\n    while ((m & 0x00800000) === 0) {\n      e -= 0x00800000;\n      m <<= 1;\n    }\n    m &= ~0x00800000;\n    e += 0x38800000;\n\n    return m | e;\n  };\n\n  const mantisaTable = new Uint32Array(2048);\n\n  mantisaTable[0] = 0;\n  for (let i = 1; i < 1024; i++) {\n    mantisaTable[i] = convertMantissa(i);\n  }\n  for (let i = 1024; i < 2048; i++) {\n    mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n  }\n\n  return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n  const exponentTable = new Uint32Array(64);\n\n  exponentTable[0] = 0;\n  exponentTable[31] = 0x47800000;\n  exponentTable[32] = 0x80000000;\n  exponentTable[63] = 0xc7800000;\n  for (let i = 1; i < 31; i++) {\n    exponentTable[i] = i << 23;\n  }\n  for (let i = 33; i < 63; i++) {\n    exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n  }\n\n  return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n  const offsetTable = new Uint32Array(64);\n\n  for (let i = 0; i < 64; i++) {\n    offsetTable[i] = 1024;\n  }\n  offsetTable[0] = offsetTable[32] = 0;\n\n  return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n *          the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n  // Algorithm is based off of\n  // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n  // Cache lookup tables\n  const mantisaTable = computeFloat16MantisaTable();\n  const exponentTable = computeFloat16ExponentTable();\n  const offsetTable = computeFloat16OffsetTable();\n\n  return (quantizedArray: Uint16Array) => {\n    const buffer = new ArrayBuffer(4 * quantizedArray.length);\n    const bufferUint32View = new Uint32Array(buffer);\n    for (let index = 0; index < quantizedArray.length; index++) {\n      const float16Bits = quantizedArray[index];\n      const float32Bits =\n          mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n          exponentTable[float16Bits >> 10];\n      bufferUint32View[index] = float32Bits;\n    }\n    return new Float32Array(buffer);\n  };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IOHandler, LoadOptions} from './types';\n\nexport type IORouter = (url: string|string[], loadOptions?: LoadOptions) =>\n    IOHandler;\n\nexport class IORouterRegistry {\n  // Singleton instance.\n  private static instance: IORouterRegistry;\n\n  private saveRouters: IORouter[];\n  private loadRouters: IORouter[];\n\n  private constructor() {\n    this.saveRouters = [];\n    this.loadRouters = [];\n  }\n\n  private static getInstance(): IORouterRegistry {\n    if (IORouterRegistry.instance == null) {\n      IORouterRegistry.instance = new IORouterRegistry();\n    }\n    return IORouterRegistry.instance;\n  }\n\n  /**\n   * Register a save-handler router.\n   *\n   * @param saveRouter A function that maps a URL-like string onto an instance\n   * of `IOHandler` with the `save` method defined or `null`.\n   */\n  static registerSaveRouter(saveRouter: IORouter) {\n    IORouterRegistry.getInstance().saveRouters.push(saveRouter);\n  }\n\n  /**\n   * Register a load-handler router.\n   *\n   * @param loadRouter A function that maps a URL-like string onto an instance\n   * of `IOHandler` with the `load` method defined or `null`.\n   */\n  static registerLoadRouter(loadRouter: IORouter) {\n    IORouterRegistry.getInstance().loadRouters.push(loadRouter);\n  }\n\n  /**\n   * Look up IOHandler for saving, given a URL-like string.\n   *\n   * @param url\n   * @returns If only one match is found, an instance of IOHandler with the\n   * `save` method defined. If no match is found, `null`.\n   * @throws Error, if more than one match is found.\n   */\n  static getSaveHandlers(url: string|string[]): IOHandler[] {\n    return IORouterRegistry.getHandlers(url, 'save');\n  }\n\n  /**\n   * Look up IOHandler for loading, given a URL-like string.\n   *\n   * @param url\n   * @param loadOptions Optional, custom load options.\n   * @returns All valid handlers for `url`, given the currently registered\n   *   handler routers.\n   */\n  static getLoadHandlers(url: string|string[], loadOptions?: LoadOptions):\n      IOHandler[] {\n    return IORouterRegistry.getHandlers(url, 'load', loadOptions);\n  }\n\n  private static getHandlers(\n      url: string|string[], handlerType: 'save'|'load',\n      loadOptions?: LoadOptions): IOHandler[] {\n    const validHandlers: IOHandler[] = [];\n    const routers = handlerType === 'load' ?\n        IORouterRegistry.getInstance().loadRouters :\n        IORouterRegistry.getInstance().saveRouters;\n    routers.forEach(router => {\n      const handler = router(url, loadOptions);\n      if (handler !== null) {\n        validHandlers.push(handler);\n      }\n    });\n    return validHandlers;\n  }\n}\n\nexport const registerSaveRouter = (loudRouter: IORouter) =>\n    IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter: IORouter) =>\n    IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url: string|string[]) =>\n    IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers =\n    (url: string|string[], loadOptions?: LoadOptions) =>\n        IORouterRegistry.getLoadHandlers(url, loadOptions);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\n\nimport {getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\n\nconst DATABASE_NAME = 'tensorflowjs';\nconst DATABASE_VERSION = 1;\n\n// Model data and ModelArtifactsInfo (metadata) are stored in two separate\n// stores for efficient access of the list of stored models and their metadata.\n// 1. The object store for model data: topology, weights and weight manifests.\nconst MODEL_STORE_NAME = 'models_store';\n// 2. The object store for ModelArtifactsInfo, including meta-information such\n//    as the type of topology (JSON vs binary), byte size of the topology, byte\n//    size of the weights, etc.\nconst INFO_STORE_NAME = 'model_info_store';\n\n/**\n * Delete the entire database for tensorflow.js, including the models store.\n */\nexport async function deleteDatabase(): Promise<void> {\n  const idbFactory = getIndexedDBFactory();\n\n  return new Promise<void>((resolve, reject) => {\n    const deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);\n    deleteRequest.onsuccess = () => resolve();\n    deleteRequest.onerror = error => reject(error);\n  });\n}\n\nfunction getIndexedDBFactory(): IDBFactory {\n  if (!env().getBool('IS_BROWSER')) {\n    // TODO(cais): Add more info about what IOHandler subtypes are available.\n    //   Maybe point to a doc page on the web and/or automatically determine\n    //   the available IOHandlers and print them in the error message.\n    throw new Error(\n        'Failed to obtain IndexedDB factory because the current environment' +\n        'is not a web browser.');\n  }\n  // tslint:disable-next-line:no-any\n  const theWindow: any = typeof window === 'undefined' ? self : window;\n  const factory = theWindow.indexedDB || theWindow.mozIndexedDB ||\n      theWindow.webkitIndexedDB || theWindow.msIndexedDB ||\n      theWindow.shimIndexedDB;\n  if (factory == null) {\n    throw new Error(\n        'The current browser does not appear to support IndexedDB.');\n  }\n  return factory;\n}\n\nfunction setUpDatabase(openRequest: IDBRequest) {\n  const db = openRequest.result as IDBDatabase;\n  db.createObjectStore(MODEL_STORE_NAME, {keyPath: 'modelPath'});\n  db.createObjectStore(INFO_STORE_NAME, {keyPath: 'modelPath'});\n}\n\n/**\n * IOHandler subclass: Browser IndexedDB.\n *\n * See the doc string of `browserIndexedDB` for more details.\n */\nexport class BrowserIndexedDB implements IOHandler {\n  protected readonly indexedDB: IDBFactory;\n  protected readonly modelPath: string;\n\n  static readonly URL_SCHEME = 'indexeddb://';\n\n  constructor(modelPath: string) {\n    this.indexedDB = getIndexedDBFactory();\n\n    if (modelPath == null || !modelPath) {\n      throw new Error(\n          'For IndexedDB, modelPath must not be null, undefined or empty.');\n    }\n    this.modelPath = modelPath;\n  }\n\n  async save(modelArtifacts: ModelArtifacts): Promise<SaveResult> {\n    // TODO(cais): Support saving GraphDef models.\n    if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n      throw new Error(\n          'BrowserLocalStorage.save() does not support saving model topology ' +\n          'in binary formats yet.');\n    }\n\n    return this.databaseAction(this.modelPath, modelArtifacts) as\n        Promise<SaveResult>;\n  }\n\n  async load(): Promise<ModelArtifacts> {\n    return this.databaseAction(this.modelPath) as Promise<ModelArtifacts>;\n  }\n\n  /**\n   * Perform database action to put model artifacts into or read model artifacts\n   * from IndexedDB object store.\n   *\n   * Whether the action is put or get depends on whether `modelArtifacts` is\n   * specified. If it is specified, the action will be put; otherwise the action\n   * will be get.\n   *\n   * @param modelPath A unique string path for the model.\n   * @param modelArtifacts If specified, it will be the model artifacts to be\n   *   stored in IndexedDB.\n   * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`\n   *   of `ModelArtifacts`, if the action is get.\n   */\n  private databaseAction(modelPath: string, modelArtifacts?: ModelArtifacts):\n      Promise<ModelArtifacts|SaveResult> {\n    return new Promise<ModelArtifacts|SaveResult>((resolve, reject) => {\n      const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n      openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n      openRequest.onsuccess = () => {\n        const db = openRequest.result;\n\n        if (modelArtifacts == null) {\n          // Read model out from object store.\n          const modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');\n          const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n          const getRequest = modelStore.get(this.modelPath);\n          getRequest.onsuccess = () => {\n            if (getRequest.result == null) {\n              db.close();\n              return reject(new Error(\n                  `Cannot find model with path '${this.modelPath}' ` +\n                  `in IndexedDB.`));\n            } else {\n              resolve(getRequest.result.modelArtifacts);\n            }\n          };\n          getRequest.onerror = error => {\n            db.close();\n            return reject(getRequest.error);\n          };\n          modelTx.oncomplete = () => db.close();\n        } else {\n          // Put model into object store.\n\n          // Concatenate all the model weights into a single ArrayBuffer. Large\n          // models (~1GB) have problems saving if they are not concatenated.\n          // TODO(mattSoulanille): Save large models to multiple indexeddb\n          // records.\n          modelArtifacts.weightData = CompositeArrayBuffer.join(\n              modelArtifacts.weightData);\n          const modelArtifactsInfo: ModelArtifactsInfo =\n              getModelArtifactsInfoForJSON(modelArtifacts);\n          // First, put ModelArtifactsInfo into info store.\n          const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n          let infoStore = infoTx.objectStore(INFO_STORE_NAME);\n          let putInfoRequest: IDBRequest<IDBValidKey>;\n          try {\n            putInfoRequest =\n              infoStore.put({modelPath: this.modelPath, modelArtifactsInfo});\n          } catch (error) {\n            return reject(error);\n          }\n          let modelTx: IDBTransaction;\n          putInfoRequest.onsuccess = () => {\n            // Second, put model data into model store.\n            modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n            const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n            let putModelRequest: IDBRequest<IDBValidKey>;\n            try {\n              putModelRequest = modelStore.put({\n                modelPath: this.modelPath,\n                modelArtifacts,\n                modelArtifactsInfo\n              });\n            } catch (error) {\n              // Sometimes, the serialized value is too large to store.\n              return reject(error);\n            }\n            putModelRequest.onsuccess = () => resolve({modelArtifactsInfo});\n            putModelRequest.onerror = error => {\n              // If the put-model request fails, roll back the info entry as\n              // well.\n              infoStore = infoTx.objectStore(INFO_STORE_NAME);\n              const deleteInfoRequest = infoStore.delete(this.modelPath);\n              deleteInfoRequest.onsuccess = () => {\n                db.close();\n                return reject(putModelRequest.error);\n              };\n              deleteInfoRequest.onerror = error => {\n                db.close();\n                return reject(putModelRequest.error);\n              };\n            };\n          };\n          putInfoRequest.onerror = error => {\n            db.close();\n            return reject(putInfoRequest.error);\n          };\n          infoTx.oncomplete = () => {\n            if (modelTx == null) {\n              db.close();\n            } else {\n              modelTx.oncomplete = () => db.close();\n            }\n          };\n        }\n      };\n      openRequest.onerror = error => reject(openRequest.error);\n    });\n  }\n}\n\nexport const indexedDBRouter: IORouter = (url: string|string[]) => {\n  if (!env().getBool('IS_BROWSER')) {\n    return null;\n  } else {\n    if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {\n      return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));\n    } else {\n      return null;\n    }\n  }\n};\nIORouterRegistry.registerSaveRouter(indexedDBRouter);\nIORouterRegistry.registerLoadRouter(indexedDBRouter);\n\n/**\n * Creates a browser IndexedDB IOHandler for saving and loading models.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n *     tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save('indexeddb://MyModel'));\n * console.log(saveResult);\n * ```\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n *   non-empty string.\n * @returns An instance of `BrowserIndexedDB` (subclass of `IOHandler`),\n *   which can be used with, e.g., `tf.Model.save`.\n */\nexport function browserIndexedDB(modelPath: string): IOHandler {\n  return new BrowserIndexedDB(modelPath);\n}\n\nfunction maybeStripScheme(key: string) {\n  return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?\n      key.slice(BrowserIndexedDB.URL_SCHEME.length) :\n      key;\n}\n\nexport class BrowserIndexedDBManager implements ModelStoreManager {\n  private indexedDB: IDBFactory;\n\n  constructor() {\n    this.indexedDB = getIndexedDBFactory();\n  }\n\n  async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n    return new Promise<{[path: string]: ModelArtifactsInfo}>(\n        (resolve, reject) => {\n          const openRequest =\n              this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n          openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n          openRequest.onsuccess = () => {\n            const db = openRequest.result;\n            const tx = db.transaction(INFO_STORE_NAME, 'readonly');\n            const store = tx.objectStore(INFO_STORE_NAME);\n            // tslint:disable:max-line-length\n            // Need to cast `store` as `any` here because TypeScript's DOM\n            // library does not have the `getAll()` method even though the\n            // method is supported in the latest version of most mainstream\n            // browsers:\n            // https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll\n            // tslint:enable:max-line-length\n            // tslint:disable-next-line:no-any\n            const getAllInfoRequest = (store as any).getAll() as IDBRequest;\n            getAllInfoRequest.onsuccess = () => {\n              const out: {[path: string]: ModelArtifactsInfo} = {};\n              for (const item of getAllInfoRequest.result) {\n                out[item.modelPath] = item.modelArtifactsInfo;\n              }\n              resolve(out);\n            };\n            getAllInfoRequest.onerror = error => {\n              db.close();\n              return reject(getAllInfoRequest.error);\n            };\n            tx.oncomplete = () => db.close();\n          };\n          openRequest.onerror = error => reject(openRequest.error);\n        });\n  }\n\n  async removeModel(path: string): Promise<ModelArtifactsInfo> {\n    path = maybeStripScheme(path);\n    return new Promise<ModelArtifactsInfo>((resolve, reject) => {\n      const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n      openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n      openRequest.onsuccess = () => {\n        const db = openRequest.result;\n        const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n        const infoStore = infoTx.objectStore(INFO_STORE_NAME);\n\n        const getInfoRequest = infoStore.get(path);\n        let modelTx: IDBTransaction;\n        getInfoRequest.onsuccess = () => {\n          if (getInfoRequest.result == null) {\n            db.close();\n            return reject(new Error(\n                `Cannot find model with path '${path}' ` +\n                `in IndexedDB.`));\n          } else {\n            // First, delete the entry in the info store.\n            const deleteInfoRequest = infoStore.delete(path);\n            const deleteModelData = () => {\n              // Second, delete the entry in the model store.\n              modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n              const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n              const deleteModelRequest = modelStore.delete(path);\n              deleteModelRequest.onsuccess = () =>\n                  resolve(getInfoRequest.result.modelArtifactsInfo);\n              deleteModelRequest.onerror = error =>\n                  reject(getInfoRequest.error);\n            };\n            // Proceed with deleting model data regardless of whether deletion\n            // of info data succeeds or not.\n            deleteInfoRequest.onsuccess = deleteModelData;\n            deleteInfoRequest.onerror = error => {\n              deleteModelData();\n              db.close();\n              return reject(getInfoRequest.error);\n            };\n          }\n        };\n        getInfoRequest.onerror = error => {\n          db.close();\n          return reject(getInfoRequest.error);\n        };\n\n        infoTx.oncomplete = () => {\n          if (modelTx == null) {\n            db.close();\n          } else {\n            modelTx.oncomplete = () => db.close();\n          }\n        };\n      };\n      openRequest.onerror = error => reject(openRequest.error);\n    });\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {arrayBufferToBase64String, base64StringToArrayBuffer, getModelArtifactsInfoForJSON} from './io_utils';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, SaveResult} from './types';\n\nconst PATH_SEPARATOR = '/';\nconst PATH_PREFIX = 'tensorflowjs_models';\nconst INFO_SUFFIX = 'info';\nconst MODEL_TOPOLOGY_SUFFIX = 'model_topology';\nconst WEIGHT_SPECS_SUFFIX = 'weight_specs';\nconst WEIGHT_DATA_SUFFIX = 'weight_data';\nconst MODEL_METADATA_SUFFIX = 'model_metadata';\n\n/**\n * Purge all tensorflow.js-saved model artifacts from local storage.\n *\n * @returns Paths of the models purged.\n */\nexport function purgeLocalStorageArtifacts(): string[] {\n  if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n      typeof window.localStorage === 'undefined') {\n    throw new Error(\n        'purgeLocalStorageModels() cannot proceed because local storage is ' +\n        'unavailable in the current environment.');\n  }\n  const LS = window.localStorage;\n  const purgedModelPaths: string[] = [];\n  for (let i = 0; i < LS.length; ++i) {\n    const key = LS.key(i);\n    const prefix = PATH_PREFIX + PATH_SEPARATOR;\n    if (key.startsWith(prefix) && key.length > prefix.length) {\n      LS.removeItem(key);\n      const modelName = getModelPathFromKey(key);\n      if (purgedModelPaths.indexOf(modelName) === -1) {\n        purgedModelPaths.push(modelName);\n      }\n    }\n  }\n  return purgedModelPaths;\n}\n\ntype LocalStorageKeys = {\n  /** Key of the localStorage entry storing `ModelArtifactsInfo`. */\n  info: string,\n  /**\n   * Key of the localStorage entry storing the 'modelTopology' key of\n   * `model.json`\n   */\n  topology: string,\n  /**\n   * Key of the localStorage entry storing the `weightsManifest.weights` entries\n   * of `model.json`\n   */\n  weightSpecs: string,\n  /** Key of the localStorage entry storing the weight data in Base64 */\n  weightData: string,\n  /**\n   * Key of the localStorage entry storing the remaining fields of `model.json`\n   * @see {@link ModelMetadata}\n   */\n  modelMetadata: string,\n};\n\ntype ModelMetadata = Omit<ModelJSON, 'modelTopology'|'weightsManifest'>;\n\nfunction getModelKeys(path: string): LocalStorageKeys {\n  return {\n    info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),\n    topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),\n    weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),\n    weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),\n    modelMetadata:\n        [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)\n  };\n}\n\nfunction removeItems(keys: LocalStorageKeys): void {\n  for (const key of Object.values(keys)) {\n    window.localStorage.removeItem(key);\n  }\n}\n\n/**\n * Get model path from a local-storage key.\n *\n * E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'\n *\n * @param key\n */\nfunction getModelPathFromKey(key: string) {\n  const items = key.split(PATH_SEPARATOR);\n  if (items.length < 3) {\n    throw new Error(`Invalid key format: ${key}`);\n  }\n  return items.slice(1, items.length - 1).join(PATH_SEPARATOR);\n}\n\nfunction maybeStripScheme(key: string) {\n  return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?\n      key.slice(BrowserLocalStorage.URL_SCHEME.length) :\n      key;\n}\n\n/**\n * IOHandler subclass: Browser Local Storage.\n *\n * See the doc string to `browserLocalStorage` for more details.\n */\nexport class BrowserLocalStorage implements IOHandler {\n  protected readonly LS: Storage;\n  protected readonly modelPath: string;\n  protected readonly keys: LocalStorageKeys;\n\n  static readonly URL_SCHEME = 'localstorage://';\n\n  constructor(modelPath: string) {\n    if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n        typeof window.localStorage === 'undefined') {\n      // TODO(cais): Add more info about what IOHandler subtypes are\n      // available.\n      //   Maybe point to a doc page on the web and/or automatically determine\n      //   the available IOHandlers and print them in the error message.\n      throw new Error(\n          'The current environment does not support local storage.');\n    }\n    this.LS = window.localStorage;\n\n    if (modelPath == null || !modelPath) {\n      throw new Error(\n          'For local storage, modelPath must not be null, undefined or empty.');\n    }\n    this.modelPath = modelPath;\n    this.keys = getModelKeys(this.modelPath);\n  }\n\n  /**\n   * Save model artifacts to browser local storage.\n   *\n   * See the documentation to `browserLocalStorage` for details on the saved\n   * artifacts.\n   *\n   * @param modelArtifacts The model artifacts to be stored.\n   * @returns An instance of SaveResult.\n   */\n  async save(modelArtifacts: ModelArtifacts): Promise<SaveResult> {\n    if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n      throw new Error(\n          'BrowserLocalStorage.save() does not support saving model topology ' +\n          'in binary formats yet.');\n    } else {\n      const topology = JSON.stringify(modelArtifacts.modelTopology);\n      const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);\n\n      const modelArtifactsInfo: ModelArtifactsInfo =\n          getModelArtifactsInfoForJSON(modelArtifacts);\n\n      // TODO(mattsoulanille): Support saving models over 2GB that exceed\n      // Chrome's ArrayBuffer size limit.\n      const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);\n\n      try {\n        this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));\n        this.LS.setItem(this.keys.topology, topology);\n        this.LS.setItem(this.keys.weightSpecs, weightSpecs);\n        this.LS.setItem(\n            this.keys.weightData,\n            arrayBufferToBase64String(weightBuffer));\n\n        // Note that JSON.stringify doesn't write out keys that have undefined\n        // values, so for some keys, we set undefined instead of a null-ish\n        // value.\n        const metadata: Required<ModelMetadata> = {\n          format: modelArtifacts.format,\n          generatedBy: modelArtifacts.generatedBy,\n          convertedBy: modelArtifacts.convertedBy,\n          signature: modelArtifacts.signature != null ?\n              modelArtifacts.signature :\n              undefined,\n          userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ?\n              modelArtifacts.userDefinedMetadata :\n              undefined,\n          modelInitializer: modelArtifacts.modelInitializer != null ?\n              modelArtifacts.modelInitializer :\n              undefined,\n          initializerSignature: modelArtifacts.initializerSignature != null ?\n              modelArtifacts.initializerSignature :\n              undefined,\n          trainingConfig: modelArtifacts.trainingConfig != null ?\n              modelArtifacts.trainingConfig :\n              undefined\n        };\n        this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata));\n\n        return {modelArtifactsInfo};\n      } catch (err) {\n        // If saving failed, clean up all items saved so far.\n        removeItems(this.keys);\n\n        throw new Error(\n            `Failed to save model '${this.modelPath}' to local storage: ` +\n            `size quota being exceeded is a possible cause of this failure: ` +\n            `modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +\n            `weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +\n            `weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);\n      }\n    }\n  }\n\n  /**\n   * Load a model from local storage.\n   *\n   * See the documentation to `browserLocalStorage` for details on the saved\n   * artifacts.\n   *\n   * @returns The loaded model (if loading succeeds).\n   */\n  async load(): Promise<ModelArtifacts> {\n    const info =\n        JSON.parse(this.LS.getItem(this.keys.info)) as ModelArtifactsInfo;\n    if (info == null) {\n      throw new Error(\n          `In local storage, there is no model with name '${this.modelPath}'`);\n    }\n\n    if (info.modelTopologyType !== 'JSON') {\n      throw new Error(\n          'BrowserLocalStorage does not support loading non-JSON model ' +\n          'topology yet.');\n    }\n\n    const out: ModelArtifacts = {};\n\n    // Load topology.\n    const topology = JSON.parse(this.LS.getItem(this.keys.topology));\n    if (topology == null) {\n      throw new Error(\n          `In local storage, the topology of model '${this.modelPath}' ` +\n          `is missing.`);\n    }\n    out.modelTopology = topology;\n\n    // Load weight specs.\n    const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));\n    if (weightSpecs == null) {\n      throw new Error(\n          `In local storage, the weight specs of model '${this.modelPath}' ` +\n          `are missing.`);\n    }\n    out.weightSpecs = weightSpecs;\n\n    // Load meta-data fields.\n    const metadataString = this.LS.getItem(this.keys.modelMetadata);\n    if (metadataString != null) {\n      const metadata = JSON.parse(metadataString) as ModelMetadata;\n      out.format = metadata.format;\n      out.generatedBy = metadata.generatedBy;\n      out.convertedBy = metadata.convertedBy;\n      if (metadata.signature != null) {\n        out.signature = metadata.signature;\n      }\n      if (metadata.userDefinedMetadata != null) {\n        out.userDefinedMetadata = metadata.userDefinedMetadata;\n      }\n      if (metadata.modelInitializer != null) {\n        out.modelInitializer = metadata.modelInitializer;\n      }\n      if (metadata.initializerSignature != null) {\n        out.initializerSignature = metadata.initializerSignature;\n      }\n      if (metadata.trainingConfig != null) {\n        out.trainingConfig = metadata.trainingConfig;\n      }\n    }\n\n    // Load weight data.\n    const weightDataBase64 = this.LS.getItem(this.keys.weightData);\n    if (weightDataBase64 == null) {\n      throw new Error(\n          `In local storage, the binary weight values of model ` +\n          `'${this.modelPath}' are missing.`);\n    }\n    out.weightData = base64StringToArrayBuffer(weightDataBase64);\n\n    return out;\n  }\n}\n\nexport const localStorageRouter: IORouter = (url: string|string[]) => {\n  if (!env().getBool('IS_BROWSER')) {\n    return null;\n  } else {\n    if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {\n      return browserLocalStorage(\n          url.slice(BrowserLocalStorage.URL_SCHEME.length));\n    } else {\n      return null;\n    }\n  }\n};\nIORouterRegistry.registerSaveRouter(localStorageRouter);\nIORouterRegistry.registerLoadRouter(localStorageRouter);\n\n/**\n * Factory function for local storage IOHandler.\n *\n * This `IOHandler` supports both `save` and `load`.\n *\n * For each model's saved artifacts, four items are saved to local storage.\n *   - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the\n *     model, such as date saved, type of the topology, size in bytes, etc.\n *   - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-\n *     style models, this is a stringized JSON.\n *   - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the\n *     model, can be used to decode the saved binary weight values (see\n *     item below).\n *   - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary\n *     weight values, stored as a base64-encoded string.\n *\n * Saving may throw an `Error` if the total size of the artifacts exceed the\n * browser-specific quota.\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n *   non-empty string.\n * @returns An instance of `IOHandler`, which can be used with, e.g.,\n *   `tf.Model.save`.\n */\nexport function browserLocalStorage(modelPath: string): IOHandler {\n  return new BrowserLocalStorage(modelPath);\n}\n\nexport class BrowserLocalStorageManager implements ModelStoreManager {\n  private readonly LS: Storage;\n\n  constructor() {\n    assert(\n        env().getBool('IS_BROWSER'),\n        () => 'Current environment is not a web browser');\n    assert(\n        typeof window === 'undefined' ||\n            typeof window.localStorage !== 'undefined',\n        () => 'Current browser does not appear to support localStorage');\n    this.LS = window.localStorage;\n  }\n\n  async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n    const out: {[path: string]: ModelArtifactsInfo} = {};\n    const prefix = PATH_PREFIX + PATH_SEPARATOR;\n    const suffix = PATH_SEPARATOR + INFO_SUFFIX;\n    for (let i = 0; i < this.LS.length; ++i) {\n      const key = this.LS.key(i);\n      if (key.startsWith(prefix) && key.endsWith(suffix)) {\n        const modelPath = getModelPathFromKey(key);\n        out[modelPath] = JSON.parse(this.LS.getItem(key)) as ModelArtifactsInfo;\n      }\n    }\n    return out;\n  }\n\n  async removeModel(path: string): Promise<ModelArtifactsInfo> {\n    path = maybeStripScheme(path);\n    const keys = getModelKeys(path);\n    if (this.LS.getItem(keys.info) == null) {\n      throw new Error(`Cannot find model at path '${path}'`);\n    }\n    const info = JSON.parse(this.LS.getItem(keys.info)) as ModelArtifactsInfo;\n    removeItems(keys);\n    return info;\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n *   string.\n * - Moving or copying model from one path to another in the same medium or from\n *   one medium to another, by using URL strings.\n */\n\nimport {assert} from '../util';\n\nimport {IORouterRegistry} from './router_registry';\nimport {ModelArtifactsInfo, ModelStoreManager} from './types';\n\nconst URL_SCHEME_SUFFIX = '://';\n\nexport class ModelStoreManagerRegistry {\n  // Singleton instance.\n  private static instance: ModelStoreManagerRegistry;\n\n  private managers: {[scheme: string]: ModelStoreManager};\n\n  private constructor() {\n    this.managers = {};\n  }\n\n  private static getInstance(): ModelStoreManagerRegistry {\n    if (ModelStoreManagerRegistry.instance == null) {\n      ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n    }\n    return ModelStoreManagerRegistry.instance;\n  }\n\n  /**\n   * Register a save-handler router.\n   *\n   * @param saveRouter A function that maps a URL-like string onto an instance\n   * of `IOHandler` with the `save` method defined or `null`.\n   */\n  static registerManager(scheme: string, manager: ModelStoreManager) {\n    assert(scheme != null, () => 'scheme must not be undefined or null.');\n    if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n      scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n    }\n    assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n    const registry = ModelStoreManagerRegistry.getInstance();\n    assert(\n        registry.managers[scheme] == null,\n        () => `A model store manager is already registered for scheme '${\n            scheme}'.`);\n    registry.managers[scheme] = manager;\n  }\n\n  static getManager(scheme: string): ModelStoreManager {\n    const manager = ModelStoreManagerRegistry.getInstance().managers[scheme];\n    if (manager == null) {\n      throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n    }\n    return manager;\n  }\n\n  static getSchemes(): string[] {\n    return Object.keys(ModelStoreManagerRegistry.getInstance().managers);\n  }\n}\n\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n *   Scheme: e.g., 'localstorage' in the example above.\n *   Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url: string): {scheme: string, path: string} {\n  if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n    throw new Error(\n        `The url string provided does not contain a scheme. ` +\n        `Supported schemes are: ` +\n        `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n  }\n  return {\n    scheme: url.split(URL_SCHEME_SUFFIX)[0],\n    path: url.split(URL_SCHEME_SUFFIX)[1],\n  };\n}\n\nasync function cloneModelInternal(\n    sourceURL: string, destURL: string,\n    deleteSource = false): Promise<ModelArtifactsInfo> {\n  assert(\n      sourceURL !== destURL,\n      () => `Old path and new path are the same: '${sourceURL}'`);\n\n  const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n  assert(\n      loadHandlers.length > 0,\n      () => `Copying failed because no load handler is found for source URL ${\n          sourceURL}.`);\n  assert(\n      loadHandlers.length < 2,\n      () => `Copying failed because more than one (${loadHandlers.length}) ` +\n          `load handlers for source URL ${sourceURL}.`);\n  const loadHandler = loadHandlers[0];\n\n  const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n  assert(\n      saveHandlers.length > 0,\n      () => `Copying failed because no save handler is found for destination ` +\n          `URL ${destURL}.`);\n  assert(\n      saveHandlers.length < 2,\n      () => `Copying failed because more than one (${loadHandlers.length}) ` +\n          `save handlers for destination URL ${destURL}.`);\n  const saveHandler = saveHandlers[0];\n\n  const sourceScheme = parseURL(sourceURL).scheme;\n  const sourcePath = parseURL(sourceURL).path;\n  const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n\n  const modelArtifacts = await loadHandler.load();\n\n  // If moving within the same storage medium, remove the old model as soon as\n  // the loading is done. Without doing this, it is possible that the combined\n  // size of the two models will cause the cloning to fail.\n  if (deleteSource && sameMedium) {\n    await ModelStoreManagerRegistry.getManager(sourceScheme)\n        .removeModel(sourcePath);\n  }\n\n  const saveResult = await saveHandler.save(modelArtifacts);\n\n  // If moving between mediums, the deletion is done after the save succeeds.\n  // This guards against the case in which saving to the destination medium\n  // fails.\n  if (deleteSource && !sameMedium) {\n    await ModelStoreManagerRegistry.getManager(sourceScheme)\n        .removeModel(sourcePath);\n  }\n\n  return saveResult.modelArtifactsInfo;\n}\n\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n *     {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n *   'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n *   heading: 'Models',\n *   subheading: 'Management',\n *   namespace: 'io',\n *   ignoreCI: true\n * }\n */\nasync function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {\n  const schemes = ModelStoreManagerRegistry.getSchemes();\n  const out: {[url: string]: ModelArtifactsInfo} = {};\n  for (const scheme of schemes) {\n    const schemeOut =\n        await ModelStoreManagerRegistry.getManager(scheme).listModels();\n    for (const path in schemeOut) {\n      const url = scheme + URL_SCHEME_SUFFIX + path;\n      out[url] = schemeOut[path];\n    }\n  }\n  return out;\n}\n\n/**\n * Remove a model specified by URL from a registered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n *     {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n *   'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n *   is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n *   heading: 'Models',\n *   subheading: 'Management',\n *   namespace: 'io',\n *   ignoreCI: true\n * }\n */\nasync function removeModel(url: string): Promise<ModelArtifactsInfo> {\n  const schemeAndPath = parseURL(url);\n  const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);\n  return manager.removeModel(schemeAndPath.path);\n}\n\n/**\n * Copy a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Copying within a storage medium, e.g.,\n *    `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Copying between two storage mediums, e.g.,\n *    `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n *     {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Copy the model, from Local Storage to IndexedDB.\n * await tf.io.copyModel(\n *     'localstorage://demo/management/model1',\n *     'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove both models.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of copying.\n * @param destURL Destination URL of copying.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n *   is successful).\n * @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or\n *   if `oldPath` and `newPath` are identical.\n *\n * @doc {\n *   heading: 'Models',\n *   subheading: 'Management',\n *   namespace: 'io',\n *   ignoreCI: true\n * }\n */\nasync function copyModel(\n    sourceURL: string, destURL: string): Promise<ModelArtifactsInfo> {\n  const deleteSource = false;\n  return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\n/**\n * Move a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Moving within a storage medium, e.g.,\n *    `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Moving between two storage mediums, e.g.,\n *    `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n *     {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Move the model, from Local Storage to IndexedDB.\n * await tf.io.moveModel(\n *     'localstorage://demo/management/model1',\n *     'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove the moved model.\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of moving.\n * @param destURL Destination URL of moving.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n *   is successful).\n * @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or\n *   if `oldPath` and `newPath` are identical.\n *\n * @doc {\n *   heading: 'Models',\n *   subheading: 'Management',\n *   namespace: 'io',\n *   ignoreCI: true\n * }\n */\nasync function moveModel(\n    sourceURL: string, destURL: string): Promise<ModelArtifactsInfo> {\n  const deleteSource = true;\n  return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\nexport {moveModel, copyModel, removeModel, listModels};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\nimport {BrowserIndexedDB, BrowserIndexedDBManager} from '../io/indexed_db';\nimport {BrowserLocalStorage, BrowserLocalStorageManager} from '../io/local_storage';\nimport {ModelStoreManagerRegistry} from '../io/model_management';\n\nimport {Platform} from './platform';\nimport {isTypedArrayBrowser} from './is_typed_array_browser';\n\nexport class PlatformBrowser implements Platform {\n  // According to the spec, the built-in encoder can do only UTF-8 encoding.\n  // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n  private textEncoder: TextEncoder;\n\n  // For setTimeoutCustom\n  private readonly messageName = 'setTimeoutCustom';\n  private functionRefs: Function[] = [];\n  private handledMessageCount = 0;\n  private hasEventListener = false;\n\n  fetch(path: string, init?: RequestInit): Promise<Response> {\n    return fetch(path, init);\n  }\n\n  now(): number {\n    return performance.now();\n  }\n\n  encode(text: string, encoding: string): Uint8Array {\n    if (encoding !== 'utf-8' && encoding !== 'utf8') {\n      throw new Error(\n          `Browser's encoder only supports utf-8, but got ${encoding}`);\n    }\n    if (this.textEncoder == null) {\n      this.textEncoder = new TextEncoder();\n    }\n    return this.textEncoder.encode(text);\n  }\n  decode(bytes: Uint8Array, encoding: string): string {\n    return new TextDecoder(encoding).decode(bytes);\n  }\n\n  // If the setTimeout nesting level is greater than 5 and timeout is less\n  // than 4ms, timeout will be clamped to 4ms, which hurts the perf.\n  // Interleaving window.postMessage and setTimeout will trick the browser and\n  // avoid the clamp.\n  setTimeoutCustom(functionRef: Function, delay: number): void {\n    if (typeof window === 'undefined' ||\n        !env().getBool('USE_SETTIMEOUTCUSTOM')) {\n      setTimeout(functionRef, delay);\n      return;\n    }\n\n    this.functionRefs.push(functionRef);\n    setTimeout(() => {\n      window.postMessage(\n          {name: this.messageName, index: this.functionRefs.length - 1}, '*');\n    }, delay);\n\n    if (!this.hasEventListener) {\n      this.hasEventListener = true;\n      window.addEventListener('message', (event: MessageEvent) => {\n        if (event.source === window && event.data.name === this.messageName) {\n          event.stopPropagation();\n          const functionRef = this.functionRefs[event.data.index];\n          functionRef();\n          this.handledMessageCount++;\n          if (this.handledMessageCount === this.functionRefs.length) {\n            this.functionRefs = [];\n            this.handledMessageCount = 0;\n          }\n        }\n      }, true);\n    }\n  }\n\n  isTypedArray(a: unknown): a is Uint8Array | Float32Array | Int32Array\n    | Uint8ClampedArray {\n    return isTypedArrayBrowser(a);\n  }\n}\n\nif (env().get('IS_BROWSER')) {\n  env().setPlatform('browser', new PlatformBrowser());\n\n  // Register LocalStorage IOHandler\n  try {\n    ModelStoreManagerRegistry.registerManager(\n        BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n  } catch (err) {\n  }\n\n  // Register IndexedDB IOHandler\n  try {\n    ModelStoreManagerRegistry.registerManager(\n        BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n  } catch (err) {\n  }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '../environment';\nimport {Platform} from './platform';\n\n// We are wrapping this within an object so it can be stubbed by Jasmine.\nexport const getNodeFetch = {\n  // tslint:disable-next-line:no-require-imports\n  importFetch: () => require('node-fetch')\n};\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise<Response>;\nlet systemFetch: FetchFn;\n// These getters and setters are for testing so we don't export a mutable\n// variable.\nexport function resetSystemFetch() {\n  systemFetch = null;\n}\nexport function setSystemFetch(fetchFn: FetchFn) {\n  systemFetch = fetchFn;\n}\nexport function getSystemFetch(): FetchFn {\n  return systemFetch;\n}\n\nexport class PlatformNode implements Platform {\n  private textEncoder: TextEncoder;\n  // tslint:disable-next-line:no-any\n  util: any;\n\n  constructor() {\n    // tslint:disable-next-line:no-require-imports\n    this.util = require('util');\n    // According to the spec, the built-in encoder can do only UTF-8 encoding.\n    // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n    this.textEncoder = new this.util.TextEncoder();\n  }\n\n  fetch(path: string, requestInits?: RequestInit): Promise<Response> {\n    if (env().global.fetch != null) {\n      return env().global.fetch(path, requestInits);\n    }\n\n    if (systemFetch == null) {\n      systemFetch = getNodeFetch.importFetch();\n    }\n    return systemFetch(path, requestInits);\n  }\n\n  now(): number {\n    const time = process.hrtime();\n    return time[0] * 1000 + time[1] / 1000000;\n  }\n\n  encode(text: string, encoding: string): Uint8Array {\n    if (encoding !== 'utf-8' && encoding !== 'utf8') {\n      throw new Error(\n          `Node built-in encoder only supports utf-8, but got ${encoding}`);\n    }\n    return this.textEncoder.encode(text);\n  }\n  decode(bytes: Uint8Array, encoding: string): string {\n    if (bytes.length === 0) {\n      return '';\n    }\n    return new this.util.TextDecoder(encoding).decode(bytes);\n  }\n  isTypedArray(a: unknown): a is Float32Array | Int32Array | Uint8Array\n    | Uint8ClampedArray {\n    return this.util.types.isFloat32Array(a)\n      || this.util.types.isInt32Array(a)\n      || this.util.types.isUint8Array(a)\n      || this.util.types.isUint8ClampedArray(a);\n  }\n}\n\nif (env().get('IS_NODE') && !env().get('IS_BROWSER')) {\n  env().setPlatform('node', new PlatformNode());\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer<R extends Rank, D extends DataType = 'float32'>(\n    shape: ShapeMap[R], dtype: D = 'float32' as D,\n    values?: DataTypeMap[D]): TensorBuffer<R, D> {\n  dtype = dtype || 'float32' as D;\n  util.assertNonNegativeIntegerDimensions(shape);\n  return new TensorBuffer<R, D>(shape, dtype, values);\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_<T extends Tensor>(x: T|TensorLike, dtype: DataType): T {\n  const $x = convertToTensor(x, 'x', 'cast');\n\n  // Sanity checks.\n  if (!util.isValidDtype(dtype)) {\n    throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n  }\n  if (dtype === 'string' && $x.dtype !== 'string' ||\n      dtype !== 'string' && $x.dtype === 'string') {\n    throw new Error('Only strings can be casted to strings');\n  }\n\n  const inputs: CastInputs = {x: $x};\n  const attrs: CastAttrs = {dtype};\n\n  return ENGINE.runKernel(\n      Cast, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const cast = /* @__PURE__ */ op({cast_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');\n  const inputs: IdentityInputs = {x: $x};\n\n  // Note this op is called tf.identity in python. Hence the kernel name used\n  // here.\n  return ENGINE.runKernel(Identity, inputs as unknown as NamedTensorMap);\n}\n\nexport const clone = /* @__PURE__ */ op({clone_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print<T extends Tensor>(x: T, verbose = false): void {\n  console.log(x.toString(verbose));\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code for tfjs-core\n\n// Set up Engine and ENV\nimport {getOrMakeEngine} from './engine';\ngetOrMakeEngine();\n\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n\n// Set up OpHandler\nimport {buffer} from './ops/buffer';\nimport {cast} from './ops/cast';\nimport {clone} from './ops/clone';\nimport {print} from './ops/print';\nimport {OpHandler, setOpHandler} from './tensor';\nconst opHandler: OpHandler = {\n  buffer,\n  cast,\n  clone,\n  print\n};\nsetOpHandler(opHandler);\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Add, AddInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print();  // or tf.add(a, b)\n * ```\n *\n * ```js\n * // Broadcast add a with b.\n * const a = tf.scalar(5);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print();  // or tf.add(a, b)\n * ```\n * @param a The first `tf.Tensor` to add.\n * @param b The second `tf.Tensor` to add. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction add_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'add');\n  let $b = convertToTensor(b, 'b', 'add');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: AddInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n\nexport const add = /* @__PURE__ */ op({add_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FloorDiv, FloorDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n * The result is rounded with floor function.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.floorDiv(b).print();  // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.floorDiv(b).print();  // or tf.floorDiv(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction floorDiv_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'floorDiv');\n  let $b = convertToTensor(b, 'b', 'floorDiv');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: FloorDivInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(FloorDiv, inputs as unknown as NamedTensorMap);\n}\n\nexport const floorDiv = /* @__PURE__ */ op({floorDiv_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RealDiv, RealDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {floorDiv} from './floorDiv';\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.div(b).print();  // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.div(b).print();  // or tf.div(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction div_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'div');\n  let $b = convertToTensor(b, 'b', 'div');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  if ($a.dtype === 'int32' && $b.dtype === 'int32') {\n    return floorDiv($a, $b);\n  }\n\n  const inputs: RealDivInputs = {a: $a, b: $b};\n  const attrs = {};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(RealDiv,\n                          inputs as unknown as NamedTensorMap, attrs) as T;\n}\n\nexport const div = /* @__PURE__ */ op({div_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multiply, MultiplyInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Multiplies two `tf.Tensor`s element-wise, A * B. Supports broadcasting.\n *\n * We also expose `tf.mulStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([2, 3, 4, 5]);\n *\n * a.mul(b).print();  // or tf.mul(a, b)\n * ```\n *\n * ```js\n * // Broadcast mul a with b.\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.scalar(5);\n *\n * a.mul(b).print();  // or tf.mul(a, b)\n * ```\n * @param a The first tensor to multiply.\n * @param b The second tensor to multiply. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction mul_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'mul');\n  let $b = convertToTensor(b, 'b', 'mul');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: MultiplyInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Multiply, inputs as unknown as NamedTensorMap);\n}\nexport const mul = /* @__PURE__ */ op({mul_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Abs, AbsInputs, ComplexAbs, ComplexAbsInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes absolute value element-wise: `abs(x)`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.abs().print();  // or tf.abs(x)\n * ```\n * @param x The input `tf.Tensor`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction abs_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'abs');\n\n  if ($x.dtype === 'complex64') {\n    const inputs: ComplexAbsInputs = {x: $x};\n    return ENGINE.runKernel(ComplexAbs, inputs as unknown as NamedTensorMap);\n  } else {\n    const inputs: AbsInputs = {x: $x};\n    return ENGINE.runKernel(Abs, inputs as unknown as NamedTensorMap);\n  }\n}\n\nexport const abs = /* @__PURE__ */ op({abs_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Acos, AcosInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes acos of the input `tf.Tensor` element-wise: `acos(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.acos().print();  // or tf.acos(x)\n * ```\n * @param x The input tensor.\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction acos_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'acos');\n  const inputs: AcosInputs = {x: $x};\n\n  return ENGINE.runKernel(Acos, inputs as unknown as NamedTensorMap);\n}\nexport const acos = /* @__PURE__ */ op({acos_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Acosh, AcoshInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the inverse hyperbolic cos of the input `tf.Tensor` element-wise:\n * `acosh(x)`\n *\n * ```js\n * const x = tf.tensor1d([10, 1, 3, 5.7]);\n *\n * x.acosh().print();  // or tf.acosh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction acosh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'acosh');\n  const inputs: AcoshInputs = {x: $x};\n\n  return ENGINE.runKernel(Acosh, inputs as unknown as NamedTensorMap);\n}\nexport const acosh = /* @__PURE__ */ op({acosh_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {AddN, AddNInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n *\n * tf.addN([a, b, c]).print();\n * ```\n * @param tensors A list of tensors with the same shape and dtype.\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction addN_<T extends Tensor>(tensors: Array<T|TensorLike>): T {\n  util.assert(\n      Array.isArray(tensors),\n      () => 'The argument passed to tf.addN() must be a list of tensors');\n  util.assert(\n      tensors.length >= 1,\n      () => `Must pass at least one tensor to tf.addN(), but got ` +\n          `${tensors.length}`);\n\n  const $tensors =\n      tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'addN'));\n\n  const firstTensor = $tensors[0];\n  $tensors.forEach(t => {\n    if (t.dtype !== firstTensor.dtype) {\n      throw new Error(\n          'All tensors passed to tf.addN() must have the same dtype');\n    }\n  });\n\n  $tensors.forEach(t => {\n    if (!util.arraysEqual(t.shape, firstTensor.shape)) {\n      throw new Error(\n          'All tensors passed to tf.addN() must have the same shape');\n    }\n  });\n\n  const inputs: AddNInputs = $tensors;\n\n  return ENGINE.runKernel(AddN, inputs as unknown as NamedTensorMap);\n}\n\nexport const addN = /* @__PURE__ */ op({addN_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {All, AllAttrs, AllInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the logical and of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 1, 1], 'bool');\n *\n * x.all().print();  // or tf.all(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');\n *\n * const axis = 1;\n * x.all(axis).print();  // or tf.all(x, axis)\n * ```\n *\n * @param x The input tensor. Must be of dtype bool.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction all_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'all', 'bool');\n\n  const inputs: AllInputs = {x: $x};\n  const attrs: AllAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      All, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const all = /* @__PURE__ */ op({all_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Any, AnyAttrs, AnyInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the logical or of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 1, 1], 'bool');\n *\n * x.any().print();  // or tf.any(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');\n *\n * const axis = 1;\n * x.any(axis).print();  // or tf.any(x, axis)\n * ```\n *\n * @param x The input tensor. Must be of dtype bool.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction any_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'any', 'bool');\n\n  const inputs: AnyInputs = {x: $x};\n  const attrs: AnyAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      Any, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\n// tslint:disable-next-line:variable-name\nexport const any = /* @__PURE__ */ op({any_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ArgMax, ArgMaxAttrs, ArgMaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the indices of the maximum values along an `axis`.\n *\n * The result has the same shape as `input` with the dimension along `axis`\n * removed.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.argMax().print();  // or tf.argMax(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);\n *\n * const axis = 1;\n * x.argMax(axis).print();  // or tf.argMax(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction argMax_<T extends Tensor>(x: Tensor|TensorLike, axis = 0): T {\n  const $x = convertToTensor(x, 'x', 'argMax');\n\n  const inputs: ArgMaxInputs = {x: $x};\n  const attrs: ArgMaxAttrs = {axis};\n\n  return ENGINE.runKernel(\n      ArgMax, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const argMax = /* @__PURE__ */ op({argMax_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ArgMin, ArgMinAttrs, ArgMinInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the indices of the minimum values along an `axis`.\n *\n * The result has the same shape as `input` with the dimension along `axis`\n * removed.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.argMin().print();  // or tf.argMin(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);\n *\n * const axis = 1;\n * x.argMin(axis).print();  // or tf.argMin(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction argMin_<T extends Tensor>(x: Tensor|TensorLike, axis = 0): T {\n  const $x = convertToTensor(x, 'x', 'argMin');\n\n  const inputs: ArgMinInputs = {x: $x};\n  const attrs: ArgMinAttrs = {axis};\n\n  return ENGINE.runKernel(\n      ArgMin, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const argMin = /* @__PURE__ */ op({argMin_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Asin, AsinInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes asin of the input `tf.Tensor` element-wise: `asin(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.asin().print();  // or tf.asin(x)\n * ```\n * @param x The input tensor.\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction asin_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'asin');\n  const inputs: AsinInputs = {x: $x};\n\n  return ENGINE.runKernel(Asin, inputs as unknown as NamedTensorMap);\n}\nexport const asin = /* @__PURE__ */ op({asin_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Asinh, AsinhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes inverse hyperbolic sin of the input `tf.Tensor` element-wise:\n * `asinh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.asinh().print();  // or tf.asinh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction asinh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'asinh');\n\n  const inputs: AsinhInputs = {x: $x};\n\n  return ENGINE.runKernel(Asinh, inputs as unknown as NamedTensorMap);\n}\nexport const asinh = /* @__PURE__ */ op({asinh_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atan, AtanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes atan of the input `tf.Tensor` element-wise: `atan(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.atan().print();  // or tf.atan(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atan_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'atan');\n\n  const inputs: AtanInputs = {x: $x};\n\n  return ENGINE.runKernel(Atan, inputs as unknown as NamedTensorMap);\n}\nexport const atan = /* @__PURE__ */ op({atan_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atan2, Atan2Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.\n * Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);\n * const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);\n *\n * tf.atan2(a, b).print()\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atan2_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'atan2');\n  let $b = convertToTensor(b, 'b', 'atan2');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: Atan2Inputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Atan2, inputs as unknown as NamedTensorMap);\n}\n\nexport const atan2 = /* @__PURE__ */ op({atan2_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atanh, AtanhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:\n * `atanh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, .1, -.1, .7]);\n *\n * x.atanh().print();  // or tf.atanh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atanh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'atanh');\n\n  const inputs: AtanhInputs = {x: $x};\n\n  return ENGINE.runKernel(Atanh, inputs as unknown as NamedTensorMap);\n}\nexport const atanh = /* @__PURE__ */ op({atanh_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\ntype PadType = 'SAME'|'VALID'|'NUMBER'|'EXPLICIT';\n\n// For NHWC should be in the following form:\n//  [[0, 0], [pad_top,pad_bottom], [pad_left, pad_right], [0, 0]]\n// For NCHW should be in the following form:\n//  [[0, 0], [0, 0], [pad_top,pad_bottom], [pad_left, pad_right]]\n// Reference: https://www.tensorflow.org/api_docs/python/tf/nn/conv2d\nexport type ExplicitPadding =\n    [[number, number], [number, number], [number, number], [number, number]];\n\nexport type PadInfo = {\n  top: number,\n  left: number,\n  right: number,\n  bottom: number,\n  type: PadType\n};\n\nexport type PadInfo3D = {\n  top: number,\n  left: number,\n  right: number,\n  bottom: number,\n  front: number,\n  back: number,\n  type: PadType\n};\n\n/**\n * Information about the forward pass of a convolution/pooling operation.\n * It includes input and output shape, strides, filter size and padding\n * information.\n */\nexport type Conv2DInfo = {\n  batchSize: number,\n  inHeight: number,\n  inWidth: number,\n  inChannels: number,\n  outHeight: number,\n  outWidth: number,\n  outChannels: number,\n  dataFormat: 'channelsFirst'|'channelsLast',\n  strideHeight: number,\n  strideWidth: number,\n  dilationHeight: number,\n  dilationWidth: number,\n  filterHeight: number,\n  filterWidth: number,\n  effectiveFilterHeight: number,\n  effectiveFilterWidth: number,\n  padInfo: PadInfo,\n  inShape: [number, number, number, number],\n  outShape: [number, number, number, number],\n  filterShape: [number, number, number, number]\n};\n\n/**\n *\n * @param inputShape Input tensor shape is of the following dimensions:\n *     `[batch, height, width, inChannels]`.\n * @param filterShape The filter shape is of the following dimensions:\n *     `[filterHeight, filterWidth, depth]`.\n * @param strides The strides of the sliding window for each dimension of the\n *     input tensor: `[strideHeight, strideWidth]`.\n *     If `strides` is a single number,\n *     then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1*1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat The data format of the input and output data.\n *     Defaults to 'NHWC'.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`.\n *     Defaults to `[1, 1]`. If `dilations` is a single number, then\n *     `dilationHeight == dilationWidth`.\n */\nexport function computeDilation2DInfo(\n    inputShape: [number, number, number, number],\n    filterShape: [number, number, number], strides: number|[number, number],\n    pad: 'same'|'valid'|number, dataFormat: 'NHWC' = 'NHWC',\n    dilations: number|[number, number]) {\n  // `computerConv2DInfo` require filterShape to be in the dimension of:\n  // `[filterHeight, filterWidth, depth, outDepth]`, dilation2d doesn't have\n  // outDepth, it should have the same depth as the input.\n  // Input shape: [batch, height, width, inChannels]\n  const inputChannels = inputShape[3];\n  const $filterShape =\n      [...filterShape, inputChannels] as [number, number, number, number];\n  const $dataFormat = convertConv2DDataFormat(dataFormat);\n\n  return computeConv2DInfo(\n      inputShape, $filterShape, strides, dilations, pad,\n      null /* roundingMode */, null /* depthWise */, $dataFormat);\n}\n\nexport function computePool2DInfo(\n    inShape: [number, number, number, number],\n    filterSize: [number, number]|number, strides: number|[number, number],\n    dilations: number|[number, number],\n    pad: 'same'|'valid'|number|ExplicitPadding,\n    roundingMode?: 'floor'|'round'|'ceil',\n    dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast'): Conv2DInfo {\n  const [filterHeight, filterWidth] = parseTupleParam(filterSize);\n\n  let filterShape: [number, number, number, number];\n  if (dataFormat === 'channelsLast') {\n    filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];\n  } else if (dataFormat === 'channelsFirst') {\n    filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n\n  return computeConv2DInfo(\n      inShape, filterShape, strides, dilations, pad, roundingMode, false,\n      dataFormat);\n}\n\n/**\n * Computes the information for a forward pass of a pooling3D operation.\n */\nexport function computePool3DInfo(\n    inShape: [number, number, number, number, number],\n    filterSize: number|[number, number, number],\n    strides: number|[number, number, number],\n    dilations: number|[number, number, number], pad: 'same'|'valid'|number,\n    roundingMode?: 'floor'|'round'|'ceil',\n    dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): Conv3DInfo {\n  const [filterDepth, filterHeight, filterWidth] = parse3TupleParam(filterSize);\n\n  let filterShape: [number, number, number, number, number];\n  let $dataFormat: 'channelsFirst'|'channelsLast';\n  if (dataFormat === 'NDHWC') {\n    $dataFormat = 'channelsLast';\n    filterShape =\n        [filterDepth, filterHeight, filterWidth, inShape[4], inShape[4]];\n  } else if (dataFormat === 'NCDHW') {\n    $dataFormat = 'channelsFirst';\n    filterShape =\n        [filterDepth, filterHeight, filterWidth, inShape[1], inShape[1]];\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n\n  return computeConv3DInfo(\n      inShape, filterShape, strides, dilations, pad, false, $dataFormat,\n      roundingMode);\n}\n\n/**\n * Computes the information for a forward pass of a convolution/pooling\n * operation.\n */\nexport function computeConv2DInfo(\n    inShape: [number, number, number, number],\n    filterShape: [number, number, number, number],\n    strides: number|[number, number], dilations: number|[number, number],\n    pad: 'same'|'valid'|number|ExplicitPadding,\n    roundingMode?: 'floor'|'round'|'ceil', depthwise = false,\n    dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast'): Conv2DInfo {\n  let [batchSize, inHeight, inWidth, inChannels] = [-1, -1, -1, -1];\n  if (dataFormat === 'channelsLast') {\n    [batchSize, inHeight, inWidth, inChannels] = inShape;\n  } else if (dataFormat === 'channelsFirst') {\n    [batchSize, inChannels, inHeight, inWidth] = inShape;\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n\n  const [filterHeight, filterWidth, , filterChannels] = filterShape;\n  const [strideHeight, strideWidth] = parseTupleParam(strides);\n  const [dilationHeight, dilationWidth] = parseTupleParam(dilations);\n\n  const effectiveFilterHeight =\n      getEffectiveFilterSize(filterHeight, dilationHeight);\n  const effectiveFilterWidth =\n      getEffectiveFilterSize(filterWidth, dilationWidth);\n  const {padInfo, outHeight, outWidth} = getPadAndOutInfo(\n      pad, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight,\n      effectiveFilterWidth, roundingMode, dataFormat);\n\n  const outChannels = depthwise ? filterChannels * inChannels : filterChannels;\n\n  let outShape: [number, number, number, number];\n  if (dataFormat === 'channelsFirst') {\n    outShape = [batchSize, outChannels, outHeight, outWidth];\n  } else if (dataFormat === 'channelsLast') {\n    outShape = [batchSize, outHeight, outWidth, outChannels];\n  }\n\n  return {\n    batchSize,\n    dataFormat,\n    inHeight,\n    inWidth,\n    inChannels,\n    outHeight,\n    outWidth,\n    outChannels,\n    padInfo,\n    strideHeight,\n    strideWidth,\n    filterHeight,\n    filterWidth,\n    effectiveFilterHeight,\n    effectiveFilterWidth,\n    dilationHeight,\n    dilationWidth,\n    inShape,\n    outShape,\n    filterShape\n  };\n}\n\n/**\n * Information about the forward pass of a 3D convolution/pooling operation.\n * It includes input and output shape, strides, filter size and padding\n * information.\n */\nexport type Conv3DInfo = {\n  batchSize: number,\n  inDepth: number,\n  inHeight: number,\n  inWidth: number,\n  inChannels: number,\n  outDepth: number,\n  outHeight: number,\n  outWidth: number,\n  outChannels: number,\n  dataFormat: 'channelsFirst'|'channelsLast',\n  strideDepth: number,\n  strideHeight: number,\n  strideWidth: number,\n  dilationDepth: number,\n  dilationHeight: number,\n  dilationWidth: number,\n  filterDepth: number,\n  filterHeight: number,\n  filterWidth: number,\n  effectiveFilterDepth: number,\n  effectiveFilterHeight: number,\n  effectiveFilterWidth: number,\n  padInfo: PadInfo3D,\n  inShape: [number, number, number, number, number],\n  outShape: [number, number, number, number, number],\n  filterShape: [number, number, number, number, number]\n};\n\n/**\n * Computes the information for a forward pass of a 3D convolution/pooling\n * operation.\n */\nexport function computeConv3DInfo(\n    inShape: [number, number, number, number, number],\n    filterShape: [number, number, number, number, number],\n    strides: number|[number, number, number],\n    dilations: number|[number, number, number], pad: 'same'|'valid'|number,\n    depthwise = false,\n    dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast',\n    roundingMode?: 'floor'|'round'|'ceil'): Conv3DInfo {\n  let [batchSize, inDepth, inHeight, inWidth, inChannels] =\n      [-1, -1, -1, -1, -1];\n  if (dataFormat === 'channelsLast') {\n    [batchSize, inDepth, inHeight, inWidth, inChannels] = inShape;\n  } else if (dataFormat === 'channelsFirst') {\n    [batchSize, inChannels, inDepth, inHeight, inWidth] = inShape;\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n\n  const [filterDepth, filterHeight, filterWidth, , filterChannels] =\n      filterShape;\n  const [strideDepth, strideHeight, strideWidth] = parse3TupleParam(strides);\n  const [dilationDepth, dilationHeight, dilationWidth] =\n      parse3TupleParam(dilations);\n\n  const effectiveFilterDepth =\n      getEffectiveFilterSize(filterDepth, dilationDepth);\n  const effectiveFilterHeight =\n      getEffectiveFilterSize(filterHeight, dilationHeight);\n  const effectiveFilterWidth =\n      getEffectiveFilterSize(filterWidth, dilationWidth);\n  const {padInfo, outDepth, outHeight, outWidth} = get3DPadAndOutInfo(\n      pad, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth,\n      effectiveFilterDepth, effectiveFilterHeight, effectiveFilterWidth,\n      roundingMode);\n\n  const outChannels = depthwise ? filterChannels * inChannels : filterChannels;\n\n  let outShape: [number, number, number, number, number];\n  if (dataFormat === 'channelsFirst') {\n    outShape = [batchSize, outChannels, outDepth, outHeight, outWidth];\n  } else if (dataFormat === 'channelsLast') {\n    outShape = [batchSize, outDepth, outHeight, outWidth, outChannels];\n  }\n\n  return {\n    batchSize,\n    dataFormat,\n    inDepth,\n    inHeight,\n    inWidth,\n    inChannels,\n    outDepth,\n    outHeight,\n    outWidth,\n    outChannels,\n    padInfo,\n    strideDepth,\n    strideHeight,\n    strideWidth,\n    filterDepth,\n    filterHeight,\n    filterWidth,\n    effectiveFilterDepth,\n    effectiveFilterHeight,\n    effectiveFilterWidth,\n    dilationDepth,\n    dilationHeight,\n    dilationWidth,\n    inShape,\n    outShape,\n    filterShape\n  };\n}\n\nfunction computeOutputShape2D(\n    inShape: [number, number], fieldSize: number, stride: number,\n    zeroPad?: number, roundingMode?: 'floor'|'round'|'ceil'): [number, number] {\n  if (zeroPad == null) {\n    zeroPad = computeDefaultPad(inShape, fieldSize, stride);\n  }\n  const inputRows = inShape[0];\n  const inputCols = inShape[1];\n\n  const outputRows =\n      round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\n  const outputCols =\n      round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\n\n  return [outputRows, outputCols];\n}\n\nfunction computeOutputShape4D(\n    inShape: [number, number, number, number],\n    filterShape: [number, number, number], outChannels: number,\n    strides: [number, number, number], zeroPad?: number,\n    roundingMode?: 'floor'|'round'|'ceil'): [number, number, number, number] {\n  if (zeroPad == null) {\n    zeroPad = computeDefaultPad(inShape, filterShape[0], strides[0]);\n  }\n  const outShape: [number, number, number, number] = [0, 0, 0, outChannels];\n  for (let index = 0; index < 3; index++) {\n    if (inShape[index] + 2 * zeroPad >= filterShape[index]) {\n      outShape[index] = round(\n          (inShape[index] - filterShape[index] + 2 * zeroPad) / strides[index] +\n              1,\n          roundingMode);\n    }\n  }\n  return outShape;\n}\n\nexport function computeDefaultPad(\n    inputShape: [number, number]|[number, number, number, number],\n    fieldSize: number, stride: number, dilation = 1): number {\n  const effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);\n  return Math.floor(\n      (inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);\n}\n\nfunction parseTupleParam(param: number|number[]): [number, number, number] {\n  if (typeof param === 'number') {\n    return [param, param, param];\n  }\n  if (param.length === 2) {\n    return [param[0], param[1], 1];\n  }\n  return param as [number, number, number];\n}\n\nfunction parse3TupleParam(param: number|[number, number, number]):\n    [number, number, number] {\n  return typeof param === 'number' ? [param, param, param] : param;\n}\n\n/* See https://www.tensorflow.org/api_docs/python/tf/nn/atrous_conv2d\n * Atrous convolution is equivalent to standard convolution with upsampled\n * filters with effective_filter_height =\n * filter_height + (filter_height - 1) * (dilation - 1)\n * and effective_filter_width =\n * filter_width + (filter_width - 1) * (dilation - 1),\n * produced by inserting dilation - 1 zeros along consecutive elements across\n * the filters' spatial dimensions.\n * When there is a dilation, this converts a filter dimension to the\n * effective filter dimension, so it can be used in a standard convolution.\n */\nfunction getEffectiveFilterSize(filterSize: number, dilation: number) {\n  if (dilation <= 1) {\n    return filterSize;\n  }\n\n  return filterSize + (filterSize - 1) * (dilation - 1);\n}\n\nfunction getPadAndOutInfo(\n    pad: 'same'|'valid'|number|ExplicitPadding, inHeight: number,\n    inWidth: number, strideHeight: number, strideWidth: number,\n    filterHeight: number, filterWidth: number,\n    roundingMode: 'floor'|'round'|'ceil',\n    dataFormat: 'channelsFirst'|\n    'channelsLast'): {padInfo: PadInfo, outHeight: number, outWidth: number} {\n  let padInfo: PadInfo;\n  let outHeight: number;\n  let outWidth: number;\n\n  if (typeof pad === 'number') {\n    const padType = (pad === 0) ? 'VALID' : 'NUMBER';\n    padInfo = {top: pad, bottom: pad, left: pad, right: pad, type: padType};\n    const outShape = computeOutputShape2D(\n        [inHeight, inWidth], filterHeight, strideHeight, pad, roundingMode);\n    outHeight = outShape[0];\n    outWidth = outShape[1];\n  } else if (pad === 'same') {\n    outHeight = Math.ceil(inHeight / strideHeight);\n    outWidth = Math.ceil(inWidth / strideWidth);\n    const padAlongHeight =\n        Math.max(0, (outHeight - 1) * strideHeight + filterHeight - inHeight);\n    const padAlongWidth =\n        Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);\n    const top = Math.floor(padAlongHeight / 2);\n    const bottom = padAlongHeight - top;\n    const left = Math.floor(padAlongWidth / 2);\n    const right = padAlongWidth - left;\n    padInfo = {top, bottom, left, right, type: 'SAME'};\n  } else if (pad === 'valid') {\n    padInfo = {top: 0, bottom: 0, left: 0, right: 0, type: 'VALID'};\n    outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);\n    outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);\n  } else if (typeof pad === 'object') {\n    const top = dataFormat === 'channelsLast' ? pad[1][0] : pad[2][0];\n    const bottom = dataFormat === 'channelsLast' ? pad[1][1] : pad[2][1];\n    const left = dataFormat === 'channelsLast' ? pad[2][0] : pad[3][0];\n    const right = dataFormat === 'channelsLast' ? pad[2][1] : pad[3][1];\n    const padType = (top === 0 && bottom === 0 && left === 0 && right === 0) ?\n        'VALID' :\n        'EXPLICIT';\n    padInfo = {top, bottom, left, right, type: padType};\n    outHeight = round(\n        (inHeight - filterHeight + top + bottom) / strideHeight + 1,\n        roundingMode);\n    outWidth = round(\n        (inWidth - filterWidth + left + right) / strideWidth + 1, roundingMode);\n  } else {\n    throw Error(`Unknown padding parameter: ${pad}`);\n  }\n  return {padInfo, outHeight, outWidth};\n}\n\nfunction get3DPadAndOutInfo(\n    pad: 'same'|'valid'|number, inDepth: number, inHeight: number,\n    inWidth: number, strideDepth: number, strideHeight: number,\n    strideWidth: number, filterDepth: number, filterHeight: number,\n    filterWidth: number, roundingMode?: 'floor'|'round'|'ceil'): {\n  padInfo: PadInfo3D,\n  outDepth: number,\n  outHeight: number,\n  outWidth: number\n} {\n  let padInfo: PadInfo3D;\n  let outDepth: number;\n  let outHeight: number;\n  let outWidth: number;\n\n  if (pad === 'valid') {\n    pad = 0;\n  }\n\n  if (typeof pad === 'number') {\n    const padType = (pad === 0) ? 'VALID' : 'NUMBER';\n    padInfo = {\n      top: pad,\n      bottom: pad,\n      left: pad,\n      right: pad,\n      front: pad,\n      back: pad,\n      type: padType\n    };\n    const outShape = computeOutputShape4D(\n        [inDepth, inHeight, inWidth, 1],\n        [filterDepth, filterHeight, filterWidth], 1,\n        [strideDepth, strideHeight, strideWidth], pad, roundingMode);\n    outDepth = outShape[0];\n    outHeight = outShape[1];\n    outWidth = outShape[2];\n  } else if (pad === 'same') {\n    outDepth = Math.ceil(inDepth / strideDepth);\n    outHeight = Math.ceil(inHeight / strideHeight);\n    outWidth = Math.ceil(inWidth / strideWidth);\n    const padAlongDepth = (outDepth - 1) * strideDepth + filterDepth - inDepth;\n    const padAlongHeight =\n        (outHeight - 1) * strideHeight + filterHeight - inHeight;\n    const padAlongWidth = (outWidth - 1) * strideWidth + filterWidth - inWidth;\n    const front = Math.floor(padAlongDepth / 2);\n    const back = padAlongDepth - front;\n    const top = Math.floor(padAlongHeight / 2);\n    const bottom = padAlongHeight - top;\n    const left = Math.floor(padAlongWidth / 2);\n    const right = padAlongWidth - left;\n\n    padInfo = {top, bottom, left, right, front, back, type: 'SAME'};\n  } else {\n    throw Error(`Unknown padding parameter: ${pad}`);\n  }\n  return {padInfo, outDepth, outHeight, outWidth};\n}\n\n/**\n * Rounds a value depending on the rounding mode\n * @param value\n * @param roundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n */\nfunction round(value: number, roundingMode?: 'floor'|'round'|'ceil') {\n  if (!roundingMode) {\n    return Math.trunc(value);\n  }\n  switch (roundingMode) {\n    case 'round':\n      // used for Caffe Conv\n      return Math.round(value);\n    case 'ceil':\n      // used for Caffe Pool\n      return Math.ceil(value);\n    case 'floor':\n      return Math.floor(value);\n    default:\n      throw new Error(`Unknown roundingMode ${roundingMode}`);\n  }\n}\n\nexport function tupleValuesAreOne(param: number|number[]): boolean {\n  const [dimA, dimB, dimC] = parseTupleParam(param);\n  return dimA === 1 && dimB === 1 && dimC === 1;\n}\n\nexport function eitherStridesOrDilationsAreOne(\n    strides: number|number[], dilations: number|number[]): boolean {\n  return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);\n}\n\nexport function stridesOrDilationsArePositive(values: number|\n                                              number[]): boolean {\n  return parseTupleParam(values).every(value => value > 0);\n}\n\n/**\n * Convert Conv2D dataFormat from 'NHWC'|'NCHW' to\n *    'channelsLast'|'channelsFirst'\n * @param dataFormat in 'NHWC'|'NCHW' mode\n * @return dataFormat in 'channelsLast'|'channelsFirst' mode\n * @throws unknown dataFormat\n */\nexport function convertConv2DDataFormat(dataFormat: 'NHWC'|'NCHW'):\n    'channelsLast'|'channelsFirst' {\n  if (dataFormat === 'NHWC') {\n    return 'channelsLast';\n  } else if (dataFormat === 'NCHW') {\n    return 'channelsFirst';\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n}\n\n/**\n * Check validity of pad when using dimRoundingMode.\n * @param opDesc A string of op description\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid` output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @throws unknown padding parameter\n */\nexport function checkPadOnDimRoundingMode(\n    opDesc: string, pad: 'valid'|'same'|number|ExplicitPadding,\n    dimRoundingMode?: 'floor'|'round'|'ceil') {\n  if (dimRoundingMode != null) {\n    if (typeof pad === 'string') {\n      throw Error(\n          `Error in ${opDesc}: pad must be an integer when using ` +\n          `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n    } else if (typeof pad === 'number') {\n      util.assert(\n          util.isInt(pad),\n          () => `Error in ${opDesc}: pad must be an integer when using ` +\n              `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n    } else if (typeof pad === 'object') {\n      (pad as ExplicitPadding).forEach(p => {\n        p.forEach(v => {\n          util.assert(\n              util.isInt(v),\n              () => `Error in ${opDesc}: pad must be an integer when using ` +\n                  `dimRoundingMode ${dimRoundingMode} but got pad ${v}.`);\n        });\n      });\n    } else {\n      throw Error(`Error in ${opDesc}: Unknown padding parameter: ${pad}`);\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reshape, ReshapeAttrs, ReshapeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Reshapes a `tf.Tensor` to a given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * If one component of shape is the special value -1, the size of that\n * dimension is computed so that the total size remains constant. In\n * particular, a shape of [-1] flattens into 1-D. At most one component of\n * shape can be -1.\n *\n * If shape is 1-D or higher, then the operation returns a tensor with shape\n * shape filled with the values of tensor. In this case, the number of\n * elements implied by shape must be the same as the number of elements in\n * tensor.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.reshape([2, 2]).print();\n * ```\n *\n * @param x The input tensor to be reshaped.\n * @param shape An array of integers defining the output tensor shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction reshape_<R extends Rank>(\n    x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor<R> {\n  const $x = convertToTensor(x, 'x', 'reshape', 'string_or_numeric');\n\n  const inputs: ReshapeInputs = {x: $x};\n  const attrs: ReshapeAttrs = {shape};\n  return ENGINE.runKernel(\n      Reshape, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\nexport const reshape = /* @__PURE__ */ op({reshape_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {AvgPool, AvgPoolAttrs, AvgPoolInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 2D average pooling of an image.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n *     `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n *     `strides` is a single number, then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm:\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *         https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction avgPool_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filterSize: [number, number]|number,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'avgPool', 'float32');\n  const dilations = 1;\n\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in avgPool: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);\n  conv_util.checkPadOnDimRoundingMode('avgPool', pad, dimRoundingMode);\n  const inputs: AvgPoolInputs = {x: x4D};\n  const attrs: AvgPoolAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  let res = ENGINE.runKernel(\n                AvgPool, inputs as unknown as NamedTensorMap,\n                attrs as unknown as NamedAttrMap) as T;\n\n  res = cast(res, $x.dtype);\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n\n  return res;\n}\n\nexport const avgPool = /* @__PURE__ */ op({avgPool_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {AvgPool3D, AvgPool3DAttrs, AvgPool3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {checkPadOnDimRoundingMode} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 3D average pooling.\n *\n * ```js\n * const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);\n * const result = tf.avgPool3d(x, 2, 1, 'valid');\n * result.print();\n * ```\n *\n * @param x The input tensor, of rank 5 or rank 4 of shape\n *     `[batch, depth, height, width, inChannels]`.\n * @param filterSize The filter size:\n *     `[filterDepth, filterHeight, filterWidth]`.\n *     If `filterSize` is a single number,\n *     then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n *     `[strideDepth, strideHeight, strideWidth]`.\n *     If `strides` is a single number,\n *     then `strideDepth == strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1*1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n *     \"NDHWC\". Specify the data format of the input and output data. With the\n *     default format \"NDHWC\", the data is stored in the order of: [batch,\n *     depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction avgPool3d_<T extends Tensor4D|Tensor5D>(\n    x: T|TensorLike, filterSize: [number, number, number]|number,\n    strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n    dimRoundingMode?: 'floor'|'round'|'ceil',\n    dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): T {\n  const $x = convertToTensor(x, 'x', 'avgPool3d', 'float32');\n\n  let x5D = $x as Tensor5D;\n  let reshapedTo5D = false;\n  if ($x.rank === 4) {\n    reshapedTo5D = true;\n    x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n  }\n\n  util.assert(\n      x5D.rank === 5,\n      () => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`);\n  util.assert(\n      dataFormat === 'NDHWC',\n      () => `Error in avgPool3d: Only NDHWC is currently supported, ` +\n          `but got dataFormat of ${dataFormat}`);\n  util.assert(\n      (typeof strides === 'number' && strides > 0) ||\n          (Array.isArray(strides) && strides[0] > 0 && strides[1] > 0 &&\n           strides[2] > 0),\n      () => `Error in avgPool3d: Stride must be > 0, but got '${strides}'`);\n  checkPadOnDimRoundingMode('avgPool3d', pad, dimRoundingMode);\n  const inputs: AvgPool3DInputs = {x: x5D};\n  const attrs:\n      AvgPool3DAttrs = {filterSize, strides, pad, dimRoundingMode, dataFormat};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  let res = ENGINE.runKernel(\n                AvgPool3D, inputs as unknown as NamedTensorMap,\n                attrs as unknown as NamedAttrMap) as T;\n\n  res = cast(res, x5D.dtype);\n\n  if (reshapedTo5D) {\n    return reshape(\n               res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n        T;\n  }\n\n  return res;\n}\n\nexport const avgPool3d = /* @__PURE__ */ op({avgPool3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Concat, ConcatAttrs, ConcatInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\n\nimport {clone} from './clone';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor`s along a given axis.\n *\n * The tensors ranks and types must match, and their sizes must match in all\n * dimensions except `axis`.\n *\n * Also available are stricter rank-specific methods that assert that\n * `tensors` are of the given rank:\n *   - `tf.concat1d`\n *   - `tf.concat2d`\n *   - `tf.concat3d`\n *   - `tf.concat4d`\n *\n * Except `tf.concat1d` (which does not have axis param), all methods have\n * same signature as this method.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * a.concat(b).print();  // or a.concat(b)\n * ```\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n * tf.concat([a, b, c]).print();\n * ```\n *\n * ```js\n * const a = tf.tensor2d([[1, 2], [10, 20]]);\n * const b = tf.tensor2d([[3, 4], [30, 40]]);\n * const axis = 1;\n * tf.concat([a, b], axis).print();\n * ```\n * @param tensors A list of tensors to concatenate.\n * @param axis The axis to concatenate along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction concat_<T extends Tensor>(tensors: Array<T|TensorLike>, axis = 0): T {\n  assert(tensors.length >= 1, () => 'Pass at least one tensor to concat');\n\n  const $tensors =\n      convertToTensorArray(tensors, 'tensors', 'concat', 'string_or_numeric');\n\n  if ($tensors[0].dtype === 'complex64') {\n    $tensors.forEach(tensor => {\n      if (tensor.dtype !== 'complex64') {\n        throw new Error(`Cannot concatenate complex64 tensors with a tensor\n          with dtype ${tensor.dtype}. `);\n      }\n    });\n  }\n\n  if ($tensors.length === 1) {\n    return clone($tensors[0]);\n  }\n\n  const inputs: ConcatInputs = $tensors;\n  const attr: ConcatAttrs = {axis};\n\n  return ENGINE.runKernel(\n      Concat, inputs as unknown as NamedTensorMap,\n      attr as unknown as NamedAttrMap);\n}\n\nexport const concat = /* @__PURE__ */ op({concat_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the dot product of two matrices, A * B. These must be matrices.\n *\n * ```js\n * const a = tf.tensor2d([1, 2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.matMul(b).print();  // or tf.matMul(a, b)\n * ```\n * @param a First matrix in dot product operation.\n * @param b Second matrix in dot product operation.\n * @param transposeA If true, `a` is transposed before multiplication.\n * @param transposeB If true, `b` is transposed before multiplication.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction matMul_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike, transposeA = false,\n    transposeB = false): T {\n  let $a = convertToTensor(a, 'a', 'matMul');\n  let $b = convertToTensor(b, 'b', 'matMul');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: BatchMatMulInputs = {a: $a, b: $b};\n  const attrs: BatchMatMulAttrs = {transposeA, transposeB};\n\n  return ENGINE.runKernel(\n      BatchMatMul, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const matMul = /* @__PURE__ */ op({matMul_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sigmoid, SigmoidInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes sigmoid element-wise, `1 / (1 + exp(-x))`\n *\n * ```js\n * const x = tf.tensor1d([0, -1, 2, -3]);\n *\n * x.sigmoid().print();  // or tf.sigmoid(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sigmoid_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sigmoid', 'float32');\n\n  const inputs: SigmoidInputs = {x: $x};\n\n  return ENGINE.runKernel(Sigmoid, inputs as unknown as NamedTensorMap);\n}\nexport const sigmoid = /* @__PURE__ */ op({sigmoid_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Slice, SliceAttrs, SliceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Extracts a slice from a `tf.Tensor` starting at coordinates `begin`\n * and is of size `size`.\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that `x` is of the given rank:\n *   - `tf.slice1d`\n *   - `tf.slice2d`\n *   - `tf.slice3d`\n *   - `tf.slice4d`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.slice([1], [2]).print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * x.slice([1, 0], [1, 2]).print();\n * ```\n * @param x The input `tf.Tensor` to slice from.\n * @param begin The coordinates to start the slice from. The length can be\n *     less than the rank of x - the rest of the axes will have implicit 0 as\n *     start. Can also be a single number, in which case it specifies the\n *     first axis.\n * @param size The size of the slice. The length can be less than the rank of\n *     x - the rest of the axes will have implicit -1. A value of -1 requests\n *     the rest of the dimensions in the axis. Can also be a single number,\n *     in which case it specifies the size of the first axis.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction slice_<R extends Rank, T extends Tensor<R>>(\n    x: T|TensorLike, begin: number|number[], size?: number|number[]): T {\n  const $x = convertToTensor(x, 'x', 'slice', 'string_or_numeric');\n\n  if ($x.rank === 0) {\n    throw new Error('Slicing scalar is not possible');\n  }\n\n  const inputs: SliceInputs = {x: $x};\n  const attrs: SliceAttrs = {begin, size};\n\n  return ENGINE.runKernel(\n      Slice, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const slice = /* @__PURE__ */ op({slice_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tanh, TanhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic tangent of the input `tf.Tensor` element-wise: `tanh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, 70]);\n *\n * x.tanh().print();  // or tf.tanh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction tanh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'tanh', 'float32');\n\n  const inputs: TanhInputs = {x: $x};\n\n  return ENGINE.runKernel(Tanh, inputs as unknown as NamedTensorMap);\n}\nexport const tanh = /* @__PURE__ */ op({tanh_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {add} from './add';\nimport {concat} from './concat';\nimport {matMul} from './mat_mul';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {sigmoid} from './sigmoid';\nimport {slice} from './slice';\nimport {tanh} from './tanh';\n\n/**\n * Computes the next state and output of a BasicLSTMCell.\n *\n * Returns `[newC, newH]`.\n *\n * Derived from tf.contrib.rnn.BasicLSTMCell.\n *\n * @param forgetBias Forget bias for the cell.\n * @param lstmKernel The weights for the cell.\n * @param lstmBias The bias for the cell.\n * @param data The input to the cell.\n * @param c Previous cell state.\n * @param h Previous cell output.\n *\n * @doc {heading: 'Operations', subheading: 'RNN'}\n */\nfunction basicLSTMCell_(\n    forgetBias: Scalar|TensorLike, lstmKernel: Tensor2D|TensorLike,\n    lstmBias: Tensor1D|TensorLike, data: Tensor2D|TensorLike,\n    c: Tensor2D|TensorLike, h: Tensor2D|TensorLike): [Tensor2D, Tensor2D] {\n  const $forgetBias =\n      convertToTensor(forgetBias, 'forgetBias', 'basicLSTMCell');\n  const $lstmKernel =\n      convertToTensor(lstmKernel, 'lstmKernel', 'basicLSTMCell');\n  const $lstmBias = convertToTensor(lstmBias, 'lstmBias', 'basicLSTMCell');\n  const $data = convertToTensor(data, 'data', 'basicLSTMCell');\n  const $c = convertToTensor(c, 'c', 'basicLSTMCell');\n  const $h = convertToTensor(h, 'h', 'basicLSTMCell');\n\n  const combined = concat([$data, $h], 1);\n  const weighted = matMul(combined, $lstmKernel);\n  const res: Tensor2D = add(weighted, $lstmBias);\n\n  // i = input_gate, j = new_input, f = forget_gate, o = output_gate\n  const batchSize = res.shape[0];\n  const sliceCols = res.shape[1] / 4;\n  const sliceSize: [number, number] = [batchSize, sliceCols];\n  const i = slice(res, [0, 0], sliceSize);\n  const j = slice(res, [0, sliceCols], sliceSize);\n  const f = slice(res, [0, sliceCols * 2], sliceSize);\n  const o = slice(res, [0, sliceCols * 3], sliceSize);\n\n  const newC: Tensor2D =\n      add(mul(sigmoid(i), tanh(j)),\n          mul($c, sigmoid(add($forgetBias, f)) as Tensor2D));\n  const newH: Tensor2D = mul(tanh(newC), sigmoid(o));\n  return [newC, newH];\n}\n\nexport const basicLSTMCell = /* @__PURE__ */ op({basicLSTMCell_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * This operation reshapes the \"batch\" dimension 0 into `M + 1` dimensions of\n * shape `blockShape + [batch]`, interleaves these blocks back into the grid\n * defined by the spatial dimensions `[1, ..., M]`, to obtain a result with\n * the same rank as the input. The spatial dimensions of this intermediate\n * result are then optionally cropped according to `crops` to produce the\n * output. This is the reverse of `tf.spaceToBatchND`. See below for a precise\n * description.\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);\n * const blockShape = [2, 2];\n * const crops = [[0, 0], [0, 0]];\n *\n * x.batchToSpaceND(blockShape, crops).print();\n * ```\n *\n * @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +\n * remainingShape`, where spatialShape has `M` dimensions.\n * @param blockShape A 1-D array. Must have shape `[M]`, all values must\n * be >= 1.\n * @param crops A 2-D array.  Must have shape `[M, 2]`, all values must be >= 0.\n * `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input\n * dimension `i + 1`, which corresponds to spatial dimension `i`. It is required\n * that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`\n *\n * This operation is equivalent to the following steps:\n *\n * 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,\n * blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,\n * x.shape[N-1]]`\n *\n * 2. Permute dimensions of `reshaped` to produce `permuted` of shape `[batch /\n * prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],\n * blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /\n * prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *\n * blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`\n * according to `crops` to produce the output of shape: `[batch /\n * prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],\n * ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -\n * crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction batchToSpaceND_<T extends Tensor>(\n    x: T|TensorLike, blockShape: number[], crops: number[][]): T {\n  const $x = convertToTensor(x, 'x', 'batchToSpaceND');\n  const prod = blockShape.reduce((a, b) => a * b);\n\n  util.assert(\n      $x.rank >= 1 + blockShape.length,\n      () => `input rank is ${$x.rank} but should be > than blockShape.length ${\n          blockShape.length}`);\n\n  util.assert(\n      crops.length === blockShape.length,\n      () => `crops.length is ${\n          crops.length} but should be equal to blockShape.length  ${\n          blockShape.length}`);\n\n  util.assert(\n      $x.shape[0] % prod === 0,\n      () => `input tensor batch is ${\n                $x.shape[0]} but is not divisible by the product of ` +\n          `the elements of blockShape ${blockShape.join(' * ')} === ${prod}`);\n\n  const inputs: BatchToSpaceNDInputs = {x: $x};\n  const attrs: BatchToSpaceNDAttrs = {blockShape, crops};\n\n  return ENGINE.runKernel(\n      BatchToSpaceND, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const batchToSpaceND = /* @__PURE__ */ op({batchToSpaceND_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor, Tensor4D} from '../tensor';\nimport {Rank} from '../types';\nimport {reshape} from './reshape';\n\nexport function xAs4D<R extends Rank>(x: Tensor<R>) {\n  let x4D: Tensor4D;\n  if (x.rank === 0 || x.rank === 1) {\n    x4D = reshape(x, [1, 1, 1, x.size]);\n  } else if (x.rank === 2) {\n    x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);\n  } else if (x.rank === 3) {\n    x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n  } else {\n    x4D = x as Tensor4D;\n  }\n\n  return x4D;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {xAs4D} from './batchnorm_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Batch normalization.\n *\n * As described in\n * [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).\n *\n * Mean, variance, scale, and offset can be of two shapes:\n *   - The same shape as the input.\n *   - In the common case, the depth dimension is the last dimension of x, so\n *     the values would be a `tf.Tensor1D` of shape [depth].\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that parameters passed are of given rank\n *   - `tf.batchNorm2d`\n *   - `tf.batchNorm3d`\n *   - `tf.batchNorm4d`\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction batchNorm_<R extends Rank>(\n    x: Tensor<R>|TensorLike, mean: Tensor<R>|Tensor1D|TensorLike,\n    variance: Tensor<R>|Tensor1D|TensorLike,\n    offset?: Tensor<R>|Tensor1D|TensorLike,\n    scale?: Tensor<R>|Tensor1D|TensorLike,\n    varianceEpsilon?: number): Tensor<R> {\n  if (varianceEpsilon == null) {\n    varianceEpsilon = 0.001;\n  }\n  const $x = convertToTensor(x, 'x', 'batchNorm');\n  const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n  const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n  let $scale: Tensor<R>|Tensor1D;\n  if (scale != null) {\n    $scale = convertToTensor(scale, 'scale', 'batchNorm');\n  }\n  let $offset: Tensor<R>|Tensor1D;\n  if (offset != null) {\n    $offset = convertToTensor(offset, 'offset', 'batchNorm');\n  }\n\n  util.assert(\n      $mean.rank === $variance.rank,\n      () => 'Batch normalization gradient requires mean and variance to have ' +\n          'equal ranks.');\n  util.assert(\n      $offset == null || $mean.rank === $offset.rank,\n      () => 'Batch normalization gradient requires mean and offset to have ' +\n          'equal ranks.');\n  util.assert(\n      $scale == null || $mean.rank === $scale.rank,\n      () => 'Batch normalization gradient requires mean and scale to have ' +\n          'equal ranks.');\n\n  const x4D: Tensor4D = xAs4D($x);\n\n  const inputs: FusedBatchNormInputs = {\n    x: x4D,\n    scale: $scale,\n    offset: $offset,\n    mean: $mean,\n    variance: $variance\n  };\n\n  const attrs: FusedBatchNormAttrs = {varianceEpsilon};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  FusedBatchNorm, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as Tensor<R>;\n\n  return reshape(res, $x.shape);\n}\n\nexport const batchNorm = /* @__PURE__ */ op({batchNorm_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 2D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm2d_(\n    x: Tensor2D|TensorLike, mean: Tensor2D|Tensor1D|TensorLike,\n    variance: Tensor2D|Tensor1D|TensorLike,\n    offset?: Tensor2D|Tensor1D|TensorLike, scale?: Tensor2D|Tensor1D|TensorLike,\n    varianceEpsilon?: number): Tensor2D {\n  const $x = convertToTensor(x, 'x', 'batchNorm');\n  const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n  const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n  let $scale: Tensor2D|Tensor1D;\n  if (scale != null) {\n    $scale = convertToTensor(scale, 'scale', 'batchNorm');\n  }\n  let $offset: Tensor2D|Tensor1D;\n  if (offset != null) {\n    $offset = convertToTensor(offset, 'offset', 'batchNorm');\n  }\n  util.assert(\n      $x.rank === 2,\n      () => `Error in batchNorm2D: x must be rank 2 but got rank ` +\n          `${$x.rank}.`);\n  util.assert(\n      $mean.rank === 2 || $mean.rank === 1,\n      () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but ` +\n          `got rank ${$mean.rank}.`);\n  util.assert(\n      $variance.rank === 2 || $variance.rank === 1,\n      () => `Error in batchNorm2D: variance must be rank 2 or rank 1 ` +\n          `but got rank ${$variance.rank}.`);\n  if ($scale != null) {\n    util.assert(\n        $scale.rank === 2 || $scale.rank === 1,\n        () => `Error in batchNorm2D: scale must be rank 2 or rank 1 ` +\n            `but got rank ${$scale.rank}.`);\n  }\n  if ($offset != null) {\n    util.assert(\n        $offset.rank === 2 || $offset.rank === 1,\n        () => `Error in batchNorm2D: offset must be rank 2 or rank 1 ` +\n            `but got rank ${$offset.rank}.`);\n  }\n\n  return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm2d = /* @__PURE__ */ op({batchNorm2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 3D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm3d_(\n    x: Tensor3D|TensorLike, mean: Tensor3D|Tensor1D|TensorLike,\n    variance: Tensor3D|Tensor1D|TensorLike,\n    offset?: Tensor3D|Tensor1D|TensorLike, scale?: Tensor3D|Tensor1D|TensorLike,\n    varianceEpsilon?: number): Tensor3D {\n  const $x = convertToTensor(x, 'x', 'batchNorm');\n  const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n  const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n  let $scale: Tensor3D|Tensor1D;\n  if (scale != null) {\n    $scale = convertToTensor(scale, 'scale', 'batchNorm');\n  }\n  let $offset: Tensor3D|Tensor1D;\n  if (offset != null) {\n    $offset = convertToTensor(offset, 'offset', 'batchNorm');\n  }\n  util.assert(\n      $x.rank === 3,\n      () => `Error in batchNorm3D: x must be rank 3 but got rank ` +\n          `${$x.rank}.`);\n  util.assert(\n      $mean.rank === 3 || $mean.rank === 1,\n      () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but ` +\n          `got rank ${$mean.rank}.`);\n  util.assert(\n      $variance.rank === 3 || $variance.rank === 1,\n      () => `Error in batchNorm3D: variance must be rank 3 or rank 1 ` +\n          `but got rank ${$variance.rank}.`);\n  if ($scale != null) {\n    util.assert(\n        $scale.rank === 3 || $scale.rank === 1,\n        () => `Error in batchNorm3D: scale must be rank 3 or rank 1 ` +\n            `but got rank ${$scale.rank}.`);\n  }\n  if ($offset != null) {\n    util.assert(\n        $offset.rank === 3 || $offset.rank === 1,\n        () => `Error in batchNorm3D: offset must be rank 3 or rank 1 ` +\n            `but got rank ${$offset.rank}.`);\n  }\n\n  return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm3d = /* @__PURE__ */ op({batchNorm3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 4D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm4d_(\n    x: Tensor4D|TensorLike, mean: Tensor4D|Tensor1D|TensorLike,\n    variance: Tensor4D|Tensor1D|TensorLike,\n    offset?: Tensor4D|Tensor1D|TensorLike, scale?: Tensor4D|Tensor1D|TensorLike,\n    varianceEpsilon?: number): Tensor4D {\n  const $x = convertToTensor(x, 'x', 'batchNorm');\n  const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n  const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n  let $scale: Tensor4D|Tensor1D;\n  if (scale != null) {\n    $scale = convertToTensor(scale, 'scale', 'batchNorm');\n  }\n  let $offset: Tensor4D|Tensor1D;\n  if (offset != null) {\n    $offset = convertToTensor(offset, 'offset', 'batchNorm');\n  }\n  util.assert(\n      $x.rank === 4,\n      () => `Error in batchNorm4D: x must be rank 4 but got rank ` +\n          `${$x.rank}.`);\n  util.assert(\n      $mean.rank === 4 || $mean.rank === 1,\n      () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but ` +\n          `got rank ${$mean.rank}.`);\n  util.assert(\n      $variance.rank === 4 || $variance.rank === 1,\n      () => `Error in batchNorm4D: variance must be rank 4 or rank 1 ` +\n          `but got rank ${$variance.rank}.`);\n  if ($scale != null) {\n    util.assert(\n        $scale.rank === 4 || $scale.rank === 1,\n        () => `Error in batchNorm4D: scale must be rank 4 or rank 1 ` +\n            `but got rank ${$scale.rank}.`);\n  }\n  if ($offset != null) {\n    util.assert(\n        $offset.rank === 4 || $offset.rank === 1,\n        () => `Error in batchNorm4D: offset must be rank 4 or rank 1 ` +\n            `but got rank ${$offset.rank}.`);\n  }\n  return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm4d = /* @__PURE__ */ op({batchNorm4d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Bincount, BincountAttrs, BincountInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Outputs a vector with length `size` and the same dtype as `weights`.\n *\n * If `weights` are empty, then index `i` stores the number of times the value\n * `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the\n * sum of the value in `weights` at each index where the corresponding value in\n * `x` is `i`.\n *\n * Values in `x` outside of the range [0, size) are ignored.\n *\n * @param x The input int tensor, rank 1.\n * @param weights The weights tensor, must have the same shape as x, or a\n *     length-0 Tensor, in which case it acts as all weights equal to 1.\n * @param size Non-negative integer.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction bincount_<T extends Tensor1D>(\n    x: T|TensorLike, weights: T|TensorLike, size: number): T {\n  const $x = convertToTensor(x, 'x', 'bincount');\n  const $weights = convertToTensor(weights, 'weights', 'bincount');\n\n  util.assert(\n      $x.dtype === 'int32',\n      () => `Error in bincount: input ` +\n          `dtype must be int32, but got ${$x.dtype}`);\n  util.assert(size >= 0, () => `size must be non-negative, but got ${size}.`);\n  util.assert(\n      $weights.size === $x.size || $weights.size === 0,\n      () => `Error in bincount: weights must have the same size as input or` +\n          `0-length, but got input shape: ${$x.shape}, weights shape: ` +\n          `${$weights.shape}.`);\n\n  const inputs: BincountInputs = {x: $x, weights: $weights};\n  const attrs: BincountAttrs = {size};\n\n  return ENGINE.runKernel(\n      Bincount, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const bincount = /* @__PURE__ */ op({bincount_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {BitwiseAnd, BitwiseAndInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank} from '../types';\nimport {arraysEqual} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Bitwise `AND` operation for input tensors.\n *\n * Given two input tensors, returns a new tensor\n * with the `AND` calculated values.\n *\n * The method supports int32 values\n *\n *\n * ```js\n * const x = tf.tensor1d([0, 5, 3, 14], 'int32');\n * const y = tf.tensor1d([5, 0, 7, 11], 'int32');\n * tf.bitwiseAnd(x, y).print();\n * ```\n *\n * @param x The input tensor to be calculated.\n * @param y The input tensor to be calculated.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction bitwiseAnd_<R extends Rank>(x: Tensor, y: Tensor): Tensor<R> {\n  const $x = convertToTensor(x, 'x', 'bitwiseAnd');\n  const $y = convertToTensor(y, 'y', 'bitwiseAnd');\n\n  if (!arraysEqual($x.shape, $y.shape)) {\n    throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${\n        $x.shape}, y: ${$y.shape}`);\n  }\n  if ($x.dtype !== 'int32' || $y.dtype !== 'int32') {\n    throw new Error(\n        `BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${\n            $x.dtype} and type of y: ${$y.dtype}`);\n  }\n\n  const inputs: BitwiseAndInputs = {a: $x, b: $y};\n  return ENGINE.runKernel(BitwiseAnd, inputs as unknown as NamedTensorMap);\n}\nexport const bitwiseAnd = /* @__PURE__ */ op({bitwiseAnd_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { NamedTensorMap } from '../tensor_types';\nimport { ENGINE } from '../engine';\nimport { BroadcastArgs, BroadcastArgsInputs } from '../kernel_names';\nimport { Tensor } from '../tensor';\nimport { convertToTensor } from '../tensor_util_env';\nimport { Rank, TensorLike } from '../types';\n\nimport { op } from './operation';\n\n/**\n * Return the shape of s0 op s1 with broadcast.\n *\n * compute r0, the broadcasted shape as a tensor.\n * s0, s1 and r0 are all integer vectors.\n *\n * This function returns the shape of the result of an operation between\n * two tensors of size s0 and s1 performed with broadcast.\n *\n * @param s0 A tensor representing a shape\n * @param s1 A tensor representing a shape\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction broadcastArgs_<R extends Rank>(\n  s0: Tensor | TensorLike, s1: Tensor | TensorLike): Tensor<R> {\n  const shape1Input = convertToTensor(s0, 's0', 'broadcastArgs', 'int32');\n  const shape2Input = convertToTensor(s1, 's1', 'broadcastArgs', 'int32');\n\n  if (shape1Input.rank !== 1) {\n    throw new Error(\n      'broadcastArgs(): first input must be a vector (rank=1). ' +\n      `Has rank ${shape1Input.rank}`);\n  }\n\n  if (shape2Input.rank !== 1) {\n    throw new Error(\n      'broadcastArgs(): second input must be a vector (rank=1). ' +\n      `Has rank ${shape2Input.rank}`);\n  }\n\n  const inputs: BroadcastArgsInputs = { s0: shape1Input, s1: shape2Input };\n  return ENGINE.runKernel(BroadcastArgs, inputs as unknown as NamedTensorMap);\n}\n\nexport const broadcastArgs = /* @__PURE__ */ op({ broadcastArgs_ });\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tile, TileAttrs, TileInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {clone} from './clone';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Broadcast an array to a compatible shape NumPy-style.\n *\n * The tensor's shape is compared to the broadcast shape from end to beginning.\n * Ones are prepended to the tensor's shape until it has the same length as\n * the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is\n * already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then\n * the input tensor is tiled N times along that axis (using tf.tile).\n *\n * @param input The tensor that is to be broadcasted.\n * @param shape The input is to be broadcast to this shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction broadcastTo_<R extends Rank>(\n    x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor<R> {\n  let input = convertToTensor(x, 'broadcastTo', 'x');\n  const xShape = input.shape;\n\n  assertNonNegativeIntegerDimensions(shape);\n\n  if (shape.length < input.rank) {\n    throw new Error(`broadcastTo(): shape.length=${shape.length} < input.rank=${\n        input.rank}.`);\n  }\n\n  if (shape.length > input.rank) {\n    const newShape = input.shape.slice();\n    while (newShape.length < shape.length) {\n      newShape.unshift(1);\n    }\n    input = reshape(input, newShape);\n  }\n\n  const inputShape = input.shape;\n  const reps: number[] = Array.from(shape);\n  for (let i = shape.length - 1; i >= 0; i--) {\n    if (inputShape[i] === shape[i]) {\n      reps[i] = 1;\n    } else if (input.shape[i] !== 1) {\n      throw new Error(\n          `broadcastTo(): [${xShape}] cannot be broadcast to [${shape}].`);\n    }\n  }\n  const axes = reps.map((n, i) => n > 1 ? i : -1).filter(i => i >= 0);\n\n  if (axes.length === 0) {\n    return clone(input) as Tensor<R>;\n  }\n\n  // TODO call broadcastTo kernel directly once backends implement broadcstTo\n  const inputs: TileInputs = {x: input};\n  const attrs: TileAttrs = {reps};\n  return ENGINE.runKernel(\n      Tile, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const broadcastTo = /* @__PURE__ */ op({broadcastTo_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Ceil, CeilInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.ceil().print();  // or tf.ceil(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction ceil_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'ceil', 'float32');\n\n  const inputs: CeilInputs = {x: $x};\n  return ENGINE.runKernel(Ceil, inputs as unknown as NamedTensorMap);\n}\nexport const ceil = /* @__PURE__ */ op({ceil_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Fill, FillAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {inferDtype} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\n/**\n * Creates a `tf.Tensor` filled with a scalar value.\n *\n * ```js\n * tf.fill([2, 2], 4).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param value The scalar value to fill the tensor with.\n * @param dtype The type of an element in the resulting tensor. Defaults to\n *     'float32' if the given param value is a number, otherwise 'string'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction fill<R extends Rank>(\n    shape: ShapeMap[R], value: number|string, dtype?: DataType): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n\n  dtype = dtype || inferDtype(value);\n  const attrs: FillAttrs = {shape, value, dtype};\n\n  return ENGINE.runKernel(Fill, {}, attrs as unknown as NamedAttrMap);\n}\n\nexport {fill};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {ClipByValue, ClipByValueAttrs, ClipByValueInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {fill} from './fill';\n\nimport {op} from './operation';\n\n/**\n * Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.clipByValue(-2, 3).print();  // or tf.clipByValue(x, -2, 3)\n * ```\n * @param x The input tensor.\n * @param clipValueMin Lower bound of range to be clipped to.\n * @param clipValueMax Upper bound of range to be clipped to.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction clipByValue_<T extends Tensor>(\n    x: T|TensorLike, clipValueMin: number, clipValueMax: number): T {\n  const $x = convertToTensor(x, 'x', 'clipByValue');\n  util.assert(\n      (clipValueMin <= clipValueMax),\n      () => `Error in clip: min (${clipValueMin}) must be ` +\n          `less than or equal to max (${clipValueMax}).`);\n\n  if (clipValueMin === clipValueMax) {\n    return fill($x.shape, clipValueMin, $x.dtype) as T;\n  }\n\n  const inputs: ClipByValueInputs = {x: $x};\n  const attrs: ClipByValueAttrs = {clipValueMin, clipValueMax};\n\n  return ENGINE.runKernel(\n      ClipByValue, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const clipByValue = /* @__PURE__ */ op({clipByValue_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of`tf.Tensor1D`s along an axis. See `concat` for details.\n *\n * For example, if:\n * A: shape(3) = |r1, g1, b1|\n * B: shape(2) = |r2, g2|\n * C = tf.concat1d([A, B]) == |r1, g1, b1, r2, g2|\n *\n * @param tensors A list of`tf.Tensor`s to concatenate.\n * @return The concatenated array.\n */\nfunction concat1d_(tensors: Array<Tensor1D|TensorLike>): Tensor1D {\n  return concat(tensors, 0 /* axis */);\n}\n\nexport const concat1d = /* @__PURE__ */ op({concat1d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of`tf.Tensor2D`s along an axis. See `concat` for details.\n *\n * For example, if:\n * A: shape(2, 3) = | r1, g1, b1 |\n *                  | r2, g2, b2 |\n *\n * B: shape(2, 3) = | r3, g3, b3 |\n *                  | r4, g4, b4 |\n *\n * C = tf.concat2d([A, B], axis)\n *\n * if axis = 0:\n * C: shape(4, 3) = | r1, g1, b1 |\n *                  | r2, g2, b2 |\n *                  | r3, g3, b3 |\n *                  | r4, g4, b4 |\n *\n * if axis = 1:\n * C = shape(2, 6) = | r1, g1, b1, r3, g3, b3 |\n *                   | r2, g2, b2, r4, g4, b4 |\n *\n *\n * @param tensors A list of `tf.Tensor`s to concatenate.\n * @param axis The axis to concatenate along.\n * @return The concatenated array.\n */\nfunction concat2d_(\n    tensors: Array<Tensor2D|TensorLike>, axis: number): Tensor2D {\n  return concat(tensors, axis);\n}\n\nexport const concat2d = /* @__PURE__ */ op({concat2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor3D`s along an axis.\n * See `concat` for details.\n *\n * For example, if:\n * A: shape(2, 1, 3) = | r1, g1, b1 |\n *                     | r2, g2, b2 |\n *\n * B: shape(2, 1, 3) = | r3, g3, b3 |\n *                     | r4, g4, b4 |\n *\n * C = tf.concat3d([A, B], axis)\n *\n * if axis = 0:\n * C: shape(4, 1, 3) = | r1, g1, b1 |\n *                     | r2, g2, b2 |\n *                     | r3, g3, b3 |\n *                     | r4, g4, b4 |\n *\n * if axis = 1:\n * C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 |\n *                     | r2, g2, b2, r4, g4, b4 |\n *\n * if axis = 2:\n * C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 |\n *                      | r2, g2, b2, r4, g4, b4 |\n *\n * @param tensors A list of`tf.Tensor`s to concatenate.\n * @param axis The axis to concate along.\n * @return The concatenated array.\n */\nfunction concat3d_(\n    tensors: Array<Tensor3D|TensorLike>, axis: number): Tensor3D {\n  return concat(tensors, axis);\n}\n\nexport const concat3d = /* @__PURE__ */ op({concat3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor4D`s along an axis.\n * See `concat` for details.\n *\n * @param tensors A list of `tf.Tensor`s to concatenate.\n * @param axis The axis to concate along.\n * @return The concatenated array.\n */\nfunction concat4d_(\n    tensors: Array<Tensor4D|TensorLike>, axis: number): Tensor4D {\n  return concat(tensors, axis);\n}\n\nexport const concat4d = /* @__PURE__ */ op({concat4d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2D, Conv2DAttrs, Conv2DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 2D convolution over the input x.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n *     `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels].\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv2d_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filter: Tensor4D|TensorLike,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n    dilations: [number, number]|number = [1, 1],\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'conv2d', 'float32');\n  const $filter = convertToTensor(filter, 'filter', 'conv2d', 'float32');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`);\n  util.assert(\n      $filter.rank === 4,\n      () => `Error in conv2d: filter must be rank 4, but got rank ` +\n          `${$filter.rank}.`);\n  conv_util.checkPadOnDimRoundingMode('conv2d', pad, dimRoundingMode);\n  const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n  util.assert(\n      inDepth === $filter.shape[2],\n      () => `Error in conv2d: depth of input (${inDepth}) must match ` +\n          `input depth for filter ${$filter.shape[2]}.`);\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in conv2D: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n  util.assert(\n      conv_util.stridesOrDilationsArePositive(dilations),\n      () => 'Error in conv2D: Dilated rates should be larger than 0.');\n  util.assert(\n      conv_util.stridesOrDilationsArePositive(strides),\n      () => 'Error in conv2D: Strides should be larger than 0.');\n\n  const inputs: Conv2DInputs = {x: x4D, filter: $filter};\n  const attrs:\n      Conv2DAttrs = {strides, pad, dataFormat, dilations, dimRoundingMode};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Conv2D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const conv2d = /* @__PURE__ */ op({conv2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D, Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {conv2d} from './conv2d';\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 1D convolution over the input x.\n *\n * @param x The input tensor, of rank 3 or rank 2, of shape\n *     `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.\n * @param filter The filter, rank 3, of shape\n *     `[filterWidth, inDepth, outDepth]`.\n * @param stride The number of entries by which the filter is moved right at\n *     each step.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat An optional string from \"NWC\", \"NCW\". Defaults to \"NWC\",\n *     the data is stored in the order of [batch, in_width, in_channels]. Only\n *     \"NWC\" is currently supported.\n * @param dilation The dilation rate in which we sample input values in\n *     atrous convolution. Defaults to `1`. If it is greater than 1, then\n *     stride must be `1`.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv1d_<T extends Tensor2D|Tensor3D>(\n    x: T|TensorLike, filter: Tensor3D|TensorLike, stride: number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NWC'|'NCW' = 'NWC', dilation = 1,\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'conv1d');\n  const $filter = convertToTensor(filter, 'filter', 'conv1d');\n\n  let x3D = $x as Tensor3D;\n  let reshapedTo3D = false;\n  if ($x.rank === 2) {\n    reshapedTo3D = true;\n    x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);\n  }\n\n  util.assert(\n      x3D.rank === 3,\n      () => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`);\n  util.assert(\n      $filter.rank === 3,\n      () => `Error in conv1d: filter must be rank 3, but got rank ` +\n          `${$filter.rank}.`);\n  conv_util.checkPadOnDimRoundingMode('conv1d', pad, dimRoundingMode);\n  util.assert(\n      x3D.shape[2] === $filter.shape[1],\n      () => `Error in conv1d: depth of input (${x3D.shape[2]}) must match ` +\n          `input depth for filter ${$filter.shape[1]}.`);\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(stride, dilation),\n      () => 'Error in conv1D: Either stride or dilation must be 1. ' +\n          `Got stride ${stride} and dilation '${dilation}'`);\n  util.assert(\n      conv_util.stridesOrDilationsArePositive(dilation),\n      () => 'Error in conv1D: Dilated rates should be larger than 0.');\n  util.assert(\n      conv_util.stridesOrDilationsArePositive(stride),\n      () => 'Error in conv1D: Stride should be larger than 0.');\n  util.assert(\n      dataFormat === 'NWC',\n      () => `Error in conv1d: got dataFormat of ${\n          dataFormat} but only NWC is currently supported.`);\n\n  const filter4D = reshape(\n      $filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);\n  const input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);\n  const strides: [number, number] = [1, stride];\n  const dilations: [number, number] = [1, dilation];\n\n  const conv2dDataFormat = 'NHWC';\n\n  const res = conv2d(\n      (input4D as Tensor4D), (filter4D as Tensor4D), strides, pad,\n      conv2dDataFormat, dilations, dimRoundingMode);\n\n  if (reshapedTo3D) {\n    return reshape(res, [res.shape[2], res.shape[3]]) as T;\n  }\n\n  return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]) as T;\n}\n\nexport const conv1d = /* @__PURE__ */ op({conv1d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the input of a 2D convolution.\n *\n * @param xShape The shape of the input: [batch, height, width, inDepth].\n * If length of 3, batch of 1 is assumed.\n * @param dy The derivative of the output, of rank 4 or rank 3 of shape\n *   `[batch, outHeight, outWidth, outDepth]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n *     `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm used:\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels].\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n */\nfunction conv2DBackpropInput_<T extends Tensor3D|Tensor4D>(\n    xShape: [number, number, number, number]|[number, number, number], dy: T,\n    filter: Tensor4D, strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  util.assert(\n      xShape.length === dy.rank,\n      () => `Length of inShape ` +\n          `(${xShape.length}) and rank of dy (${dy.rank}) must match`);\n\n  let xShape4D = xShape as [number, number, number, number];\n  let dy4D = dy as Tensor4D;\n  let reshapedTo4D = false;\n  if (dy.rank === 3) {\n    reshapedTo4D = true;\n    dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n    xShape4D = [1, xShape[0], xShape[1], xShape[2]];\n  }\n\n  util.assert(\n      xShape4D.length === 4,\n      () =>\n          `Error in conv2dDerInput: inShape must be length 4, but got length ` +\n          `${xShape4D.length}.`);\n  util.assert(\n      dy4D.rank === 4,\n      () => `Error in conv2dDerInput: dy must be rank 4, but got ` +\n          `rank ${dy4D.rank}`);\n  util.assert(\n      filter.rank === 4,\n      () => `Error in conv2dDerInput: filter must be rank 4, but got ` +\n          `rank ${filter.rank}`);\n  const inDepth = dataFormat === 'NHWC' ? xShape4D[3] : xShape4D[1];\n  const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];\n  util.assert(\n      inDepth === filter.shape[2],\n      () => `Error in conv2dDerInput: depth of input (${inDepth}) must ` +\n          `match input depth for filter ${filter.shape[2]}.`);\n  util.assert(\n      outDepth === filter.shape[3],\n      () => `Error in conv2dDerInput: depth of output (${outDepth}) must ` +\n          `match output depth for filter ${filter.shape[3]}.`);\n  conv_util.checkPadOnDimRoundingMode('conv2dDerInput', pad, dimRoundingMode);\n  const inputs: Conv2DBackpropInputInputs = {dy: dy4D, filter};\n  const attrs: Conv2DBackpropInputAttrs =\n      {strides, pad, dataFormat, dimRoundingMode, inputShape: xShape4D};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Conv2DBackpropInput, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const conv2DBackpropInput = /* @__PURE__ */ op({conv2DBackpropInput_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {conv2DBackpropInput} from './conv2d_backprop_input';\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\n\n/**\n * Computes the transposed 2D convolution of an image, also known as a\n * deconvolution.\n *\n * @param x The input image, of rank 4 or rank 3, of shape\n *   `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.\n * @param filter The filter, rank 4, of shape\n *     `[filterHeight, filterWidth, outDepth, inDepth]`.\n *     `inDepth` must match `inDepth` in `x`.\n * @param outputShape Output shape, of rank 4 or rank 3:\n *     `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.\n * @param strides The strides of the original convolution:\n *     `[strideHeight, strideWidth]`.\n * @param pad  The type of padding algorithm used in the non-transpose version\n *    of the op.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv2dTranspose_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filter: Tensor4D|TensorLike,\n    outputShape: [number, number, number, number]|[number, number, number],\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|ExplicitPadding,\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'conv2dTranspose');\n  const $filter = convertToTensor(filter, 'filter', 'conv2dTranspose');\n\n  return conv2DBackpropInput(\n      outputShape, $x, $filter, strides, pad, 'NHWC', dimRoundingMode);\n}\n\nexport const conv2dTranspose = /* @__PURE__ */ op({conv2dTranspose_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv3D, Conv3DAttrs, Conv3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {eitherStridesOrDilationsAreOne, stridesOrDilationsArePositive} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 3D convolution over the input x.\n *\n * @param x The input tensor, of rank 5 or rank 4, of shape\n *     `[batch, depth, height, width, channels]`. If rank 4,\n * batch of 1 is assumed.\n * @param filter The filter, rank 5, of shape\n *     `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.\n *      inChannels must match between input and filter.\n * @param strides The strides of the convolution: `[strideDepth, strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat: An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n *     \"NDHWC\". Specify the data format of the input and output data. With the\n *     default format \"NDHWC\", the data is stored in the order of: [batch,\n *     depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @param dilations The dilation rates: `[dilationDepth, dilationHeight,\n *     dilationWidth]` in which we sample input values across the height\n *     and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.\n *     If `dilations` is a single number, then\n *     `dilationDepth == dilationHeight == dilationWidth`. If it is greater\n *     than 1, then all values of `strides` must be 1.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv3d_<T extends Tensor4D|Tensor5D>(\n    x: T|TensorLike, filter: Tensor5D|TensorLike,\n    strides: [number, number, number]|number, pad: 'valid'|'same',\n    dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC',\n    dilations: [number, number, number]|number = [1, 1, 1]): T {\n  const $x = convertToTensor(x, 'x', 'conv3d');\n  const $filter = convertToTensor(filter, 'filter', 'conv3d');\n\n  let x5D = $x as Tensor5D;\n  let reshapedTo5D = false;\n\n  if ($x.rank === 4) {\n    reshapedTo5D = true;\n    x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n  }\n  util.assert(\n      x5D.rank === 5,\n      () => `Error in conv3d: input must be rank 5, but got rank ${x5D.rank}.`);\n  util.assert(\n      $filter.rank === 5,\n      () => `Error in conv3d: filter must be rank 5, but got rank ` +\n          `${$filter.rank}.`);\n  util.assert(\n      x5D.shape[4] === $filter.shape[3],\n      () => `Error in conv3d: depth of input (${x5D.shape[4]}) must match ` +\n          `input depth for filter ${$filter.shape[3]}.`);\n  util.assert(\n      eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in conv3D: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n  util.assert(\n      dataFormat === 'NDHWC',\n      () => `Error in conv3d: got dataFormat of ${\n          dataFormat} but only NDHWC is currently supported.`);\n  util.assert(\n      stridesOrDilationsArePositive(dilations),\n      () => 'Error in conv3D: Dilated rates should be larger than 0.');\n  util.assert(\n      stridesOrDilationsArePositive(strides),\n      () => 'Error in conv3D: Strides should be larger than 0.');\n\n  const inputs: Conv3DInputs = {x: x5D, filter: $filter};\n\n  const attrs: Conv3DAttrs = {strides, pad, dataFormat, dilations};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Conv3D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo5D) {\n    return reshape(\n               res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n        T;\n  }\n  return res;\n}\n\nexport const conv3d = /* @__PURE__ */ op({conv3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv3DBackpropInputV2, Conv3DBackpropInputV2Attrs, Conv3DBackpropInputV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the input of a 3D convolution.\n *\n * @param xShape The shape of the input: [batch, depth, height, width,\n * in_channels]. If length of 4, batch of 1 is assumed.\n * @param dy The derivative of the output, of rank 5 or rank 4 of shape\n *   `[batch, outDepth, outHeight, outWidth, in_channels]`.\n * If rank 4, batch of 1 is assumed.\n * @param filter The filter, rank 5, of shape\n *     `[filterDepth, filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideDepth, strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm used:\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n */\nfunction conv3DBackpropInput_<T extends Tensor4D|Tensor5D>(\n    xShape:\n        [number, number, number, number,\n         number]|[number, number, number, number],\n    dy: T, filter: Tensor5D, strides: [number, number, number]|number,\n    pad: 'valid'|'same'): T {\n  util.assert(\n      xShape.length === dy.rank,\n      () => `Length of inShape ` +\n          `(${xShape.length}) and rank of dy (${dy.rank}) must match`);\n\n  let xShape5D = xShape as [number, number, number, number, number];\n  let dy5D = dy as Tensor5D;\n  let reshapedTo5D = false;\n  if (dy.rank === 4) {\n    reshapedTo5D = true;\n    dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);\n    xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];\n  }\n\n  const inDepth = xShape5D[4];\n  const outDepth = dy5D.shape[4];\n  util.assert(\n      xShape5D.length === 5,\n      () =>\n          `Error in conv3dDerInput: inShape must be length 5, but got length ` +\n          `${xShape5D.length}.`);\n  util.assert(\n      dy5D.rank === 5,\n      () => `Error in conv3dDerInput: dy must be rank 5, but got ` +\n          `rank ${dy5D.rank}`);\n  util.assert(\n      filter.rank === 5,\n      () => `Error in conv3dDerInput: filter must be rank 5, but got ` +\n          `rank ${filter.rank}`);\n  util.assert(\n      inDepth === filter.shape[3],\n      () => `Error in conv3dDerInput: depth of input (${inDepth}) must ` +\n          `match input depth for filter ${filter.shape[3]}.`);\n  util.assert(\n      outDepth === filter.shape[4],\n      () => `Error in conv3dDerInput: depth of output (${outDepth}) must ` +\n          `match output depth for filter ${filter.shape[4]}.`);\n\n  const inputs: Conv3DBackpropInputV2Inputs = {dy: dy5D, filter};\n\n  const attrs:\n      Conv3DBackpropInputV2Attrs = {pad, strides, inputShape: xShape5D};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Conv3DBackpropInputV2, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo5D) {\n    return reshape(\n               res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n        T;\n  }\n  return res;\n}\n\nexport const conv3DBackpropInput = /* @__PURE__ */ op({conv3DBackpropInput_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {conv3DBackpropInput} from './conv3d_backprop_input';\nimport {op} from './operation';\n\n/**\n * Computes the transposed 3D convolution of a volume, also known as a\n * deconvolution.\n *\n * @param x The input image, of rank 5 or rank 4, of shape\n *   `[batch, depth, height, width, inDepth]`. If rank 4, batch of 1 is assumed.\n * @param filter The filter, rank 4, of shape\n *     `[depth, filterHeight, filterWidth, outDepth, inDepth]`.\n *     `inDepth` must match `inDepth` in `x`.\n * @param outputShape Output shape, of rank 5 or rank 4:\n *     `[batch, depth, height, width, outDepth]`. If rank 3, batch of 1 is\n *    assumed.\n * @param strides The strides of the original convolution:\n *     `[strideDepth, strideHeight, strideWidth]`.\n * @param pad  The type of padding algorithm used in the non-transpose version\n *    of the op.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv3dTranspose_<T extends Tensor4D|Tensor5D>(\n    x: T|TensorLike, filter: Tensor5D|TensorLike,\n    outputShape:\n        [number, number, number, number,\n         number]|[number, number, number, number],\n    strides: [number, number, number]|number, pad: 'valid'|'same'): T {\n  const $x = convertToTensor(x, 'x', 'conv3dTranspose');\n  const $filter = convertToTensor(filter, 'filter', 'conv3dTranspose');\n\n  return conv3DBackpropInput(outputShape, $x, $filter, strides, pad);\n}\n\nexport const conv3dTranspose = /* @__PURE__ */ op({conv3dTranspose_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cos, CosInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes cos of the input `tf.Tensor` element-wise: `cos(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.cos().print();  // or tf.cos(x)\n * ```\n * @param x The input tensor. Must be float32 type.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction cos_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'cos', 'float32');\n\n  const inputs: CosInputs = {x: $x};\n\n  return ENGINE.runKernel(Cos, inputs as unknown as NamedTensorMap);\n}\nexport const cos = /* @__PURE__ */ op({cos_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cosh, CoshInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.cosh().print();  // or tf.cosh(x)\n * ```\n * @param x The input tensor. Must be float32 type.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction cosh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'cosh', 'float32');\n  const inputs: CoshInputs = {x: $x};\n\n  return ENGINE.runKernel(Cosh, inputs as unknown as NamedTensorMap);\n}\nexport const cosh = /* @__PURE__ */ op({cosh_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { ENGINE } from '../engine';\nimport { Cumprod, CumprodAttrs, CumprodInputs } from '../kernel_names';\nimport { NamedAttrMap } from '../kernel_registry';\nimport { Tensor } from '../tensor';\nimport { NamedTensorMap } from '../tensor_types';\nimport { convertToTensor } from '../tensor_util_env';\nimport { TensorLike } from '../types';\n\nimport { op } from './operation';\n\n/**\n * Computes the cumulative product of a `tf.Tensor` along `axis`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4]);\n * x.cumprod().print();\n * ```\n * ```js\n * const x = tf.tensor([[1, 2], [3, 4]]);\n * x.cumprod().print();\n * ```\n *\n * @param x The input tensor to cumulatively multiply.\n * @param axis The axis along which to multiply. Optional. Defaults to 0.\n * @param exclusive Whether to perform exclusive cumulative product. Optional.\n *     Defaults to false. If set to true then the product of each tensor entry\n *     does not include its own value, but only the values previous to it\n *     along the specified axis.\n * @param reverse Whether to multiply in the opposite direction. Optional.\n *     Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Scan'}\n */\nfunction cumprod_<T extends Tensor>(\n  x: Tensor | TensorLike,\n  axis = 0,\n  exclusive = false,\n  reverse = false\n): T {\n  const $x = convertToTensor(x, 'x', 'cumprod');\n\n  const inputs: CumprodInputs = { x: $x };\n  const attrs: CumprodAttrs = { axis, exclusive, reverse };\n\n  return ENGINE.runKernel(\n    Cumprod,\n    inputs as unknown as NamedTensorMap,\n    attrs as unknown as NamedAttrMap\n  );\n}\n\nexport const cumprod = /* @__PURE__ */ op({ cumprod_ });\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cumsum, CumsumAttrs, CumsumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the cumulative sum of a `tf.Tensor` along `axis`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4]);\n * x.cumsum().print();\n * ```\n * ```js\n * const x = tf.tensor([[1, 2], [3, 4]]);\n * x.cumsum().print();\n * ```\n *\n * @param x The input tensor to be summed.\n * @param axis The axis along which to sum. Optional. Defaults to 0.\n * @param exclusive Whether to perform exclusive cumulative sum. Optional.\n *     Defaults to false. If set to true then the sum of each tensor entry\n *     does not include its own value, but only the values previous to it\n *     along the specified axis.\n * @param reverse Whether to sum in the opposite direction. Optional.\n *     Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Scan'}\n */\nfunction cumsum_<T extends Tensor>(\n    x: Tensor|TensorLike, axis = 0, exclusive = false, reverse = false): T {\n  const $x = convertToTensor(x, 'x', 'cumsum');\n\n  const inputs: CumsumInputs = {x: $x};\n  const attrs: CumsumAttrs = {axis, exclusive, reverse};\n\n  return ENGINE.runKernel(\n      Cumsum, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const cumsum = /* @__PURE__ */ op({cumsum_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {DenseBincount, DenseBincountAttrs, DenseBincountInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Outputs a vector with length `size` and the same dtype as `weights`.\n *\n * If `weights` are empty, then index `i` stores the number of times the value\n * `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the\n * sum of the value in `weights` at each index where the corresponding value in\n * `x` is `i`.\n *\n * Values in `x` outside of the range [0, size) are ignored.\n *\n * @param x The input int tensor, rank 1 or rank 2.\n * @param weights The weights tensor, must have the same shape as x, or a\n *     length-0 Tensor, in which case it acts as all weights equal to 1.\n * @param size Non-negative integer.\n * @param binaryOutput Optional. Whether the kernel should count the appearance\n *     or number of occurrences. Defaults to False.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction denseBincount_<T extends Tensor1D|Tensor2D>(\n    x: T|TensorLike, weights: T|TensorLike, size: number,\n    binaryOutput = false): T {\n  const $x = convertToTensor(x, 'x', 'denseBincount');\n  const $weights = convertToTensor(weights, 'weights', 'denseBincount');\n\n  util.assert(\n      $x.dtype === 'int32',\n      () => `Error in denseBincount: input ` +\n          `dtype must be int32, but got ${$x.dtype}`);\n  util.assert(\n      $x.rank <= 2,\n      () => `Error in denseBincount: input must be at most rank 2, but got ` +\n          `rank ${$x.rank}.`);\n  util.assert(size >= 0, () => `size must be non-negative, but got ${size}.`);\n  util.assert(\n      $weights.size === $x.size || $weights.size === 0,\n      () =>\n          `Error in denseBincount: weights must have the same shape as x or ` +\n          `0-length, but got x shape: ${$x.shape}, weights shape: ` +\n          `${$weights.shape}.`);\n\n  const inputs: DenseBincountInputs = {x: $x, weights: $weights};\n  const attrs: DenseBincountAttrs = {size, binaryOutput};\n\n  return ENGINE.runKernel(\n      DenseBincount, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const denseBincount = /* @__PURE__ */ op({denseBincount_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike4D} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Rearranges data from depth into blocks of spatial data. More specifically,\n * this op outputs a copy of the input tensor where values from the `depth`\n * dimension are moved in spatial blocks to the `height` and `width` dimensions.\n * The attr `blockSize` indicates the input block size and how the data is\n * moved.\n *\n *  - Chunks of data of size `blockSize * blockSize` from depth are rearranged\n * into non-overlapping blocks of size `blockSize x blockSize`\n *\n *  - The width the output tensor is `inputWidth * blockSize`, whereas the\n * height is `inputHeight * blockSize`\n *\n *  - The Y, X coordinates within each block of the output image are determined\n * by the high order component of the input channel index\n *\n *  - The depth of the input tensor must be divisible by `blockSize *\n * blockSize`\n *\n * The `dataFormat` attr specifies the layout of the input and output tensors\n * with the following options: \"NHWC\": [ `batch, height, width, channels` ]\n * \"NCHW\": [ `batch, channels, height, width` ]\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);\n * const blockSize = 2;\n * const dataFormat = \"NHWC\";\n *\n * tf.depthToSpace(x, blockSize, dataFormat).print();\n * ```\n *\n * @param x The input tensor of rank 4\n * @param blockSIze  An `int` that is `>= 2`. The size of the spatial block\n * @param dataFormat An optional string from: \"NHWC\", \"NCHW\". Defaults to \"NHWC\"\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction depthToSpace_(\n    x: Tensor4D|TensorLike4D, blockSize: number,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC'): Tensor4D {\n  const $x = convertToTensor(x, 'x', 'depthToSpace', 'float32') as Tensor4D;\n\n  const inputHeight = (dataFormat === 'NHWC') ? $x.shape[1] : $x.shape[2];\n  const inputWidth = (dataFormat === 'NHWC') ? $x.shape[2] : $x.shape[3];\n  const inputDepth = (dataFormat === 'NHWC') ? $x.shape[3] : $x.shape[1];\n\n  util.assert(\n      blockSize > 1,\n      () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);\n\n  util.assert(\n      inputHeight * blockSize >= 0,\n      () => `Negative dimension size caused by overflow when multiplying\n    ${inputHeight} and ${blockSize}  for depthToSpace with input shape\n    ${$x.shape}`);\n\n  util.assert(\n      inputWidth * blockSize >= 0,\n      () => `Negative dimension size caused by overflow when multiplying\n    ${inputWidth} and ${blockSize} for depthToSpace with input shape\n        ${$x.shape}`);\n\n  util.assert(\n      (inputDepth % (blockSize * blockSize) === 0),\n      () => `Dimension size must be evenly divisible by ${\n          blockSize * blockSize} but is ${\n          inputDepth} for depthToSpace with input shape ${$x.shape}`);\n\n  const inputs: DepthToSpaceInputs = {x: $x};\n  const attrs: DepthToSpaceAttrs = {blockSize, dataFormat};\n\n  return ENGINE.runKernel(\n      DepthToSpace, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const depthToSpace = /* @__PURE__ */ op({depthToSpace_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Depthwise 2D convolution.\n *\n * Given a 4D `input` array and a `filter` array of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing\n * `inChannels` convolutional filters of depth 1, this op applies a\n * different filter to each input channel (expanding from 1 channel to\n * `channelMultiplier` channels for each), then concatenates the results\n * together. The output has `inChannels * channelMultiplier` channels.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](\n *     https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)\n * for more details.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter tensor, rank 4, of shape\n *     `[filterHeight, filterWidth, inChannels, channelMultiplier]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction depthwiseConv2d_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filter: Tensor4D|TensorLike,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n    dilations: [number, number]|number = [1, 1],\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'depthwiseConv2d', 'float32');\n  const $filter =\n      convertToTensor(filter, 'filter', 'depthwiseConv2d', 'float32');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in depthwiseConv2d: input must be rank 4, but got ` +\n          `rank ${x4D.rank}.`);\n  util.assert(\n      $filter.rank === 4,\n      () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ` +\n          `${$filter.rank}.`);\n  const inChannels = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n  util.assert(\n      inChannels === $filter.shape[2],\n      () => `Error in depthwiseConv2d: number of input channels ` +\n          `(${inChannels}) must match the inChannels dimension in ` +\n          `filter ${$filter.shape[2]}.`);\n  conv_util.checkPadOnDimRoundingMode('depthwiseConv2d', pad, dimRoundingMode);\n  const inputs: DepthwiseConv2dNativeInputs = {x: x4D, filter: $filter};\n  const attrs: DepthwiseConv2dNativeAttrs =\n      {strides, pad, dataFormat, dilations, dimRoundingMode};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  DepthwiseConv2dNative, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const depthwiseConv2d = /* @__PURE__ */ op({depthwiseConv2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Diag, DiagInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\n\nimport {op} from './operation';\n\n/**\n * Returns a diagonal tensor with given diagonal values.\n *\n * Given a diagonal, this operation returns a tensor with the diagonal and\n * everything else padded with zeros.\n *\n * Assume the input has dimensions `[D1,..., Dk]`, then the output is a tensor\n * of rank 2k with dimensions `[D1,..., Dk, D1,..., Dk]`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * tf.diag(x).print()\n * ```\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [4, 2])\n *\n * tf.diag(x).print()\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction diag_(x: Tensor): Tensor {\n  const $x = convertToTensor(x, 'x', 'diag');\n\n  const inputs: DiagInputs = {x: $x};\n\n  return ENGINE.runKernel(Diag, inputs as unknown as NamedTensorMap);\n}\n\nexport const diag = /* @__PURE__ */ op({diag_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Dilation2D, Dilation2DAttrs, Dilation2DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the grayscale dilation over the input `x`.\n *\n * @param x The input tensor, rank 3 or rank 4 of shape\n *     `[batch, height, width, depth]`. If rank 3, batch of 1 is assumed.\n * @param filter The filter tensor, rank 3, of shape\n *     `[filterHeight, filterWidth, depth]`.\n * @param strides The strides of the sliding window for each dimension of the\n *     input tensor: `[strideHeight, strideWidth]`.\n *     If `strides` is a single number,\n *     then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1*1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat Specify the data format of the input and output data.\n *      Defaults to 'NHWC'. Only 'NHWC' is currently supported. With the\n *      default format \"NHWC\", the data is stored in the order of: [batch,\n *      height, width, channels].\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     for atrous morphological dilation. Defaults to `[1, 1]`. If `dilations`\n *     is a single number, then `dilationHeight == dilationWidth`. If it is\n *     greater than 1, then all values of `strides` must be 1.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction dilation2d_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filter: Tensor3D|TensorLike,\n    strides: [number, number]|number, pad: 'valid'|'same',\n    dilations: [number, number]|number = [1, 1],\n    dataFormat: 'NHWC' = 'NHWC'): T {\n  const $x = convertToTensor(x, 'x', 'dilation2d');\n  const $filter = convertToTensor(filter, 'filter', 'dilation2d');\n\n  util.assert(\n      $x.rank === 3 || $x.rank === 4,\n      () => `Error in dilation2d: input must be rank 3 or 4, but got rank ` +\n          `${$x.rank}.`);\n  util.assert(\n      $filter.rank === 3,\n      () => `Error in dilation2d: filter must be rank 3, but got rank ` +\n          `${$filter.rank}.`);\n  util.assert(\n      dataFormat === 'NHWC',\n      () => `Error in dilation2d: Only NHWC is currently supported, ` +\n          `but got dataFormat of ${dataFormat}`);\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n\n  if ($x.rank === 3) {\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n    reshapedTo4D = true;\n  }\n\n  util.assert(\n      x4D.shape[3] === $filter.shape[2],\n      () => `Error in dilation2d:  input and filter must have the same depth: ${\n          x4D.shape[3]} vs ${$filter.shape[2]}`);\n\n  const inputs: Dilation2DInputs = {x: x4D, filter: $filter};\n  const attrs: Dilation2DAttrs = {strides, pad, dilations};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Dilation2D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n\n  return res;\n}\n\nexport const dilation2d = /* @__PURE__ */ op({dilation2d_});\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Returns the dimensions in the input shape that are broadcasted to\n * produce the provided output shape.\n *\n * The returned dimensions are 0-indexed and sorted. An example:\n * inShape = [4, 1, 3]\n * outShape = [5, 4, 3, 3]\n * result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.\n */\nexport function getBroadcastDims(\n    inShape: number[], outShape: number[]): number[] {\n  const inRank = inShape.length;\n  const dims: number[] = [];\n  for (let i = 0; i < inRank; i++) {\n    const dim = inRank - 1 - i;\n    const a = inShape[dim] || 1;\n    const b = outShape[outShape.length - 1 - i] || 1;\n    if (b > 1 && a === 1) {\n      dims.unshift(dim);\n    }\n  }\n  return dims;\n}\n\n/**\n * Returns the axes in the output space that should be reduced to produce\n * the input space.\n */\nexport function getReductionAxes(\n    inShape: number[], outShape: number[]): number[] {\n  const result: number[] = [];\n  for (let i = 0; i < outShape.length; i++) {\n    const inDim = inShape[inShape.length - i - 1];\n    const outAxis = outShape.length - i - 1;\n    const outDim = outShape[outAxis];\n    if (inDim == null || (inDim === 1 && outDim > 1)) {\n      result.unshift(outAxis);\n    }\n  }\n  return result;\n}\n\nexport function assertAndGetBroadcastShape(\n    shapeA: number[], shapeB: number[]): number[] {\n  const l = Math.max(shapeA.length, shapeB.length);\n  const result = new Array(l);\n\n  for (let i = 0; i < l; i++) {\n    let a = shapeA[shapeA.length - i - 1];\n    if (a == null) {\n      a = 1;\n    }\n    let b = shapeB[shapeB.length - i - 1];\n    if (b == null) {\n      b = 1;\n    }\n    if (a === 1) {\n      result[l - i - 1] = b;\n    } else if (b === 1) {\n      result[l - i - 1] = a;\n    } else if (a !== b) {\n      const errMsg = `Operands could not be broadcast together with shapes ` +\n          `${shapeA} and ${shapeB}.`;\n      throw Error(errMsg);\n    } else {\n      result[l - i - 1] = a;\n    }\n  }\n  return result;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Equal, EqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a == b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.equal(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction equal_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'equal', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'equal', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: EqualInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Equal, inputs as unknown as NamedTensorMap);\n}\n\nexport const equal = /* @__PURE__ */ op({equal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Select, SelectInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {broadcastTo} from './broadcast_to';\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the elements, either `a` or `b` depending on the `condition`.\n *\n * If the condition is true, select from `a`, otherwise select from `b`.\n *\n * ```js\n * const cond = tf.tensor1d([false, false, true], 'bool');\n * const a = tf.tensor1d([1 , 2, 3]);\n * const b = tf.tensor1d([-1, -2, -3]);\n *\n * a.where(cond, b).print();\n * ```\n *\n * @param condition The input condition. Must be of dtype bool.\n * @param a If `condition` is rank 1, `a` may have a higher rank but\n *     its first dimension must match the size of `condition`.\n * @param b A tensor with the same dtype as `a` and with shape that is\n *     compatible with `a`.\n * @return A tensor with same dtype as `a` and `b`, and shape that is\n *     broadcastable from `a` and `b`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction where_<T extends Tensor>(\n    condition: Tensor|TensorLike, a: T|TensorLike, b: T|TensorLike): T {\n  const $a = convertToTensor(a, 'a', 'where');\n  const $b = convertToTensor(b, 'b', 'where');\n  const $condition = convertToTensor(condition, 'condition', 'where', 'bool');\n  // TODO: move this logic to forward function when the broadcastTo op is\n  // implemented in WASM.\n  // Find the broadcastable shape for $condition, $a, and $b.\n  const broadcastShape = assertAndGetBroadcastShape(\n      assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);\n  const $broadcastedCondition = broadcastTo($condition, broadcastShape);\n  const $broadcastedA = broadcastTo($a, broadcastShape);\n  const $broadcastedB = broadcastTo($b, broadcastShape);\n\n  const inputs: SelectInputs = {\n    condition: $broadcastedCondition,\n    t: $broadcastedA,\n    e: $broadcastedB\n  };\n  return ENGINE.runKernel(Select, inputs as unknown as NamedTensorMap);\n}\n\nexport const where = /* @__PURE__ */ op({where_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ZerosLike, ZerosLikeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0 with the same shape as the\n * given tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n * tf.zerosLike(x).print();\n * ```\n *\n * @param x The tensor of required shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction zerosLike_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'zerosLike');\n  const inputs: ZerosLikeInputs = {x: $x};\n  return ENGINE.runKernel(ZerosLike, inputs as unknown as NamedTensorMap);\n}\nexport const zerosLike = /* @__PURE__ */ op({zerosLike_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {div} from './div';\nimport {equal} from './equal';\nimport {op} from './operation';\nimport {where} from './where';\nimport {zerosLike} from './zeros_like';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting. Return 0\n * if denominator is 0.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n * const c = tf.tensor1d([0, 0, 0, 0]);\n *\n * a.divNoNan(b).print();  // or tf.divNoNan(a, b)\n * a.divNoNan(c).print();  // or tf.divNoNan(a, c)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n * const c = tf.scalar(0);\n *\n * a.divNoNan(b).print();  // or tf.divNoNan(a, b)\n * a.divNoNan(c).print();  // or tf.divNoNan(a, c)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction divNoNan_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  // TODO: Make this into its own kernel.\n  let $a = convertToTensor(a, 'a', 'div');\n  let $b = convertToTensor(b, 'b', 'div');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const divResult = div($a, $b);\n  const zeros = zerosLike(divResult);\n  const bEqualsZero = equal($b, zeros);\n  return where(bEqualsZero, zeros, divResult) as T;\n}\n\nexport const divNoNan = /* @__PURE__ */ op({divNoNan_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor,} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {matMul} from './mat_mul';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the dot product of two matrices and/or vectors, `t1` and `t2`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor2d([[1, 2], [3, 4]]);\n * const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n *\n * a.dot(b).print();  // or tf.dot(a, b)\n * b.dot(a).print();\n * b.dot(c).print();\n * ```\n * @param t1 The first tensor in the dot operation.\n * @param t2 The second tensor in the dot operation.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction dot_(t1: Tensor|TensorLike, t2: Tensor|TensorLike): Tensor {\n  const $t1 = convertToTensor(t1, 't1', 'dot');\n  const $t2 = convertToTensor(t2, 't2', 'dot');\n\n  util.assert(\n      ($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2),\n      () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ` +\n          `${$t1.rank} and ${$t2.rank}.`);\n\n  const t1Inner = ($t1.rank === 1 ? $t1.size : $t1.shape[1]);\n  const t2Inner = ($t2.rank === 1 ? $t2.size : $t2.shape[0]);\n\n  util.assert(\n      t1Inner === t2Inner,\n      () => `Error in dot: inner dimensions of inputs must match, but got ` +\n          `${t1Inner} and ${t2Inner}.`);\n\n  if ($t1.rank === 1 && $t2.rank === 1) {\n    const t12D = reshape($t1, [1, -1]);\n    const t22D = reshape($t2, [-1, 1]);\n    const t1t2 = matMul(t12D, t22D);\n    return reshape(t1t2, []);\n  } else if ($t1.rank === 1 && $t2.rank === 2) {\n    const t12D = reshape($t1, [1, -1]);\n    const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);\n    const t1t2 = matMul(t12D, t22D);\n    return reshape(t1t2, [t1t2.size]);\n  } else if ($t1.rank === 2 && $t2.rank === 1) {\n    const t22D = reshape($t2, [-1, 1]);\n    const t1t2 = matMul($t1, t22D);\n    return reshape(t1t2, [t1t2.size]);\n  } else {\n    const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);\n    const t1t2 = matMul($t1, t22D);\n    return t1t2;\n  }\n}\n\nexport const dot = /* @__PURE__ */ op({dot_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Einsum, EinsumAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\n\nimport {op} from './operation';\n\n/**\n * Tensor contraction over specified indices and outer product.\n *\n * `einsum` allows defining Tensors by defining their element-wise computation.\n * This computation is based on\n * [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).\n *\n * Some special cases include:\n *\n * Matrix multiplication:\n * ```js\n * const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n * const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);\n * x.print();\n * y.print();\n * tf.einsum('ij,jk->ik', x, y).print();\n * ```\n *\n * Dot product:\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n * const y = tf.tensor1d([0, 1, 2]);\n * x.print();\n * y.print();\n * tf.einsum('i,i->', x, y).print();\n * ```\n *\n * Batch dot product:\n * ```js\n * const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n * const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);\n * x.print();\n * y.print();\n * tf.einsum('bi,bi->b', x, y).print();\n * ```\n *\n * Outer prouduct:\n * ```js\n * const x = tf.tensor1d([1, 3, 5]);\n * const y = tf.tensor1d([2, 4, 6]);\n * x.print();\n * y.print();\n * tf.einsum('i,j->ij', x, y).print();\n * ```\n *\n * Matrix transpose:\n * ```js\n * const x = tf.tensor2d([[1, 2], [3, 4]]);\n * x.print();\n * tf.einsum('ij->ji', x).print();\n * ```\n *\n * Batch matrix transpose:\n * ```js\n * const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);\n * x.print();\n * tf.einsum('bij->bji', x).print();\n * ```\n *\n * Limitations:\n *\n * This implementation of einsum has the following limitations:\n *\n * - Does not support >2 input tensors.\n * - Does not support duplicate axes for any given input tensor. E.g., equation\n *   'ii->' is not supported.\n * - The `...` notation is not supported.\n *\n * @param equation a string describing the contraction, in the same format as\n * [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).\n * @param tensors the input(s) to contract (each one a Tensor), whose shapes\n *     should be consistent with equation.\n * @returns The output tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Matrices'}\n */\nexport function einsum_(equation: string, ...tensors: Tensor[]): Tensor {\n  const $tensors =\n      tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'einsum'));\n  const attrs: EinsumAttrs = {equation};\n  return ENGINE.runKernel(\n      Einsum, $tensors as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const einsum = /* @__PURE__ */ op({einsum_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Elu, EluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential linear element-wise: `x > 0 ? x : (e ^ x) - 1`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 1, -3, 2]);\n *\n * x.elu().print();  // or tf.elu(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction elu_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'elu', 'float32');\n\n  const inputs: EluInputs = {x: $x};\n\n  return ENGINE.runKernel(Elu, inputs as unknown as NamedTensorMap);\n}\n\nexport const elu = /* @__PURE__ */ op({elu_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap} from '../types';\nimport {arraysEqualWithNull} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Checks the input tensor mathes the given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * The method supports the null value in tensor. It will still check the shapes,\n * and null is a placeholder.\n *\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const y = tf.tensor1d([1, null, 3, 4]);\n * const z = tf.tensor2d([1, 2, 3, 4], [2,2]);\n * tf.ensureShape(x, [4]).print();\n * tf.ensureShape(y, [4]).print();\n * tf.ensureShape(z, [null, 2]).print();\n * ```\n *\n * @param x The input tensor to be ensured.\n * @param shape A TensorShape representing the shape of this tensor, an array\n *     or null.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction ensureShape_<R extends Rank>(x: Tensor, shape: ShapeMap[R]): Tensor {\n  const $x = convertToTensor(x, 'x', 'ensureShape', 'string_or_numeric');\n  if (!arraysEqualWithNull($x.shape, shape)) {\n    throw new Error(`EnsureShape: Shape of tensor ${\n        $x.shape} is not compatible with expected shape ${shape}`);\n  }\n\n  return x;\n}\nexport const ensureShape = /* @__PURE__ */ op({ensureShape_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Erf, ErfInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes Gauss error function of the input `tf.Tensor` element-wise:\n * `erf(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, .1, -.1, .7]);\n *\n * x.erf().print(); // or tf.erf(x);\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction erf_<T extends Tensor>(x: T|TensorLike): T {\n  let $x = convertToTensor(x, 'x', 'erf');\n  util.assert(\n      $x.dtype === 'int32' || $x.dtype === 'float32',\n      () => 'Input dtype must be `int32` or `float32`.');\n\n  if ($x.dtype === 'int32') {\n    $x = cast($x, 'float32');\n  }\n\n  const inputs: ErfInputs = {x: $x};\n  return ENGINE.runKernel(Erf, inputs as unknown as NamedTensorMap);\n}\nexport const erf = /* @__PURE__ */ op({erf_});\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\n/**\n * Returns true if the axis specifies the inner most dimensions of the\n * array.\n */\nexport function axesAreInnerMostDims(axes: number[], rank: number): boolean {\n  for (let i = 0; i < axes.length; ++i) {\n    if (axes[axes.length - i - 1] !== rank - 1 - i) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function combineLocations(\n    outputLoc: number[], reduceLoc: number[], axes: number[]): number[] {\n  const rank = outputLoc.length + reduceLoc.length;\n  const loc = [];\n  let outIdx = 0;\n  let reduceIdx = 0;\n    for (let dim = 0; dim < rank; dim++) {\n    if (axes.indexOf(dim) === -1) {\n      loc.push(outputLoc[outIdx++]);\n    } else {\n      loc.push(reduceLoc[reduceIdx++]);\n    }\n  }\n  return loc;\n}\n\nexport function computeOutAndReduceShapes(\n    aShape: number[], axes: number[]): [number[], number[]] {\n  const outShape = [];\n  const rank = aShape.length;\n  for (let dim = 0; dim < rank; dim++) {\n    if (axes.indexOf(dim) === -1) {\n      outShape.push(aShape[dim]);\n    }\n  }\n  const reduceShape = axes.map(dim => aShape[dim]);\n  return [outShape, reduceShape];\n}\n\nexport function expandShapeToKeepDim(\n    shape: number[], axes: number[]): number[] {\n  const reduceSubShape = axes.map(x => 1);\n  return combineLocations(shape, reduceSubShape, axes);\n}\n\nexport function assertAxesAreInnerMostDims(\n    msg: string, axes: number[], rank: number): void {\n  util.assert(\n      axesAreInnerMostDims(axes, rank),\n      () => `${msg} supports only inner-most axes for now. ` +\n          `Got axes ${axes} and rank-${rank} input.`);\n}\n\n/**\n * Returns the axes permutation to be used with `tf.transpose`, if such\n * permutation is necessary. Otherwise it returns null. This method is used by\n * operations that operate only on inner-most axes.\n */\nexport function getAxesPermutation(axes: number[], rank: number): number[]|\n    null {\n  if (axesAreInnerMostDims(axes, rank)) {\n    return null;\n  }\n  const result: number[] = [];\n  for (let i = 0; i < rank; ++i) {\n    if (axes.indexOf(i) === -1) {\n      result.push(i);\n    }\n  }\n  axes.forEach(axis => result.push(axis));\n  return result;\n}\n\n/** Returns the axes permutation that undoes the original permutation. */\nexport function getUndoAxesPermutation(axes: number[]): number[] {\n  return axes.map((axis, i) => [i, axis])\n      .sort((a, b) => a[1] - b[1])\n      .map(x => x[0]);\n}\n\nexport function getInnerMostAxes(numAxes: number, rank: number): number[] {\n  const res: number[] = [];\n  for (let i = rank - numAxes; i < rank; ++i) {\n    res.push(i);\n  }\n  return res;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Max, MaxAttrs, MaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the maximum of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.max().print();  // or tf.max(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.max(axis).print();  // or tf.max(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction max_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'max');\n\n  const inputs: MaxInputs = {x: $x};\n  const attrs: MaxAttrs = {reductionIndices: axis, keepDims};\n\n  return ENGINE.runKernel(\n      Max, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const max = /* @__PURE__ */ op({max_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Min, MinAttrs, MinInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the minimum value from the input.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the array is reduced by 1 for each entry in `axes`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axes` has no entries, all dimensions are reduced, and an array with a\n * single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.min().print();  // or tf.min(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.min(axis).print();  // or tf.min(x, axis)\n * ```\n *\n * @param x The input Tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction min_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'min');\n\n  const inputs: MinInputs = {x: $x};\n  const attrs: MinAttrs = {axis, keepDims};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             Min, inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as T;\n}\n\nexport const min = /* @__PURE__ */ op({min_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Pow, PowInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the power of one `tf.Tensor` to another. Supports broadcasting.\n *\n * Given a `tf.Tensor` x and a `tf.Tensor` y, this operation computes x^y for\n * corresponding elements in x and y. The result's dtype will be the upcasted\n * type of the `base` and `exp` dtypes.\n *\n * ```js\n * const a = tf.tensor([[2, 3], [4, 5]])\n * const b = tf.tensor([[1, 2], [3, 0]]).toInt();\n *\n * a.pow(b).print();  // or tf.pow(a, b)\n * ```\n *\n * ```js\n * const a = tf.tensor([[1, 2], [3, 4]])\n * const b = tf.tensor(2).toInt();\n *\n * a.pow(b).print();  // or tf.pow(a, b)\n * ```\n * We also expose `powStrict` which has the same signature as this op and\n * asserts that `base` and `exp` are the same shape (does not broadcast).\n *\n * @param base The base `tf.Tensor` to pow element-wise.\n * @param exp The exponent `tf.Tensor` to pow element-wise.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction pow_<T extends Tensor>(\n    base: Tensor|TensorLike, exp: Tensor|TensorLike): T {\n  let $base = convertToTensor(base, 'base', 'pow');\n  let $exp = convertToTensor(exp, 'exp', 'pow');\n  [$base, $exp] = makeTypesMatch($base, $exp);\n\n  const inputs: PowInputs = {a: $base, b: $exp};\n\n  return ENGINE.runKernel(Pow, inputs as unknown as NamedTensorMap);\n}\n\nexport const pow = /* @__PURE__ */ op({pow_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar} from '../tensor';\nimport {DataType} from '../types';\nimport {isTypedArray} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.scalar` as it makes the code more readable.\n *\n * ```js\n * tf.scalar(3.14).print();\n * ```\n *\n * @param value The value of the scalar.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function scalar(\n    value: number|boolean|string|Uint8Array, dtype?: DataType): Scalar {\n  if (((isTypedArray(value) && dtype !== 'string') || Array.isArray(value)) &&\n      dtype !== 'complex64') {\n    throw new Error(\n        'Error creating a new Scalar: value must be a primitive ' +\n        '(number|boolean|string)');\n  }\n  if (dtype === 'string' && isTypedArray(value) &&\n      !(value instanceof Uint8Array)) {\n    throw new Error(\n        'When making a scalar from encoded string, ' +\n        'the value must be `Uint8Array`.');\n  }\n  const shape: number[] = [];\n  const inferredShape: number[] = [];\n  return makeTensor(value, shape, inferredShape, dtype) as Scalar;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sqrt, SqrtInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes square root of the input `tf.Tensor` element-wise: `y = sqrt(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 4, -1]);\n *\n * x.sqrt().print();  // or tf.sqrt(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sqrt_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sqrt', 'float32');\n\n  const inputs: SqrtInputs = {x: $x};\n\n  return ENGINE.runKernel(Sqrt, inputs as unknown as NamedTensorMap);\n}\nexport const sqrt = /* @__PURE__ */ op({sqrt_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Computes square of `x` element-wise: `x ^ 2`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);\n *\n * x.square().print();  // or tf.square(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction square_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'square');\n  const attrs = {};\n  return ENGINE.runKernel('Square', {x: $x}, attrs);\n}\n\nexport const square = /* @__PURE__ */ op({square_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Sum, SumAttrs, SumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes the sum of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If axes has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.sum().print();  // or tf.sum(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.sum(axis).print();  // or tf.sum(x, axis)\n * ```\n *\n * @param x The input tensor to compute the sum over. If the dtype is `bool`\n *   it will be converted to `int32` and the output dtype will be `int32`.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction sum_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  let $x = convertToTensor(x, 'x', 'sum');\n  if ($x.dtype === 'bool') {\n    $x = cast($x, 'int32');\n  }\n\n  const inputs: SumInputs = {x: $x};\n  const attrs: SumAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      Sum, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const sum = /* @__PURE__ */ op({sum_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {abs} from './abs';\nimport * as axis_util from './axis_util';\nimport {max} from './max';\nimport {min} from './min';\nimport {op} from './operation';\nimport {pow} from './pow';\nimport {reshape} from './reshape';\nimport {scalar} from './scalar';\nimport {sqrt} from './sqrt';\nimport {square} from './square';\nimport {sum} from './sum';\n\n/**\n * Computes the norm of scalar, vectors, and matrices.\n * This function can compute several different vector norms (the 1-norm, the\n * Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0)\n * and matrix norms (Frobenius, 1-norm, and inf-norm).\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.norm().print();  // or tf.norm(x)\n * ```\n *\n * @param x The input array.\n * @param ord Optional. Order of the norm. Supported norm types are\n * following:\n *\n *  | ord        | norm for matrices         | norm for vectors\n *  |------------|---------------------------|---------------------\n *  |'euclidean' |Frobenius norm             |2-norm\n *  |'fro'       |Frobenius norm\t           |\n *  |Infinity    |max(sum(abs(x), axis=1))   |max(abs(x))\n *  |-Infinity   |min(sum(abs(x), axis=1))   |min(abs(x))\n *  |1           |max(sum(abs(x), axis=0))   |sum(abs(x))\n *  |2           |                           |sum(abs(x)^2)^(1/2)\n *\n * @param axis Optional. If axis is null (the default), the input is\n * considered a vector and a single vector norm is computed over the entire\n * set of values in the Tensor, i.e. norm(x, ord) is equivalent\n * to norm(x.reshape([-1]), ord). If axis is an integer, the input\n * is considered a batch of vectors, and axis determines the axis in x\n * over which to compute vector norms. If axis is a 2-tuple of integer it is\n * considered a batch of matrices and axis determines the axes in NDArray\n * over which to compute a matrix norm.\n * @param keepDims Optional. If true, the norm has the same dimensionality\n * as the input.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction norm_(\n    x: Tensor|TensorLike, ord: number|'euclidean'|'fro' = 'euclidean',\n    axis: number|number[] = null, keepDims = false): Tensor {\n  x = convertToTensor(x, 'x', 'norm');\n\n  const norm = normImpl(x, ord, axis);\n  let keepDimsShape = norm.shape;\n  if (keepDims) {\n    const axes = parseAxisParam(axis, x.shape);\n    keepDimsShape = axis_util.expandShapeToKeepDim(norm.shape, axes);\n  }\n  return reshape(norm, keepDimsShape);\n}\n\nfunction normImpl(\n    x: Tensor, p: number|string, axis: number|number[] = null): Tensor {\n  if (x.rank === 0) {\n    return abs(x);\n  }\n\n  // consider vector when no axis is specified\n  if (x.rank !== 1 && axis === null) {\n    return normImpl(reshape(x, [-1]), p, axis);\n  }\n\n  // vector\n  if (x.rank === 1 || typeof axis === 'number' ||\n      Array.isArray(axis) && axis.length === 1) {\n    if (p === 1) {\n      return sum(abs(x), axis);\n    }\n    if (p === Infinity) {\n      return max(abs(x), axis);\n    }\n    if (p === -Infinity) {\n      return min(abs(x), axis);\n    }\n    if (p === 'euclidean' || p === 2) {\n      // norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2\n      return sqrt(sum(pow(abs(x), scalar(2, 'int32')), axis));\n    }\n\n    throw new Error(`Error in norm: invalid ord value: ${p}`);\n  }\n\n  // matrix (assumption axis[0] < axis[1])\n  if (Array.isArray(axis) && axis.length === 2) {\n    if (p === 1) {\n      return max(sum(abs(x), axis[0]), axis[1] - 1);\n    }\n    if (p === Infinity) {\n      return max(sum(abs(x), axis[1]), axis[0]);\n    }\n    if (p === -Infinity) {\n      return min(sum(abs(x), axis[1]), axis[0]);\n    }\n    if (p === 'fro' || p === 'euclidean') {\n      // norm(x) = sqrt(sum(pow(x, 2)))\n      return sqrt(sum(square(x), axis));\n    }\n\n    throw new Error(`Error in norm: invalid ord value: ${p}`);\n  }\n\n  throw new Error(`Error in norm: invalid axis: ${axis}`);\n}\n\nexport const norm = /* @__PURE__ */ op({norm_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {norm} from './norm';\nimport {op} from './operation';\n\n/**\n * Computes the Euclidean norm of scalar, vectors, and matrices.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.euclideanNorm().print();  // or tf.euclideanNorm(x)\n * ```\n *\n * @param x The input array.\n * @param axis Optional. If axis is null (the default), the input is\n * considered a vector and a single vector norm is computed over the entire\n * set of values in the Tensor, i.e. euclideanNorm(x) is equivalent\n * to euclideanNorm(x.reshape([-1])). If axis is an integer, the input\n * is considered a batch of vectors, and axis determines the axis in x\n * over which to compute vector norms. If axis is a 2-tuple of integer it is\n * considered a batch of matrices and axis determines the axes in NDArray\n * over which to compute a matrix norm.\n * @param keepDims Optional. If true, the norm has the same dimensionality\n * as the input.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction euclideanNorm_(\n    x: Tensor|TensorLike, axis: number|number[] = null,\n    keepDims = false): Tensor {\n  return norm(x, 'euclidean', axis, keepDims);\n}\n\nexport const euclideanNorm = /* @__PURE__ */ op({euclideanNorm_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Exp, ExpInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential of the input `tf.Tensor` element-wise. `e ^ x`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, -3]);\n *\n * x.exp().print();  // or tf.exp(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction exp_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'exp');\n\n  const inputs: ExpInputs = {x: $x};\n  return ENGINE.runKernel(Exp, inputs as unknown as NamedTensorMap);\n}\nexport const exp = /* @__PURE__ */ op({exp_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Returns a `tf.Tensor` that has expanded rank, by inserting a dimension\n * into the tensor's shape.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const axis = 1;\n * x.expandDims(axis).print();\n * ```\n *\n * @param x The input tensor whose dimensions are to be expanded.\n * @param axis The dimension index at which to insert shape of `1`. Defaults\n *     to 0 (the first dimension).\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction expandDims_<T extends Tensor>(x: Tensor|TensorLike, axis = 0): T {\n  const $x = convertToTensor(x, 'x', 'expandDims', 'string_or_numeric');\n\n  util.assert(axis <= $x.rank, () => 'Axis must be <= rank of the tensor');\n\n  const inputs: ExpandDimsInputs = {input: $x};\n  const attrs: ExpandDimsAttrs = {dim: axis};\n\n  return ENGINE.runKernel(\n      ExpandDims, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const expandDims = /* @__PURE__ */ op({expandDims_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Expm1, Expm1Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential of the input `tf.Tensor` minus one element-wise.\n * `e ^ x - 1`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, -3]);\n *\n * x.expm1().print();  // or tf.expm1(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction expm1_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'expm1');\n\n  const inputs: Expm1Inputs = {x: $x};\n  return ENGINE.runKernel(Expm1, inputs as unknown as NamedTensorMap);\n}\nexport const expm1 = /* @__PURE__ */ op({expm1_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tile, TileAttrs, TileInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Construct a tensor by repeating it the number of times given by reps.\n *\n * This operation creates a new tensor by replicating `input` `reps`\n * times. The output tensor's `i`th dimension has `input.shape[i] *\n * reps[i]` elements, and the values of `input` are replicated\n * `reps[i]` times along the `i`th dimension. For example, tiling\n * `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n *\n * a.tile([2]).print();    // or tf.tile(a, [2])\n * ```\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.tile([1, 2]).print();  // or tf.tile(a, [1,2])\n * ```\n * @param x The tensor to tile.\n * @param reps Determines the number of replications per dimension.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction tile_<T extends Tensor>(x: T|TensorLike, reps: number[]): T {\n  const $x = convertToTensor(x, 'x', 'tile', 'string_or_numeric');\n  util.assert(\n      $x.rank === reps.length,\n      () => `Error in transpose: rank of input ${$x.rank} ` +\n          `must match length of reps ${reps}.`);\n\n  const inputs: TileInputs = {x: $x};\n  const attrs: TileAttrs = {reps};\n\n  return ENGINE.runKernel(\n      Tile, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const tile = /* @__PURE__ */ op({tile_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {DataType} from '../types';\n\nimport {buffer} from './buffer';\nimport {expandDims} from './expand_dims';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {tile} from './tile';\n\n/**\n * Create an identity matrix.\n *\n * @param numRows Number of rows.\n * @param numColumns Number of columns. Defaults to `numRows`.\n * @param batchShape If provided, will add the batch shape to the beginning\n *   of the shape of the returned `tf.Tensor` by repeating the identity\n *   matrix.\n * @param dtype Data type.\n * @returns Identity matrix of the specified size and data type, possibly\n *   with batch repetition if `batchShape` is specified.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction eye_(\n    numRows: number, numColumns?: number,\n    batchShape?:\n        [\n          number\n        ]|[number,\n           number]|[number, number, number]|[number, number, number, number],\n    dtype: DataType = 'float32'): Tensor2D {\n  if (numColumns == null) {\n    numColumns = numRows;\n  }\n  const buff = buffer([numRows, numColumns], dtype);\n  const n = numRows <= numColumns ? numRows : numColumns;\n  for (let i = 0; i < n; ++i) {\n    buff.set(1, i, i);\n  }\n  const out: Tensor2D = reshape(buff.toTensor(), [numRows, numColumns]);\n  if (batchShape == null) {\n    return out;\n  } else {\n    if (batchShape.length === 1) {\n      return tile(expandDims(out, 0), [batchShape[0], 1, 1]) as Tensor2D;\n    } else if (batchShape.length === 2) {\n      // tslint:disable-next-line:no-unnecessary-type-assertion\n      return tile(\n                 expandDims(expandDims(out, 0), 0),\n                 [batchShape[0], batchShape[1], 1, 1]) as Tensor2D;\n    } else if (batchShape.length === 3) {\n      // tslint:disable-next-line:no-unnecessary-type-assertion\n      return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [\n               batchShape[0], batchShape[1], batchShape[2], 1, 1\n             ]) as Tensor2D;\n    } else {\n      throw new Error(\n          `eye() currently supports only 1D and 2D ` +\n          // tslint:disable-next-line:no-any\n          `batchShapes, but received ${(batchShape as any).length}D.`);\n    }\n  }\n}\n\nexport const eye = /* @__PURE__ */ op({eye_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Floor, FloorInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes floor of input `tf.Tensor` element-wise: `floor(x)`.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.floor().print();  // or tf.floor(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction floor_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'floor', 'float32');\n\n  const inputs: FloorInputs = {x: $x};\n  return ENGINE.runKernel(Floor, inputs as unknown as NamedTensorMap);\n}\nexport const floor = /* @__PURE__ */ op({floor_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {GatherV2, GatherV2Attrs, GatherV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Gather slices from tensor `x`'s axis `axis` according to `indices`.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const indices = tf.tensor1d([1, 3, 3], 'int32');\n *\n * x.gather(indices).print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const indices = tf.tensor1d([1, 1, 0], 'int32');\n *\n * x.gather(indices).print();\n * ```\n * @param x The input tensor whose slices are to be gathered.\n * @param indices The indices of the values to extract.\n * @param axis The axis over which to select values. Defaults to 0.\n * @param batchDims Optional. The number of batch dimensions. It must be less\n *     than or equal to rank(indices). Defaults to 0.\n *     The output tensor will have shape of\n *     `x.shape[:axis] + indices.shape[batchDims:] + x.shape[axis + 1:]`\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction gather_<T extends Tensor>(\n    x: T|TensorLike, indices: Tensor|TensorLike, axis = 0, batchDims = 0): T {\n  const $x = convertToTensor(x, 'x', 'gather');\n  const $indices = convertToTensor(indices, 'indices', 'gather', 'int32');\n\n  const inputs: GatherV2Inputs = {x: $x, indices: $indices};\n  const attrs: GatherV2Attrs = {axis, batchDims};\n\n  return ENGINE.runKernel(\n      GatherV2, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const gather = /* @__PURE__ */ op({gather_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Greater, GreaterInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a > b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.greater(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction greater_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'greater', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'greater', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: GreaterInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Greater, inputs as unknown as NamedTensorMap);\n}\n\nexport const greater = /* @__PURE__ */ op({greater_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {GreaterEqual, GreaterEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a >= b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.greaterEqual(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction greaterEqual_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'greaterEqual', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'greaterEqual', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: GreaterEqualInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(GreaterEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const greaterEqual = /* @__PURE__ */ op({greaterEqual_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Imag, ImagInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n/**\n * Returns the imaginary part of a complex (or real) tensor.\n *\n * Given a tensor input, this operation returns a tensor of type float that is\n * the imaginary part of each element in input considered as a complex number.\n * If input is real, a tensor of all zeros is returned.\n *\n * ```js\n * const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);\n * tf.imag(x).print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction imag_<T extends Tensor>(input: T|TensorLike): T {\n  const $input = convertToTensor(input, 'input', 'imag');\n\n  const inputs: ImagInputs = {input: $input};\n  return ENGINE.runKernel(Imag, inputs as unknown as NamedTensorMap);\n}\n\nexport const imag = /* @__PURE__ */ op({imag_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsFinite, IsFiniteInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are finite.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isFinite().print();  // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isFinite_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'isFinite');\n\n  const inputs: IsFiniteInputs = {x: $x};\n\n  return ENGINE.runKernel(IsFinite, inputs as unknown as NamedTensorMap);\n}\nexport const isFinite = /* @__PURE__ */ op({isFinite_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsInf, IsInfInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are Infinity or -Infinity.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isInf().print();  // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isInf_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'isInf');\n\n  const inputs: IsInfInputs = {x: $x};\n\n  return ENGINE.runKernel(IsInf, inputs as unknown as NamedTensorMap);\n}\nexport const isInf = /* @__PURE__ */ op({isInf_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsNan, IsNanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are NaN.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isNaN().print();  // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isNaN_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'isNaN');\n  const inputs: IsNanInputs = {x: $x};\n\n  return ENGINE.runKernel(IsNan, inputs as unknown as NamedTensorMap);\n}\nexport const isNaN = /* @__PURE__ */ op({isNaN_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LeakyRelu, LeakyReluAttrs, LeakyReluInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes leaky rectified linear element-wise.\n *\n * See\n * [http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf](\n *     http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf)\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.leakyRelu(0.1).print();  // or tf.leakyRelu(x, 0.1)\n * ```\n * @param x The input tensor.\n * @param alpha The scaling factor for negative values, defaults to 0.2.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction leakyRelu_<T extends Tensor>(x: T|TensorLike, alpha = 0.2): T {\n  const $x = convertToTensor(x, 'x', 'leakyRelu');\n\n  const inputs: LeakyReluInputs = {x: $x};\n  const attrs: LeakyReluAttrs = {alpha};\n\n  return ENGINE.runKernel(\n      LeakyRelu, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const leakyRelu = /* @__PURE__ */ op({leakyRelu_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Less, LessInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a < b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.less(b).print();\n * ```\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction less_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'less', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'less', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: LessInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Less, inputs as unknown as NamedTensorMap);\n}\n\nexport const less = /* @__PURE__ */ op({less_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {LessEqual, LessEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a <= b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.lessEqual(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction lessEqual_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'lessEqual', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'lessEqual', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: LessEqualInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(LessEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const lessEqual = /* @__PURE__ */ op({lessEqual_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LinSpace, LinSpaceAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\n\n/**\n * Return an evenly spaced sequence of numbers over the given interval.\n *\n * ```js\n * tf.linspace(0, 9, 10).print();\n * ```\n * @param start The start value of the sequence.\n * @param stop The end value of the sequence.\n * @param num The number of values to generate.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function linspace(start: number, stop: number, num: number): Tensor1D {\n  if (num <= 0) {\n    throw new Error('The number of values should be positive.');\n  }\n\n  const attrs: LinSpaceAttrs = {start, stop, num};\n  return ENGINE.runKernel(LinSpace, {}, attrs as unknown as NamedAttrMap);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LRN, LRNAttrs, LRNInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Normalizes the activation of a local neighborhood across or within\n * channels.\n *\n * @param x The input tensor. The 4-D input tensor is treated as a 3-D array\n *     of 1D vectors (along the last dimension), and each vector is\n *     normalized independently.\n * @param depthRadius The number of adjacent channels in the 1D normalization\n *     window.\n * @param bias A constant bias term for the basis.\n * @param alpha A scale factor, usually positive.\n * @param beta An exponent.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction localResponseNormalization_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5): T {\n  const $x = convertToTensor(x, 'x', 'localResponseNormalization');\n  util.assert(\n      $x.rank === 4 || $x.rank === 3,\n      () => `Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank ${$x.rank}.`);\n  util.assert(\n      util.isInt(depthRadius),\n      () => `Error in localResponseNormalization: depthRadius must be an ` +\n          `integer but got depthRadius ${depthRadius}.`);\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  const inputs: LRNInputs = {x: x4D};\n\n  const attrs: LRNAttrs = {depthRadius, bias, alpha, beta};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  LRN, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  } else {\n    return res;\n  }\n}\n\nexport const localResponseNormalization = /* @__PURE__ */ op({localResponseNormalization_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Log, LogInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes natural logarithm of the input `tf.Tensor` element-wise: `ln(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.E]);\n *\n * x.log().print();  // or tf.log(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction log_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'log', 'float32');\n\n  const inputs: LogInputs = {x: $x};\n  return ENGINE.runKernel(Log, inputs as unknown as NamedTensorMap);\n}\nexport const log = /* @__PURE__ */ op({log_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Log1p, Log1pInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes natural logarithm of the input `tf.Tensor` plus one\n * element-wise: `ln(1 + x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.E - 1]);\n *\n * x.log1p().print();  // or tf.log1p(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction log1p_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'log1p');\n\n  const inputs: Log1pInputs = {x: $x};\n  return ENGINE.runKernel(Log1p, inputs as unknown as NamedTensorMap);\n}\nexport const log1p = /* @__PURE__ */ op({log1p_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {CustomGradientFunc, ENGINE} from './engine';\nimport {Scalar, Tensor, Variable} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {convertToTensor, convertToTensorArray} from './tensor_util_env';\nimport {TensorLike} from './types';\nimport * as util from './util';\n\n/**\n * Provided `f(x)`, returns another function `g(x, dy?)`, which gives the\n * gradient of `f(x)` with respect to `x`.\n *\n * If `dy` is provided, the gradient of `f(x).mul(dy).sum()` with respect to\n * `x` is computed instead. `f(x)` must take a single tensor `x` and return a\n * single tensor `y`. If `f()` takes multiple inputs, use `tf.grads` instead.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.grad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * g(x).print();\n * ```\n *\n * ```js\n * // f(x) = x ^ 3\n * const f = x => x.pow(tf.scalar(3, 'int32'));\n * // f'(x) = 3x ^ 2\n * const g = tf.grad(f);\n * // f''(x) = 6x\n * const gg = tf.grad(g);\n *\n * const x = tf.tensor1d([2, 3]);\n * gg(x).print();\n * ```\n *\n * @param f The function f(x), to compute gradient for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grad(f: (x: Tensor) => Tensor): (\n    x: TensorLike|Tensor, dy?: TensorLike|Tensor) => Tensor {\n  util.assert(\n      util.isFunction(f), () => 'The f passed in grad(f) must be a function');\n  return (x: TensorLike|Tensor, dy?: TensorLike|Tensor): Tensor => {\n    // x can be of any dtype, thus null as the last argument.\n    const $x = convertToTensor(x, 'x', 'tf.grad', 'string_or_numeric');\n    const $dy: Tensor =\n        (dy != null) ? convertToTensor(dy, 'dy', 'tf.grad') : null;\n    return ENGINE.tidy(() => {\n      const {value, grads} = ENGINE.gradients(() => f($x), [$x], $dy);\n      if ($dy != null) {\n        util.assertShapesMatch(\n            value.shape, $dy.shape,\n            'The shape of dy passed in grad(f)(x, dy) must match the shape ' +\n                'returned by f(x)');\n      }\n      checkGrads(grads);\n      return grads[0];\n    });\n  };\n}\n\n/**\n * Provided `f(x1, x2,...)`, returns another function `g([x1, x2,...], dy?)`,\n * which gives an array of gradients of `f()` with respect to each input\n * [`x1`,`x2`,...].\n *\n * If `dy` is passed when calling `g()`, the gradient of\n * `f(x1,...).mul(dy).sum()` with respect to each input is computed instead.\n * The provided `f` must take one or more tensors and return a single tensor\n * `y`. If `f()` takes a single input, we recommend using `tf.grad` instead.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df / da = b, df / db = a\n * const g = tf.grads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const [da, db] = g([a, b]);\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @param f The function `f(x1, x2,...)` to compute gradients for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grads(f: (...args: Tensor[]) => Tensor): (\n    args: Array<Tensor|TensorLike>, dy?: Tensor|TensorLike) => Tensor[] {\n  util.assert(\n      util.isFunction(f), () => 'The f passed in grads(f) must be a function');\n  return (args: Array<Tensor|TensorLike>, dy?: Tensor|TensorLike): Tensor[] => {\n    util.assert(\n        Array.isArray(args),\n        () => 'The args passed in grads(f)(args) must be an array ' +\n            'of `Tensor`s or `TensorLike`s');\n    // args can be of any dtype, thus null as the last argument.\n    const $args =\n        convertToTensorArray(args, 'args', 'tf.grads', 'string_or_numeric');\n    const $dy: Tensor =\n        (dy != null) ? convertToTensor(dy, 'dy', 'tf.grads') : null;\n    return ENGINE.tidy(() => {\n      const {value, grads} = ENGINE.gradients(() => f(...$args), $args, $dy);\n      if ($dy != null) {\n        util.assertShapesMatch(\n            value.shape, $dy.shape,\n            'The shape of dy passed in grads(f)([x1,...], dy) must ' +\n                'match the shape returned by f([x1,...])');\n      }\n      checkGrads(grads);\n      return grads;\n    });\n  };\n}\n\n/**\n * Like `tf.grad`, but also returns the value of `f()`. Useful when `f()`\n * returns a metric you want to show.\n *\n * The result is a rich object with the following properties:\n * - grad: The gradient of `f(x)` w.r.t. `x` (result of `tf.grad`).\n * - value: The value returned by `f(x)`.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.valueAndGrad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * const {value, grad} = g(x);\n *\n * console.log('value');\n * value.print();\n * console.log('grad');\n * grad.print();\n * ```\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction valueAndGrad<I extends Tensor, O extends Tensor>(f: (x: I) => O): (\n    x: I, dy?: O) => {\n  value: O;\n  grad: I;\n} {\n  util.assert(\n      util.isFunction(f),\n      () => 'The f passed in valueAndGrad(f) must be a function');\n  return (x: I, dy?: O) => {\n    util.assert(\n        x instanceof Tensor,\n        () => 'The x passed in valueAndGrad(f)(x) must be a tensor');\n    util.assert(\n        dy == null || dy instanceof Tensor,\n        () => 'The dy passed in valueAndGrad(f)(x, dy) must be a tensor');\n    const {grads, value} = ENGINE.gradients(() => f(x), [x], dy);\n    checkGrads(grads);\n    return {grad: grads[0] as I, value};\n  };\n}\n\n/**\n * Like `tf.grads`, but returns also the value of `f()`. Useful when `f()`\n * returns a metric you want to show.\n *\n * The result is a rich object with the following properties:\n * - grads: The gradients of `f()` w.r.t. each input (result of `tf.grads`).\n * - value: The value returned by `f(x)`.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df/da = b, df/db = a\n * const g = tf.valueAndGrads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const {value, grads} = g([a, b]);\n *\n * const [da, db] = grads;\n *\n * console.log('value');\n * value.print();\n *\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction valueAndGrads<O extends Tensor>(f: (...args: Tensor[]) => O): (\n    args: Tensor[], dy?: O) => {\n  grads: Tensor[];\n  value: O;\n} {\n  util.assert(\n      util.isFunction(f),\n      () => 'The f passed in valueAndGrads(f) must be a function');\n  return (args: Tensor[], dy?: O) => {\n    util.assert(\n        Array.isArray(args) && args.every(arg => arg instanceof Tensor),\n        () => 'The args passed in valueAndGrads(f)(args) must be array of ' +\n            'tensors');\n    util.assert(\n        dy == null || dy instanceof Tensor,\n        () => 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');\n    const res = ENGINE.gradients(() => f(...args), args, dy);\n    if (dy != null) {\n      util.assertShapesMatch(\n          res.value.shape, dy.shape,\n          'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +\n              'match the shape returned by f([x1,...])');\n    }\n    checkGrads(res.grads);\n    return res;\n  };\n}\n\n/**\n * Computes and returns the gradient of f(x) with respect to the list of\n * trainable variables provided by `varList`. If no list is provided, it\n * defaults to all trainable variables.\n *\n * ```js\n * const a = tf.variable(tf.tensor1d([3, 4]));\n * const b = tf.variable(tf.tensor1d([5, 6]));\n * const x = tf.tensor1d([1, 2]);\n *\n * // f(a, b) = a * x ^ 2 + b * x\n * const f = () => a.mul(x.square()).add(b.mul(x)).sum();\n * // df/da = x ^ 2, df/db = x\n * const {value, grads} = tf.variableGrads(f);\n *\n * Object.keys(grads).forEach(varName => grads[varName].print());\n * ```\n *\n * @param f The function to execute. f() should return a scalar.\n * @param varList The list of variables to compute the gradients with respect\n *     to. Defaults to all trainable variables.\n * @returns An object with the following keys and values:\n *   - `value`: The value of the function `f`.\n *   - `grads`: A map from the names of the variables to the gradients.\n *     If the `varList` argument is provided explicitly and contains a subset of\n *     non-trainable variables, this map in the return value will contain keys\n *     that map the names of the non-trainable variables to `null`.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction variableGrads(f: () => Scalar, varList?: Variable[]):\n    {value: Scalar, grads: NamedTensorMap} {\n  util.assert(\n      util.isFunction(f),\n      () => 'The f passed in variableGrads(f) must be a function');\n  util.assert(\n      varList == null ||\n          Array.isArray(varList) && varList.every(v => v instanceof Variable),\n      () =>\n          'The varList passed in variableGrads(f, varList) must be an array ' +\n          'of variables');\n\n  const specifiedVarList = varList != null;\n  if (!specifiedVarList) {\n    // Get all of the trainable variables.\n    varList = [];\n    for (const varName in ENGINE.registeredVariables) {\n      varList.push(ENGINE.registeredVariables[varName]);\n    }\n  }\n\n  const specifiedNonTrainable: Variable[] =\n      specifiedVarList ? varList.filter(variable => !variable.trainable) : null;\n\n  // Prune non-trainable variables.\n  const originalVarCount = varList.length;\n  varList = varList.filter(variable => variable.trainable);\n  util.assert(\n      varList.length > 0,\n      () => `variableGrads() expects at least one of the input variables to ` +\n          `be trainable, but none of the ${originalVarCount} variables is ` +\n          `trainable.`);\n\n  const allowNoGradients = true;\n  const {value, grads} = ENGINE.gradients(f, varList, null, allowNoGradients);\n\n  util.assert(\n      grads.some(g => g != null),\n      () => 'Cannot find a connection between any variable and the result of ' +\n          'the loss function y=f(x). Please make sure the operations that ' +\n          'use variables are inside the function f passed to minimize().');\n  util.assert(\n      value.rank === 0,\n      () => `The f passed in variableGrads(f) must return a scalar, but it ` +\n          `returned a rank-${value.rank} tensor`);\n\n  const namedGrads: NamedTensorMap = {};\n  varList.forEach((v, i) => {\n    if (grads[i] != null) {\n      namedGrads[v.name] = grads[i];\n    }\n  });\n  if (specifiedNonTrainable != null) {\n    // If varList is explicitly provided and contains non-trainable values,\n    // add them to the returned gradients with `null` values.\n    specifiedNonTrainable.forEach(v => namedGrads[v.name] = null);\n  }\n  return {value, grads: namedGrads};\n}\n\n/**\n * Overrides the gradient computation of a function `f`.\n *\n * Takes a function\n * `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`\n * and returns another function `g(...inputs)` which takes the same inputs as\n * `f`. When called, `g` returns `f().value`. In backward mode, custom gradients\n * with respect to each input of `f` are computed using `f().gradFunc`.\n *\n * The `save` function passed to `f` should be used for saving tensors needed\n * in the gradient. And the `saved` passed to the `gradFunc` is a\n * `NamedTensorMap`, which contains those saved tensors.\n *\n * ```js\n * const customOp = tf.customGrad((x, save) => {\n *   // Save x to make sure it's available later for the gradient.\n *   save([x]);\n *   // Override gradient of our custom x ^ 2 op to be dy * abs(x);\n *   return {\n *     value: x.square(),\n *     // Note `saved.x` which points to the `x` we saved earlier.\n *     gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]\n *   };\n * });\n *\n * const x = tf.tensor1d([-1, -2, 3]);\n * const dx = tf.grad(x => customOp(x));\n *\n * console.log(`f(x):`);\n * customOp(x).print();\n * console.log(`f'(x):`);\n * dx(x).print();\n * ```\n *\n * @param f The function to evaluate in forward mode, which should return\n *     `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`\n *     returns the custom gradients of `f` with respect to its inputs.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction customGrad<T extends Tensor>(f: CustomGradientFunc<T>):\n    (...args: Tensor[]) => T {\n  return ENGINE.customGrad(f);\n}\n\nfunction checkGrads(grads: Tensor[]) {\n  const numNullGradients = grads.filter(g => g == null).length;\n  if (numNullGradients > 0) {\n    throw new Error(\n        `Cannot compute gradient of y=f(x) with respect to x. Make sure that\n    the f you passed encloses all operations that lead from x to y.`);\n  }\n}\n\nexport {\n  customGrad,\n  variableGrads,\n  valueAndGrad,\n  valueAndGrads,\n  grad,\n  grads,\n};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Neg, NegInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes `-1 * x` element-wise.\n *\n * ```js\n * const x = tf.tensor2d([1, 2, -2, 0], [2, 2]);\n *\n * x.neg().print();  // or tf.neg(x)\n * ```\n *\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction neg_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'neg');\n\n  const inputs: NegInputs = {x: $x};\n  return ENGINE.runKernel(Neg, inputs as unknown as NamedTensorMap);\n}\nexport const neg = /* @__PURE__ */ op({neg_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Softplus, SoftplusInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes softplus of the input `tf.Tensor` element-wise: `log(exp(x) + 1)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.softplus().print();  // or tf.softplus(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction softplus_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'softplus');\n\n  const inputs: SoftplusInputs = {x: $x};\n  return ENGINE.runKernel(Softplus, inputs as unknown as NamedTensorMap);\n}\nexport const softplus = /* @__PURE__ */ op({softplus_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {customGrad} from '../gradients';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {mul} from './mul';\nimport {neg} from './neg';\nimport {op} from './operation';\nimport {sigmoid} from './sigmoid';\nimport {softplus} from './softplus';\n\n/**\n * Computes log sigmoid of the input `tf.Tensor` element-wise:\n * `logSigmoid(x)`. For numerical stability, we use `-tf.softplus(-x)`.\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.logSigmoid().print();  // or tf.logSigmoid(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction logSigmoid_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'logSigmoid');\n\n  // Use a custom gradient to maintain previous implementation.\n  // There is no LogSigmoid kernel in TF so we can't use engine.runKernel\n  // directly\n  const customOp = customGrad((x: Tensor) => {\n    // TODO(yassogba) we can remove the chained softplus call here only\n    // after backends have modualrized softplus at which point we can call\n    // engine runKernel(..., Sotfplus, ...) directly.\n    const value = neg(softplus(neg(x)));\n\n    const gradFunc = (dy: T) => {\n      const derX = mul(dy, sigmoid(neg(x)));\n      return derX;\n    };\n    return {value, gradFunc};\n  });\n\n  return customOp($x) as T;\n}\nexport const logSigmoid = /* @__PURE__ */ op({logSigmoid_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Sub, SubInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Subtracts two `tf.Tensor`s element-wise, A - B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([10, 20, 30, 40]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.sub(b).print();  // or tf.sub(a, b)\n * ```\n *\n * ```js\n * // Broadcast subtract a with b.\n * const a = tf.tensor1d([10, 20, 30, 40]);\n * const b = tf.scalar(5);\n *\n * a.sub(b).print();  // or tf.sub(a, b)\n * ```\n * @param a The first `tf.Tensor` to subtract from.\n * @param b The second `tf.Tensor` to be subtracted. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction sub_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'sub');\n  let $b = convertToTensor(b, 'b', 'sub');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: SubInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Sub, inputs as unknown as NamedTensorMap);\n}\n\nexport const sub = /* @__PURE__ */ op({sub_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {customGrad} from '../gradients';\n\nimport {Tensor} from '../tensor';\nimport {GradSaveFunc} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {exp} from './exp';\nimport {log} from './log';\nimport {max} from './max';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {sub} from './sub';\nimport {sum} from './sum';\n\n/**\n * Computes the log softmax.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n *\n * a.logSoftmax().print();  // or tf.logSoftmax(a)\n * ```\n *\n * ```js\n * const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);\n *\n * a.logSoftmax().print();  // or tf.logSoftmax(a)\n * ```\n *\n * @param logits The logits array.\n * @param axis The dimension softmax would be performed on. Defaults to `-1`\n *     which indicates the last dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction logSoftmax_<T extends Tensor>(logits: T|TensorLike, axis = -1): T {\n  const $logits = convertToTensor(logits, 'logits', 'logSoftmax');\n\n  if (axis === -1) {\n    axis = $logits.rank - 1;\n  }\n  if (axis !== $logits.rank - 1) {\n    throw Error(\n        'Log Softmax along a non-last dimension is not yet supported. ' +\n        `Logits was rank ${$logits.rank} and axis was ${axis}`);\n  }\n\n  // const forward: ForwardFunc<Tensor> = (backend, save) => {\n  //   const keepDims = true;\n  //   const xMax = max(logits, axis, true);\n  //   const shifted = sub(logits, xMax);\n  //   const value =\n  //       sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis,\n  //       keepDims)));\n  //   save([value]);\n  //   return value;\n  // };\n\n  // Use a custom gradient for numerical stability.\n  const customOp = customGrad((logits: Tensor, save: GradSaveFunc) => {\n    const keepDims = true;\n    const xMax = max(logits, axis, true);\n    const shifted = sub(logits, xMax);\n    const value =\n        sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis, keepDims)));\n    save([value]);\n\n    const gradFunc = (dy: Tensor, saved: Tensor[]) => {\n      const [value] = saved;\n      const keepDims = true;\n      const softmax = exp(value);\n      return sub(dy, mul(sum(dy, axis, keepDims), softmax));\n    };\n    return {value, gradFunc};\n  });\n\n  return customOp($logits) as T;\n\n  // TODO Use Engine.runKernel when CPU/WebGL/WASM backends implement this.\n  // const inputs: LogSoftmaxInputs = {logits: $logits};\n  // const attrs: LogSoftmaxAttrs = {axis};\n  // return ENGINE.runKernel(\n  //            LogSoftmax, inputs as unknown as NamedTensorMap,\n  //            attrs as unknown as NamedAttrMap);\n}\n\nexport const logSoftmax = /* @__PURE__ */ op({logSoftmax_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {add} from './add';\nimport {expandShapeToKeepDim} from './axis_util';\nimport {exp} from './exp';\nimport {log} from './log';\nimport {max} from './max';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {sub} from './sub';\nimport {sum} from './sum';\n\n/**\n * Computes the log(sum(exp(elements across the reduction dimensions))).\n *\n * Reduces the input along the dimensions given in `axis`. Unless `keepDims`\n * is true, the rank of the array is reduced by 1 for each entry in `axis`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axis` has no entries, all dimensions are reduced, and an array with a\n * single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.logSumExp().print();  // or tf.logSumExp(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.logSumExp(axis).print();  // or tf.logSumExp(a, axis)\n * ```\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. If null (the default),\n *     reduces all dimensions.\n * @param keepDims If true, retains reduced dimensions with length\n *     of 1. Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction logSumExp_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'logSumExp');\n\n  const axes = parseAxisParam(axis, $x.shape);\n  const xMax = max($x, axes, true /* keepDims */);\n  const a = sub($x, xMax);\n  const b = exp(a);\n  const c = sum(b, axes);\n  const d = log(c);\n  const res = add(reshape(xMax, d.shape), d);\n\n  if (keepDims) {\n    const newShape = expandShapeToKeepDim(res.shape, axes);\n    return reshape(res, newShape) as T;\n  }\n  return res as T;\n}\n\nexport const logSumExp = /* @__PURE__ */ op({logSumExp_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {LogicalAnd, LogicalAndInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a AND b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalAnd(b).print();\n * ```\n *\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalAnd_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  const $a = convertToTensor(a, 'a', 'logicalAnd', 'bool');\n  const $b = convertToTensor(b, 'b', 'logicalAnd', 'bool');\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: LogicalAndInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(LogicalAnd, inputs as unknown as NamedTensorMap);\n}\n\nexport const logicalAnd = /* @__PURE__ */ op({logicalAnd_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LogicalNot, LogicalNotInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `NOT x` element-wise.\n *\n * ```js\n * const a = tf.tensor1d([false, true], 'bool');\n *\n * a.logicalNot().print();\n * ```\n *\n * @param x The input tensor. Must be of dtype 'bool'.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalNot_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'logicalNot', 'bool');\n  const inputs: LogicalNotInputs = {x: $x};\n  return ENGINE.runKernel(LogicalNot, inputs as unknown as NamedTensorMap);\n}\n\nexport const logicalNot = /* @__PURE__ */ op({logicalNot_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LogicalOr, LogicalOrInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a OR b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalOr(b).print();\n * ```\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalOr_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  const $a = convertToTensor(a, 'a', 'logicalOr', 'bool');\n  const $b = convertToTensor(b, 'b', 'logicalOr', 'bool');\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: LogicalOrInputs = {a: $a, b: $b};\n  return ENGINE.runKernel(LogicalOr, inputs as unknown as NamedTensorMap);\n}\nexport const logicalOr = /* @__PURE__ */ op({logicalOr_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {logicalAnd} from './logical_and';\nimport {logicalNot} from './logical_not';\nimport {logicalOr} from './logical_or';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a XOR b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalXor(b).print();\n * ```\n *\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalXor_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  const $a = convertToTensor(a, 'a', 'logicalXor', 'bool');\n  const $b = convertToTensor(b, 'b', 'logicalXor', 'bool');\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  // x ^ y = (x | y) & ~(x & y)\n  return logicalAnd(logicalOr(a, b), logicalNot(logicalAnd(a, b)));\n}\n\nexport const logicalXor = /* @__PURE__ */ op({logicalXor_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SearchSorted, SearchSortedAttrs, SearchSortedInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nconst INT32_MAX = 2147483648;\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The side argument controls which index is returned if a value lands exactly\n * on an edge.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'sortedSequence' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);\n * let values = tf.tensor1d([0.0, 4.1, 12.0]);\n * const result1 = tf.searchSorted(edges, values, 'left');\n * result1.print(); // [1, 2, 4]\n *\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * values = tf.tensor1d([0, 4, 10]);\n * const result2 = tf.searchSorted(seq, values, 'left');\n * result2.print(); // [0, 2, 3]\n * const result3 = tf.searchSorted(seq, values, 'right');\n * result3.print(); // [1, 2, 5]\n *\n * const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],\n *                                     [1., 2., 3., 4., 5.]]);\n * values = tf.tensor2d([[9.8, 2.1, 4.3],\n *                       [0.1, 6.6, 4.5, ]]);\n * const result4 = tf.searchSorted(sortedSequence, values, 'left');\n * result4.print(); // [[4, 1, 2], [0, 5, 4]]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @param side: 'left'|'right'. Defaults to 'left'. 'left' corresponds to lower\n *     bound and 'right' to upper bound.\n * @return An N-D int32 tensor the size of values containing the result of\n *     applying either lower bound or upper bound (depending on side) to each\n *     value. The result is not a global index to the entire Tensor, but the\n *     index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction searchSorted_(\n    sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike,\n    side: 'left'|'right' = 'left'): Tensor {\n  const $sortedSequence =\n      convertToTensor(sortedSequence, 'sortedSequence', 'searchSorted');\n  const $values = convertToTensor(values, 'values', 'searchSorted');\n\n  const sequenceSize = $sortedSequence.shape[$sortedSequence.shape.length - 1];\n  const valuesSize = $values.shape[$values.shape.length - 1];\n  const $sortedSequence2D = reshape($sortedSequence, [-1, sequenceSize]);\n  const $values2D = reshape($values, [-1, valuesSize]);\n\n  if ($sortedSequence2D.rank < 2) {\n    throw new Error(`Sorted input argument must be at least 2-dimensional`);\n  }\n  if ($sortedSequence2D.shape[0] !== $values2D.shape[0]) {\n    throw new Error(\n        `Leading dimension of 'sortedSequence' and 'values' must match.`);\n  }\n  if (sizeFromShape($values2D.shape) >= INT32_MAX) {\n    throw new Error(`values tensor size must less than ${INT32_MAX}`);\n  }\n  if ($sortedSequence2D.shape[1] >= INT32_MAX) {\n    throw new Error(`trailing dim_size must less than ${\n        INT32_MAX} for int32 output type, was ${$sortedSequence2D.shape[1]}`);\n  }\n\n  const inputs: SearchSortedInputs = {\n    sortedSequence: $sortedSequence2D,\n    values: $values2D,\n  };\n  const attrs: SearchSortedAttrs = {side};\n\n  return ENGINE.runKernel(SearchSorted, inputs as {}, attrs as {});\n}\n\nexport const searchSorted = /* @__PURE__ */ op({searchSorted_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\nimport {searchSorted} from './search_sorted';\n\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The index returned corresponds to the first edge greater than or equal to the\n * value.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'lowerBound' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);\n * let values = tf.tensor1d([0.0, 4.1, 12.0]);\n * const result1 = tf.lowerBound(edges, values);\n * result1.print(); // [1, 2, 4]\n *\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * values = tf.tensor1d([0, 4, 10]);\n * const result2 = tf.lowerBound(seq, values);\n * result2.print(); // [0, 2, 3]\n *\n * const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],\n *                                     [1., 2., 3., 4., 5.]]);\n * values = tf.tensor2d([[9.8, 2.1, 4.3],\n *                       [0.1, 6.6, 4.5, ]]);\n * const result3 = tf.lowerBound(sortedSequence, values);\n * result3.print(); // [[4, 1, 2], [0, 5, 4]]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @return An N-D int32 tensor the size of values containing the result of\n *     applying lower bound to each value. The result is not a global index to\n *     the entire Tensor, but the index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function lowerBound(\n    sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike): Tensor {\n  return searchSorted(sortedSequence, values, 'left');\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPool, MaxPoolAttrs, MaxPoolInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 2D max pooling of an image.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n *     `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n *     `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n */\nfunction maxPool_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filterSize: [number, number]|number,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'maxPool');\n  const dilations = 1;\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n  conv_util.checkPadOnDimRoundingMode('maxPool', pad, dimRoundingMode);\n  const inputs: MaxPoolInputs = {x: x4D};\n  const attrs: MaxPoolAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  MaxPool, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const maxPool = /* @__PURE__ */ op({maxPool_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPool3D, MaxPool3DAttrs, MaxPool3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {checkPadOnDimRoundingMode} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 3D max pooling.\n *\n * ```js\n * const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);\n * const result = tf.maxPool3d(x, 2, 1, 'valid');\n * result.print();\n * ```\n *\n * @param x The input tensor, of rank 5 or rank 4 of shape\n *     `[batch, depth, height, width, inChannels]`.\n * @param filterSize The filter size:\n *     `[filterDepth, filterHeight, filterWidth]`.\n *     If `filterSize` is a single number,\n *     then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n *     `[strideDepth, strideHeight, strideWidth]`.\n *     If `strides` is a single number,\n *     then `strideDepth == strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1*1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n *     \"NDHWC\". Specify the data format of the input and output data. With the\n *     default format \"NDHWC\", the data is stored in the order of: [batch,\n *     depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction maxPool3d_<T extends Tensor4D|Tensor5D>(\n    x: T|TensorLike, filterSize: [number, number, number]|number = [1, 1, 1],\n    strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n    dimRoundingMode?: 'floor'|'round'|'ceil',\n    dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): T {\n  const $x = convertToTensor(x, 'x', 'maxPool3d');\n\n  let x5D = $x as Tensor5D;\n  let reshapedTo5D = false;\n  if ($x.rank === 4) {\n    reshapedTo5D = true;\n    x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n  }\n\n  util.assert(\n      x5D.rank === 5,\n      () => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`);\n  util.assert(\n      dataFormat === 'NDHWC',\n      () => `Error in maxPool3d: Only NDHWC is currently supported, ` +\n          `but got dataFormat of ${dataFormat}`);\n  checkPadOnDimRoundingMode('maxPool3d', pad, dimRoundingMode);\n  const inputs: MaxPool3DInputs = {x: x5D};\n  const attrs:\n      MaxPool3DAttrs = {filterSize, strides, pad, dimRoundingMode, dataFormat};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  MaxPool3D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo5D) {\n    return reshape(\n               res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n        T;\n  }\n\n  return res;\n}\n\nexport const maxPool3d = /* @__PURE__ */ op({maxPool3d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPoolWithArgmax, MaxPoolWithArgmaxAttrs, MaxPoolWithArgmaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the 2D max pooling of an image with Argmax index.\n * The indices in argmax are flattened, so that a maximum value at position `[b,\n * y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if\n * include_batch_in_index is False; `((b * height + y) * width + x) * channels\n * +c` if include_batch_in_index is True.\n *\n * The indices returned are always in `[0, height) x [0, width)` before\n * flattening.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n *     `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n *     `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n *     \"NDHWC\". Specify the data format of the input and output data. With the\n *     default format \"NDHWC\", the data is stored in the order of: [batch,\n *     depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param includeBatchIndex Defaults to False. Whether to include batch\n *    dimension in flattened index of argmax.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction maxPoolWithArgmax_<T extends Tensor4D>(\n    x: T|TensorLike, filterSize: [number, number]|number,\n    strides: [number, number]|number, pad: 'valid'|'same'|number,\n    includeBatchInIndex = false): NamedTensorMap {\n  const $x = convertToTensor(x, 'x', 'maxPoolWithArgmax');\n\n  const inputs: MaxPoolWithArgmaxInputs = {x: $x};\n  const attrs:\n      MaxPoolWithArgmaxAttrs = {filterSize, strides, pad, includeBatchInIndex};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const result = ENGINE.runKernel(\n                     MaxPoolWithArgmax, inputs as unknown as NamedTensorMap,\n                     attrs as unknown as NamedAttrMap) as Tensor[];\n\n  return {result: result[0], indexes: result[1]};\n}\n\nexport const maxPoolWithArgmax = /* @__PURE__ */ op({maxPoolWithArgmax_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Maximum, MaximumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the max of a and b (`a > b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `tf.maximumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.maximum(b).print();  // or tf.maximum(a, b)\n * ```\n *\n * ```js\n * // Broadcast maximum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.maximum(b).print();  // or tf.maximum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction maximum_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'maximum');\n  let $b = convertToTensor(b, 'b', 'maximum');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  if ($a.dtype === 'bool') {\n    $a = cast($a, 'int32');\n    $b = cast($b, 'int32');\n  }\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: MaximumInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Maximum, inputs as unknown as NamedTensorMap);\n}\n\nexport const maximum = /* @__PURE__ */ op({maximum_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Mean, MeanAttrs, MeanInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the mean of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces `x` along the dimensions given in `axis`. Unless `keepDims` is\n * true, the rank of the `tf.Tensor` is reduced by 1 for each entry in `axis`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axis` has no entries, all dimensions are reduced, and a `tf.Tensor` with\n * a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.mean().print();  // or tf.mean(a)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.mean(axis).print();  // or tf.mean(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction mean_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'mean');\n\n  const inputs: MeanInputs = {x: $x};\n  const attrs: MeanAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      Mean, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const mean = /* @__PURE__ */ op({mean_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions, makeZerosTypedArray, sizeFromShape} from '../util';\n\nimport {complex} from './complex';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0.\n *\n * ```js\n * tf.zeros([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The type of an element in the resulting tensor. Can\n *     be 'float32', 'int32' or 'bool'. Defaults to 'float'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function zeros<R extends Rank>(\n    shape: ShapeMap[R], dtype: DataType = 'float32'): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (dtype === 'complex64') {\n    const real = zeros(shape, 'float32');\n    const imag = zeros(shape, 'float32');\n    return complex(real, imag);\n  }\n  const values = makeZerosTypedArray(sizeFromShape(shape), dtype);\n  return ENGINE.makeTensor(values, shape, dtype) as Tensor<R>;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {makeOnesTypedArray, sizeFromShape} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\nimport {complex} from './complex';\nimport {zeros} from './zeros';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 1.\n *\n * ```js\n * tf.ones([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The type of an element in the resulting tensor. Defaults to\n *     'float'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function ones<R extends Rank>(\n    shape: ShapeMap[R], dtype: DataType = 'float32'): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (dtype === 'complex64') {\n    const real = ones(shape, 'float32');\n    const imag = zeros(shape, 'float32');\n    return complex(real, imag);\n  }\n  const values = makeOnesTypedArray(sizeFromShape(shape), dtype);\n  return ENGINE.makeTensor(values, shape, dtype) as Tensor<R>;\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {matMul} from './mat_mul';\nimport {ones} from './ones';\nimport {reshape} from './reshape';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\n\n/**\n * Broadcasts parameters for evaluation on an N-D grid.\n *\n * Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`\n * of N-D coordinate arrays for evaluating expressions on an N-D grid.\n *\n * Notes:\n * `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.\n * When the `indexing` argument is set to 'xy' (the default), the broadcasting\n * instructions for the first two dimensions are swapped.\n * Examples:\n * Calling `const [X, Y] = meshgrid(x, y)` with the tensors\n *\n * ```javascript\n * const x = [1, 2, 3];\n * const y = [4, 5, 6];\n * const [X, Y] = tf.meshgrid(x, y);\n * // X = [[1, 2, 3],\n * //      [1, 2, 3],\n * //      [1, 2, 3]]\n * // Y = [[4, 4, 4],\n * //      [5, 5, 5],\n * //      [6, 6, 6]]\n * ```\n *\n * @param x Tensor with rank geq 1.\n * @param y Tensor with rank geq 1.\n * @param indexing\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nexport function meshgrid<T extends Tensor>(\n    x?: T|TensorLike, y?: T|TensorLike, {indexing = 'xy'} = {}): T[] {\n  if (indexing !== 'xy' && indexing !== 'ij') {\n    throw new TypeError(\n        `${indexing} is not a valid third argument to meshgrid`);\n  }\n  if (x === undefined) {\n    return [];\n  }\n  let $x = convertToTensor(\n      x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');\n\n  if (y === undefined) {\n    return [$x];\n  }\n  let $y = convertToTensor(\n      y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');\n\n  const w = sizeFromShape($x.shape);\n  const h = sizeFromShape($y.shape);\n\n  if (indexing === 'xy') {\n    $x = reshape($x, [1, -1]) as T;\n    $y = reshape($y, [-1, 1]) as T;\n    return [\n      matMul(ones([h, 1], $x.dtype), $x),\n      matMul($y, ones([1, w], $y.dtype)),\n    ];\n  }\n\n  $x = reshape($x, [-1, 1]) as T;\n  $y = reshape($y, [1, -1]) as T;\n  return [\n    matMul($x, ones([1, h], $x.dtype)),\n    matMul(ones([w, 1], $y.dtype), $y),\n  ];\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Minimum, MinimumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the min of a and b (`a < b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `minimumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.minimum(b).print();  // or tf.minimum(a, b)\n * ```\n *\n * ```js\n * // Broadcast minimum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.minimum(b).print();  // or tf.minimum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction minimum_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'minimum');\n  let $b = convertToTensor(b, 'b', 'minimum');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  if ($a.dtype === 'bool') {\n    $a = cast($a, 'int32');\n    $b = cast($b, 'int32');\n  }\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: MinimumInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Minimum, inputs as unknown as NamedTensorMap);\n}\n\nexport const minimum = /* @__PURE__ */ op({minimum_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MirrorPad, MirrorPadAttrs, MirrorPadInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Pads a `tf.Tensor` using mirror padding.\n *\n * This operation implements the `REFLECT` and `SYMMETRIC` modes of pad.\n *\n * ```js\n * const x = tf.range(0, 9).reshape([1, 1, 3, 3]);\n * x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').print();\n * ```\n * @param x The tensor to pad.\n * @param paddings An array of length `R` (the rank of the tensor), where\n * each element is a length-2 tuple of ints `[padBefore, padAfter]`,\n * specifying how much to pad along each dimension of the tensor.\n * In \"reflect\" mode, the padded regions do not include the borders,\n * while in \"symmetric\" mode the padded regions do include the borders.\n * For example, if the input is `[1, 2, 3]` and paddings is `[0, 2]`,\n * then the output is `[1, 2, 3, 2, 1]` in \"reflect\" mode, and\n * `[1, 2, 3, 3, 2]` in \"symmetric\" mode.\n * If `mode` is \"reflect\" then both `paddings[D, 0]` and `paddings[D, 1]`\n * must be no greater than `x.shape[D] - 1`. If mode is \"symmetric\"\n * then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than\n * `x.shape[D]`\n * @param mode String to specify padding mode. Can be `'reflect' | 'symmetric'`\n */\n/** @doc {heading: 'Tensors', subheading: 'Transformations'} */\nfunction mirrorPad_<T extends Tensor>(\n    x: T|TensorLike, paddings: Array<[number, number]>,\n    mode: 'reflect'|'symmetric'): T {\n  util.assert(\n      mode === 'reflect' || mode === 'symmetric',\n      () => `Invalid mode. Mode must be either reflect or symmetric. ` +\n          `Got ${mode}.`);\n\n  const $x = convertToTensor(x, 'x', 'mirrorPad');\n  if ($x.rank === 0) {\n    throw new Error(\n        'mirrorPad(scalar) is not defined. ' +\n        'Pass non-scalar to mirrorPad');\n  }\n  util.assert(\n      paddings.length === $x.rank,\n      () => `Padding doesn't match input. Must be ${$x.rank}. ` +\n          `Got ${paddings.length}.`);\n  const shapeOffset = mode === 'reflect' ? 1 : 0;\n  for (let i = 0; i < $x.rank; i++) {\n    util.assert(\n        paddings[i].length === 2,\n        () => `Invalid number of paddings. Must be length of 2 each.`);\n    util.assert(\n        paddings[i][0] >= 0 && paddings[i][0] <= $x.shape[i] - shapeOffset &&\n            paddings[i][1] >= 0 && paddings[i][1] <= $x.shape[i] - shapeOffset,\n        () => `Padding in dimension ${i} cannot be greater than or equal ` +\n            `to ${$x.shape[i] - shapeOffset} or less than 0 for input of ` +\n            `shape ${$x.shape}`);\n  }\n\n  const attrs: MirrorPadAttrs = {paddings, mode};\n  const inputs: MirrorPadInputs = {x: $x};\n  return ENGINE.runKernel(\n      MirrorPad, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const mirrorPad = /* @__PURE__ */ op({mirrorPad_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Mod, ModInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the mod of a and b element-wise.\n * `floor(x / y) * y + mod(x, y) = x`\n * Supports broadcasting.\n *\n * We also expose `tf.modStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.mod(b).print();  // or tf.mod(a, b)\n * ```\n *\n * ```js\n * // Broadcast a mod b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.mod(b).print();  // or tf.mod(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction mod_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'mod');\n  let $b = convertToTensor(b, 'b', 'mod');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: ModInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Mod, inputs as unknown as NamedTensorMap);\n}\n\nexport const mod = /* @__PURE__ */ op({mod_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {expandShapeToKeepDim} from './axis_util';\nimport {cast} from './cast';\nimport {mean} from './mean';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {square} from './square';\nimport {sub} from './sub';\n\n/**\n * Calculates the mean and variance of `x`. The mean and variance are\n * calculated by aggregating the contents of `x` across `axes`. If `x` is\n * 1-D and `axes = [0]` this is just the mean and variance of a vector.\n *\n * @param x The input tensor.\n * @param axis The dimension(s) along with to compute mean and\n *     variance. By default it reduces all dimensions.\n * @param keepDims If true, the moments have the same dimensionality as the\n *     input.\n * @return An object with two keys: `mean` and `variance`.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction moments_(\n    x: Tensor|TensorLike, axis: number|number[] = null,\n    keepDims = false): {mean: Tensor, variance: Tensor} {\n  x = convertToTensor(x, 'x', 'moments');\n  const axes = parseAxisParam(axis, x.shape);\n  const xMean = mean(x, axes, keepDims);\n  let keepDimsShape = xMean.shape;\n  if (!keepDims) {\n    keepDimsShape = expandShapeToKeepDim(xMean.shape, axes);\n  }\n  const devSquared =\n      square(sub(cast(x, 'float32'), reshape(xMean, keepDimsShape)));\n  const variance = mean(devSquared, axes, keepDims);\n  return {mean: xMean, variance};\n}\n\nexport const moments = /* @__PURE__ */ op({moments_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor, convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * @docalias (data: Tensor2D, c: Tensor2D, h: Tensor2D): [Tensor2D, Tensor2D]\n */\nexport type LSTMCellFunc = {\n  (data: Tensor2D, c: Tensor2D, h: Tensor2D): [Tensor2D, Tensor2D];\n};\n\n/**\n * Computes the next states and outputs of a stack of LSTMCells.\n *\n * Each cell output is used as input to the next cell.\n *\n * Returns `[cellState, cellOutput]`.\n *\n * Derived from tf.contrib.rn.MultiRNNCell.\n *\n * @param lstmCells Array of LSTMCell functions.\n * @param data The input to the cell.\n * @param c Array of previous cell states.\n * @param h Array of previous cell outputs.\n *\n * @doc {heading: 'Operations', subheading: 'RNN'}\n */\nfunction multiRNNCell_(\n    lstmCells: LSTMCellFunc[], data: Tensor2D|TensorLike,\n    c: Array<Tensor2D|TensorLike>,\n    h: Array<Tensor2D|TensorLike>): [Tensor2D[], Tensor2D[]] {\n  const $data = convertToTensor(data, 'data', 'multiRNNCell');\n  const $c = convertToTensorArray(c, 'c', 'multiRNNCell');\n  const $h = convertToTensorArray(h, 'h', 'multiRNNCell');\n\n  let input = $data;\n  const newStates = [];\n  for (let i = 0; i < lstmCells.length; i++) {\n    const output = lstmCells[i](input, $c[i], $h[i]);\n    newStates.push(output[0]);\n    newStates.push(output[1]);\n    input = output[1];\n  }\n  const newC: Tensor2D[] = [];\n  const newH: Tensor2D[] = [];\n  for (let i = 0; i < newStates.length; i += 2) {\n    newC.push(newStates[i]);\n    newH.push(newStates[i + 1]);\n  }\n  return [newC, newH];\n}\nexport const multiRNNCell = /* @__PURE__ */ op({multiRNNCell_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multinomial, MultinomialAttrs, MultinomialInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Creates a `tf.Tensor` with values drawn from a multinomial distribution.\n *\n * ```js\n * const probs = tf.tensor([.75, .25]);\n * tf.multinomial(probs, 3).print();\n * ```\n *\n * @param logits 1D array with unnormalized log-probabilities, or\n *     2D array of shape `[batchSize, numOutcomes]`. See the `normalized`\n *     parameter.\n * @param numSamples Number of samples to draw for each row slice.\n * @param seed The seed number.\n * @param normalized Whether the provided `logits` are normalized true\n *     probabilities (sum to 1). Defaults to false.\n * @return 1D array of shape `[numSamples]`, or 2D array of shape\n *     `[batchSize, numSamples]`, depending on the rank of the input.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction multinomial_(\n    logits: Tensor1D|Tensor2D|TensorLike, numSamples: number, seed?: number,\n    normalized = false): Tensor1D|Tensor2D {\n  const $logits = convertToTensor(logits, 'logits', 'multinomial');\n  const numOutcomes = $logits.size;\n  const origRank = $logits.rank;\n  if (numOutcomes < 2) {\n    throw new Error(\n        `Error in multinomial: you need at least 2 outcomes, but got ` +\n        `${numOutcomes}.`);\n  }\n  if (origRank > 2) {\n    throw new Error(`Rank of probabilities must be 1 or 2, but is ${origRank}`);\n  }\n  // TODO(lina128): Investigate correct seed behavior. The code seems not allow\n  // setting see to 0.\n  seed = seed || Math.random();\n\n  // The kernel only accepts (and returns) rank 2 tensors.\n  const logits2D: Tensor2D =\n      origRank === 1 ? reshape($logits, [1, -1]) : $logits as Tensor2D;\n\n  const inputs: MultinomialInputs = {logits: logits2D};\n  const attrs: MultinomialAttrs = {numSamples, seed, normalized};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Multinomial, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as Tensor2D;\n\n  // tslint:disable-next-line:no-unnecessary-type-assertion\n  return origRank === 1 ? reshape(res, [res.size]) as Tensor1D : res;\n}\n\nexport const multinomial = /* @__PURE__ */ op({multinomial_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {NotEqual, NotEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a != b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([0, 2, 3]);\n *\n * a.notEqual(b).print();\n * ```\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction notEqual_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'notEqual', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'notEqual', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: NotEqualInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(NotEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const notEqual = /* @__PURE__ */ op({notEqual_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {OneHot, OneHotAttrs, OneHotInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take\n * value `onValue` (defaults to 1), while all other locations take value\n * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank\n * `R+1` with the last axis of size `depth`.\n * `indices` used to encode prediction class must start from 0. For example,\n *  if you have 3 classes of data, class 1 should be encoded as 0, class 2\n *  should be 1, and class 3 should be 2.\n *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`. Indices must\n * start from 0.\n * @param depth The depth of the one hot dimension.\n * @param onValue A number used to fill in the output when the index matches\n * the location.\n * @param offValue A number used to fill in the output when the index does\n *     not match the location.\n * @param dtype The dtype of the output tensor, default to 'int32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(\n    indices: Tensor|TensorLike, depth: number, onValue = 1, offValue = 0,\n    dtype: DataType = 'int32'): Tensor {\n  if (depth < 2) {\n    throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);\n  }\n  const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');\n\n  const inputs: OneHotInputs = {indices: $indices};\n  const attrs: OneHotAttrs = {dtype, depth, onValue, offValue};\n\n  return ENGINE.runKernel(\n      OneHot, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const oneHot = /* @__PURE__ */ op({oneHot_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {OnesLike, OnesLikeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 1 with the same shape as the\n * given tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n * tf.onesLike(x).print();\n * ```\n * @param x A tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction onesLike_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'onesLike');\n\n  const inputs: OnesLikeInputs = {x: $x};\n  return ENGINE.runKernel(OnesLike, inputs as unknown as NamedTensorMap);\n}\n\nexport const onesLike = /* @__PURE__ */ op({onesLike_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {matMul} from './mat_mul';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the outer product of two vectors, `v1` and `v2`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([3, 4, 5]);\n *\n * tf.outerProduct(a, b).print();\n * ```\n * @param v1 The first vector in the outer product operation.\n * @param v2 The second vector in the outer product operation.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction outerProduct_(\n    v1: Tensor1D|TensorLike, v2: Tensor1D|TensorLike): Tensor2D {\n  const $v1 = convertToTensor(v1, 'v1', 'outerProduct');\n  const $v2 = convertToTensor(v2, 'v2', 'outerProduct');\n\n  util.assert(\n      $v1.rank === 1 && $v2.rank === 1,\n      () => `Error in outerProduct: inputs must be rank 1, but got ranks ` +\n          `${$v1.rank} and ${$v2.rank}.`);\n\n  const v12D = reshape($v1, [-1, 1]);\n  const v22D = reshape($v2, [1, -1]);\n  return matMul(v12D, v22D);\n}\n\nexport const outerProduct = /* @__PURE__ */ op({outerProduct_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {PadV2, PadV2Attrs, PadV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Pads a `tf.Tensor` with a given value and paddings.\n *\n * This operation implements `CONSTANT` mode. For `REFLECT` and `SYMMETRIC`,\n * refer to `tf.mirrorPad`.\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that `paddings` is of given length.\n *   - `tf.pad1d`\n *   - `tf.pad2d`\n *   - `tf.pad3d`\n *   - `tf.pad4d`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.pad([[1, 2]]).print();\n * ```\n * @param x The tensor to pad.\n * @param paddings An array of length `R` (the rank of the tensor), where\n * each element is a length-2 tuple of ints `[padBefore, padAfter]`,\n * specifying how much to pad along each dimension of the tensor.\n * @param constantValue The pad value to use. Defaults to 0.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction pad_<T extends Tensor>(\n    x: T|TensorLike, paddings: Array<[number, number]>, constantValue = 0): T {\n  const $x = convertToTensor(x, 'x', 'pad');\n  if ($x.rank === 0) {\n    throw new Error('pad(scalar) is not defined. Pass non-scalar to pad');\n  }\n\n  const attrs: PadV2Attrs = {paddings, constantValue};\n  const inputs: PadV2Inputs = {x: $x};\n  return ENGINE.runKernel(\n      PadV2, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const pad = /* @__PURE__ */ op({pad_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor1D` with a given value and paddings. See `pad` for details.\n */\nfunction pad1d_(\n    x: Tensor1D|TensorLike, paddings: [number, number],\n    constantValue = 0): Tensor1D {\n  assert(\n      paddings.length === 2,\n      () => 'Invalid number of paddings. Must be length of 2.');\n  return pad(x, [paddings], constantValue);\n}\n\nexport const pad1d = /* @__PURE__ */ op({pad1d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor2D` with a given value and paddings. See `pad` for details.\n */\nfunction pad2d_(\n    x: Tensor2D|TensorLike, paddings: [[number, number], [number, number]],\n    constantValue = 0): Tensor2D {\n  assert(\n      paddings.length === 2 && paddings[0].length === 2 &&\n          paddings[1].length === 2,\n      () => 'Invalid number of paddings. Must be length of 2 each.');\n  return pad(x, paddings, constantValue);\n}\n\nexport const pad2d = /* @__PURE__ */ op({pad2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor3D` with a given value and paddings. See `pad` for details.\n */\nfunction pad3d_(\n    x: Tensor3D|TensorLike,\n    paddings: [[number, number], [number, number], [number, number]],\n    constantValue = 0): Tensor3D {\n  assert(\n      paddings.length === 3 && paddings[0].length === 2 &&\n          paddings[1].length === 2 && paddings[2].length === 2,\n      () => 'Invalid number of paddings. Must be length of 2 each.');\n  return pad(x, paddings, constantValue);\n}\n\nexport const pad3d = /* @__PURE__ */ op({pad3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details.\n */\nfunction pad4d_(\n    x: Tensor4D|TensorLike,\n    paddings:\n        [\n          [number, number], [number, number], [number, number], [number, number]\n        ],\n    constantValue = 0): Tensor4D {\n  assert(\n      paddings.length === 4 && paddings[0].length === 2 &&\n          paddings[1].length === 2 && paddings[2].length === 2 &&\n          paddings[3].length === 2,\n      () => 'Invalid number of paddings. Must be length of 2 each.');\n  return pad(x, paddings, constantValue);\n}\n\nexport const pad4d = /* @__PURE__ */ op({pad4d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * This operation divides \"spatial\" dimensions `[1, ..., M]` of the input into\n * a grid of blocks of shape `blockShape`, and interleaves these blocks with\n * the \"batch\" dimension (0) such that in the output, the spatial\n * dimensions `[1, ..., M]` correspond to the position within the grid,\n * and the batch dimension combines both the position within a spatial block\n * and the original batch position. Prior to division into blocks,\n * the spatial dimensions of the input are optionally zero padded\n * according to `paddings`. See below for a precise description.\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);\n * const blockShape = [2, 2];\n * const paddings = [[0, 0], [0, 0]];\n *\n * x.spaceToBatchND(blockShape, paddings).print();\n * ```\n *\n * @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +\n * remainingShape`, where spatialShape has `M` dimensions.\n * @param blockShape A 1-D array. Must have shape `[M]`, all values must\n * be >= 1.\n * @param paddings A 2-D array. Must have shape `[M, 2]`, all values must be >=\n *     0. `paddings[i] = [padStart, padEnd]` specifies the amount to zero-pad\n * from input dimension `i + 1`, which corresponds to spatial dimension `i`. It\n * is required that\n * `(inputShape[i + 1] + padStart + padEnd) % blockShape[i] === 0`\n *\n * This operation is equivalent to the following steps:\n *\n * 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input\n * according to `paddings` to produce `padded` of shape paddedShape.\n *\n * 2. Reshape `padded` to `reshapedPadded` of shape:\n * `[batch] + [paddedShape[1] / blockShape[0], blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1], blockShape[M-1]] + remainingShape`\n *\n * 3. Permute dimensions of `reshapedPadded` to produce `permutedReshapedPadded`\n * of shape: `blockShape + [batch] + [paddedShape[1] / blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1]] + remainingShape`\n *\n * 4. Reshape `permutedReshapedPadded` to flatten `blockShape` into the\n * batch dimension, producing an output tensor of shape:\n * `[batch * prod(blockShape)] + [paddedShape[1] / blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1]] + remainingShape`\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction spaceToBatchND_<T extends Tensor>(\n    x: T|TensorLike, blockShape: number[], paddings: number[][]): T {\n  const $x = convertToTensor(x, 'x', 'spaceToBatchND');\n\n  util.assert(\n      $x.rank >= 1 + blockShape.length,\n      () => `input rank ${$x.rank} should be > than [blockShape] ${\n          blockShape.length}`);\n\n  util.assert(\n      paddings.length === blockShape.length,\n      () => `paddings.shape[0] ${\n          paddings.length} must be equal to [blockShape] ${blockShape.length}`);\n\n  util.assert(\n      $x.shape.reduce(\n          (a, b, i) => {\n            if (i > 0 && i <= blockShape.length) {\n              return a &&\n                  ((b + paddings[i - 1][0] + paddings[i - 1][1]) %\n                       blockShape[i - 1] ===\n                   0);\n            }\n            return a;\n          },\n          true),\n      () => `input spatial dimensions ${$x.shape.slice(1)} with paddings ${\n          paddings.toString()} must be divisible by blockShapes ${\n          blockShape.toString()}`);\n\n  const inputs: SpaceToBatchNDInputs = {x: $x};\n  const attrs: SpaceToBatchNDAttrs = {blockShape, paddings};\n\n  return ENGINE.runKernel(\n      SpaceToBatchND, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const spaceToBatchND = /* @__PURE__ */ op({spaceToBatchND_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {avgPool} from './avg_pool';\nimport {batchToSpaceND} from './batch_to_space_nd';\nimport * as conv_util from './conv_util';\nimport {maxPool} from './max_pool';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {spaceToBatchND} from './space_to_batch_nd';\n\n/**\n * Performs an N-D pooling operation\n *\n * @param input The input tensor, of rank 4 or rank 3 of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param windowShape The filter size: `[filterHeight, filterWidth]`. If\n *     `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param poolingType The type of pooling, either 'max' or 'avg'.\n * @param pad The type of padding algorithm:\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_guides/python/nn#Convolution](\n *         https://www.tensorflow.org/api_guides/python/nn#Convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n *     `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction pool_<T extends Tensor3D|Tensor4D>(\n    input: T|TensorLike, windowShape: [number, number]|number,\n    poolingType: 'avg'|'max',\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dilations?: [number, number]|number, strides?: [number, number]|number,\n    dimRoundingMode?: 'floor'|'round'|'ceil') {\n  if (dilations == null) {\n    dilations = [1, 1];\n  }\n  if (strides == null) {\n    strides = 1;\n  }\n  if (pad === 0) {\n    pad = 'valid';\n  }\n\n  const $x = convertToTensor(input, 'x', 'maxPool');\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in pool: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n\n  const convInfo = conv_util.computePool2DInfo(\n      x4D.shape, windowShape, strides, dilations, pad);\n  const dilation: [number, number] =\n      [convInfo.dilationHeight, convInfo.dilationWidth];\n\n  // The following implementation does batchToSpace(pool(spaceToBatch(x)))\n  // whenever dilation > 1 since the TF kernels do not support dilation > 1.\n  // tslint:disable-next-line:max-line-length\n  // https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037\n\n  let basePadding: number[][];\n  if (pad === 'same') {\n    basePadding = withSpaceToBatchBasePaddings(\n        [convInfo.filterHeight, convInfo.filterWidth], dilation);\n  } else {\n    basePadding = [[0, 0], [0, 0]];\n  }\n\n  const isDilationOne = dilation[0] === 1 && dilation[1] === 1;\n  const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings(\n      [convInfo.inHeight, convInfo.inWidth], dilation, basePadding);\n  const convertedPad = isDilationOne ? pad : 'valid';\n  const convertedX =\n      isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);\n\n  const forwardOp = poolingType === 'avg' ?\n      () => avgPool(convertedX, windowShape, strides, convertedPad,\n                    dimRoundingMode) :\n      () => maxPool(convertedX, windowShape, strides, convertedPad,\n                    dimRoundingMode);\n  const y = forwardOp();\n\n  const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n\n  return res as T;\n}\n\n// Helper function to compute crops and paddings for pool with dilation > 1.\n// tslint:disable-next-line:max-line-length\n// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184\nfunction requiredSpaceToBatchPaddings(\n    inputShape: [number, number], blockShape: [number, number],\n    basePadding: number[][]) {\n  const padStart = basePadding.map(b => b[0]);\n  const origPadEnd = basePadding.map(b => b[1]);\n  const fullInputShape = inputShape.concat(padStart, origPadEnd);\n  const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);\n  const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);\n  const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);\n  const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);\n  return [paddings, crops];\n}\n\n// Helper function to compute base paddings for pool with dilation > 1.\n// tslint:disable-next-line:max-line-length\n// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524\nfunction withSpaceToBatchBasePaddings(\n    filterShape: [number, number], dilation: [number, number]) {\n  // Spatial dimensions of the filters and the upsampled filters in which we\n  // introduce (rate - 1) zeros between consecutive filter values.\n  const dilatedFilterShape = filterShape.map((s, i) => {\n    return s + (s - 1) * (dilation[i] - 1);\n  });\n  const padExtraShape = dilatedFilterShape.map(s => s - 1);\n\n  // When padding is odd, we pad more at end, following the same\n  // convention as conv2d.\n  const padExtraStart = padExtraShape.map(s => Math.floor(s / 2));\n  const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);\n  return padExtraShape.map((_, i) => {\n    return [padExtraStart[i], padExtraEnd[i]];\n  });\n}\n\nexport const pool = /* @__PURE__ */ op({pool_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Prelu, PreluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes leaky rectified linear element-wise with parametric alphas.\n *\n * `x < 0 ? alpha * x : f(x) = x`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n * const alpha = tf.scalar(0.1);\n *\n * x.prelu(alpha).print();  // or tf.prelu(x, alpha)\n * ```\n * @param x The input tensor.\n * @param alpha Scaling factor for negative values.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction prelu_<T extends Tensor>(x: T|TensorLike, alpha: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'prelu');\n  const $alpha = convertToTensor(alpha, 'alpha', 'prelu');\n\n  const inputs: PreluInputs = {x: $x, alpha: $alpha};\n  return ENGINE.runKernel(Prelu, inputs as unknown as NamedTensorMap);\n}\n\nexport const prelu = /* @__PURE__ */ op({prelu_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Prod, ProdAttrs, ProdInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes the product of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.prod().print();  // or tf.prod(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.prod(axis).print();  // or tf.prod(x, axis)\n * ```\n *\n * @param x The input tensor to compute the product over. If the dtype is `bool`\n *   it will be converted to `int32` and the output dtype will be `int32`.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction prod_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  let $x = convertToTensor(x, 'x', 'prod');\n\n  if ($x.dtype === 'bool') {\n    // bool is not an allowed type for the underlying kernel.\n    $x = cast($x, 'int32');\n  }\n\n  const inputs: ProdInputs = {x: $x};\n  const attrs: ProdAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      Prod, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const prod = /* @__PURE__ */ op({prod_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedGather, RaggedGatherAttrs, RaggedGatherInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Gather ragged slices from params axis 0 according to indices.\n *\n * @param paramsNestedSplits: A list of at least 1 Tensor with type 'int32' The\n *     nestedRowSplits tensors that define the row-partitioning for the params\n *     RaggedTensor input.\n * @param paramsDenseValues: A Tensor. The flatValues for the params\n *     RaggedTensor.\n * @param indices: A Tensor. Must be one of type: int32. Indices in the\n *     outermost dimension of params of the values that should be gathered.\n * @param outputRaggedRank: An int that is >= 0. The ragged rank of the output\n *     RaggedTensor. outputNestedSplits will contain this number of rowSplits\n *     tensors. This value should equal indices.shape.ndims + params.raggedRank\n *     - 1.\n * @return A map with the following properties:\n *     - outputNestedSplits: A list of outputRaggedRank Tensor objects with the\n * same type as paramsNestedSplits.\n *     - outputDenseValues: A Tensor. Has the same type as paramsDenseValues.\n * @doc {heading: 'Operations', subheading: 'Ragged'}\n */\n\ninterface RaggedGatherMap {\n  outputNestedSplits: Tensor[];\n  outputDenseValues: Tensor;\n}\n\nfunction raggedGather_(\n    paramsNestedSplits: Tensor[], paramsDenseValues: Tensor|TensorLike,\n    indices: Tensor|TensorLike, outputRaggedRank: number): RaggedGatherMap {\n  const $paramsNestedSplits = paramsNestedSplits.map(\n      (t, i) => convertToTensor(t, `tensors${i}`, 'raggedGather', 'int32'));\n  const $paramsDenseValues =\n      convertToTensor(paramsDenseValues, 'paramsDenseValues', 'raggedGather');\n  const $indices = convertToTensor(indices, 'indices', 'raggedGather', 'int32');\n\n  const inputs: RaggedGatherInputs = {\n    paramsNestedSplits: $paramsNestedSplits,\n    paramsDenseValues: $paramsDenseValues,\n    indices: $indices,\n  };\n  const attrs: RaggedGatherAttrs = {outputRaggedRank};\n\n  const result: Tensor[] =\n      ENGINE.runKernel(RaggedGather, inputs as {}, attrs as {});\n  return {\n    outputNestedSplits: result.slice(0, result.length - 1),\n    outputDenseValues: result[result.length - 1],\n  };\n}\n\nexport const raggedGather = /* @__PURE__ */ op({raggedGather_});\n", "/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedRange, RaggedRangeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns a RaggedTensor result composed from rtDenseValues and rtNestedSplits,\n * such that result[i] = [starts[i], starts[i] + deltas[i], ..., limits[i]]).\n *\n * @param starts: A Tensor. Must be one of the following types:\n *     'float32', 'int32'. The starts of each range.\n * @param limits: A Tensor. Must have the same type as starts. The limits of\n *     each range.\n * @param deltas: A Tensor. Must have the same type as starts. The deltas of\n *     each range.\n * @return A map with the following properties:\n *     - rtNestedSplits: A Tensor of type 'int32'.\n *     - rtDenseValues: A Tensor. Has the same type as starts.\n */\n\nfunction raggedRange_(\n    starts: Tensor|TensorLike, limits: Tensor|TensorLike,\n    deltas: Tensor|TensorLike): NamedTensorMap {\n  const $starts = convertToTensor(starts, 'starts', 'raggedRange');\n  const $limits =\n      convertToTensor(limits, 'limits', 'raggedRange', $starts.dtype);\n  const $deltas =\n      convertToTensor(deltas, 'deltas', 'raggedRange', $starts.dtype);\n\n  const inputs: RaggedRangeInputs = {\n    starts: $starts,\n    limits: $limits,\n    deltas: $deltas,\n  };\n\n  const result: Tensor[] = ENGINE.runKernel(RaggedRange, inputs as {});\n  return {\n    rtNestedSplits: result[0],\n    rtDenseValues: result[1],\n  };\n}\n\nexport const raggedRange = /* @__PURE__ */ op({raggedRange_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedTensorToTensor, RaggedTensorToTensorAttrs, RaggedTensorToTensorInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Create a dense tensor from a ragged tensor, possibly altering its shape.\n *\n * The raggedTensorToTensor op creates a dense tensor from am array of row\n * partition tensors, a value vector, and default values. If the shape is\n * unspecified, the minimal shape required to contain all the elements in the\n * ragged tensor (the natural shape) will be used. If some dimensions are left\n * unspecified, then the size of the natural shape is used in that dimension.\n *\n * The defaultValue will be broadcast to the output shape. After that, the\n * values from the ragged tensor overwrite the default values. Note that the\n * defaultValue must have less dimensions than the value.\n *\n * The row partition tensors are in the order of the dimensions. At present, the\n * types can be: \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n *   \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n *   \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n * is preceded by \"FIRST_DIM_SIZE\".\n * ```\n * @param shape: A Tensor. Must be one of the following types: 'int32'. The\n *     desired shape of the output tensor. If left unspecified (empty), the\n *     minimal shape required to contain all the elements in the ragged tensor\n *     (the natural shape) will be used. If some dimensions are left\n *     unspecified, then the size of the natural shape is used in that\n *     dimension.\n *\n *     Note that dense dimensions cannot be modified by the shape argument.\n *     Trying to change the size of a dense dimension will cause the op to fail.\n *     Examples: natural shape: [4, 5, 6] shape: -1 output shape: [4, 5, 6]\n *\n *     natural shape: [4, 5, 6] shape: [3, -1, 2] output shape: [3, 5, 2]\n *\n *     natural shape: [4, 5, 6] shape: [3, 7, 2] output shape: [3, 7, 2]\n * @param values: A Tensor. A 1D tensor representing the values of the ragged\n *     tensor.\n * @param defaultValue: A Tensor. Must have the same type as values. The\n *     defaultValue when the shape is larger than the ragged tensor. The\n *     defaultValue is broadcast until it is the shape of the output tensor,\n *     and then overwritten by values in the ragged tensor. The default value\n *     must be compatible with this broadcast operation, and must have fewer\n *     dimensions than the value tensor.\n * @param rowPartitionTensors: A list of at least 1 Tensor objects with the same\n *     type in: 'int32'.\n * @param rowPartitionTypes: A list of strings. The types of the row partition\n *     tensors. At present, these can be:\n *     \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n *     \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n *     \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then\n *         it is preceded by \"FIRST_DIM_SIZE\". The tensors are in the order of\n *         the dimensions.\n * @return A Tensor. Has the same type as values.\n * @doc {heading: 'Operations', subheading: 'Ragged'}\n */\nfunction raggedTensorToTensor_(\n    shape: Tensor|TensorLike, values: Tensor|TensorLike,\n    defaultValue: Tensor|TensorLike, rowPartitionTensors: Tensor[],\n    rowPartitionTypes: string[]): Tensor {\n  const $shape =\n      convertToTensor(shape, 'shape', 'raggedTensorToTensor', 'int32');\n  const $values = convertToTensor(values, 'values', 'raggedTensorToTensor');\n  const $defaultValue = convertToTensor(\n      defaultValue, 'defaultValue', 'raggedTensorToTensor', $values.dtype);\n  const $rowPartitionTensors = rowPartitionTensors.map(\n      (t, i) =>\n          convertToTensor(t, `tensors${i}`, 'raggedTensorToTensor', 'int32'));\n\n  const inputs: RaggedTensorToTensorInputs = {\n    shape: $shape,\n    values: $values,\n    defaultValue: $defaultValue,\n    rowPartitionTensors: $rowPartitionTensors\n  };\n  const attrs: RaggedTensorToTensorAttrs = {rowPartitionTypes};\n\n  return ENGINE.runKernel(RaggedTensorToTensor, inputs as {}, attrs as {});\n}\n\nexport const raggedTensorToTensor = /* @__PURE__ */ op({raggedTensorToTensor_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {sizeFromShape} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a random number generator\n * function defined by the user.\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param randFunction A random number generator function which is called\n * for each element in the output tensor.\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction rand_<R extends Rank>(\n    shape: ShapeMap[R], randFunction: () => number,\n    dtype?: DataType): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  const size = sizeFromShape(shape);\n  let values = null;\n  if (dtype == null || dtype === 'float32') {\n    values = new Float32Array(size);\n  } else if (dtype === 'int32') {\n    values = new Int32Array(size);\n  } else if (dtype === 'bool') {\n    values = new Uint8Array(size);\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n  for (let i = 0; i < size; i++) {\n    values[i] = randFunction();\n  }\n  return ENGINE.makeTensor(values, shape, dtype) as Tensor<R>;\n}\n\nexport const rand = /* @__PURE__ */ op({rand_});\n", "// A port of an algorithm by Johannes Baagøe <baagoe@baagoe.com>, 2010\n// http://baagoe.com/en/RandomMusings/javascript/\n// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror\n// Original work is under MIT license -\n\n// Copyright (C) 2010 by Johannes Baagøe <baagoe@baagoe.org>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n\n(function(global, module, define) {\n\nfunction Alea(seed) {\n  var me = this, mash = Mash();\n\n  me.next = function() {\n    var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32\n    me.s0 = me.s1;\n    me.s1 = me.s2;\n    return me.s2 = t - (me.c = t | 0);\n  };\n\n  // Apply the seeding algorithm from Baagoe.\n  me.c = 1;\n  me.s0 = mash(' ');\n  me.s1 = mash(' ');\n  me.s2 = mash(' ');\n  me.s0 -= mash(seed);\n  if (me.s0 < 0) { me.s0 += 1; }\n  me.s1 -= mash(seed);\n  if (me.s1 < 0) { me.s1 += 1; }\n  me.s2 -= mash(seed);\n  if (me.s2 < 0) { me.s2 += 1; }\n  mash = null;\n}\n\nfunction copy(f, t) {\n  t.c = f.c;\n  t.s0 = f.s0;\n  t.s1 = f.s1;\n  t.s2 = f.s2;\n  return t;\n}\n\nfunction impl(seed, opts) {\n  var xg = new Alea(seed),\n      state = opts && opts.state,\n      prng = xg.next;\n  prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }\n  prng.double = function() {\n    return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n  };\n  prng.quick = prng;\n  if (state) {\n    if (typeof(state) == 'object') copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nfunction Mash() {\n  var n = 0xefc8249d;\n\n  var mash = function(data) {\n    data = String(data);\n    for (var i = 0; i < data.length; i++) {\n      n += data.charCodeAt(i);\n      var h = 0.02519603282416938 * n;\n      n = h >>> 0;\n      h -= n;\n      h *= n;\n      n = h >>> 0;\n      h -= n;\n      n += h * 0x100000000; // 2^32\n    }\n    return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n  };\n\n  return mash;\n}\n\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.alea = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xor128\" prng algorithm by\n// George Marsaglia.  See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this, strseed = '';\n\n  me.x = 0;\n  me.y = 0;\n  me.z = 0;\n  me.w = 0;\n\n  // Set up generator function.\n  me.next = function() {\n    var t = me.x ^ (me.x << 11);\n    me.x = me.y;\n    me.y = me.z;\n    me.z = me.w;\n    return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);\n  };\n\n  if (seed === (seed | 0)) {\n    // Integer seed.\n    me.x = seed;\n  } else {\n    // String seed.\n    strseed += seed;\n  }\n\n  // Mix in string seed, then discard an initial batch of 64 values.\n  for (var k = 0; k < strseed.length + 64; k++) {\n    me.x ^= strseed.charCodeAt(k) | 0;\n    me.next();\n  }\n}\n\nfunction copy(f, t) {\n  t.x = f.x;\n  t.y = f.y;\n  t.z = f.z;\n  t.w = f.w;\n  return t;\n}\n\nfunction impl(seed, opts) {\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (typeof(state) == 'object') copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.xor128 = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xorwow\" prng algorithm by\n// George Marsaglia.  See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this, strseed = '';\n\n  // Set up generator function.\n  me.next = function() {\n    var t = (me.x ^ (me.x >>> 2));\n    me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;\n    return (me.d = (me.d + 362437 | 0)) +\n       (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;\n  };\n\n  me.x = 0;\n  me.y = 0;\n  me.z = 0;\n  me.w = 0;\n  me.v = 0;\n\n  if (seed === (seed | 0)) {\n    // Integer seed.\n    me.x = seed;\n  } else {\n    // String seed.\n    strseed += seed;\n  }\n\n  // Mix in string seed, then discard an initial batch of 64 values.\n  for (var k = 0; k < strseed.length + 64; k++) {\n    me.x ^= strseed.charCodeAt(k) | 0;\n    if (k == strseed.length) {\n      me.d = me.x << 10 ^ me.x >>> 4;\n    }\n    me.next();\n  }\n}\n\nfunction copy(f, t) {\n  t.x = f.x;\n  t.y = f.y;\n  t.z = f.z;\n  t.w = f.w;\n  t.v = f.v;\n  t.d = f.d;\n  return t;\n}\n\nfunction impl(seed, opts) {\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (typeof(state) == 'object') copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.xorwow = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xorshift7\" algorithm by\n// François Panneton and Pierre L'ecuyer:\n// \"On the Xorgshift Random Number Generators\"\n// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this;\n\n  // Set up generator function.\n  me.next = function() {\n    // Update xor generator.\n    var X = me.x, i = me.i, t, v, w;\n    t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n    t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n    t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n    t = X[(i + 4) & 7]; v ^= t ^ (t << 7);\n    t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n    X[i] = v;\n    me.i = (i + 1) & 7;\n    return v;\n  };\n\n  function init(me, seed) {\n    var j, w, X = [];\n\n    if (seed === (seed | 0)) {\n      // Seed state array using a 32-bit integer.\n      w = X[0] = seed;\n    } else {\n      // Seed state using a string.\n      seed = '' + seed;\n      for (j = 0; j < seed.length; ++j) {\n        X[j & 7] = (X[j & 7] << 15) ^\n            (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);\n      }\n    }\n    // Enforce an array length of 8, not all zeroes.\n    while (X.length < 8) X.push(0);\n    for (j = 0; j < 8 && X[j] === 0; ++j);\n    if (j == 8) w = X[7] = -1; else w = X[j];\n\n    me.x = X;\n    me.i = 0;\n\n    // Discard an initial 256 values.\n    for (j = 256; j > 0; --j) {\n      me.next();\n    }\n  }\n\n  init(me, seed);\n}\n\nfunction copy(f, t) {\n  t.x = f.x.slice();\n  t.i = f.i;\n  return t;\n}\n\nfunction impl(seed, opts) {\n  if (seed == null) seed = +(new Date);\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (state.x) copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.xorshift7 = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n", "// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\n//\n// This fast non-cryptographic random number generator is designed for\n// use in Monte-Carlo algorithms. It combines a long-period xorshift\n// generator with a Weyl generator, and it passes all common batteries\n// of stasticial tests for randomness while consuming only a few nanoseconds\n// for each prng generated.  For background on the generator, see Brent's\n// paper: \"Some long-period random number generators using shifts and xors.\"\n// http://arxiv.org/pdf/1004.3115v1.pdf\n//\n// Usage:\n//\n// var xor4096 = require('xor4096');\n// random = xor4096(1);                        // Seed with int32 or string.\n// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.\n// assert.equal(random.int32(), 1806534897);   // signed int32, 32 bits.\n//\n// For nonzero numeric keys, this impelementation provides a sequence\n// identical to that by Brent's xorgens 3 implementaion in C.  This\n// implementation also provides for initalizing the generator with\n// string seeds, or for saving and restoring the state of the generator.\n//\n// On Chrome, this prng benchmarks about 2.1 times slower than\n// Javascript's built-in Math.random().\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this;\n\n  // Set up generator function.\n  me.next = function() {\n    var w = me.w,\n        X = me.X, i = me.i, t, v;\n    // Update Weyl generator.\n    me.w = w = (w + 0x61c88647) | 0;\n    // Update xor generator.\n    v = X[(i + 34) & 127];\n    t = X[i = ((i + 1) & 127)];\n    v ^= v << 13;\n    t ^= t << 17;\n    v ^= v >>> 15;\n    t ^= t >>> 12;\n    // Update Xor generator array state.\n    v = X[i] = v ^ t;\n    me.i = i;\n    // Result is the combination.\n    return (v + (w ^ (w >>> 16))) | 0;\n  };\n\n  function init(me, seed) {\n    var t, v, i, j, w, X = [], limit = 128;\n    if (seed === (seed | 0)) {\n      // Numeric seeds initialize v, which is used to generates X.\n      v = seed;\n      seed = null;\n    } else {\n      // String seeds are mixed into v and X one character at a time.\n      seed = seed + '\\0';\n      v = 0;\n      limit = Math.max(limit, seed.length);\n    }\n    // Initialize circular array and weyl value.\n    for (i = 0, j = -32; j < limit; ++j) {\n      // Put the unicode characters into the array, and shuffle them.\n      if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n      // After 32 shuffles, take v as the starting w value.\n      if (j === 0) w = v;\n      v ^= v << 10;\n      v ^= v >>> 15;\n      v ^= v << 4;\n      v ^= v >>> 13;\n      if (j >= 0) {\n        w = (w + 0x61c88647) | 0;     // Weyl.\n        t = (X[j & 127] ^= (v + w));  // Combine xor and weyl to init array.\n        i = (0 == t) ? i + 1 : 0;     // Count zeroes.\n      }\n    }\n    // We have detected all zeroes; make the key nonzero.\n    if (i >= 128) {\n      X[(seed && seed.length || 0) & 127] = -1;\n    }\n    // Run the generator 512 times to further mix the state before using it.\n    // Factoring this as a function slows the main generator, so it is just\n    // unrolled here.  The weyl generator is not advanced while warming up.\n    i = 127;\n    for (j = 4 * 128; j > 0; --j) {\n      v = X[(i + 34) & 127];\n      t = X[i = ((i + 1) & 127)];\n      v ^= v << 13;\n      t ^= t << 17;\n      v ^= v >>> 15;\n      t ^= t >>> 12;\n      X[i] = v ^ t;\n    }\n    // Storing state as object members is faster than using closure variables.\n    me.w = w;\n    me.X = X;\n    me.i = i;\n  }\n\n  init(me, seed);\n}\n\nfunction copy(f, t) {\n  t.i = f.i;\n  t.w = f.w;\n  t.X = f.X.slice();\n  return t;\n};\n\nfunction impl(seed, opts) {\n  if (seed == null) seed = +(new Date);\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (state.X) copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.xor4096 = impl;\n}\n\n})(\n  this,                                     // window object or global\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n", "// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\n// Samuel Neves and Filipe Araujo.\n// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this, strseed = '';\n\n  // Set up generator function.\n  me.next = function() {\n    var b = me.b, c = me.c, d = me.d, a = me.a;\n    b = (b << 25) ^ (b >>> 7) ^ c;\n    c = (c - d) | 0;\n    d = (d << 24) ^ (d >>> 8) ^ a;\n    a = (a - b) | 0;\n    me.b = b = (b << 20) ^ (b >>> 12) ^ c;\n    me.c = c = (c - d) | 0;\n    me.d = (d << 16) ^ (c >>> 16) ^ a;\n    return me.a = (a - b) | 0;\n  };\n\n  /* The following is non-inverted tyche, which has better internal\n   * bit diffusion, but which is about 25% slower than tyche-i in JS.\n  me.next = function() {\n    var a = me.a, b = me.b, c = me.c, d = me.d;\n    a = (me.a + me.b | 0) >>> 0;\n    d = me.d ^ a; d = d << 16 ^ d >>> 16;\n    c = me.c + d | 0;\n    b = me.b ^ c; b = b << 12 ^ d >>> 20;\n    me.a = a = a + b | 0;\n    d = d ^ a; me.d = d = d << 8 ^ d >>> 24;\n    me.c = c = c + d | 0;\n    b = b ^ c;\n    return me.b = (b << 7 ^ b >>> 25);\n  }\n  */\n\n  me.a = 0;\n  me.b = 0;\n  me.c = 2654435769 | 0;\n  me.d = 1367130551;\n\n  if (seed === Math.floor(seed)) {\n    // Integer seed.\n    me.a = (seed / 0x100000000) | 0;\n    me.b = seed | 0;\n  } else {\n    // String seed.\n    strseed += seed;\n  }\n\n  // Mix in string seed, then discard an initial batch of 64 values.\n  for (var k = 0; k < strseed.length + 20; k++) {\n    me.b ^= strseed.charCodeAt(k) | 0;\n    me.next();\n  }\n}\n\nfunction copy(f, t) {\n  t.a = f.a;\n  t.b = f.b;\n  t.c = f.c;\n  t.d = f.d;\n  return t;\n};\n\nfunction impl(seed, opts) {\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (typeof(state) == 'object') copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.tychei = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n\n", "/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\n\n(function (global, pool, math) {\n//\n// The following constants are related to IEEE 754 limits.\n//\n\nvar width = 256,        // each RC4 output is 0 <= x < 256\n    chunks = 6,         // at least six RC4 outputs for each double\n    digits = 52,        // there are 52 significant digits in a double\n    rngname = 'random', // rngname: name for Math.random and Math.seedrandom\n    startdenom = math.pow(width, chunks),\n    significance = math.pow(2, digits),\n    overflow = significance * 2,\n    mask = width - 1,\n    nodecrypto;         // node.js crypto module, initialized at the bottom.\n\n//\n// seedrandom()\n// This is the seedrandom function described above.\n//\nfunction seedrandom(seed, options, callback) {\n  var key = [];\n  options = (options == true) ? { entropy: true } : (options || {});\n\n  // Flatten the seed string or build one from local entropy if needed.\n  var shortseed = mixkey(flatten(\n    options.entropy ? [seed, tostring(pool)] :\n    (seed == null) ? autoseed() : seed, 3), key);\n\n  // Use the seed to initialize an ARC4 generator.\n  var arc4 = new ARC4(key);\n\n  // This function returns a random double in [0, 1) that contains\n  // randomness in every bit of the mantissa of the IEEE 754 value.\n  var prng = function() {\n    var n = arc4.g(chunks),             // Start with a numerator n < 2 ^ 48\n        d = startdenom,                 //   and denominator d = 2 ^ 48.\n        x = 0;                          //   and no 'extra last byte'.\n    while (n < significance) {          // Fill up all significant digits by\n      n = (n + x) * width;              //   shifting numerator and\n      d *= width;                       //   denominator and generating a\n      x = arc4.g(1);                    //   new least-significant-byte.\n    }\n    while (n >= overflow) {             // To avoid rounding up, before adding\n      n /= 2;                           //   last byte, shift everything\n      d /= 2;                           //   right using integer math until\n      x >>>= 1;                         //   we have exactly the desired bits.\n    }\n    return (n + x) / d;                 // Form the number within [0, 1).\n  };\n\n  prng.int32 = function() { return arc4.g(4) | 0; }\n  prng.quick = function() { return arc4.g(4) / 0x100000000; }\n  prng.double = prng;\n\n  // Mix the randomness into accumulated entropy.\n  mixkey(tostring(arc4.S), pool);\n\n  // Calling convention: what to return as a function of prng, seed, is_math.\n  return (options.pass || callback ||\n      function(prng, seed, is_math_call, state) {\n        if (state) {\n          // Load the arc4 state from the given state if it has an S array.\n          if (state.S) { copy(state, arc4); }\n          // Only provide the .state method if requested via options.state.\n          prng.state = function() { return copy(arc4, {}); }\n        }\n\n        // If called as a method of Math (Math.seedrandom()), mutate\n        // Math.random because that is how seedrandom.js has worked since v1.0.\n        if (is_math_call) { math[rngname] = prng; return seed; }\n\n        // Otherwise, it is a newer calling convention, so return the\n        // prng directly.\n        else return prng;\n      })(\n  prng,\n  shortseed,\n  'global' in options ? options.global : (this == math),\n  options.state);\n}\n\n//\n// ARC4\n//\n// An ARC4 implementation.  The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4.  Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\nfunction ARC4(key) {\n  var t, keylen = key.length,\n      me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];\n\n  // The empty key [] is treated as [0].\n  if (!keylen) { key = [keylen++]; }\n\n  // Set up S using the standard key scheduling algorithm.\n  while (i < width) {\n    s[i] = i++;\n  }\n  for (i = 0; i < width; i++) {\n    s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];\n    s[j] = t;\n  }\n\n  // The \"g\" method returns the next (count) outputs as one number.\n  (me.g = function(count) {\n    // Using instance members instead of closure state nearly doubles speed.\n    var t, r = 0,\n        i = me.i, j = me.j, s = me.S;\n    while (count--) {\n      t = s[i = mask & (i + 1)];\n      r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];\n    }\n    me.i = i; me.j = j;\n    return r;\n    // For robust unpredictability, the function call below automatically\n    // discards an initial batch of values.  This is called RC4-drop[256].\n    // See http://google.com/search?q=rsa+fluhrer+response&btnI\n  })(width);\n}\n\n//\n// copy()\n// Copies internal state of ARC4 to or from a plain object.\n//\nfunction copy(f, t) {\n  t.i = f.i;\n  t.j = f.j;\n  t.S = f.S.slice();\n  return t;\n};\n\n//\n// flatten()\n// Converts an object tree to nested arrays of strings.\n//\nfunction flatten(obj, depth) {\n  var result = [], typ = (typeof obj), prop;\n  if (depth && typ == 'object') {\n    for (prop in obj) {\n      try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}\n    }\n  }\n  return (result.length ? result : typ == 'string' ? obj : obj + '\\0');\n}\n\n//\n// mixkey()\n// Mixes a string seed into a key that is an array of integers, and\n// returns a shortened string seed that is equivalent to the result key.\n//\nfunction mixkey(seed, key) {\n  var stringseed = seed + '', smear, j = 0;\n  while (j < stringseed.length) {\n    key[mask & j] =\n      mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));\n  }\n  return tostring(key);\n}\n\n//\n// autoseed()\n// Returns an object for autoseeding, using window.crypto and Node crypto\n// module if available.\n//\nfunction autoseed() {\n  try {\n    var out;\n    if (nodecrypto && (out = nodecrypto.randomBytes)) {\n      // The use of 'out' to remember randomBytes makes tight minified code.\n      out = out(width);\n    } else {\n      out = new Uint8Array(width);\n      (global.crypto || global.msCrypto).getRandomValues(out);\n    }\n    return tostring(out);\n  } catch (e) {\n    var browser = global.navigator,\n        plugins = browser && browser.plugins;\n    return [+new Date, global, plugins, global.screen, tostring(pool)];\n  }\n}\n\n//\n// tostring()\n// Converts an array of charcodes to a string\n//\nfunction tostring(a) {\n  return String.fromCharCode.apply(0, a);\n}\n\n//\n// When seedrandom.js is loaded, we immediately mix a few bits\n// from the built-in RNG into the entropy pool.  Because we do\n// not want to interfere with deterministic PRNG state later,\n// seedrandom will not call math.random on its own again after\n// initialization.\n//\nmixkey(math.random(), pool);\n\n//\n// Nodejs and AMD support: export the implementation as a module using\n// either convention.\n//\nif ((typeof module) == 'object' && module.exports) {\n  module.exports = seedrandom;\n  // When in node.js, try using crypto package for autoseeding.\n  try {\n    nodecrypto = require('crypto');\n  } catch (ex) {}\n} else if ((typeof define) == 'function' && define.amd) {\n  define(function() { return seedrandom; });\n} else {\n  // When included as a plain script, set up Math.seedrandom global.\n  math['seed' + rngname] = seedrandom;\n}\n\n\n// End anonymous scope, and pass initial values.\n})(\n  // global: `self` in browsers (including strict mode and web workers),\n  // otherwise `this` in Node and other environments\n  (typeof self !== 'undefined') ? self : this,\n  [],     // pool: entropy pool starts empty\n  Math    // math: package containing random, pow, and seedrandom\n);\n", "// A library of seedable RNGs implemented in Javascript.\n//\n// Usage:\n//\n// var seedrandom = require('seedrandom');\n// var random = seedrandom(1); // or any seed.\n// var x = random();       // 0 <= x < 1.  Every bit is random.\n// var x = random.quick(); // 0 <= x < 1.  32 bits of randomness.\n\n// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.\n// Period: ~2^116\n// Reported to pass all BigCrush tests.\nvar alea = require('./lib/alea');\n\n// xor128, a pure xor-shift generator by George Marsaglia.\n// Period: 2^128-1.\n// Reported to fail: MatrixRank and LinearComp.\nvar xor128 = require('./lib/xor128');\n\n// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.\n// Period: 2^192-2^32\n// Reported to fail: CollisionOver, SimpPoker, and LinearComp.\nvar xorwow = require('./lib/xorwow');\n\n// xorshift7, by François Panneton and Pierre L'ecuyer, takes\n// a different approach: it adds robustness by allowing more shifts\n// than Marsaglia's original three.  It is a 7-shift generator\n// with 256 bits, that passes BigCrush with no systmatic failures.\n// Period 2^256-1.\n// No systematic BigCrush failures reported.\nvar xorshift7 = require('./lib/xorshift7');\n\n// xor4096, by Richard Brent, is a 4096-bit xor-shift with a\n// very long period that also adds a Weyl generator. It also passes\n// BigCrush with no systematic failures.  Its long period may\n// be useful if you have many generators and need to avoid\n// collisions.\n// Period: 2^4128-2^32.\n// No systematic BigCrush failures reported.\nvar xor4096 = require('./lib/xor4096');\n\n// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random\n// number generator derived from ChaCha, a modern stream cipher.\n// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n// Period: ~2^127\n// No systematic BigCrush failures reported.\nvar tychei = require('./lib/tychei');\n\n// The original ARC4-based prng included in this library.\n// Period: ~2^1600\nvar sr = require('./seedrandom');\n\nsr.alea = alea;\nsr.xor128 = xor128;\nsr.xorwow = xorwow;\nsr.xorshift7 = xorshift7;\nsr.xor4096 = xor4096;\nsr.tychei = tychei;\n\nmodule.exports = sr;\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {inferShape} from './tensor_util_env';\nimport {RecursiveArray, TensorLike, TypedArray} from './types';\nimport {arraysEqual, encodeString, flatten, isString, isTypedArray} from './util';\n\nconst TEST_EPSILON_FLOAT32 = 1e-3;\nexport const TEST_EPSILON_FLOAT16 = 1e-1;\n\nexport function expectArraysClose(\n    actual: TypedArray|number|RecursiveArray<number>,\n    expected: TypedArray|number|RecursiveArray<number>, epsilon?: number) {\n  if (epsilon == null) {\n    epsilon = testEpsilon();\n  }\n  return expectArraysPredicate(\n      actual, expected, (a, b) => areClose(a as number, b as number, epsilon));\n}\n\nexport function testEpsilon() {\n  return ENGINE.backend.floatPrecision() === 32 ? TEST_EPSILON_FLOAT32 :\n                                                  TEST_EPSILON_FLOAT16;\n}\n\nfunction expectArraysPredicate(\n    actual: TensorLike, expected: TensorLike,\n    predicate: (a: {}, b: {}) => boolean) {\n  let checkClassType = true;\n  if (isTypedArray(actual) || isTypedArray(expected)) {\n    checkClassType = false;\n  }\n  if (isTypedArray(actual) && isTypedArray(expected)) {\n    checkClassType = true;\n  }\n  if (checkClassType) {\n    const aType = actual.constructor.name;\n    const bType = expected.constructor.name;\n\n    if (aType !== bType) {\n      throw new Error(\n          `Arrays are of different type. Actual: ${aType}. ` +\n          `Expected: ${bType}`);\n    }\n  }\n\n  if (Array.isArray(actual) && Array.isArray(expected)) {\n    const actualShape = inferShape(actual);\n    const expectedShape = inferShape(expected);\n    if (!arraysEqual(actualShape, expectedShape)) {\n      throw new Error(\n          `Arrays have different shapes. ` +\n          `Actual: [${actualShape}]. Expected: [${expectedShape}]`);\n    }\n  }\n\n  const actualFlat =\n      isTypedArray(actual) ? actual : flatten(actual as RecursiveArray<number>);\n  const expectedFlat = isTypedArray(expected) ?\n      expected :\n      flatten(expected as RecursiveArray<number>);\n\n  if (actualFlat.length !== expectedFlat.length) {\n    throw new Error(\n        `Arrays have different lengths actual: ${actualFlat.length} vs ` +\n        `expected: ${expectedFlat.length}.\\n` +\n        `Actual:   ${actualFlat}.\\n` +\n        `Expected: ${expectedFlat}.`);\n  }\n  for (let i = 0; i < expectedFlat.length; ++i) {\n    const a = actualFlat[i];\n    const e = expectedFlat[i];\n\n    if (!predicate(a, e)) {\n      throw new Error(\n          `Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${e}.\\n` +\n          `Actual:   ${actualFlat}.\\n` +\n          `Expected: ${expectedFlat}.`);\n    }\n  }\n  if (typeof expect !== 'undefined') {\n    expect().nothing();\n  }\n}\n\nexport interface DoneFn {\n  (): void;\n  fail: (message?: Error|string) => void;\n}\n\nexport function expectPromiseToFail(fn: () => Promise<{}>, done: DoneFn): void {\n  fn().then(() => done.fail(), () => done());\n  if (typeof expect !== 'undefined') {\n    expect().nothing();\n  }\n}\n\nexport function expectArraysEqual(actual: TensorLike, expected: TensorLike) {\n  const exp = typeof expected === 'string' || typeof expected === 'number' ||\n          typeof expected === 'boolean' ?\n      [expected] as number[] :\n      expected as number[];\n  if (isString(actual) || isString((actual as string[])[0]) ||\n      isString(expected) || isString((expected as string[])[0])) {\n    // tslint:disable-next-line: triple-equals\n    return expectArraysPredicate(actual, exp, (a, b) => a == b);\n  }\n  return expectArraysPredicate(\n      actual, expected, (a, b) => areClose(a as number, b as number, 0));\n}\n\nexport function expectNumbersClose(a: number, e: number, epsilon?: number) {\n  if (epsilon == null) {\n    epsilon = testEpsilon();\n  }\n  if (!areClose(a, e, epsilon)) {\n    throw new Error(`Numbers differ: actual === ${a}, expected === ${e}`);\n  }\n  if (typeof expect !== 'undefined') {\n    expect().nothing();\n  }\n}\n\nfunction areClose(a: number, e: number, epsilon: number): boolean {\n  if (!isFinite(a) && !isFinite(e)) {\n    return true;\n  }\n  if (isNaN(a) || isNaN(e) || Math.abs(a - e) > epsilon) {\n    return false;\n  }\n  return true;\n}\n\nexport function expectValuesInRange(\n    actual: TypedArray|number[], low: number, high: number) {\n  for (let i = 0; i < actual.length; i++) {\n    if (actual[i] < low || actual[i] > high) {\n      throw new Error(\n          `Value out of range:${actual[i]} low: ${low}, high: ${high}`);\n    }\n  }\n}\n\nexport function expectArrayBuffersEqual(\n    actual: ArrayBuffer, expected: ArrayBuffer) {\n  // Safari does not like comparing ArrayBuffers directly. Wrapping in\n  // a Float32Array solves this issue.\n  const actualArray = new Float32Array(actual);\n  const expectedArray = new Float32Array(expected);\n  if (actualArray.length !== expectedArray.length) {\n    throw new Error(\n        'Expected ArrayBuffer to be of length ' +\n        `${expectedArray.length}, but it was ${actualArray.length}`);\n  }\n\n  for (let i = 0; i < expectedArray.length; i++) {\n    if (actualArray[i] !== expectedArray[i]) {\n      throw new Error(\n          `Expected ArrayBuffer value at ${i} to be ` +\n          `${expectedArray[i]} but got ${actualArray[i]} instead`);\n    }\n  }\n}\n\n/** Encodes strings into utf-8 bytes. */\nexport function encodeStrings(a: RecursiveArray<{}>):\n    RecursiveArray<Uint8Array> {\n  for (let i = 0; i < (a as Array<{}>).length; i++) {\n    const val = a[i];\n    if (Array.isArray(val)) {\n      encodeStrings(val);\n    } else {\n      a[i] = encodeString(val as string);\n    }\n  }\n  return a as RecursiveArray<Uint8Array>;\n}\n\n/** Creates an HTMLVideoElement with autoplay-friendly default settings. */\nexport function createVideoElement(source: HTMLSourceElement):\n    Promise<HTMLVideoElement> {\n  const video = document.createElement('video');\n  if ('playsInline' in video) {\n    // tslint:disable-next-line:no-any\n    (video as any).playsInline = true;\n  }\n  video.muted = true;\n  video.loop = true;\n  video.style.position = 'fixed';\n  video.style.left = '0px';\n  video.style.top = '0px';\n\n  video.preload = 'auto';\n  video.appendChild(source);\n  return new Promise(resolve => {\n    video.addEventListener('loadeddata', _ => resolve(video));\n    video.load();\n  });\n}\n\nexport async function play(video: HTMLVideoElement) {\n  await video.play();\n  if ('requestVideoFrameCallback' in video) {\n    await new Promise(resolve => {\n      // tslint:disable-next-line:no-any\n      (video as any).requestVideoFrameCallback(resolve);\n    });\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as seedrandom from 'seedrandom';\n\nimport {expectNumbersClose, testEpsilon} from '../test_util';\nimport {TypedArray} from '../types';\n\nexport interface RandomBase {\n  nextValue(): number;\n}\n\nexport interface RandomGamma {\n  nextValue(): number;\n}\n\nexport interface RandNormalDataTypes {\n  float32: Float32Array;\n  int32: Int32Array;\n}\n\nexport interface RandGammaDataTypes {\n  float32: Float32Array;\n  int32: Int32Array;\n}\n\n// https://en.wikipedia.org/wiki/Marsaglia_polar_method\nexport class MPRandGauss implements RandomBase {\n  private mean: number;\n  private stdDev: number;\n  private nextVal: number;\n  private dtype?: keyof RandNormalDataTypes;\n  private truncated?: boolean;\n  private upper?: number;\n  private lower?: number;\n  private random: seedrandom.prng;\n\n  constructor(\n      mean: number, stdDeviation: number, dtype?: keyof RandNormalDataTypes,\n      truncated?: boolean, seed?: number) {\n    this.mean = mean;\n    this.stdDev = stdDeviation;\n    this.dtype = dtype;\n    this.nextVal = NaN;\n    this.truncated = truncated;\n    if (this.truncated) {\n      this.upper = this.mean + this.stdDev * 2;\n      this.lower = this.mean - this.stdDev * 2;\n    }\n    const seedValue = seed ? seed : Math.random();\n    this.random = seedrandom.alea(seedValue.toString());\n  }\n\n  /** Returns next sample from a Gaussian distribution. */\n  public nextValue(): number {\n    if (!isNaN(this.nextVal)) {\n      const value = this.nextVal;\n      this.nextVal = NaN;\n      return value;\n    }\n\n    let resultX: number, resultY: number;\n    let isValid = false;\n    while (!isValid) {\n      let v1: number, v2: number, s: number;\n      do {\n        v1 = 2 * this.random() - 1;\n        v2 = 2 * this.random() - 1;\n        s = v1 * v1 + v2 * v2;\n      } while (s >= 1 || s === 0);\n\n      const mul = Math.sqrt(-2.0 * Math.log(s) / s);\n      resultX = this.mean + this.stdDev * v1 * mul;\n      resultY = this.mean + this.stdDev * v2 * mul;\n\n      if (!this.truncated || this.isValidTruncated(resultX)) {\n        isValid = true;\n      }\n    }\n\n    if (!this.truncated || this.isValidTruncated(resultY)) {\n      this.nextVal = this.convertValue(resultY);\n    }\n    return this.convertValue(resultX);\n  }\n\n  /** Handles proper rounding for non-floating-point numbers. */\n  private convertValue(value: number): number {\n    if (this.dtype == null || this.dtype === 'float32') {\n      return value;\n    }\n    return Math.round(value);\n  }\n\n  /** Returns true if less than 2-standard-deviations from the mean. */\n  private isValidTruncated(value: number): boolean {\n    return value <= this.upper && value >= this.lower;\n  }\n}\n\n// Marsaglia, George, and Wai Wan Tsang. 2000. \"A Simple Method for Generating\n// Gamma Variables.\"\nexport class RandGamma implements RandomGamma {\n  private alpha: number;\n  private beta: number;\n  private d: number;\n  private c: number;\n  private dtype?: keyof RandGammaDataTypes;\n  private randu: seedrandom.prng;\n  private randn: MPRandGauss;\n\n  constructor(\n      alpha: number, beta: number, dtype: keyof RandGammaDataTypes,\n      seed?: number) {\n    this.alpha = alpha;\n    this.beta = 1 / beta;  // convert rate to scale parameter\n    this.dtype = dtype;\n\n    const seedValue = seed ? seed : Math.random();\n    this.randu = seedrandom.alea(seedValue.toString());\n    this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());\n\n    if (alpha < 1) {\n      this.d = alpha + (2 / 3);\n    } else {\n      this.d = alpha - (1 / 3);\n    }\n    this.c = 1 / Math.sqrt(9 * this.d);\n  }\n\n  /** Returns next sample from a gamma distribution. */\n  public nextValue(): number {\n    let x2: number, v0: number, v1: number, x: number, u: number, v: number;\n    while (true) {\n      do {\n        x = this.randn.nextValue();\n        v = 1 + (this.c * x);\n      } while (v <= 0);\n      v *= v * v;\n      x2 = x * x;\n      v0 = 1 - (0.331 * x2 * x2);\n      v1 = (0.5 * x2) + (this.d * (1 - v + Math.log(v)));\n      u = this.randu();\n      if (u < v0 || Math.log(u) < v1) {\n        break;\n      }\n    }\n    v = (1 / this.beta) * this.d * v;\n    if (this.alpha < 1) {\n      v *= Math.pow(this.randu(), 1 / this.alpha);\n    }\n    return this.convertValue(v);\n  }\n  /** Handles proper rounding for non-floating-point numbers. */\n  private convertValue(value: number): number {\n    if (this.dtype === 'float32') {\n      return value;\n    }\n    return Math.round(value);\n  }\n}\n\nexport class UniformRandom implements RandomBase {\n  private min: number;\n  private range: number;\n  private random: seedrandom.prng;\n  private dtype?: keyof RandNormalDataTypes;\n\n  constructor(\n      min = 0, max = 1, dtype?: keyof RandNormalDataTypes,\n      seed?: string|number) {\n    this.min = min;\n    this.range = max - min;\n    this.dtype = dtype;\n    if (seed == null) {\n      seed = Math.random();\n    }\n    if (typeof seed === 'number') {\n      seed = seed.toString();\n    }\n\n    if (!this.canReturnFloat() && this.range <= 1) {\n      throw new Error(\n          `The difference between ${min} - ${max} <= 1 and dtype is not float`);\n    }\n    this.random = seedrandom.alea(seed);\n  }\n\n  /** Handles proper rounding for non floating point numbers. */\n  private canReturnFloat = () =>\n      (this.dtype == null || this.dtype === 'float32');\n\n  private convertValue(value: number): number {\n    if (this.canReturnFloat()) {\n      return value;\n    }\n    return Math.round(value);\n  }\n\n  nextValue() {\n    return this.convertValue(this.min + this.range * this.random());\n  }\n}\n\nexport function jarqueBeraNormalityTest(values: TypedArray|number[]) {\n  // https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test\n  const n = values.length;\n  const s = skewness(values);\n  const k = kurtosis(values);\n  const jb = n / 6 * (Math.pow(s, 2) + 0.25 * Math.pow(k - 3, 2));\n  // JB test requires 2-degress of freedom from Chi-Square @ 0.95:\n  // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm\n  const CHI_SQUARE_2DEG = 5.991;\n  if (jb > CHI_SQUARE_2DEG) {\n    throw new Error(`Invalid p-value for JB: ${jb}`);\n  }\n}\n\nexport function expectArrayInMeanStdRange(\n    actual: TypedArray|number[], expectedMean: number, expectedStdDev: number,\n    epsilon?: number) {\n  if (epsilon == null) {\n    epsilon = testEpsilon();\n  }\n  const actualMean = mean(actual);\n  expectNumbersClose(actualMean, expectedMean, epsilon);\n  expectNumbersClose(\n      standardDeviation(actual, actualMean), expectedStdDev, epsilon);\n}\n\nfunction mean(values: TypedArray|number[]) {\n  let sum = 0;\n  for (let i = 0; i < values.length; i++) {\n    sum += values[i];\n  }\n  return sum / values.length;\n}\n\nfunction standardDeviation(values: TypedArray|number[], mean: number) {\n  let squareDiffSum = 0;\n  for (let i = 0; i < values.length; i++) {\n    const diff = values[i] - mean;\n    squareDiffSum += diff * diff;\n  }\n  return Math.sqrt(squareDiffSum / values.length);\n}\n\nfunction kurtosis(values: TypedArray|number[]) {\n  // https://en.wikipedia.org/wiki/Kurtosis\n  const valuesMean = mean(values);\n  const n = values.length;\n  let sum2 = 0;\n  let sum4 = 0;\n  for (let i = 0; i < n; i++) {\n    const v = values[i] - valuesMean;\n    sum2 += Math.pow(v, 2);\n    sum4 += Math.pow(v, 4);\n  }\n  return (1 / n) * sum4 / Math.pow((1 / n) * sum2, 2);\n}\n\nfunction skewness(values: TypedArray|number[]) {\n  // https://en.wikipedia.org/wiki/Skewness\n  const valuesMean = mean(values);\n  const n = values.length;\n  let sum2 = 0;\n  let sum3 = 0;\n  for (let i = 0; i < n; i++) {\n    const v = values[i] - valuesMean;\n    sum2 += Math.pow(v, 2);\n    sum3 += Math.pow(v, 3);\n  }\n  return (1 / n) * sum3 / Math.pow((1 / (n - 1)) * sum2, 3 / 2);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {RandGamma} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a gamma distribution.\n *\n * ```js\n * tf.randomGamma([2, 2], 1).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param alpha The shape parameter of the gamma distribution.\n * @param beta The inverse scale parameter of the gamma distribution. Defaults\n *     to 1.\n * @param dtype The data type of the output. Defaults to float32.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomGamma_<R extends Rank>(\n    shape: ShapeMap[R], alpha: number, beta = 1,\n    dtype: 'float32'|'int32' = 'float32', seed?: number): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (beta == null) {\n    beta = 1;\n  }\n  if (dtype == null) {\n    dtype = 'float32';\n  }\n  if (dtype !== 'float32' && dtype !== 'int32') {\n    throw new Error(`Unsupported data type ${dtype}`);\n  }\n  const rgamma = new RandGamma(alpha, beta, dtype, seed);\n  const res = buffer(shape, dtype);\n  for (let i = 0; i < res.values.length; i++) {\n    res.values[i] = rgamma.nextValue();\n  }\n  return res.toTensor();\n}\n\nexport const randomGamma = /* @__PURE__ */ op({randomGamma_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {MPRandGauss} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a normal distribution.\n *\n * ```js\n * tf.randomNormal([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param mean The mean of the normal distribution.\n * @param stdDev The standard deviation of the normal distribution.\n * @param dtype The data type of the output.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomNormal_<R extends Rank>(\n    shape: ShapeMap[R], mean = 0, stdDev = 1, dtype?: 'float32'|'int32',\n    seed?: number): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (dtype != null && (dtype as DataType) === 'bool') {\n    throw new Error(`Unsupported data type ${dtype}`);\n  }\n  const randGauss =\n      new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);\n  const res = buffer(shape, dtype);\n  for (let i = 0; i < res.values.length; i++) {\n    res.values[i] = randGauss.nextValue();\n  }\n  return res.toTensor();\n}\n\nexport const randomNormal = /* @__PURE__ */ op({randomNormal_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {op} from './operation';\nimport {randomNormal} from './random_normal';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a normal distribution.\n *\n * The generated values will have mean 0 and standard deviation 1.\n *\n * ```js\n * tf.randomStandardNormal([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The data type of the output.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomStandardNormal_<R extends Rank>(\n    shape: ShapeMap[R], dtype?: 'float32'|'int32', seed?: number): Tensor<R> {\n  if (dtype != null && (dtype as DataType) === 'bool') {\n    throw new Error(`Unsupported data type ${dtype}`);\n  }\n  return randomNormal(shape, 0, 1, dtype, seed);\n}\n\nexport const randomStandardNormal = /* @__PURE__ */ op({randomStandardNormal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {UniformRandom} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a uniform distribution.\n *\n * The generated values follow a uniform distribution in the range [minval,\n * maxval). The lower bound minval is included in the range, while the upper\n * bound maxval is excluded.\n *\n * ```js\n * tf.randomUniform([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param minval The lower bound on the range of random values to generate.\n *   Defaults to 0.\n * @param maxval The upper bound on the range of random values to generate.\n *   Defaults to 1.\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n * @param seed An optional int. Defaults to 0. If seed is set to be non-zero,\n *   the random number generator is seeded by the given seed. Otherwise, it is\n *   seeded by a random seed.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomUniform_<R extends Rank>(\n    shape: ShapeMap[R], minval = 0, maxval = 1, dtype: DataType = 'float32',\n    seed?: number|string): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  const res = buffer(shape, dtype);\n  const random = new UniformRandom(minval, maxval, null, seed);\n  for (let i = 0; i < res.values.length; i++) {\n    res.values[i] = random.nextValue();\n  }\n  return res.toTensor();\n}\n\nexport const randomUniform = /* @__PURE__ */ op({randomUniform_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {Rank, ShapeMap} from '../types';\nimport {op} from './operation';\nimport {randomUniform} from './random_uniform';\n\n/**\n * Creates a `tf.Tensor` with integers sampled from a uniform distribution.\n *\n * The generated values are uniform integers in the range [minval, maxval). The\n * lower bound minval is included in the range, while the upper bound maxval is\n * excluded.\n *\n * ```js\n * tf.randomUniformInt([2, 2], 0, 10).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param minval Inclusive lower bound on the generated integers.\n * @param maxval Exclusive upper bound on the generated integers.\n * @param seed An optional int. Defaults to 0. If seed is set to be non-zero,\n *   the random number generator is seeded by the given seed. Otherwise, it is\n *   seeded by a random seed.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomUniformInt_<R extends Rank>(\n  shape: ShapeMap[R], minval: number, maxval: number,\n    seed?: number|string): Tensor<R> {\n  // TODO(mattsoulanille): Handle optional seed2 input.\n  return randomUniform(shape, minval, maxval, 'int32', seed);\n}\n\nexport const randomUniformInt = /* @__PURE__ */ op({randomUniformInt_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Range, RangeAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\n\n/**\n * Creates a new `tf.Tensor1D` filled with the numbers in the range provided.\n *\n * The tensor is a half-open interval meaning it includes start, but\n * excludes stop. Decrementing ranges and negative step values are also\n * supported.\n *\n *\n * ```js\n * tf.range(0, 9, 2).print();\n * ```\n *\n * @param start An integer start value\n * @param stop An integer stop value\n * @param step An integer increment (will default to 1 or -1)\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function range(\n    start: number, stop: number, step = 1,\n    dtype: 'float32'|'int32' = 'float32'): Tensor1D {\n  if (step === 0) {\n    throw new Error('Cannot have a step of zero');\n  }\n\n  const attrs: RangeAttrs = {start, stop, step, dtype};\n\n  return ENGINE.runKernel(Range, {} /* inputs */,\n      attrs as unknown as NamedAttrMap);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Real, RealInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns the real part of a complex (or real) tensor.\n *\n * Given a tensor input, this operation returns a tensor of type float that is\n * the real part of each element in input considered as a complex number.\n *\n * If the input is real, it simply makes a clone.\n *\n * ```js\n * const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);\n * tf.real(x).print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction real_<T extends Tensor>(input: T|TensorLike): T {\n  const $input = convertToTensor(input, 'input', 'real');\n\n  const inputs: RealInputs = {input: $input};\n  return ENGINE.runKernel(Real, inputs as unknown as NamedTensorMap);\n}\n\nexport const real = /* @__PURE__ */ op({real_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reciprocal, ReciprocalInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes reciprocal of x element-wise: `1 / x`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, 2]);\n *\n * x.reciprocal().print();  // or tf.reciprocal(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction reciprocal_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'reciprocal');\n\n  const inputs: ReciprocalInputs = {x: $x};\n  return ENGINE.runKernel(Reciprocal, inputs as unknown as NamedTensorMap);\n}\nexport const reciprocal = /* @__PURE__ */ op({reciprocal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Relu, ReluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes rectified linear element-wise: `max(x, 0)`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.relu().print();  // or tf.relu(x)\n * ```\n * @param x The input tensor. If the dtype is `bool`, the output dtype will be\n *     `int32`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction relu_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'relu');\n\n  const inputs: ReluInputs = {x: $x};\n\n  return ENGINE.runKernel(Relu, inputs as unknown as NamedTensorMap);\n}\n\nexport const relu = /* @__PURE__ */ op({relu_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Relu6, Relu6Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes rectified linear 6 element-wise: `min(max(x, 0), 6)`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 8]);\n *\n * x.relu6().print();  // or tf.relu6(x)\n * ```\n * @param x The input tensor. If the dtype is `bool`, the output dtype will be\n *     `int32`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction relu6_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'relu6');\n\n  const inputs: Relu6Inputs = {x: $x};\n\n  return ENGINE.runKernel(Relu6, inputs as unknown as NamedTensorMap);\n}\n\nexport const relu6 = /* @__PURE__ */ op({relu6_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reverse, ReverseAttrs, ReverseInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Reverses a `tf.Tensor` along a specified axis.\n *\n * Also available are stricter rank-specific methods that assert that `x` is\n * of the given rank:\n *   - `tf.reverse1d`\n *   - `tf.reverse2d`\n *   - `tf.reverse3d`\n *   - `tf.reverse4d`\n *\n * Except `tf.reverse1d` (which does not have axis param), all methods have\n * same signature as this method.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.reverse().print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.reverse(axis).print();\n * ```\n * @param x The input tensor to be reversed.\n * @param axis The set of dimensions to reverse. Must be in the\n *     range [-rank(x), rank(x)). Defaults to all axes.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction reverse_<T extends Tensor>(\n    x: T|TensorLike, axis?: number|number[]): T {\n  const $x = convertToTensor(x, 'x', 'reverse');\n\n  const inputs: ReverseInputs = {x: $x};\n  const attrs: ReverseAttrs = {dims: axis};\n\n  return ENGINE.runKernel(\n      Reverse, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const reverse = /* @__PURE__ */ op({reverse_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor1D`.\n *\n * @param x The input tensor.\n */\nfunction reverse1d_(x: Tensor1D|TensorLike): Tensor1D {\n  const $x = convertToTensor(x, 'x', 'reverse');\n  util.assert(\n      $x.rank === 1,\n      () => `Error in reverse1D: x must be rank 1 but got rank ${$x.rank}.`);\n  return reverse($x, 0);\n}\n\nexport const reverse1d = /* @__PURE__ */ op({reverse1d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor2D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n *     range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse2d_(x: Tensor2D|TensorLike, axis?: number|number[]): Tensor2D {\n  const $x = convertToTensor(x, 'x', 'reverse');\n  util.assert(\n      $x.rank === 2,\n      () => `Error in reverse2D: x must be rank 2 but got rank ${$x.rank}.`);\n  return reverse($x, axis);\n}\n\nexport const reverse2d = /* @__PURE__ */ op({reverse2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor3D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n *     range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse3d_(x: Tensor3D|TensorLike, axis?: number|number[]): Tensor3D {\n  const $x = convertToTensor(x, 'x', 'reverse');\n  util.assert(\n      $x.rank === 3,\n      () => `Error in reverse3D: x must be rank 3 but got rank ${$x.rank}.`);\n  return reverse($x, axis);\n}\n\nexport const reverse3d = /* @__PURE__ */ op({reverse3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor4D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n *     range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse4d_(x: Tensor4D|TensorLike, axis?: number|number[]): Tensor4D {\n  const $x = convertToTensor(x, 'x', 'reverse');\n  util.assert(\n      $x.rank === 4,\n      () => `Error in reverse4D: x must be rank 4 but got rank ${$x.rank}.`);\n  return reverse($x, axis);\n}\n\nexport const reverse4d = /* @__PURE__ */ op({reverse4d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Round, RoundInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes round of input `tf.Tensor` element-wise: `round(x)`.\n * It implements banker's rounding.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.round().print();  // or tf.round(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction round_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'round');\n  const inputs: RoundInputs = {x: $x};\n\n  return ENGINE.runKernel(Round, inputs as unknown as NamedTensorMap);\n}\n\nexport const round = /* @__PURE__ */ op({round_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Rsqrt, RsqrtInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes reciprocal of square root of the input `tf.Tensor` element-wise:\n * `y = 1 / sqrt(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 4, -1]);\n *\n * x.rsqrt().print();  // or tf.rsqrt(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction rsqrt_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'rsqrt', 'float32');\n\n  const inputs: RsqrtInputs = {x: $x};\n\n  return ENGINE.runKernel(Rsqrt, inputs as unknown as NamedTensorMap);\n}\nexport const rsqrt = /* @__PURE__ */ op({rsqrt_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Selu, SeluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes scaled exponential linear element-wise.\n *\n * `x < 0 ? scale * alpha * (exp(x) - 1) : scale * x`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.selu().print();  // or tf.selu(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction selu_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'selu');\n\n  const inputs: SeluInputs = {x: $x};\n\n  return ENGINE.runKernel(Selu, inputs as unknown as NamedTensorMap);\n}\n\nexport const selu = /* @__PURE__ */ op({selu_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {conv2d} from './conv2d';\nimport {depthwiseConv2d} from './depthwise_conv2d';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * 2-D convolution with separable filters.\n *\n * Performs a depthwise convolution that acts separately on channels followed\n * by a pointwise convolution that mixes channels. Note that this is\n * separability between dimensions [1, 2] and 3, not spatial separability\n * between dimensions 1 and 2.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d](\n *     https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d)\n * for more details.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param depthwiseFilter The depthwise filter tensor, rank 4, of shape\n *     `[filterHeight, filterWidth, inChannels, channelMultiplier]`. This is\n *     the filter used in the first step.\n * @param pointwiseFilter The pointwise filter tensor, rank 4, of shape\n *     `[1, 1, inChannels * channelMultiplier, outChannels]`. This is\n *     the filter used in the second step.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels]. Only \"NHWC\" is currently supported.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction separableConv2d_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, depthwiseFilter: Tensor4D|TensorLike,\n    pointwiseFilter: Tensor4D|TensorLike, strides: [number, number]|number,\n    pad: 'valid'|'same', dilation: [number, number]|number = [1, 1],\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC'): T {\n  const $x = convertToTensor(x, 'x', 'separableConv2d');\n  const $depthwiseFilter =\n      convertToTensor(depthwiseFilter, 'depthwiseFilter', 'separableConv2d');\n  const $pointwiseFilter =\n      convertToTensor(pointwiseFilter, 'pointwiseFilter', 'separableConv2d');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  if (dataFormat === 'NCHW') {\n    throw new Error(\n        'separableConv2d currently does not support dataFormat NCHW; only ' +\n        'NHWC is supported');\n  }\n\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in separableConv2d: input must be rank 4, but got ` +\n          `rank ${x4D.rank}.`);\n  util.assert(\n      $depthwiseFilter.rank === 4,\n      () => `Error in separableConv2d: depthwise filter must be rank 4, but ` +\n          `got rank ${$depthwiseFilter.rank}.`);\n  util.assert(\n      $pointwiseFilter.rank === 4,\n      () => `Error in separableConv2d: pointwise filter must be rank 4, but ` +\n          `got rank ${$depthwiseFilter.rank}.`);\n  util.assert(\n      $pointwiseFilter.shape[0] === 1,\n      () =>\n          `Error in separableConv2d: the first dimension of pointwise filter ` +\n          ` must be 1, but got ${$pointwiseFilter.shape[0]}.`);\n  util.assert(\n      $pointwiseFilter.shape[1] === 1,\n      () => `Error in separableConv2d: the second dimension of pointwise ` +\n          `filter must be 1, but got ${$pointwiseFilter.shape[1]}.`);\n\n  const inChannels = $depthwiseFilter.shape[2];\n  const channelMultiplier = $depthwiseFilter.shape[3];\n  util.assert(\n      $pointwiseFilter.shape[2] === inChannels * channelMultiplier,\n      () =>\n          `Error in separableConv2d: the third dimension of pointwise filter ` +\n          `must be ${inChannels * channelMultiplier}, ` +\n          `but got ${$pointwiseFilter.shape[2]}.`);\n\n  const depthwise = depthwiseConv2d(\n      x4D, $depthwiseFilter, strides, pad, dataFormat, dilation);\n  const pointwiseStride = 1;\n  const res =\n      conv2d(depthwise, $pointwiseFilter, pointwiseStride, 'valid', dataFormat);\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res as T;\n}\n\nexport const separableConv2d = /* @__PURE__ */ op({separableConv2d_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor, TensorBuffer} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\n/**\n * Computes the difference between two lists of numbers.\n *\n * Given a Tensor `x` and a Tensor `y`, this operation returns a Tensor `out`\n * that represents all values that are in `x` but not in `y`. The returned\n * Tensor `out` is sorted in the same order that the numbers appear in `x`\n * (duplicates are preserved). This operation also returns a Tensor indices that\n * represents the position of each out element in `x`. In other words:\n *\n * `out[i] = x[idx[i]] for i in [0, 1, ..., out.length - 1]`\n *\n * ```js\n * const x = [1, 2, 3, 4, 5, 6];\n * const y = [1, 3, 5];\n *\n * const [out, indices] = await tf.setdiff1dAsync(x, y);\n * out.print(); // [2, 4, 6]\n * indices.print(); // [1, 3, 5]\n * ```\n *\n * @param x 1-D Tensor. Values to keep.\n * @param y 1-D Tensor. Must have the same type as x. Values to exclude in the\n *     output.\n * @returns Promise of Tensor tuple [out, indices].\n *  out: Tensor with the same type as x.\n *  indices: A Tensor of type int32.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nasync function setdiff1dAsync_(\n    x: Tensor|TensorLike, y: Tensor|TensorLike): Promise<[Tensor, Tensor]> {\n  const $x = convertToTensor(x, 'x', 'setdiff1d');\n  const $y = convertToTensor(y, 'y', 'setdiff1d');\n\n  util.assert(\n      $x.dtype === $y.dtype,\n      () => `x and y should have the same dtype, but got x (${\n          $x.dtype}) and y (${$y.dtype}).`);\n\n  util.assert(\n      $x.rank === 1, () => `x should be 1D tensor, but got x (${$x.shape}).`);\n\n  util.assert(\n      $y.rank === 1, () => `y should be 1D tensor, but got y (${$y.shape}).`);\n\n  const xVals = await $x.data();\n  const yVals = await $y.data();\n  const ySet = new Set(yVals);\n\n  let outputSize = 0;\n  for (let i = 0; i < xVals.length; i++) {\n    if (!ySet.has(xVals[i])) {\n      outputSize++;\n    }\n  }\n\n  const buffer = new TensorBuffer([outputSize], $x.dtype);\n  const indices = new TensorBuffer([outputSize], 'int32');\n  for (let i = 0, p = 0; i < xVals.length; i++) {\n    if (!ySet.has(xVals[i])) {\n      buffer.values[p] = xVals[i];\n      indices.values[p] = i;\n      p++;\n    }\n  }\n  return [buffer.toTensor(), indices.toTensor()];\n}\nexport const setdiff1dAsync = setdiff1dAsync_;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sign, SignInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns an element-wise indication of the sign of a number.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3, NaN, 0]);\n *\n * x.sign().print();  // or tf.sign(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sign_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sign');\n  const inputs: SignInputs = {x: $x};\n  return ENGINE.runKernel(Sign, inputs as unknown as NamedTensorMap);\n}\nexport const sign = /* @__PURE__ */ op({sign_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sin, SinInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes sin of the input Tensor element-wise: `sin(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.sin().print();  // or tf.sin(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sin_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sin', 'float32');\n\n  const inputs: SinInputs = {x: $x};\n\n  return ENGINE.runKernel(Sin, inputs as unknown as NamedTensorMap);\n}\nexport const sin = /* @__PURE__ */ op({sin_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sinh, SinhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic sin of the input `tf.Tensor` element-wise: `sinh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.sinh().print();  // or tf.sinh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sinh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sinh');\n  const inputs: SinhInputs = {x: $x};\n\n  return ENGINE.runKernel(Sinh, inputs as unknown as NamedTensorMap);\n}\nexport const sinh = /* @__PURE__ */ op({sinh_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 1D slice from 1D array starting at coordinates `begin` and is\n * of length `size`. See `slice` for details.\n */\nfunction slice1d_(\n    x: Tensor1D|TensorLike, begin: number, size: number): Tensor1D {\n  const $x = convertToTensor(x, 'x', 'slice1d');\n  util.assert(\n      $x.rank === 1,\n      () =>\n          `slice1d expects a rank-1 tensor, but got a rank-${$x.rank} tensor`);\n  return slice($x, [begin], [size]);\n}\nexport const slice1d = /* @__PURE__ */ op({slice1d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 2D slice from a 2D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice2d_(\n    x: Tensor2D|TensorLike, begin: [number, number],\n    size: [number, number]): Tensor2D {\n  const $x = convertToTensor(x, 'x', 'slice2d');\n  util.assert(\n      $x.rank === 2,\n      () =>\n          `slice2d expects a rank-2 tensor, but got a rank-${$x.rank} tensor`);\n  return slice($x, begin, size);\n}\nexport const slice2d = /* @__PURE__ */ op({slice2d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 3D slice from a 3D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice3d_(\n    x: Tensor3D|TensorLike, begin: [number, number, number],\n    size: [number, number, number]): Tensor3D {\n  const $x = convertToTensor(x, 'x', 'slice3d');\n  util.assert(\n      $x.rank === 3,\n      () =>\n          `slice3d expects a rank-3 tensor, but got a rank-${$x.rank} tensor`);\n  return slice($x, begin, size);\n}\nexport const slice3d = /* @__PURE__ */ op({slice3d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 4D slice from a 4D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice4d_(\n    x: Tensor4D|TensorLike, begin: [number, number, number, number],\n    size: [number, number, number, number]): Tensor4D {\n  const $x = convertToTensor(x, 'x', 'slice4d');\n  util.assert(\n      $x.rank === 4,\n      () =>\n          `slice4d expects a rank-4 tensor, but got a rank-${$x.rank} tensor`);\n  return slice($x, begin, size);\n}\nexport const slice4d = /* @__PURE__ */ op({slice4d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Softmax, SoftmaxAttrs, SoftmaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the softmax normalized vector given the logits.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n *\n * a.softmax().print();  // or tf.softmax(a)\n * ```\n *\n * ```js\n * const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);\n *\n * a.softmax().print();  // or tf.softmax(a)\n * ```\n *\n * @param logits The logits array.\n * @param dim The dimension softmax would be performed on. Defaults to `-1`\n *     which indicates the last dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction softmax_<T extends Tensor>(logits: T|TensorLike, dim = -1): T {\n  const $logits = convertToTensor(logits, 'logits', 'softmax', 'float32');\n\n  if (dim === -1) {\n    dim = $logits.rank - 1;\n  }\n  if (dim !== $logits.rank - 1) {\n    throw Error(\n        'Softmax along a non-last dimension is not yet supported. ' +\n        `Logits was rank ${$logits.rank} and dim was ${dim}`);\n  }\n\n  const inputs: SoftmaxInputs = {logits: $logits};\n  const attrs: SoftmaxAttrs = {dim};\n\n  return ENGINE.runKernel(\n      Softmax, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const softmax = /* @__PURE__ */ op({softmax_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {FFT, FFTInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {assert} from '../../util';\nimport {op} from '../operation';\n\n/**\n * Fast Fourier transform.\n *\n * Computes the 1-dimensional discrete Fourier transform over the inner-most\n * dimension of input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([1, 2, 3]);\n * const x = tf.complex(real, imag);\n *\n * x.fft().print();  // tf.spectral.fft(x).print();\n * ```\n * @param input The complex input to compute an fft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction fft_(input: Tensor): Tensor {\n  assert(\n      input.dtype === 'complex64',\n      () => `The dtype for tf.spectral.fft() must be complex64 ` +\n          `but got ${input.dtype}.`);\n\n  const inputs: FFTInputs = {input};\n\n  return ENGINE.runKernel(FFT, inputs as unknown as NamedTensorMap);\n}\n\nexport const fft = /* @__PURE__ */ op({fft_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {IFFT, IFFTInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {assert} from '../../util';\nimport {op} from '../operation';\n\n/**\n * Inverse fast Fourier transform.\n *\n * Computes the inverse 1-dimensional discrete Fourier transform over the\n * inner-most dimension of input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([1, 2, 3]);\n * const x = tf.complex(real, imag);\n *\n * x.ifft().print();  // tf.spectral.ifft(x).print();\n * ```\n * @param input The complex input to compute an ifft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction ifft_(input: Tensor): Tensor {\n  assert(\n      input.dtype === 'complex64',\n      () => `The dtype for tf.spectral.ifft() must be complex64 ` +\n          `but got ${input.dtype}.`);\n\n  const inputs: IFFTInputs = {input};\n\n  return ENGINE.runKernel(IFFT, inputs as unknown as NamedTensorMap);\n}\n\nexport const ifft = /* @__PURE__ */ op({ifft_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor2D} from '../../tensor';\nimport {complex} from '../complex';\nimport {concat} from '../concat';\nimport {imag} from '../imag';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {real} from '../real';\nimport {reshape} from '../reshape';\nimport {reverse} from '../reverse';\nimport {scalar} from '../scalar';\nimport {slice} from '../slice';\n\nimport {ifft} from './ifft';\n\n/**\n * Inversed real value input fast Fourier transform.\n *\n * Computes the 1-dimensional inversed discrete Fourier transform over the\n * inner-most dimension of the real input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([0, 0, 0]);\n * const x = tf.complex(real, imag);\n *\n * x.irfft().print();\n * ```\n * @param input The real value input to compute an irfft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction irfft_(input: Tensor): Tensor {\n  const innerDimensionSize = input.shape[input.shape.length - 1];\n  const batch = input.size / innerDimensionSize;\n  let ret: Tensor;\n  if (innerDimensionSize <= 2) {\n    const complexInput = reshape(input, [batch, innerDimensionSize]);\n    ret = ifft(complexInput);\n  } else {\n    // The length of unique components of the DFT of a real-valued signal\n    // is 2 * (input_len - 1)\n    const outputShape = [batch, 2 * (innerDimensionSize - 1)];\n    const realInput = reshape(real(input), [batch, innerDimensionSize]);\n    const imagInput = reshape(imag(input), [batch, innerDimensionSize]);\n\n    const realConjugate =\n        reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);\n    const imagConjugate: Tensor2D = mul(\n        reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1),\n        scalar(-1));\n\n    const r = concat([realInput, realConjugate], 1);\n    const i = concat([imagInput, imagConjugate], 1);\n    const complexInput =\n        reshape(complex(r, i), [outputShape[0], outputShape[1]]);\n    ret = ifft(complexInput);\n  }\n  ret = real(ret);\n  // reshape the result if the input is 3D tensor.\n  if (input.rank === 3 && input.shape[0] !== 0) {\n    const temp = ret;\n    const batch = input.shape[0];\n    ret = reshape(ret, [batch, ret.shape[0] / batch, ret.shape[1]]);\n    temp.dispose();\n  }\n  return ret;\n}\n\nexport const irfft = /* @__PURE__ */ op({irfft_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {SplitV, SplitVAttrs, SplitVInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Splits a `tf.Tensor` into sub tensors.\n *\n * If `numOrSizeSplits` is a number, splits `x` along dimension `axis`\n * into `numOrSizeSplits` smaller tensors.\n * Requires that `numOrSizeSplits` evenly divides `x.shape[axis]`.\n *\n * If `numOrSizeSplits` is a number array, splits `x` into\n * `numOrSizeSplits.length` pieces. The shape of the `i`-th piece has the\n * same size as `x` except along dimension `axis` where the size is\n * `numOrSizeSplits[i]`.\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [2, 4]);\n * const [a, b] = tf.split(x, 2, 1);\n * a.print();\n * b.print();\n *\n * const [c, d, e] = tf.split(x, [1, 2, 1], 1);\n * c.print();\n * d.print();\n * e.print();\n * ```\n *\n * @param x The input tensor to split.\n * @param numOrSizeSplits Either an integer indicating the number of\n * splits along the axis or an array of integers containing the sizes of\n * each output tensor along the axis. If a number then it must evenly divide\n * `x.shape[axis]`; otherwise the sum of sizes must match `x.shape[axis]`.\n * Can contain one -1 indicating that dimension is to be inferred.\n * @param axis The dimension along which to split. Defaults to 0 (the first\n * dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction split_<T extends Tensor>(\n    x: Tensor|TensorLike, numOrSizeSplits: number[]|number, axis = 0): T[] {\n  const $x = convertToTensor(x, 'x', 'split');\n\n  const inputs: SplitVInputs = {x: $x};\n  const attr: SplitVAttrs = {numOrSizeSplits, axis};\n\n  return ENGINE.runKernel(\n             SplitV, inputs as unknown as NamedTensorMap,\n             attr as unknown as NamedAttrMap) as unknown as T[];\n}\n\nexport const split = /* @__PURE__ */ op({split_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {assert} from '../../util';\nimport {complex} from '../complex';\nimport {concat} from '../concat';\nimport {imag} from '../imag';\nimport {op} from '../operation';\nimport {real} from '../real';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {split} from '../split';\nimport {zeros} from '../zeros';\nimport {zerosLike} from '../zeros_like';\n\nimport {fft} from './fft';\n\n/**\n * Real value input fast Fourier transform.\n *\n * Computes the 1-dimensional discrete Fourier transform over the\n * inner-most dimension of the real input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n *\n * real.rfft().print();\n * ```\n * @param input The real value input to compute an rfft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction rfft_(input: Tensor, fftLength?: number): Tensor {\n  assert(\n      input.dtype === 'float32',\n      () => `The dtype for rfft() must be real value but got ${input.dtype}`);\n\n  let innerDimensionSize = input.shape[input.shape.length - 1];\n  const batch = input.size / innerDimensionSize;\n\n  let adjustedInput: Tensor;\n  if (fftLength != null && fftLength < innerDimensionSize) {\n    // Need to crop\n    const begin = input.shape.map(v => 0);\n    const size = input.shape.map(v => v);\n    size[input.shape.length - 1] = fftLength;\n    adjustedInput = slice(input, begin, size);\n    innerDimensionSize = fftLength;\n  } else if (fftLength != null && fftLength > innerDimensionSize) {\n    // Need to pad with zeros\n    const zerosShape = input.shape.map(v => v);\n    zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;\n    adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);\n    innerDimensionSize = fftLength;\n  } else {\n    adjustedInput = input;\n  }\n\n  // Complement the input with zero imaginary numbers.\n  const zerosInput = zerosLike(adjustedInput);\n  const complexInput =\n      reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);\n\n  const ret = fft(complexInput);\n\n  // Exclude complex conjugations. These conjugations are put symmetrically.\n  const half = Math.floor(innerDimensionSize / 2) + 1;\n  const realValues = real(ret);\n  const imagValues = imag(ret);\n  const realComplexConjugate = split(\n      realValues, [half, innerDimensionSize - half],\n      realValues.shape.length - 1);\n  const imagComplexConjugate = split(\n      imagValues, [half, innerDimensionSize - half],\n      imagValues.shape.length - 1);\n\n  const outputShape = adjustedInput.shape.slice();\n  outputShape[adjustedInput.shape.length - 1] = half;\n\n  return reshape(\n      complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);\n}\n\nexport const rfft = /* @__PURE__ */ op({rfft_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SquaredDifference, SquaredDifferenceInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns (a - b) * (a - b) element-wise.\n * Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.squaredDifference(b).print();  // or tf.squaredDifference(a, b)\n * ```\n *\n * ```js\n * // Broadcast squared difference  a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.squaredDifference(b).print();  // or tf.squaredDifference(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction squaredDifference_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'squaredDifference');\n  let $b = convertToTensor(b, 'b', 'squaredDifference');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: SquaredDifferenceInputs = {a: $a, b: $b};\n  const attrs = {};\n\n  return ENGINE.runKernel(\n      SquaredDifference, inputs as unknown as NamedTensorMap, attrs);\n}\n\nexport const squaredDifference = /* @__PURE__ */ op({squaredDifference_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {squeezeShape} from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Removes dimensions of size 1 from the shape of a `tf.Tensor`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);\n * x.squeeze().print();\n * ```\n *\n * @param x The input tensor to be squeezed.\n * @param axis An optional list of numbers. If specified, only\n *     squeezes the dimensions listed. The dimension index starts at 0. It\n * is an error to squeeze a dimension that is not 1.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction squeeze_<T extends Tensor>(x: Tensor|TensorLike, axis?: number[]): T {\n  const $x = convertToTensor(x, 'x', 'squeeze', 'string_or_numeric');\n  return reshape($x, squeezeShape($x.shape, axis).newShape) as T;\n}\n\nexport const squeeze = /* @__PURE__ */ op({squeeze_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Pack, PackAttrs, PackInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Stacks a list of rank-`R` `tf.Tensor`s into one rank-`(R+1)` `tf.Tensor`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n * tf.stack([a, b, c]).print();\n * ```\n *\n * @param tensors A list of tensor objects with the same shape and dtype.\n * @param axis The axis to stack along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction stack_<T extends Tensor>(\n    tensors: Array<T|TensorLike>, axis = 0): Tensor {\n  const $tensors =\n      convertToTensorArray(tensors, 'tensors', 'stack', 'string_or_numeric');\n\n  util.assert(\n      $tensors.length >= 1, () => 'Pass at least one tensor to tf.stack');\n\n  if ($tensors.length > 0) {\n    util.assert(\n        axis <= $tensors[0].rank, () => 'Axis must be <= rank of the tensor');\n  }\n\n  const inputs: PackInputs = $tensors;\n  const attrs: PackAttrs = {axis};\n\n  return ENGINE.runKernel(\n      Pack, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const stack = /* @__PURE__ */ op({stack_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Step, StepAttrs, StepInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha`\n *\n * ```js\n * const x = tf.tensor1d([0, 2, -1, -3]);\n *\n * x.step(.5).print();  // or tf.step(x, .5)\n * ```\n * @param x The input tensor.\n * @param alpha The gradient when input is negative. Defaults to 0.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction step_<T extends Tensor>(x: T|TensorLike, alpha = 0.0): T {\n  const $x = convertToTensor(x, 'x', 'step');\n\n  const inputs: StepInputs = {x: $x};\n  const attrs: StepAttrs = {alpha};\n\n  return ENGINE.runKernel(\n      Step, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\nexport const step = /* @__PURE__ */ op({step_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {StridedSlice, StridedSliceAttrs, StridedSliceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Extracts a strided slice of a tensor.\n *\n * Roughly speaking, this op extracts a slice of size (end-begin)/stride from\n * the given input tensor (x). Starting at the location specified by begin the\n * slice continues by adding stride to the index until all dimensions are not\n * less than end. Note that a stride can be negative, which causes a reverse\n * slice.\n *\n * ```js\n * const t = tf.tensor3d([1, 1, 1 ,2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],\n *    [3, 2, 3]);\n * t.stridedSlice([1, 0, 0], [2, 1, 3], [1, 1, 1]).print()  // [[[3, 3, 3]]]\n * t.stridedSlice([1, 0, 0], [2, 2, 3], [1, 1, 1]).print()  // [[[3, 3, 3],\n *                                                     // [4, 4, 4]]]\n * t.stridedSlice([1, -1, 0], [2, -3, 3], [1, -1, 1]).print() // [[[4, 4, 4],\n *                                                     // [3, 3, 3]]]\n * ```\n *\n * @param x The tensor to stride slice.\n * @param begin The coordinates to start the slice from.\n * @param end: The coordinates to end the slice at.\n * @param strides: The size of the slice.\n * @param beginMask: If the ith bit of beginMask is set, begin[i] is ignored\n *      and the fullest possible range in that dimension is used instead.\n * @param endMask: If the ith bit of endMask is set, end[i] is ignored\n *      and the fullest possible range in that dimension is used instead.\n * @param shrinkAxisMask: a bitmask where bit i implies that\n * the ith specification should shrink the dimensionality. begin and end must\n * imply a slice of size 1 in the dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction stridedSlice_(\n    x: Tensor|TensorLike, begin: number[], end: number[], strides?: number[],\n    beginMask = 0, endMask = 0, ellipsisMask = 0, newAxisMask = 0,\n    shrinkAxisMask = 0): Tensor {\n  const $x = convertToTensor(x, 'x', 'stridedSlice', 'string_or_numeric');\n\n  const inputs: StridedSliceInputs = {x: $x};\n  const attrs: StridedSliceAttrs = {\n    begin,\n    end,\n    strides,\n    beginMask,\n    endMask,\n    ellipsisMask,\n    newAxisMask,\n    shrinkAxisMask\n  };\n\n  return ENGINE.runKernel(\n      StridedSlice, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const stridedSlice = /* @__PURE__ */ op({stridedSlice_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tan, TanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes tan of the input `tf.Tensor` element-wise, `tan(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.tan().print();  // or tf.tan(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction tan_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'tan', 'float32');\n\n  const inputs: TanInputs = {x: $x};\n\n  return ENGINE.runKernel(Tan, inputs as unknown as NamedTensorMap);\n}\nexport const tan = /* @__PURE__ */ op({tan_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike1D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-1 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor1d` as it makes the code more readable.\n *\n * ```js\n * tf.tensor1d([1, 2, 3]).print();\n * ```\n *\n * @param values The values of the tensor. Can be array of numbers,\n *     or a `TypedArray`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor1d(values: TensorLike1D, dtype?: DataType): Tensor1D {\n  assertNonNull(values);\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 1) {\n    throw new Error('tensor1d() requires values to be a flat/TypedArray');\n  }\n  const shape: number[] = null;\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor1D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike2D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-2 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor2d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor2d([[1, 2], [3, 4]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n *     `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor2d(\n    values: TensorLike2D, shape?: [number, number],\n    dtype?: DataType): Tensor2D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 2) {\n    throw new Error('tensor2d() requires shape to have two numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 2 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor2d() requires values to be number[][] or flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor2d() requires shape to be provided when `values` ' +\n        'are a flat/TypedArray');\n  }\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor2D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike3D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor3d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor3d([[[1], [2]], [[3], [4]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided,  it is inferred from\n *     `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor3d(\n    values: TensorLike3D, shape?: [number, number, number],\n    dtype?: DataType): Tensor3D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 3) {\n    throw new Error('tensor3d() requires shape to have three numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 3 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor3d() requires values to be number[][][] or flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor3d() requires shape to be provided when `values` ' +\n        'are a flat array');\n  }\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor3D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike4D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-4 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor4d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor4d([[[[1], [2]], [[3], [4]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n *   it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor4d(\n    values: TensorLike4D, shape?: [number, number, number, number],\n    dtype?: DataType): Tensor4D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 4) {\n    throw new Error('tensor4d() requires shape to have four numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 4 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor4d() requires values to be number[][][][] or flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor4d() requires shape to be provided when `values` ' +\n        'are a flat array');\n  }\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor4D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor5D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike5D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-5 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor5d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor5d([[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n *   it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor5d(\n    values: TensorLike5D, shape?: [number, number, number, number, number],\n    dtype?: DataType): Tensor5D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 5) {\n    throw new Error('tensor5d() requires shape to have five numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 5 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor5d() requires values to be ' +\n        'number[][][][][] or flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor5d() requires shape to be provided when `values` ' +\n        'are a flat array');\n  }\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor5D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor6D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike6D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-6 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor6d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor6d([[[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor6d([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 2, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n *   it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor6d(\n    values: TensorLike6D,\n    shape?: [number, number, number, number, number, number],\n    dtype?: DataType): Tensor6D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 6) {\n    throw new Error('tensor6d() requires shape to have six numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 6 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor6d() requires values to be number[][][][][][] or ' +\n        'flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor6d() requires shape to be provided when `values` ' +\n        'are a flat array');\n  }\n  shape = shape ||\n      inferredShape as [number, number, number, number, number, number];\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor6D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { TensorInfo } from '../tensor_info';\nimport {Tensor} from '../tensor';\nimport {computeStrides, sizeFromShape} from '../util';\n\n/**\n * Check whether updates.shape = indices.shape[:batchDim] +\n * shape[sliceDim:]\n *\n * @param x The input tensor.\n */\nexport function validateUpdateShape(\n    shape: number[], indices: Tensor, updates: Tensor) {\n  const sliceDim = (indices.rank > 1) ? indices.shape[indices.rank - 1] : 1;\n  const batchDim = (indices.rank > 1) ? indices.rank - 1 : 1;\n\n  const shapeError = 'Must have updates.shape = indices.shape[:batchDim] + ' +\n      `shape[sliceDim:], got updates.shape: ${updates.shape}` +\n      `, indices.shape: ${indices.shape}, shape: ${shape}` +\n      `, sliceDim: ${sliceDim}, and batchDim: ${batchDim}.`;\n\n  if (updates.rank < batchDim) {\n    throw new Error(shapeError + ` update.rank < ${batchDim}. `);\n  }\n  if (shape.length < sliceDim + (updates.rank - batchDim)) {\n    throw new Error(\n        shapeError +\n        ` Output shape length < ${sliceDim + (updates.rank - batchDim)}`);\n  }\n  if (updates.rank !== batchDim + shape.length - sliceDim) {\n    throw new Error(\n        shapeError + ` update.rank != ${batchDim + shape.length - sliceDim}`);\n  }\n  for (let d = 0; d < batchDim; ++d) {\n    if (updates.shape[d] !== indices.shape[d]) {\n      throw new Error(\n          shapeError +\n          ` updates.shape[${d}] (${updates.shape[d]}) != indices.shape[${d}] (${\n              indices.shape[d]}).`);\n    }\n  }\n  for (let d = 0; d < updates.rank - batchDim; ++d) {\n    if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {\n      throw new Error(\n          shapeError +\n          ` updates.shape[${d + batchDim}] (${\n              updates.shape[d + batchDim]}) != shape[${d + batchDim}] (${\n              shape[d + batchDim]})`);\n    }\n  }\n}\n\nexport interface ScatterShapeInfo {\n  sliceRank: number;\n  numUpdates: number;\n  sliceSize: number;\n  strides: number[];\n  outputSize: number;\n}\n/**\n * Validate scatter nd inputs.\n *\n * @param update The tensor contains the update values.\n * @param indices The tensor contains the indices for the update values.\n * @param shape The shape of the output tensor.\n */\nexport function validateInput(\n    updates: Tensor, indices: Tensor, shape: number[]) {\n  if (indices.rank < 1) {\n    throw new Error(\n        'tf.scatterND() expects the indices to be rank 1 or higher,' +\n        ` but the rank was ${indices.rank}.`);\n  }\n  if (updates.rank < 1) {\n    throw new Error(\n        'tf.scatterND() expects the updates to be rank 1 or higher,' +\n        ` but the rank was ${updates.rank}.`);\n  }\n  if (indices.dtype !== 'int32') {\n    throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${\n        indices.dtype}`);\n  }\n  if (shape.length < 1) {\n    throw new Error(\n        `Output rank must be greater or equal to 1, but got shape: ${shape}`);\n  }\n\n  if (shape.length === 0) {\n    if (indices.size === 0) {\n      throw new Error(`Indices specified for empty output. indices shape: ${\n          indices.shape}`);\n    }\n    if (updates.size === 0) {\n      throw new Error(`Updates specified for empty output. updates shape: ${\n          updates.shape}`);\n    }\n  }\n\n  validateUpdateShape(shape, indices, updates);\n}\n\n/**\n * Calculate the shape information for the output.\n *\n * @param update The tensor contains the update values.\n * @param indices The tensor contains the indices for the update values.\n * @param shape The shape of the output tensor.\n *\n * @returns ScatterShapeInfo\n */\nexport function calculateShapes(\n    updates: TensorInfo, indices: TensorInfo,\n    shape: number[]): ScatterShapeInfo {\n  // Calculate the number of dimensions in indices\n  const indicesRank = indices.shape.length;\n  const sliceRank = (indicesRank > 1) ? indices.shape[indicesRank - 1] : 1;\n\n  // Calculate the number of elements that make up each slice of our updated\n  // tensor. This allows us to work with flattened tensors and copy over whole\n  // slices at a time.\n  const totalNd = shape.length;\n\n  let sliceSize = 1;\n  for (let i = sliceRank; i < totalNd; ++i) {\n    sliceSize *= shape[i];\n  }\n\n  const safeSliceDim = (sliceRank < 1) ? 1 : sliceRank;\n  const numUpdates = sizeFromShape(indices.shape) / safeSliceDim;\n\n  const strides = [...computeStrides(shape.slice(0, sliceRank)), 1];\n  const outputSize = sizeFromShape(shape);\n  return {sliceRank, numUpdates, sliceSize, strides, outputSize};\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {TensorScatterUpdate, TensorScatterUpdateAttrs, TensorScatterUpdateInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\n\nimport {op} from './operation';\nimport * as scatter_nd_util from './scatter_nd_util';\n\n/**\n * Creates a new tensor by applying sparse updates to individual\n * values or slices to the passed in tensor according to\n * indices. This operator is the similar to scatterNd op, except that the\n * udpates are scattered on an existing tensor (as opposed to a zero-tensor).\n *\n * If indices contains duplicates, then we pick the last update for the index.\n *\n * If an out of bound index is found on CPU, an error is returned.\n *\n * Warning: There are some GPU specific semantics for this operation.\n *  - If an out of bound index is found, the index is ignored.\n *  - The order in which updates are applied is nondeterministic, so the output\n * will be nondeterministic if indices contains duplicates.\n * ```js\n * const shape = [8];\n * const tensor = tf.ones(shape);\n * const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');\n * const updates = tf.tensor1d([9, 10, 11, 12]);\n *\n * tf.tensorScatterUpdate(tensor, indices, updates).print();\n *    //[1, 11, 1, 10, 9, 1, 1, 12]\n * ```\n *\n * @param tensor A Tensor. Tensor to copy/update.\n * @param indices The tensor contains the indices into the output tensor, must\n *     have at least 2 axes: (num_updates, index_depth).\n * @param updates The tensor contains the value for the indices.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction tensorScatterUpdate_<R extends Rank>(\n    tensor: Tensor<R>|TensorLike, indices: Tensor|TensorLike,\n    updates: Tensor|TensorLike): Tensor<R> {\n  const $tensor = convertToTensor(tensor, 'tensor', 'tensorScatterupdate');\n  const $indices =\n      convertToTensor(indices, 'indices', 'tensorScatterupdate', 'int32');\n  const $updates = convertToTensor(updates, 'updates', 'tensorScatterupdate');\n  scatter_nd_util.validateInput($updates, $indices, $tensor.shape);\n  if ($tensor.dtype !== $updates.dtype) {\n    throw new Error(\n        `tensor and updates must have the same dtype, instead they are ${\n            $tensor.dtype} and ${$updates.dtype}.`);\n  }\n\n  const inputs: TensorScatterUpdateInputs = {\n    tensor: $tensor,\n    indices: $indices,\n    updates: $updates\n  };\n  const attrs: TensorScatterUpdateAttrs = {};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             TensorScatterUpdate, inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as Tensor<R>;\n}\n\nexport const tensorScatterUpdate = op({tensorScatterUpdate_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {TopK, TopKAttrs, TopKInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Finds the values and indices of the `k` largest entries along the last\n * dimension.\n *\n * If the input is a vector (rank=1), finds the k largest entries in the vector\n * and outputs their values and indices as vectors. Thus values[j] is the j-th\n * largest entry in input, and its index is indices[j].\n * For higher rank inputs, computes the top k entries along the last dimension.\n *\n * If two elements are equal, the lower-index element appears first.\n *\n * ```js\n * const a = tf.tensor2d([[1, 5], [4, 3]]);\n * const {values, indices} = tf.topk(a);\n * values.print();\n * indices.print();\n * ```\n * @param x 1-D or higher `tf.Tensor` with last dimension being at least `k`.\n * @param k Number of top elements to look for along the last dimension.\n * @param sorted If true, the resulting `k` elements will be sorted by the\n *     values in descending order.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction topk_<T extends Tensor>(\n    x: T|TensorLike, k = 1, sorted = true): {values: T, indices: T} {\n  const $x = convertToTensor(x, 'x', 'topk');\n  if ($x.rank === 0) {\n    throw new Error('topk() expects the input to be of rank 1 or higher');\n  }\n  const lastDim = $x.shape[$x.shape.length - 1];\n\n  if (k < 0) {\n    throw new Error(`'k' passed to topk() must be >= 0 but got ${k}`);\n  }\n\n  if (k > lastDim) {\n    throw new Error(\n        `'k' passed to topk() must be <= the last dimension (${lastDim}) ` +\n        `but got ${k}`);\n  }\n\n  const inputs: TopKInputs = {x: $x};\n  const attrs: TopKAttrs = {k, sorted};\n\n  const [values, indices] = ENGINE.runKernel(\n      TopK, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap) as [T, T];\n\n  return {values, indices};\n}\n\nexport const topk = /* @__PURE__ */ op({topk_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {MPRandGauss} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a truncated normal\n * distribution.\n *\n * ```js\n * tf.truncatedNormal([2, 2]).print();\n * ```\n *\n * The generated values follow a normal distribution with specified mean and\n * standard deviation, except that values whose magnitude is more than 2\n * standard deviations from the mean are dropped and re-picked.\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param mean The mean of the normal distribution.\n * @param stdDev The standard deviation of the normal distribution.\n * @param dtype The data type of the output tensor.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction truncatedNormal_<R extends Rank>(\n    shape: ShapeMap[R], mean = 0, stdDev = 1, dtype?: 'float32'|'int32',\n    seed?: number): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (dtype != null && (dtype as DataType) === 'bool') {\n    throw new Error(`Unsupported data type $ { dtype }`);\n  }\n  const randGauss =\n      new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);\n  const res = buffer(shape, dtype);\n  for (let i = 0; i < res.values.length; i++) {\n    res.values[i] = randGauss.nextValue();\n  }\n  return res.toTensor();\n}\n\nexport const truncatedNormal = /* @__PURE__ */ op({truncatedNormal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Unique, UniqueAttrs, UniqueInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\n\nimport {op} from './operation';\n\n/**\n * Finds unique elements along an axis of a tensor.\n *\n * It returns a tensor `values` containing all of the unique elements along the\n * `axis` of the given tensor `x` in the same order that they occur along the\n * `axis` in `x`; `x` does not need to be sorted. It also returns a tensor\n * `indices` the same size as the number of the elements in `x` along the `axis`\n * dimension. It contains the index in the unique output `values`.\n *\n * ```js\n * // A 1-D tensor\n * const a = tf.tensor1d([1, 1, 2, 4, 4, 4, 7, 8, 8]);\n * const {values, indices} = tf.unique(a);\n * values.print();   // [1, 2, 4, 7, 8,]\n * indices.print();  // [0, 0, 1, 2, 2, 2, 3, 4, 4]\n * ```\n *\n * ```js\n * // A 2-D tensor with axis=0\n * //\n * // 'a' is: [[1, 0, 0],\n * //          [1, 0, 0],\n * //          [2, 0, 0]]\n * const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);\n * const {values, indices} = tf.unique(a, 0)\n * values.print();   // [[1, 0, 0],\n *                   //  [2, 0, 0]]\n * indices.print();  // [0, 0, 1]\n * ```\n *\n * ```js\n * // A 2-D tensor with axis=1\n * //\n * // 'a' is: [[1, 0, 0],\n * //          [1, 0, 0],\n * //          [2, 0, 0]]\n * const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);\n * const {values, indices} = tf.unique(a, 1)\n * values.print();   // [[1, 0],\n *                   //  [1, 0],\n *                   //  [2, 0]]\n * indices.print();  // [0, 1, 1]\n * ```\n * @param x A tensor (int32, string, bool).\n * @param axis The axis of the tensor to find the unique elements.\n * @returns [uniqueElements, indices] (see above for details)\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction unique_<T extends Tensor>(\n    x: T|TensorLike, axis = 0): {values: T, indices: Tensor1D} {\n  const $x = convertToTensor(x, 'x', 'unique', 'string_or_numeric');\n  assert($x.rank > 0, () => 'The input tensor must be at least 1D');\n\n  const inputs: UniqueInputs = {x: $x};\n  const attrs: UniqueAttrs = {axis};\n  const [values, indices] = ENGINE.runKernel(\n      Unique, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap) as [T, Tensor1D];\n  return {values, indices};\n}\n\nexport const unique = /* @__PURE__ */ op({unique_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert, isInt} from '../util';\n\nimport {op} from './operation';\n\n/**\n * Computes the sum along segments of a `tf.Tensor`.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const segmentIds = tf.tensor1d([1, 2, 0, 1], 'int32');\n * const numSegments = 3;\n *\n * x.unsortedSegmentSum(segmentIds, numSegments).print()\n * //or tf.unsortedSegmentSum(x, segmentIds, numSegments)\n * ```\n * @param x The `tf.Tensor` that will be summed along its segments.\n * @param segmentIds A `tf.Tensor1D` whose rank is equal to the rank of `x`'s\n * dimension along the `axis`.  Maps each element of `x` to a segment.\n * @param numSegments The number of distinct `segmentIds`.\n *\n * @doc {heading: 'Operations', subheading: 'Segment'}\n */\nfunction unsortedSegmentSum_<T extends Tensor>(\n    x: T|TensorLike, segmentIds: Tensor1D|TensorLike, numSegments: number): T {\n  const $x = convertToTensor(x, 'x', 'unsortedSegmentSum');\n  const $segmentIds =\n      convertToTensor(segmentIds, 'segmentIds', 'unsortedSegmentSum', 'int32');\n  assert(isInt(numSegments), () => 'numSegments must be of dtype int');\n\n  const inputs: UnsortedSegmentSumInputs = {x: $x, segmentIds: $segmentIds};\n  const attrs: UnsortedSegmentSumAttrs = {numSegments};\n\n  return ENGINE.runKernel(\n      UnsortedSegmentSum, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const unsortedSegmentSum = /* @__PURE__ */ op({unsortedSegmentSum_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Unpack, UnpackAttrs, UnpackInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Unstacks a `tf.Tensor` of rank-`R` into a list of rank-`(R-1)` `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * tf.unstack(a).forEach(tensor => tensor.print());\n * ```\n *\n * @param x A tensor object.\n * @param axis The axis to unstack along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction unstack_(x: Tensor|TensorLike, axis = 0): Tensor[] {\n  const $x = convertToTensor(x, 'x', 'unstack', 'string_or_numeric');\n  util.assert(\n      axis >= -$x.shape.length && axis < $x.shape.length,\n      () =>\n          `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);\n\n  const inputs: UnpackInputs = {value: $x};\n  const attrs: UnpackAttrs = {axis};\n\n  return ENGINE.runKernel(\n      Unpack, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const unstack = /* @__PURE__ */ op({unstack_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\nimport {searchSorted} from './search_sorted';\n\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The index returned corresponds to the first edge greater than the value.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'upperBound' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * const values = tf.tensor1d([0, 4, 10]);\n * const result = tf.upperBound(seq, values);\n * result.print(); // [1, 2, 5]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @return An N-D int32 tensor the size of values containing the result of\n *     applying upper bound to each value. The result is not a global index to\n *     the entire Tensor, but the index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function upperBound(\n    sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike): Tensor {\n  return searchSorted(sortedSequence, values, 'right');\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor, Variable} from '../tensor';\nimport {DataType, Rank} from '../types';\n\n/**\n * Creates a new variable with the provided initial value.\n * ```js\n * const x = tf.variable(tf.tensor([1, 2, 3]));\n * x.assign(tf.tensor([4, 5, 6]));\n *\n * x.print();\n * ```\n *\n * @param initialValue Initial value for the tensor.\n * @param trainable If true, optimizers are allowed to update it.\n * @param name Name of the variable. Defaults to a unique id.\n * @param dtype If set, initialValue will be converted to the given type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function variable<R extends Rank>(\n    initialValue: Tensor<R>, trainable = true, name?: string,\n    dtype?: DataType): Variable<R> {\n  return ENGINE.makeVariable(initialValue, trainable, name, dtype) as\n      Variable<R>;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** An implementation of the Where kernel shared between cpu and webgl */\n\nimport {buffer} from '../ops/buffer';\nimport {Tensor2D} from '../tensor';\nimport {TypedArray} from '../types';\n\nexport function whereImpl(condShape: number[], condVals: TypedArray): Tensor2D {\n  const indices = [];\n  for (let i = 0; i < condVals.length; i++) {\n    if (condVals[i]) {\n      indices.push(i);\n    }\n  }\n\n  const inBuffer = buffer(condShape, 'int32');\n\n  const out = buffer([indices.length, condShape.length], 'int32');\n  for (let i = 0; i < indices.length; i++) {\n    const loc = inBuffer.indexToLoc(indices[i]);\n    const offset = i * condShape.length;\n    out.values.set(loc, offset);\n  }\n  return out.toTensor() as Tensor2D;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {whereImpl} from '../backends/where_impl';\nimport {Tensor, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\n/**\n * Returns the coordinates of true elements of condition.\n *\n * The coordinates are returned in a 2-D tensor where the first dimension (rows)\n * represents the number of true elements, and the second dimension (columns)\n * represents the coordinates of the true elements. Keep in mind, the shape of\n * the output tensor can vary depending on how many true values there are in\n * input. Indices are output in row-major order. The resulting tensor has the\n * shape `[numTrueElems, condition.rank]`.\n *\n * This is analogous to calling the python `tf.where(cond)` without an x or y.\n *\n * ```js\n * const cond = tf.tensor1d([false, false, true], 'bool');\n * const result = await tf.whereAsync(cond);\n * result.print();\n * ```\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nasync function whereAsync_(condition: Tensor|TensorLike): Promise<Tensor2D> {\n  const $condition =\n      convertToTensor(condition, 'condition', 'whereAsync', 'bool');\n  const vals = await $condition.data();\n  const res = whereImpl($condition.shape, vals);\n  if (condition !== $condition) {\n    $condition.dispose();\n  }\n  return res;\n}\n\nexport const whereAsync = whereAsync_;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {gather} from './gather';\nimport {reshape} from './reshape';\nimport {squeeze} from './squeeze';\nimport {whereAsync} from './where_async';\n\n/**\n * Apply boolean mask to tensor.\n *\n * ```js\n * const tensor = tf.tensor2d([1, 2, 3, 4, 5, 6], [3, 2]);\n * const mask = tf.tensor1d([1, 0, 1], 'bool');\n * const result = await tf.booleanMaskAsync(tensor, mask);\n * result.print();\n * ```\n *\n * @param tensor N-D tensor.\n * @param mask K-D boolean tensor, K <= N and K must be known statically.\n * @param axis A 0-D int Tensor representing the axis in tensor to mask from.\n *     By default, axis is 0 which will mask from the first dimension.\n *     Otherwise K + axis <= N.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nasync function booleanMaskAsync_(\n    tensor: Tensor|TensorLike, mask: Tensor|TensorLike,\n    axis?: number): Promise<Tensor> {\n  const $tensor = convertToTensor(tensor, 'tensor', 'boolMask');\n  const $mask = convertToTensor(mask, 'mask', 'boolMask', 'bool');\n\n  const axisFrom = axis == null ? 0 : axis;\n  const maskDim = $mask.rank;\n  const tensorShape = $tensor.shape;\n\n  util.assert(maskDim > 0, () => 'mask cannot be scalar');\n  util.assertShapesMatch(\n      tensorShape.slice(axisFrom, axisFrom + maskDim), $mask.shape,\n      `mask's shape must match the first K dimensions of tensor's shape,`);\n\n  let leadingSize = 1;\n  for (let i = axisFrom; i < axisFrom + maskDim; i++) {\n    leadingSize *= tensorShape[i];\n  }\n  const targetTensorShape =\n      tensorShape.slice(0, axisFrom)\n          .concat([leadingSize], tensorShape.slice(axisFrom + maskDim));\n  const reshapedTensor = reshape($tensor, targetTensorShape);\n  const reshapedMask = reshape($mask, [-1]);\n  const positivePositions = await whereAsync(reshapedMask);\n  const indices = squeeze(positivePositions, [1]);\n\n  const res = gather(reshapedTensor, indices, axisFrom);\n\n  // Ensure no memory leak.\n  if (tensor !== $tensor) {\n    $tensor.dispose();\n  }\n  if (mask !== $mask) {\n    $mask.dispose();\n  }\n  indices.dispose();\n  reshapedTensor.dispose();\n  reshapedMask.dispose();\n  positivePositions.dispose();\n\n  return res;\n}\n\nexport const booleanMaskAsync = booleanMaskAsync_;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {tidy} from '../globals';\nimport {Transpose, TransposeAttrs, TransposeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {complex} from './complex';\nimport {imag} from './imag';\nimport {neg} from './neg';\nimport {op} from './operation';\nimport {real} from './real';\n\n/**\n * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.\n *\n * The returned `tf.Tensor`'s dimension `i` will correspond to the input\n * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,\n * where `n` is the rank of the input `tf.Tensor`. Hence by default, this\n * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);\n *\n * a.transpose().print();  // or tf.transpose(a)\n * ```\n *\n * @param x The tensor to transpose.\n * @param perm The permutation of the dimensions of a.\n * @param conjugate Will conjugate complex input if true.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_<T extends Tensor>(\n    x: T|TensorLike, perm?: number[], conjugate?: boolean): T {\n  const $x = convertToTensor(x, 'x', 'transpose');\n\n  if (perm == null) {\n    perm = $x.shape.map((s, i) => i).reverse();\n  }\n  util.assert(\n      $x.rank === perm.length,\n      () => `Error in transpose: rank of input ${$x.rank} ` +\n          `must match length of perm ${perm}.`);\n  perm.forEach(axis => {\n    util.assert(\n        axis >= 0 && axis < $x.rank,\n        () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +\n            ` but got ${perm}`);\n  });\n\n  if ($x.rank <= 1) {\n    return $x.clone();\n  }\n\n  const inputs: TransposeInputs = {x: $x};\n  const attrs: TransposeAttrs = {perm};\n\n  if ($x.dtype === 'complex64') {\n    return tidy(() => {\n      let $real = real($x);\n      let $imag = imag($x);\n      $real = ENGINE.runKernel(\n          Transpose, {x: $real} as unknown as NamedTensorMap,\n          attrs as unknown as NamedAttrMap);\n      $imag = ENGINE.runKernel(\n          Transpose, {x: $imag} as unknown as NamedTensorMap,\n          attrs as unknown as NamedAttrMap);\n      if (conjugate) {\n        $imag = neg($imag);\n      }\n      return complex($real, $imag);\n    });\n  }\n\n  return ENGINE.runKernel(\n      Transpose, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const transpose = /* @__PURE__ */ op({transpose_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor} from '../tensor';\nimport {assertTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {add} from './add';\nimport {div} from './div';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {pow} from './pow';\nimport {scalar} from './scalar';\nimport {sub} from './sub';\n\n/**\n * Compute the moving average of a variable.\n *\n * Without zeroDebias, the moving average operation is defined by:\n *   `v += delta`\n * where\n *   `delta = (1 - decay) * (x - v)`\n *\n * With zeroDebias (default), the `delta` term is scaled to debias the\n * effect of the (assumed) zero-initialization of `v`.\n *   `delta /= (1 - decay ^ step)`\n *\n * For more details on the zero-debiasing algorithm, see:\n *   https://arxiv.org/abs/1412.6980\n *\n * Note that this function is completely stateless and does not keep track of\n * step count. The step count needs to be maintained by the caller and passed\n * in as `step`.\n *\n * @param v The current moving average value.\n * @param x New input value, must have the same shape and dtype as `v`.\n * @param decay The decay factor. Typical values are 0.95 and 0.99.\n * @param step Step count.\n * @param zeroDebias: Whether zeroDebias is to be performed (default: `true`).\n * @returns The new moving average value.\n *\n * @doc {heading: 'Operations', subheading: 'Moving Average'}\n */\nfunction movingAverage_<T extends Tensor>(\n    v: T|TensorLike, x: T|TensorLike, decay: number|Scalar,\n    step?: number|Scalar, zeroDebias = true): T {\n  const $v = convertToTensor(v, 'v', 'movingAverage');\n  const $x = convertToTensor(x, 'x', 'movingAverage');\n  const $decay = convertToTensor(decay, 'decay', 'movingAverage');\n\n  assertTypesMatch($v, $x);\n  util.assert(\n      util.arraysEqual($v.shape, $x.shape), () => 'Shape mismatch in v and x');\n\n  const one = scalar(1);\n  const oneMinusDecay = sub(one, $decay);\n\n  let update = mul(sub($x, $v), oneMinusDecay);\n  if (zeroDebias) {\n    util.assert(\n        step != null, () => 'When using zeroDebias: true, step is required.');\n    const $step = convertToTensor(step, 'step', 'movingAverage');\n    update = div(update, sub(one, pow($decay, $step)));\n  }\n  return add($v, update);\n}\n\nexport const movingAverage = /* @__PURE__ */ op({movingAverage_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ScatterNd, ScatterNdAttrs, ScatterNdInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\nimport * as scatter_nd_util from './scatter_nd_util';\n\n/**\n * Creates a new tensor by applying sparse updates to individual\n * values or slices within a zero tensor of the given shape tensor according to\n * indices. This operator is the inverse of the `tf.gatherND` operator which\n * extracts values or slices from a given tensor.\n *\n * ```js\n * const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');\n * const updates = tf.tensor1d([9, 10, 11, 12]);\n * const shape = [8];\n * tf.scatterND(indices, updates, shape).print() //[0, 11, 0, 10, 9, 0, 0, 12]\n * ```\n *\n * @param indices The tensor contains the indices into the output tensor.\n * @param updates The tensor contains the value for the indices.\n * @param shape: The shape of the output tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction scatterND_<R extends Rank>(\n    indices: Tensor|TensorLike, updates: Tensor|TensorLike,\n    shape: ShapeMap[R]): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  const $indices = convertToTensor(indices, 'indices', 'scatterND', 'int32');\n  const $updates = convertToTensor(updates, 'updates', 'scatterND');\n  scatter_nd_util.validateInput($updates, $indices, shape);\n\n  const inputs: ScatterNdInputs = {indices: $indices, updates: $updates};\n  const attrs: ScatterNdAttrs = {shape};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             ScatterNd, inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as Tensor<R>;\n}\n\nexport const scatterND = /* @__PURE__ */ op({scatterND_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../tensor';\n\n/**\n * Validate sparseToDense inputs.\n *\n * @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.\n * sparseIndices[i] contains the complete index where sparseValues[i] will be\n * placed.\n * @param sparseValues A 0-D or 1-D Tensor. Values\n * corresponding to each row of sparseIndices, or a scalar value to be used for\n * all sparse indices.\n * @param outputShape number[]. Shape of the dense output tensor.\n * @param validateIndices boolean. indice validation is not supported, error\n * will be thrown if it is set.\n */\nexport function validateInput(\n    sparseIndices: Tensor, sparseValues: Tensor, outputShape: number[],\n    defaultValues: Tensor) {\n  if (sparseIndices.dtype !== 'int32') {\n    throw new Error(\n        'tf.sparseToDense() expects the indices to be int32 type,' +\n        ` but the dtype was ${sparseIndices.dtype}.`);\n  }\n  if (sparseIndices.rank > 2) {\n    throw new Error(\n        'sparseIndices should be a scalar, vector, or matrix,' +\n        ` but got shape ${sparseIndices.shape}.`);\n  }\n\n  const numElems = sparseIndices.rank > 0 ? sparseIndices.shape[0] : 1;\n  const numDims = sparseIndices.rank > 1 ? sparseIndices.shape[1] : 1;\n\n  if (outputShape.length !== numDims) {\n    throw new Error(\n        'outputShape has incorrect number of elements:,' +\n        ` ${outputShape.length}, should be: ${numDims}.`);\n  }\n\n  const numValues = sparseValues.size;\n  if (!(sparseValues.rank === 0 ||\n        sparseValues.rank === 1 && numValues === numElems)) {\n    throw new Error(\n        'sparseValues has incorrect shape ' +\n        `${sparseValues.shape}, should be [] or [${numElems}]`);\n  }\n\n  if (sparseValues.dtype !== defaultValues.dtype) {\n    throw new Error('sparseValues.dtype must match defaultValues.dtype');\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SparseToDense, SparseToDenseAttrs, SparseToDenseInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport * as sparse_to_dense from '../ops/sparse_to_dense_util';\nimport {Scalar, Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ScalarLike, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Converts a sparse representation into a dense tensor.\n *\n * Builds an array dense with shape outputShape such that:\n *\n * // If sparseIndices is scalar\n * dense[i] = (i == sparseIndices ? sparseValues : defaultValue)\n *\n * // If sparseIndices is a vector, then for each i\n * dense[sparseIndices[i]] = sparseValues[i]\n *\n * // If sparseIndices is an n by d matrix, then for each i in [0, n)\n * dense[sparseIndices[i][0], ..., sparseIndices[i][d-1]] = sparseValues[i]\n * All other values in dense are set to defaultValue. If sparseValues is a\n * scalar, all sparse indices are set to this single value.\n *\n * If indices are repeated the final value is summed over all values for those\n * indices.\n *\n * ```js\n * const indices = tf.tensor1d([4, 5, 6, 1, 2, 3], 'int32');\n * const values = tf.tensor1d([10, 11, 12, 13, 14, 15], 'float32');\n * const shape = [8];\n * tf.sparseToDense(indices, values, shape).print();\n * ```\n *\n * @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.\n * sparseIndices[i] contains the complete index where sparseValues[i] will be\n * placed.\n * @param sparseValues A 0-D or 1-D Tensor. Values\n * corresponding to each row of sparseIndices, or a scalar value to be used for\n * all sparse indices.\n * @param outputShape Shape of the dense output tensor. The type is inferred.\n * @param defaultValue Scalar. Value to set for indices not specified in\n * sparseIndices. Defaults to zero.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction sparseToDense_<R extends Rank>(\n    sparseIndices: Tensor|TensorLike, sparseValues: Tensor|TensorLike,\n    outputShape: ShapeMap[R], defaultValue: Scalar|ScalarLike = 0): Tensor<R> {\n  assertNonNegativeIntegerDimensions(outputShape);\n\n  const $sparseIndices =\n      convertToTensor(sparseIndices, 'sparseIndices', 'sparseToDense', 'int32');\n  const $sparseValues = convertToTensor(\n      sparseValues, 'sparseValues', 'sparseToDense', 'string_or_numeric');\n  const $defaultValue = convertToTensor(\n      defaultValue, 'defaultValue', 'sparseToDense', $sparseValues.dtype);\n\n  sparse_to_dense.validateInput(\n      $sparseIndices, $sparseValues, outputShape, $defaultValue);\n\n  const inputs: SparseToDenseInputs = {\n    sparseIndices: $sparseIndices,\n    sparseValues: $sparseValues,\n    defaultValue: $defaultValue\n  };\n\n  const attrs: SparseToDenseAttrs = {outputShape};\n\n  return ENGINE.runKernel(\n      SparseToDense, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const sparseToDense = /* @__PURE__ */ op({sparseToDense_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {GatherNd, GatherNdInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Gather slices from input tensor into a Tensor with shape specified by\n * `indices`.\n *\n * `indices` is a K-dimensional integer tensor, best thought of as a\n * (K-1)-dimensional tensor of indices into input, where each element defines a\n * slice of input:\n * output[\\\\(i_0, ..., i_{K-2}\\\\)] = input[indices[\\\\(i_0, ..., i_{K-2}\\\\)]]\n *\n * Whereas in `tf.gather`, `indices` defines slices into the first dimension of\n * input, in `tf.gatherND`, `indices` defines slices into the first N dimensions\n * of input, where N = indices.shape[-1].\n *\n * The last dimension of indices can be at most the rank of input:\n * indices.shape[-1] <= input.rank\n *\n * The last dimension of `indices` corresponds to elements\n * (if indices.shape[-1] == input.rank) or slices\n * (if indices.shape[-1] < input.rank) along dimension indices.shape[-1] of\n * input.\n * The output tensor has shape\n * indices.shape[:-1] + input.shape[indices.shape[-1]:]\n *\n * Note that on CPU, if an out of bound index is found, an error is returned. On\n * GPU, if an out of bound index is found, a 0 is stored in the corresponding\n * output value.\n *\n * ```js\n * const indices = tf.tensor2d([0, 1, 1, 0], [2,2], 'int32');\n * const input = tf.tensor2d([9, 10, 11, 12], [2, 2]);\n * tf.gatherND(input, indices).print() // [10, 11]\n * ```\n *\n * @param x The tensor from which to gather values.\n * @param indices Index tensor, must be of type int32.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction gatherND_(x: Tensor|TensorLike, indices: Tensor|TensorLike): Tensor {\n  const $indices = convertToTensor(indices, 'indices', 'gatherND', 'int32');\n  const $x = convertToTensor(x, 'x', 'gatherND', 'string_or_numeric');\n\n  const inputs: GatherNdInputs = {params: $x, indices: $indices};\n\n  return ENGINE.runKernel(GatherNd, inputs as unknown as NamedTensorMap);\n}\n\nexport const gatherND = /* @__PURE__ */ op({gatherND_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport * as util from '../util';\n\n/**\n * Normalize noise shape based on provided tensor and noise shape.\n *\n * @param x Tensor.\n * @param noiseShape The shape for the randomly generated keep/drop flags, as\n *   an array of numbers. Optional.\n * @returns Normalized noise shape.\n */\nexport function getNoiseShape(x: Tensor, noiseShape?: number[]): number[] {\n  if (noiseShape == null) {\n    return x.shape.slice();\n  }\n  if (util.arraysEqual(x.shape, noiseShape)) {\n    return noiseShape;\n  }\n  if (x.shape.length === noiseShape.length) {\n    const newDimension: number[] = [];\n    for (let i = 0; i < x.shape.length; i++) {\n      if (noiseShape[i] == null && x.shape[i] != null) {\n        newDimension.push(x.shape[i]);\n      } else {\n        newDimension.push(noiseShape[i]);\n      }\n    }\n    return newDimension;\n  }\n\n  return noiseShape;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {add} from './add';\nimport {div} from './div';\nimport {getNoiseShape} from './dropout_util';\nimport {floor} from './floor';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {randomUniform} from './random_uniform';\n\n/**\n * Computes dropout.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 2, 1]);\n * const rate = 0.75;\n * const output = tf.dropout(x, rate);\n * output.print();\n * ```\n *\n * @param x A floating point Tensor or TensorLike.\n * @param rate A float in the range [0, 1). The probability that each element\n *   of x is discarded.\n * @param noiseShape An array of numbers of type int32, representing the\n * shape for randomly generated keep/drop flags. If the noiseShape has null\n * value, it will be automatically replaced with the x's relative dimension\n * size. Optional.\n * @param seed Used to create random seeds. Optional.\n * @returns A Tensor of the same shape of x.\n *\n * @doc {heading: 'Operations', subheading: 'Dropout'}\n */\nfunction dropout_(\n    x: Tensor|TensorLike, rate: number, noiseShape?: number[],\n    seed?: number|string): Tensor {\n  const $x = convertToTensor(x, 'x', 'dropout');\n\n  util.assert(\n      $x.dtype === 'float32',\n      () => `x has to be a floating point tensor since it's going to be ` +\n          `scaled, but got a ${$x.dtype} tensor instead.`);\n  util.assert(\n      rate >= 0 && rate < 1,\n      () => `rate must be a float in the range [0, 1), but got ${rate}.`);\n\n  if (rate === 0) {\n    return x instanceof Tensor ? $x.clone() : $x;\n  }\n\n  const $noiseShape = getNoiseShape($x, noiseShape);\n  const keepProb = 1 - rate;\n  const multiplier = div(\n      floor(add(randomUniform($noiseShape, 0, 1, 'float32', seed), keepProb)),\n      keepProb);\n\n  return mul($x, multiplier);\n}\n\nexport const dropout = /* @__PURE__ */ op({dropout_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {tensor1d} from './tensor1d';\n\nexport function enclosingPowerOfTwo(value: number) {\n  // Return 2**N for integer N such that 2**N >= value.\n  return Math.floor(Math.pow(2, Math.ceil(Math.log(value) / Math.log(2.0))));\n}\n\nexport function cosineWindow(\n    windowLength: number, a: number, b: number): Tensor1D {\n  const even = 1 - windowLength % 2;\n  const newValues = new Float32Array(windowLength);\n  for (let i = 0; i < windowLength; ++i) {\n    const cosArg = (2.0 * Math.PI * i) / (windowLength + even - 1);\n    newValues[i] = a - b * Math.cos(cosArg);\n  }\n  return tensor1d(newValues, 'float32');\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert, assertShapesMatch, getTypedArrayFromDType} from '../util';\nimport {tensor} from './tensor';\n\n/**\n * Returns whether the targets are in the top K predictions.\n *\n * ```js\n * const predictions = tf.tensor2d([[20, 10, 40, 30], [30, 50, -20, 10]]);\n * const targets = tf.tensor1d([2, 0]);\n * const precision = await tf.inTopKAsync(predictions, targets);\n * precision.print();\n * ```\n * @param predictions 2-D or higher `tf.Tensor` with last dimension being\n *     at least `k`.\n * @param targets 1-D or higher `tf.Tensor`.\n * @param k Optional Number of top elements to look at for computing precision,\n *     default to 1.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nasync function inTopKAsync_<T extends Tensor, U extends Tensor>(\n    predictions: T|TensorLike, targets: U|TensorLike, k = 1): Promise<U> {\n  const $predictions = convertToTensor(predictions, 'predictions', 'inTopK');\n  const $targets = convertToTensor(targets, 'targets', 'inTopK');\n\n  assert(\n      $predictions.rank > 1,\n      () => 'inTopK() expects the predictions to be of rank 2 or higher, ' +\n          `but got ${$predictions.rank}`);\n  assert(\n      $predictions.rank - 1 === $targets.rank,\n      () => `predictions rank should be 1 larger than ` +\n          `targets rank, but got predictions rank ` +\n          `${$predictions.rank} and targets rank ${$targets.rank}`);\n  assertShapesMatch(\n      $predictions.shape.slice(0, $predictions.shape.length - 1),\n      $targets.shape,\n      `predictions's shape should be align with the targets' shape, ` +\n          'except the last dimension.');\n  const lastDim = $predictions.shape[$predictions.shape.length - 1];\n  assert(\n      k > 0 && k <= lastDim,\n      () => `'k' passed to inTopK() must be > 0 && <= the predictions last ` +\n          `dimension (${lastDim}), but got ${k}`);\n\n  const predictionsVals = await $predictions.data();\n  const targetsVals = await $targets.data();\n\n  // Reshape predictionsVals into a 2d tensor [batch, lastDim]\n  // and look up topK along lastDim.\n  const [batch, size] = [predictionsVals.length / lastDim, lastDim];\n  const precision = getTypedArrayFromDType('bool', batch);\n\n  for (let b = 0; b < batch; b++) {\n    const offset = b * size;\n    const vals = predictionsVals.subarray(offset, offset + size);\n    const valAndInd: Array<{value: number, index: number}> = [];\n    for (let i = 0; i < vals.length; i++) {\n      valAndInd.push({value: vals[i], index: i});\n    }\n    valAndInd.sort((a, b) => b.value - a.value);\n\n    precision[b] = 0;\n    for (let i = 0; i < k; i++) {\n      if (valAndInd[i].index === targetsVals[b]) {\n        precision[b] = 1;\n        break;\n      }\n    }\n  }\n\n  if (predictions !== $predictions) {\n    $predictions.dispose();\n  }\n  if (targets !== $targets) {\n    $targets.dispose();\n  }\n\n  // Output precision has the same shape as targets.\n  return tensor(precision, $targets.shape, 'bool') as U;\n}\n\nexport const inTopKAsync = inTopKAsync_;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the filter of a 2D convolution.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n *     [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed.\n * @param dy The dy image, of rank 4 or rank 3, of shape\n *     [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed.\n * @param filterShape The shape of the filter, length 4,\n *     [filterHeight, filterWidth, inDepth, outDepth].\n * @param strides The strides of the convolution: [strideHeight,\n * strideWidth].\n * @param pad A string from: 'same', 'valid'. The type of padding algorithm\n *     used in the forward prop of the op.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels].\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n */\nfunction conv2DBackpropFilter_<T extends Tensor3D|Tensor4D>(\n    x: T, dy: T, filterShape: [number, number, number, number],\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n    dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n  let x4D = x as Tensor4D;\n  if (x.rank === 3) {\n    x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n  }\n  let dy4D = dy as Tensor4D;\n  if (dy4D.rank === 3) {\n    dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n  }\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in conv2dDerFilter: input must be rank 4, but got shape ` +\n          `${x4D.shape}.`);\n  util.assert(\n      dy4D.rank === 4,\n      () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ` +\n          `${dy4D.shape}.`);\n  util.assert(\n      filterShape.length === 4,\n      () => `Error in conv2dDerFilter: filterShape must be length 4, but got ` +\n          `${filterShape}.`);\n  const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n  const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];\n  util.assert(\n      inDepth === filterShape[2],\n      () => `Error in conv2dDerFilter: depth of input ${inDepth}) must ` +\n          `match input depth in filter (${filterShape[2]}.`);\n  util.assert(\n      outDepth === filterShape[3],\n      () => `Error in conv2dDerFilter: depth of dy (${outDepth}) must ` +\n          `match output depth for filter (${filterShape[3]}).`);\n  conv_util.checkPadOnDimRoundingMode('conv2dDerFilter', pad, dimRoundingMode);\n  const inputs: Conv2DBackpropFilterInputs = {x: x4D, dy: dy4D};\n  const attrs: Conv2DBackpropFilterAttrs =\n      {strides, pad, dataFormat, dimRoundingMode, filterShape};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             Conv2DBackpropFilter, inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as Tensor4D;\n}\n\nexport const conv2DBackpropFilter = /* @__PURE__ */ op({conv2DBackpropFilter_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\nimport * as broadcast_util from './broadcast_util';\nimport {elu} from './elu';\nimport {Activation} from './fused_types';\nimport {leakyRelu} from './leaky_relu';\nimport {mul} from './mul';\nimport {prelu} from './prelu';\nimport {relu} from './relu';\nimport {relu6} from './relu6';\nimport {reshape} from './reshape';\nimport {sigmoid} from './sigmoid';\nimport {step} from './step';\nimport {sum} from './sum';\n\n// Returns gradient for fused activation.\nexport function getFusedDyActivation(\n    dy: Tensor, y: Tensor, activation: Activation): Tensor {\n  if (activation == null || activation === 'linear') {\n    return dy;\n  }\n  if (activation === 'relu') {\n    return mul(dy, step(y));\n  }\n  throw new Error(\n      `Cannot compute gradient for fused activation ${activation}.`);\n}\n\n// Returns gradient for fused bias.\nexport function getFusedBiasGradient(\n    bias: Tensor, dyActivation: Tensor): Tensor {\n  let res = dyActivation;\n  const reduceAxes =\n      broadcast_util.getReductionAxes(bias.shape, dyActivation.shape);\n  if (reduceAxes.length > 0) {\n    res = sum(res, reduceAxes);\n  }\n  return reshape(res, bias.shape);\n}\n\nexport function applyActivation(\n    x: Tensor, activation: Activation, preluActivationWeights?: Tensor,\n    leakyreluAlpha?: number): Tensor {\n  if (activation === 'linear') {\n    return x;\n  } else if (activation === 'relu') {\n    return relu(x);\n  } else if (activation === 'elu') {\n    return elu(x);\n  } else if (activation === 'relu6') {\n    return relu6(x);\n  } else if (activation === 'prelu') {\n    return prelu(x, preluActivationWeights);\n  } else if (activation === 'leakyrelu') {\n    return leakyRelu(x, leakyreluAlpha);\n  } else if (activation === 'sigmoid') {\n    return sigmoid(x);\n  }\n  throw new Error(`Unknown fused activation ${activation}.`);\n}\n\n// Whether we should call fused ops.\nexport const shouldFuse = (gradientDepth: number, activation: Activation) => {\n  const gradientMode = gradientDepth > 0;\n  return !gradientMode || activation === 'linear';\n};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport {conv2d as unfusedConv2d} from '../conv2d';\nimport {conv2DBackpropFilter} from '../conv2d_backprop_filter';\nimport {conv2DBackpropInput} from '../conv2d_backprop_input';\nimport * as conv_util from '../conv_util';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes a 2D convolution over the input x, optionally fused with adding a\n * bias and applying an activation.\n *\n * ```js\n * const inputDepth = 2;\n * const inShape = [2, 2, 2, inputDepth];\n * const outputDepth = 2;\n * const fSize = 1;\n * const pad = 0;\n * const strides = 1;\n *\n * const x = tf.tensor4d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n * 16], inShape);\n * const w = tf.tensor4d([-1, 1, -2, 0.5], [fSize, fSize, inputDepth,\n * outputDepth]);\n *\n * tf.fused.conv2d({ x, filter: w, strides, pad, dataFormat: 'NHWC',\n * dilations: [1, 1], bias: tf.scalar(5), activation: 'relu' }).print();\n * ```\n *\n * @param obj An object with the following properties:\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n *     `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid` output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @param bias Tensor to be added to the result.\n * @param activation Name of activation kernel (defaults to `linear`) to be\n *     applied\n *      after biasAdd.\n * @param preluActivationWeights Tensor of prelu weights to be applied as part\n *     of a `prelu` activation, typically the same shape as `x`.\n * @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`\n *     activation.\n */\nfunction fusedConv2d_<T extends Tensor3D|Tensor4D>({\n  x,\n  filter,\n  strides,\n  pad,\n  dataFormat = 'NHWC',\n  dilations = [1, 1],\n  dimRoundingMode,\n  bias,\n  activation = 'linear',\n  preluActivationWeights,\n  leakyreluAlpha\n}: {\n  x: T|TensorLike,\n  filter: Tensor4D|TensorLike,\n  strides: [number, number]|number,\n  pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n  dataFormat?: 'NHWC'|'NCHW',\n  dilations?: [number, number]|number,\n  dimRoundingMode?: 'floor'|'round'|'ceil',\n  bias?: Tensor|TensorLike,\n  activation?: Activation,\n  preluActivationWeights?: Tensor,\n  leakyreluAlpha?: number\n}): T {\n  activation = activation || 'linear';\n\n  if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n    // TODO: Transpose bias and preluActivationWeights properly for NCHW\n    // format before computation.\n    util.assert(\n        dataFormat === 'NHWC',\n        () => `Error in fused conv2d: got dataFormat of ${dataFormat} but ` +\n            `only NHWC is currently supported for the case of gradient depth ` +\n            `is 0 and the activation is not linear.`);\n\n    let result = unfusedConv2d(\n        x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);\n    if (bias != null) {\n      result = add(result, bias);\n    }\n\n    return applyActivation(\n               result, activation, preluActivationWeights, leakyreluAlpha) as T;\n  }\n\n  const $x = convertToTensor(x, 'x', 'conv2d', 'float32');\n  const $filter = convertToTensor(filter, 'filter', 'conv2d', 'float32');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in fused conv2d: input must be rank 4, but got rank ` +\n          `${x4D.rank}.`);\n  util.assert(\n      $filter.rank === 4,\n      () => `Error in fused conv2d: filter must be rank 4, but got rank ` +\n          `${$filter.rank}.`);\n  conv_util.checkPadOnDimRoundingMode('fused conv2d', pad, dimRoundingMode);\n  const inputChannels = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n  util.assert(\n      $filter.shape[2] === inputChannels,\n      () => `Error in conv2d: depth of input (${inputChannels}) must match ` +\n          `input depth for filter ${$filter.shape[2]}.`);\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in conv2D: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n\n  const convInfo = conv_util.computeConv2DInfo(\n      x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode);\n\n  let $bias: Tensor;\n  if (bias != null) {\n    $bias = convertToTensor(bias, 'bias', 'fused conv2d');\n    [$bias] = makeTypesMatch($bias, $x);\n\n    // According to TensorFlow, the bias is supposed be a 1-D tensor or a\n    // scalar.\n    //\n    // 3-D or 4-D bias is not disabled for NHWC format, because they are\n    // currently being used in some cases. For examplem in our code base,\n    // https://github.com/tensorflow/tfjs/blob/b53bd47e880367ae57493f0ea628abaf08db2d5d/tfjs-core/src/ops/fused/fused_conv2d_test.ts#L1972.\n    if (dataFormat === 'NHWC') {\n      broadcast_util.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);\n    } else {\n      util.assert(\n          $bias.shape.length <= 1,\n          () => `Error in fused conv2d: only supports scalar or 1-D Tensor ` +\n              `bias for NCHW format but got the bias of ` +\n              `rank-${$bias.shape.length}.`);\n\n      util.assert(\n          $bias.shape.length === 0 || $bias.shape[0] === convInfo.outChannels ||\n              $bias.shape[0] === 1,\n          () => `Error in fused conv2d: bias shape (${$bias.shape}) is not ` +\n              `compatible with the number of output channels ` +\n              `(${convInfo.outChannels})`);\n    }\n  }\n\n  let $preluActivationWeights: Tensor;\n  if (preluActivationWeights != null) {\n    // PReLU's activation weights could be a scalar, a 1-D tensor or a 3-D\n    // tensor.\n    const alphaShape = preluActivationWeights.shape;\n    util.assert(\n        alphaShape.length <= 1 || alphaShape.length === 3,\n        () => `Error in fused conv2d: only supports scalar, 1-D Tensor or ` +\n            `3-D Tensor PReLU activation weights but got a tensor of ` +\n            `rank-${alphaShape.length}.`);\n\n    if (alphaShape.length === 1) {\n      // Whether the data format is NCHW or NHWC, the 1-D PReLU activation\n      // weights tensor should be aligned with the output channels of conv2d\n      // result.\n      util.assert(\n          alphaShape[0] === 1 || alphaShape[0] === convInfo.outChannels,\n          () => `Error in fused conv2d: PReLU activation weights ` +\n              `(${alphaShape}) is not compatible with the number of output ` +\n              `channels (${convInfo.outChannels}).`);\n    } else if (alphaShape.length === 3) {\n      // Whether the data format is NCHW or NHWC, the PReLU activation weights\n      // tensor should has the compatible shape with the result of conv2d.\n      try {\n        broadcast_util.assertAndGetBroadcastShape(\n            alphaShape, convInfo.outShape);\n      } catch (e) {\n        const errMsg =\n            `Error in fused conv2d: PReLU activation weights (${alphaShape}) ` +\n            `is not compatible with the output shape of the conv2d ` +\n            `(${convInfo.outShape}).`;\n        throw Error(errMsg);\n      }\n    }\n\n    $preluActivationWeights = convertToTensor(\n        preluActivationWeights, 'prelu weights', 'fused conv2d');\n  }\n\n  const grad = (dy: Tensor4D, saved: Tensor[]) => {\n    util.assert(\n        dataFormat === 'NHWC',\n        () => `Error in gradient of fused conv2D: got dataFormat of ${\n            dataFormat} but only NHWC is currently supported.`);\n\n    const [$filter, x4D, y, $bias] =\n        saved as [Tensor4D, Tensor4D, Tensor4D, Tensor];\n\n    const dyActivation = getFusedDyActivation(dy, y, activation) as Tensor4D;\n\n    util.assert(\n        conv_util.tupleValuesAreOne(dilations),\n        () => 'Error in gradient of fused conv2D: ' +\n            `dilation rates greater than 1 ` +\n            `are not yet supported in gradients. Got dilations '${dilations}'`);\n\n    const xDer =\n        conv2DBackpropInput(x4D.shape, dyActivation, $filter, strides, pad);\n    const filterDer =\n        conv2DBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad);\n    const der: Tensor[] = [xDer, filterDer];\n\n    if ($bias != null) {\n      const biasDer = getFusedBiasGradient($bias, dyActivation);\n      der.push(biasDer);\n    }\n    return der;\n  };\n\n  const inputs: FusedConv2DInputs = {\n    x: x4D,\n    filter: $filter,\n    bias: $bias,\n    preluActivationWeights: $preluActivationWeights\n  };\n\n  const attrs: FusedConv2DAttrs = {\n    strides,\n    pad,\n    dataFormat,\n    dilations,\n    dimRoundingMode,\n    activation,\n    leakyreluAlpha\n  };\n\n  // Depending on the the params passed in we will have different number of\n  // inputs and thus a a different number of elements in the gradient.\n  if (bias == null) {\n    const customOp =\n        customGrad((x4D: Tensor4D, filter: Tensor4D, save: GradSaveFunc) => {\n          let res: Tensor4D|Tensor3D =\n              // tslint:disable-next-line: no-unnecessary-type-assertion\n              ENGINE.runKernel(\n                  FusedConv2D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap);\n\n          save([filter, x4D, res]);\n\n          if (reshapedTo4D) {\n            // tslint:disable-next-line: no-unnecessary-type-assertion\n            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n                Tensor3D;\n          }\n\n          return {value: res, gradFunc: grad};\n        });\n    return customOp(x4D, $filter) as T;\n  } else {\n    const customOpWithBias = customGrad(\n        (x4D: Tensor4D, filter: Tensor4D, bias: Tensor, save: GradSaveFunc) => {\n          let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n              FusedConv2D, inputs as unknown as NamedTensorMap,\n              attrs as unknown as NamedAttrMap);\n\n          save([filter, x4D, res, bias]);\n\n          if (reshapedTo4D) {\n            // tslint:disable-next-line: no-unnecessary-type-assertion\n            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n                Tensor3D;\n          }\n\n          return {value: res, gradFunc: grad};\n        });\n\n    return customOpWithBias(x4D, $filter, $bias) as T;\n  }\n}\nexport const conv2d = /* @__PURE__ */ op({fusedConv2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nfunction depthwiseConv2dNativeBackpropFilter_<T extends Tensor3D|Tensor4D>(\n    x: T, dy: T, filterShape: [number, number, number, number],\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|ExplicitPadding,\n    dilations: [number, number]|number = [1, 1],\n    dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n  let x4D = x as Tensor4D;\n  if (x.rank === 3) {\n    x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n  }\n  let dy4D = dy as Tensor4D;\n  if (dy4D.rank === 3) {\n    dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n  }\n\n  const inputs: DepthwiseConv2dNativeBackpropFilterInputs = {x: x4D, dy: dy4D};\n  const attrs: DepthwiseConv2dNativeBackpropFilterAttrs =\n      {strides, pad, dimRoundingMode, dilations, filterShape};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             DepthwiseConv2dNativeBackpropFilter,\n             inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as Tensor4D;\n}\n\nexport const depthwiseConv2dNativeBackpropFilter =\n    op({depthwiseConv2dNativeBackpropFilter_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNativeBackpropInput, DepthwiseConv2dNativeBackpropInputAttrs, DepthwiseConv2dNativeBackpropInputInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nfunction depthwiseConv2dNativeBackpropInput_<T extends Tensor3D|Tensor4D>(\n    xShape: [number, number, number, number], dy: T, filter: Tensor4D,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|ExplicitPadding,\n    dilations: [number, number]|number = [1, 1],\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  let dy4D = dy as Tensor4D;\n  let reshapedTo4D = false;\n  if (dy.rank === 3) {\n    reshapedTo4D = true;\n    dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n  }\n\n  const inputs: DepthwiseConv2dNativeBackpropInputInputs = {dy: dy4D, filter};\n  const attrs: DepthwiseConv2dNativeBackpropInputAttrs =\n      {strides, pad, dimRoundingMode, dilations, inputShape: xShape};\n\n  const res =\n      // tslint:disable-next-line: no-unnecessary-type-assertion\n      ENGINE.runKernel(\n          DepthwiseConv2dNativeBackpropInput,\n          inputs as unknown as NamedTensorMap,\n          attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const depthwiseConv2dNativeBackpropInput =\n    op({depthwiseConv2dNativeBackpropInput_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport * as conv_util from '../conv_util';\nimport {depthwiseConv2d as unfusedDepthwiseConv2d} from '../depthwise_conv2d';\nimport {depthwiseConv2dNativeBackpropFilter} from '../depthwise_conv2d_native_backprop_filter';\nimport {depthwiseConv2dNativeBackpropInput} from '../depthwise_conv2d_native_backprop_input';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes depthwise 2D convolution, optionally fused with adding a\n * bias and applying an activation.\n *\n * Given a 4D `input` array and a `filter` array of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing\n * `inChannels` convolutional filters of depth 1, this op applies a\n * different filter to each input channel (expanding from 1 channel to\n * `channelMultiplier` channels for each), then concatenates the results\n * together. The output has `inChannels * channelMultiplier` channels.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](\n *     https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)\n * for more details.\n *\n * @param obj An object with the following properties:\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter tensor, rank 4, of shape\n *     `[filterHeight, filterWidth, inChannels, channelMultiplier]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @param bias Tensor to be added to the result.\n * @param activation Name of activation kernel (defaults to `linear`).\n * @param preluActivationWeights Tensor of prelu weights to be applied as part\n *     of a `prelu` activation, typically the same shape as `x`.\n * @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`\n *     activation.\n */\nfunction fusedDepthwiseConv2d_<T extends Tensor3D|Tensor4D>({\n  x,\n  filter,\n  strides,\n  pad,\n  dataFormat = 'NHWC',\n  dilations = [1, 1],\n  dimRoundingMode,\n  bias,\n  activation = 'linear',\n  preluActivationWeights,\n  leakyreluAlpha\n}: {\n  x: T|TensorLike,\n  filter: Tensor4D|TensorLike,\n  strides: [number, number]|number,\n  pad: 'valid'|'same'|number,\n  dataFormat?: 'NHWC'|'NCHW',\n  dilations?: [number, number]|number,\n  dimRoundingMode?: 'floor'|'round'|'ceil',\n  bias?: Tensor|TensorLike,\n  activation?: Activation,\n  preluActivationWeights?: Tensor,\n  leakyreluAlpha?: number\n}): T {\n  if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n    let result = unfusedDepthwiseConv2d(\n        x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);\n    if (bias != null) {\n      result = add(result, bias);\n    }\n\n    return applyActivation(\n               result, activation, preluActivationWeights, leakyreluAlpha) as T;\n  }\n\n  const $x = convertToTensor(x, 'x', 'depthwiseConv2d', 'float32');\n  const $filter =\n      convertToTensor(filter, 'filter', 'depthwiseConv2d', 'float32');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in fused depthwiseConv2d: input must be rank 4, but got ` +\n          `rank ${x4D.rank}.`);\n  util.assert(\n      $filter.rank === 4,\n      () => `Error in fused depthwiseConv2d: filter must be rank 4, ` +\n          `but got rank ${$filter.rank}.`);\n  util.assert(\n      x4D.shape[3] === $filter.shape[2],\n      () => `Error in fused depthwiseConv2d: number of input channels ` +\n          `(${x4D.shape[3]}) must match the inChannels dimension in ` +\n          `filter ${$filter.shape[2]}.`);\n  if (dilations == null) {\n    dilations = [1, 1];\n  }\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () =>\n          'Error in fused depthwiseConv2d: Either strides or dilations must ' +\n          `be 1. Got strides ${strides} and dilations '${dilations}'`);\n  conv_util.checkPadOnDimRoundingMode(\n      'fused depthwiseConv2d', pad, dimRoundingMode);\n  const convInfo = conv_util.computeConv2DInfo(\n      x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode,\n      true /* depthwise */);\n\n  let $bias: Tensor;\n  if (bias != null) {\n    $bias = convertToTensor(bias, 'bias', 'fused conv2d');\n    [$bias] = makeTypesMatch($bias, $x);\n\n    broadcast_util.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);\n  }\n\n  let $preluActivationWeights: Tensor;\n  if (preluActivationWeights != null) {\n    $preluActivationWeights = convertToTensor(\n        preluActivationWeights, 'prelu weights', 'fused depthwiseConv2d');\n  }\n\n  const grad = (dy: Tensor4D, saved: Tensor[]) => {\n    util.assert(\n        conv_util.tupleValuesAreOne(dilations),\n        () => 'Error in gradient of fused depthwiseConv2d: dilation rates ' +\n            `greater than 1 are not yet supported. Got dilations ` +\n            `'${dilations}'`);\n    const [$filter, x4D, y, bias] = saved;\n\n    const dyActivation = getFusedDyActivation(dy, y, activation) as Tensor4D;\n\n    const xDer = depthwiseConv2dNativeBackpropInput(\n        (x4D as Tensor4D).shape, dyActivation, $filter as Tensor4D, strides,\n        pad, dilations, dimRoundingMode);\n    const filterDer = depthwiseConv2dNativeBackpropFilter(\n        x4D as Tensor4D, dyActivation, ($filter as Tensor4D).shape, strides,\n        pad, dilations, dimRoundingMode);\n\n    if (bias != null) {\n      const biasDer = getFusedBiasGradient($bias, dyActivation);\n      return [xDer, filterDer, biasDer];\n    }\n    return [xDer, filterDer];\n  };\n\n  const inputs: FusedDepthwiseConv2DInputs = {\n    x: x4D,\n    filter: $filter,\n    bias: $bias,\n    preluActivationWeights: $preluActivationWeights\n  };\n  const attrs: FusedDepthwiseConv2DAttrs = {\n    strides,\n    pad,\n    dataFormat,\n    dilations,\n    dimRoundingMode,\n    activation,\n    leakyreluAlpha\n  };\n\n  // Depending on the the params passed in we will have different number of\n  // inputs and thus a a different number of elements in the gradient.\n  if (bias == null) {\n    const customOp =\n        customGrad((x4D: Tensor4D, filter: Tensor4D, save: GradSaveFunc) => {\n          // tslint:disable-next-line: no-unnecessary-type-assertion\n          let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n              FusedDepthwiseConv2D, inputs as unknown as NamedTensorMap,\n              attrs as unknown as NamedAttrMap);\n\n          save([filter, x4D, res]);\n\n          if (reshapedTo4D) {\n            // tslint:disable-next-line: no-unnecessary-type-assertion\n            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n                Tensor3D;\n          }\n\n          return {value: res, gradFunc: grad};\n        });\n    return customOp(x4D, $filter) as T;\n  } else {\n    const customOpWithBias = customGrad(\n        (x4D: Tensor4D, filter: Tensor4D, bias: Tensor, save: GradSaveFunc) => {\n          // tslint:disable-next-line: no-unnecessary-type-assertion\n          let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n              FusedDepthwiseConv2D, inputs as unknown as NamedTensorMap,\n              attrs as unknown as NamedAttrMap);\n\n          save([filter, x4D, res, bias]);\n\n          if (reshapedTo4D) {\n            // tslint:disable-next-line: no-unnecessary-type-assertion\n            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n                Tensor3D;\n          }\n\n          return {value: res, gradFunc: grad};\n        });\n\n    return customOpWithBias(x4D, $filter, $bias) as T;\n  }\n}\nexport const depthwiseConv2d = /* @__PURE__ */ op({fusedDepthwiseConv2d_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {matMul as unfusedMatMul} from '../mat_mul';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes the dot product of two matrices with optional activation and bias.\n *\n * ```js\n * const a = tf.tensor2d([-1, -2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const bias = tf.tensor2d([1, 2], [1, 2]);\n *\n * tf.fused.matMul({a, b, bias, activation: 'relu'}).print();\n * ```\n *\n * @param obj An object with the following properties:\n * - `a` First matrix in dot product operation.\n * - `b` Second matrix in dot product operation.\n * - `transposeA` If true, `a` is transposed before multiplication.\n * - `transposeB` If true, `b` is transposed before multiplication.\n * - `bias` Matrix to be added to the result.\n * - `activation` Name of activation kernel (defaults to `linear`).\n * - `preluActivationWeights` Tensor of prelu weights.\n * - `leakyreluAlpha` Alpha of leakyrelu.\n */\nfunction fusedMatMul_({\n  a,\n  b,\n  transposeA = false,\n  transposeB = false,\n  bias,\n  activation = 'linear',\n  preluActivationWeights,\n  leakyreluAlpha = 0.2,\n}: {\n  a: Tensor|TensorLike,\n  b: Tensor|TensorLike,\n  transposeA?: boolean,\n  transposeB?: boolean,\n  bias?: Tensor|TensorLike,\n  activation?: Activation,\n  preluActivationWeights?: Tensor\n  leakyreluAlpha?: number\n}): Tensor {\n    if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n      let result = unfusedMatMul(a, b, transposeA, transposeB);\n      if (bias != null) {\n        result = add(result, bias);\n      }\n\n      return applyActivation(\n                 result, activation, preluActivationWeights, leakyreluAlpha);\n    }\n\n    let $a = convertToTensor(a, 'a', 'fused matMul');\n    let $b = convertToTensor(b, 'b', 'fused matMul');\n    [$a, $b] = makeTypesMatch($a, $b);\n\n    const innerShapeA =\n        transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];\n    const innerShapeB =\n        transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];\n\n    const outerShapeA =\n        transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];\n    const outerShapeB =\n        transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];\n\n    const outerDimsA = $a.shape.slice(0, -2);\n    const outerDimsB = $b.shape.slice(0, -2);\n    const batchDimA = util.sizeFromShape(outerDimsA);\n    const batchDimB = util.sizeFromShape(outerDimsB);\n\n    util.assert(\n        innerShapeA === innerShapeB,\n        () => `Error in fused matMul: inner shapes (${innerShapeA}) and (` +\n            `${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +\n            `${$b.shape} and transposeA=${transposeA}` +\n            ` and transposeB=${transposeB} must match.`);\n\n    const outShapeOuterDims = broadcast_util.assertAndGetBroadcastShape(\n        $a.shape.slice(0, -2), $b.shape.slice(0, -2));\n    const outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);\n\n    const a3D: Tensor3D = transposeA ?\n        reshape($a, [batchDimA, innerShapeA, outerShapeA]) :\n        reshape($a, [batchDimA, outerShapeA, innerShapeA]);\n    const b3D: Tensor3D = transposeB ?\n        reshape($b, [batchDimB, outerShapeB, innerShapeB]) :\n        reshape($b, [batchDimB, innerShapeB, outerShapeB]);\n\n    let $bias: Tensor;\n    if (bias != null) {\n      $bias = convertToTensor(bias, 'bias', 'fused matMul');\n      [$bias] = makeTypesMatch($bias, $a);\n\n      broadcast_util.assertAndGetBroadcastShape(outShape, $bias.shape);\n    }\n\n    let $preluActivationWeights: Tensor;\n    if (preluActivationWeights != null) {\n      $preluActivationWeights = convertToTensor(\n          preluActivationWeights, 'prelu weights', 'fused matMul');\n    }\n\n    const grad = (dy: Tensor3D, saved: Tensor[]) => {\n      const [a3D, b3D, y, $bias] = saved;\n      // we reshape dy because the result of the forward is not\n      // necessarily going to be a 3d tensor due to a reshape done at the end of\n      // the customOp.\n      const dyActivation =\n          getFusedDyActivation(reshape(dy, y.shape), y, activation);\n      let aDer: Tensor;\n      let bDer: Tensor;\n\n      if (!transposeA && !transposeB) {\n        aDer = unfusedMatMul(dyActivation, b3D, false, true);\n        bDer = unfusedMatMul(a3D, dyActivation, true, false);\n      } else if (!transposeA && transposeB) {\n        aDer = unfusedMatMul(dyActivation, b3D, false, false);\n        bDer = unfusedMatMul(dyActivation, a3D, true, false);\n      } else if (transposeA && !transposeB) {\n        aDer = unfusedMatMul(b3D, dyActivation, false, true);\n        bDer = unfusedMatMul(a3D, dyActivation, false, false);\n      } else {\n        aDer = unfusedMatMul(b3D, dyActivation, true, true);\n        bDer = unfusedMatMul(dyActivation, a3D, true, true);\n      }\n\n      if (bias != null) {\n        const biasDer = getFusedBiasGradient($bias, dyActivation);\n        return [aDer, bDer, biasDer];\n      } else {\n        return [aDer, bDer];\n      }\n    };\n\n    const inputs: _FusedMatMulInputs = {\n      a: a3D,\n      b: b3D,\n      bias: $bias,\n      preluActivationWeights: $preluActivationWeights\n    };\n    const attrs: _FusedMatMulAttrs =\n        {transposeA, transposeB, activation, leakyreluAlpha};\n\n    // Depending on the the params passed in we will have different number of\n    // inputs and thus a a different number of elements in the gradient.\n    if (bias == null) {\n      const customOp =\n          customGrad((a3D: Tensor3D, b3D: Tensor3D, save: GradSaveFunc) => {\n            const res =\n                // tslint:disable-next-line: no-unnecessary-type-assertion\n                ENGINE.runKernel(\n                    _FusedMatMul, inputs as unknown as NamedTensorMap,\n                    attrs as unknown as NamedAttrMap) as Tensor;\n\n            save([a3D, b3D, res]);\n\n            return {value: reshape(res, outShape), gradFunc: grad};\n          });\n      return customOp(a3D, b3D);\n    } else {\n      const customOpWithBias = customGrad(\n          (a3D: Tensor3D, b3D: Tensor3D, $bias: Tensor, save: GradSaveFunc) => {\n            const res =\n                // tslint:disable-next-line: no-unnecessary-type-assertion\n                ENGINE.runKernel(\n                    _FusedMatMul, inputs as unknown as NamedTensorMap,\n                    attrs as unknown as NamedAttrMap) as Tensor;\n\n            save([a3D, b3D, res, $bias]);\n\n            return {value: reshape(res, outShape), gradFunc: grad};\n          });\n\n      return customOpWithBias(a3D, b3D, $bias);\n    }\n  }\n\n  export const matMul = /* @__PURE__ */ op({fusedMatMul_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {conv2d} from './fused/conv2d';\nimport {depthwiseConv2d} from './fused/depthwise_conv2d';\nimport {matMul} from './fused/mat_mul';\nimport {Activation} from './fused_types';\n\nexport {Activation, conv2d, depthwiseConv2d, matMul};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../../tensor';\nimport {op} from '../operation';\nimport {cosineWindow} from '../signal_ops_util';\n\n/**\n * Generate a hamming window.\n *\n * See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows\n *\n * ```js\n * tf.signal.hammingWindow(10).print();\n * ```\n * @param The length of window\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction hammingWindow_(windowLength: number): Tensor1D {\n  return cosineWindow(windowLength, 0.54, 0.46);\n}\nexport const hammingWindow = /* @__PURE__ */ op({hammingWindow_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../../tensor';\nimport {op} from '../operation';\nimport {cosineWindow} from '../signal_ops_util';\n\n/**\n * Generate a Hann window.\n *\n * See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows\n *\n * ```js\n * tf.signal.hannWindow(10).print();\n * ```\n * @param The length of window\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction hannWindow_(windowLength: number): Tensor1D {\n  return cosineWindow(windowLength, 0.5, 0.5);\n}\n\nexport const hannWindow = /* @__PURE__ */ op({hannWindow_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {concat} from '../concat';\nimport {fill} from '../fill';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {tensor2d} from '../tensor2d';\n\n/**\n * Expands input into frames of frameLength.\n * Slides a window size with frameStep.\n *\n * ```js\n * tf.signal.frame([1, 2, 3], 2, 1).print();\n * ```\n * @param signal The input tensor to be expanded\n * @param frameLength Length of each frame\n * @param frameStep The frame hop size in samples.\n * @param padEnd Whether to pad the end of signal with padValue.\n * @param padValue A number to use where the input signal does\n *     not exist when padEnd is True.\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction frame_(\n    signal: Tensor1D, frameLength: number, frameStep: number, padEnd = false,\n    padValue = 0): Tensor {\n  let start = 0;\n  const output: Tensor[] = [];\n  while (start + frameLength <= signal.size) {\n    output.push(slice(signal, start, frameLength));\n    start += frameStep;\n  }\n\n  if (padEnd) {\n    while (start < signal.size) {\n      const padLen = (start + frameLength) - signal.size;\n      const pad = concat([\n        slice(signal, start, frameLength - padLen), fill([padLen], padValue)\n      ]);\n      output.push(pad);\n      start += frameStep;\n    }\n  }\n\n  if (output.length === 0) {\n    return tensor2d([], [0, frameLength]);\n  }\n\n  return reshape(concat(output), [output.length, frameLength]);\n}\nexport const frame = /* @__PURE__ */ op({frame_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {enclosingPowerOfTwo} from '../signal_ops_util';\nimport {rfft} from '../spectral/rfft';\n\nimport {frame} from './frame';\nimport {hannWindow} from './hann_window';\n\n/**\n * Computes the Short-time Fourier Transform of signals\n * See: https://en.wikipedia.org/wiki/Short-time_Fourier_transform\n *\n * ```js\n * const input = tf.tensor1d([1, 1, 1, 1, 1])\n * tf.signal.stft(input, 3, 1).print();\n * ```\n * @param signal 1-dimensional real value tensor.\n * @param frameLength The window length of samples.\n * @param frameStep The number of samples to step.\n * @param fftLength The size of the FFT to apply.\n * @param windowFn A callable that takes a window length and returns 1-d tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction stft_(\n    signal: Tensor1D, frameLength: number, frameStep: number,\n    fftLength?: number,\n    windowFn: (length: number) => Tensor1D = hannWindow): Tensor {\n  if (fftLength == null) {\n    fftLength = enclosingPowerOfTwo(frameLength);\n  }\n  const framedSignal = frame(signal, frameLength, frameStep);\n  const windowedSignal = mul(framedSignal, windowFn(frameLength));\n  return rfft(windowedSignal, fftLength);\n}\nexport const stft = /* @__PURE__ */ op({stft_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {CropAndResize, CropAndResizeAttrs, CropAndResizeInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor1D, Tensor2D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Extracts crops from the input image tensor and resizes them using bilinear\n * sampling or nearest neighbor sampling (possibly with aspect ratio change)\n * to a common output size specified by cropSize.\n *\n * @param image 4d tensor of shape `[batch,imageHeight,imageWidth, depth]`,\n *     where imageHeight and imageWidth must be positive, specifying the\n *     batch of images from which to take crops\n * @param boxes 2d float32 tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the normalized\n *     coordinates of the box in the `boxInd[i]`th image in the batch\n * @param boxInd 1d int32 tensor of shape `[numBoxes]` with values in range\n *     `[0, batch)` that specifies the image that the `i`-th box refers to.\n * @param cropSize 1d int32 tensor of 2 elements `[cropHeigh, cropWidth]`\n *     specifying the size to which all crops are resized to.\n * @param method Optional string from `'bilinear' | 'nearest'`,\n *     defaults to bilinear, which specifies the sampling method for resizing\n * @param extrapolationValue A threshold for deciding when to remove boxes based\n *     on score. Defaults to 0.\n * @return A 4D tensor of the shape `[numBoxes,cropHeight,cropWidth,depth]`\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction cropAndResize_(\n    image: Tensor4D|TensorLike,\n    boxes: Tensor2D|TensorLike,\n    boxInd: Tensor1D|TensorLike,\n    cropSize: [number, number],\n    method: 'bilinear'|'nearest' = 'bilinear',\n    extrapolationValue = 0,\n    ): Tensor4D {\n  const $image = convertToTensor(image, 'image', 'cropAndResize');\n  const $boxes = convertToTensor(boxes, 'boxes', 'cropAndResize', 'float32');\n  const $boxInd = convertToTensor(boxInd, 'boxInd', 'cropAndResize', 'int32');\n\n  const numBoxes = $boxes.shape[0];\n\n  util.assert(\n      $image.rank === 4,\n      () => 'Error in cropAndResize: image must be rank 4,' +\n          `but got rank ${$image.rank}.`);\n  util.assert(\n      $boxes.rank === 2 && $boxes.shape[1] === 4,\n      () => `Error in cropAndResize: boxes must be have size [${numBoxes},4] ` +\n          `but had shape ${$boxes.shape}.`);\n  util.assert(\n      $boxInd.rank === 1 && $boxInd.shape[0] === numBoxes,\n      () => `Error in cropAndResize: boxInd must be have size [${numBoxes}] ` +\n          `but had shape ${$boxes.shape}.`);\n  util.assert(\n      cropSize.length === 2,\n      () => `Error in cropAndResize: cropSize must be of length 2, but got ` +\n          `length ${cropSize.length}.`);\n  util.assert(\n      cropSize[0] >= 1 && cropSize[1] >= 1,\n      () => `cropSize must be atleast [1,1], but was ${cropSize}`);\n  util.assert(\n      method === 'bilinear' || method === 'nearest',\n      () => `method must be bilinear or nearest, but was ${method}`);\n\n  const inputs:\n      CropAndResizeInputs = {image: $image, boxes: $boxes, boxInd: $boxInd};\n  const attrs: CropAndResizeAttrs = {method, extrapolationValue, cropSize};\n  const res = ENGINE.runKernel(\n      CropAndResize, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n  return res as Tensor4D;\n}\n\nexport const cropAndResize = /* @__PURE__ */ op({cropAndResize_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {FlipLeftRight, FlipLeftRightInputs} from '../../kernel_names';\nimport {Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {op} from '../operation';\n\n/**\n * Flips the image left to right. Currently available in the CPU, WebGL, and\n * WASM backends.\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n */\n/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */\nfunction flipLeftRight_(image: Tensor4D|TensorLike): Tensor4D {\n  const $image = convertToTensor(image, 'image', 'flipLeftRight', 'float32');\n\n  util.assert(\n      $image.rank === 4,\n      () => 'Error in flipLeftRight: image must be rank 4,' +\n          `but got rank ${$image.rank}.`);\n\n  const inputs: FlipLeftRightInputs = {image: $image};\n  const res =\n      ENGINE.runKernel(FlipLeftRight, inputs as unknown as NamedTensorMap, {});\n  return res as Tensor4D;\n}\n\nexport const flipLeftRight = /* @__PURE__ */ op({flipLeftRight_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D, Tensor3D, Tensor4D, Tensor5D, Tensor6D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {tile} from '../tile';\n\n/**\n * Converts images from grayscale to RGB format.\n *\n * @param image A grayscale tensor to convert. The `image`'s last dimension must\n *     be size 1 with at least a two-dimensional shape.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction grayscaleToRGB_<T extends Tensor2D|Tensor3D|Tensor4D|Tensor5D|\n                         Tensor6D>(image: T|TensorLike): T {\n  const $image = convertToTensor(image, 'image', 'grayscaleToRGB');\n\n  const lastDimsIdx = $image.rank - 1;\n  const lastDims = $image.shape[lastDimsIdx];\n\n  util.assert(\n      $image.rank >= 2,\n      () => 'Error in grayscaleToRGB: images must be at least rank 2, ' +\n          `but got rank ${$image.rank}.`);\n\n  util.assert(\n      lastDims === 1,\n      () => 'Error in grayscaleToRGB: last dimension of a grayscale image ' +\n          `should be size 1, but got size ${lastDims}.`);\n\n  const reps = new Array($image.rank);\n\n  reps.fill(1, 0, lastDimsIdx);\n  reps[lastDimsIdx] = 3;\n\n  return tile($image, reps);\n}\n\nexport const grayscaleToRGB = /* @__PURE__ */ op({grayscaleToRGB_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D, Tensor3D, Tensor4D, Tensor5D, Tensor6D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {cast} from '../cast';\nimport {einsum} from '../einsum';\nimport {expandDims} from '../expand_dims';\nimport {op} from '../operation';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Converts images from RGB format to grayscale.\n *\n * @param image A RGB tensor to convert. The `image`'s last dimension must\n *     be size 3 with at least a two-dimensional shape.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction rgbToGrayscale_<T extends Tensor2D|Tensor3D|Tensor4D|Tensor5D|\n                         Tensor6D>(image: T|TensorLike): T {\n  const $image = convertToTensor(image, 'image', 'RGBToGrayscale');\n\n  const lastDimsIdx = $image.rank - 1;\n  const lastDims = $image.shape[lastDimsIdx];\n\n  util.assert(\n      $image.rank >= 2,\n      () => 'Error in RGBToGrayscale: images must be at least rank 2, ' +\n          `but got rank ${$image.rank}.`);\n\n  util.assert(\n      lastDims === 3,\n      () => 'Error in RGBToGrayscale: last dimension of an RGB image ' +\n          `should be size 3, but got size ${lastDims}.`);\n\n  // Remember original dtype so we can convert back if needed\n  const origDtype = $image.dtype;\n  const fltImage = cast($image, 'float32');\n\n  const rgbWeights = tensor1d([0.2989, 0.5870, 0.1140]);\n\n  let grayFloat;\n  switch ($image.rank) {\n    case 2:\n      grayFloat = einsum('ij,j->i', fltImage, rgbWeights);\n      break;\n    case 3:\n      grayFloat = einsum('ijk,k->ij', fltImage, rgbWeights);\n      break;\n    case 4:\n      grayFloat = einsum('ijkl,l->ijk', fltImage, rgbWeights);\n      break;\n    case 5:\n      grayFloat = einsum('ijklm,m->ijkl', fltImage, rgbWeights);\n      break;\n    case 6:\n      grayFloat = einsum('ijklmn,n->ijklm', fltImage, rgbWeights);\n      break;\n    default:\n      throw new Error('Not a valid tensor rank.');\n  }\n  grayFloat = expandDims(grayFloat, -1);\n\n  return cast(grayFloat, origDtype) as T;\n}\n\nexport const rgbToGrayscale = /* @__PURE__ */ op({rgbToGrayscale_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Rotates the input image tensor counter-clockwise with an optional offset\n * center of rotation. Currently available in the CPU, WebGL, and WASM backends.\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n * @param radians The amount of rotation.\n * @param fillValue The value to fill in the empty space leftover\n *     after rotation. Can be either a single grayscale value (0-255), or an\n *     array of three numbers `[red, green, blue]` specifying the red, green,\n *     and blue channels. Defaults to `0` (black).\n * @param center The center of rotation. Can be either a single value (0-1), or\n *     an array of two numbers `[centerX, centerY]`. Defaults to `0.5` (rotates\n *     the image around its center).\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction rotateWithOffset_(\n    image: Tensor4D|TensorLike, radians: number,\n    fillValue: number|[number, number, number] = 0,\n    center: number|[number, number] = 0.5): Tensor4D {\n  const $image = convertToTensor(image, 'image', 'rotateWithOffset', 'float32');\n\n  util.assert(\n      $image.rank === 4,\n      () => 'Error in rotateWithOffset: image must be rank 4,' +\n          `but got rank ${$image.rank}.`);\n\n  const inputs: RotateWithOffsetInputs = {image: $image};\n  const attrs: RotateWithOffsetAttrs = {radians, fillValue, center};\n  const res = ENGINE.runKernel(\n      RotateWithOffset, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n  return res as Tensor4D;\n}\n\nexport const rotateWithOffset = /* @__PURE__ */ op({rotateWithOffset_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport * as util from '../util';\n\nfunction nonMaxSuppSanityCheck(\n    boxes: Tensor2D, scores: Tensor1D, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number, softNmsSigma?: number): {\n  maxOutputSize: number,\n  iouThreshold: number,\n  scoreThreshold: number,\n  softNmsSigma: number\n} {\n  if (iouThreshold == null) {\n    iouThreshold = 0.5;\n  }\n  if (scoreThreshold == null) {\n    scoreThreshold = Number.NEGATIVE_INFINITY;\n  }\n  if (softNmsSigma == null) {\n    softNmsSigma = 0.0;\n  }\n\n  const numBoxes = boxes.shape[0];\n  maxOutputSize = Math.min(maxOutputSize, numBoxes);\n\n  util.assert(\n      0 <= iouThreshold && iouThreshold <= 1,\n      () => `iouThreshold must be in [0, 1], but was '${iouThreshold}'`);\n  util.assert(\n      boxes.rank === 2,\n      () => `boxes must be a 2D tensor, but was of rank '${boxes.rank}'`);\n  util.assert(\n      boxes.shape[1] === 4,\n      () =>\n          `boxes must have 4 columns, but 2nd dimension was ${boxes.shape[1]}`);\n  util.assert(scores.rank === 1, () => 'scores must be a 1D tensor');\n  util.assert(\n      scores.shape[0] === numBoxes,\n      () => `scores has incompatible shape with boxes. Expected ${numBoxes}, ` +\n          `but was ${scores.shape[0]}`);\n  util.assert(\n      0 <= softNmsSigma && softNmsSigma <= 1,\n      () => `softNmsSigma must be in [0, 1], but was '${softNmsSigma}'`);\n  return {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma};\n}\n\nexport {nonMaxSuppSanityCheck};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV3} from '../../kernel_names';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @return A 1D tensor with the selected box indices.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppression_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY): Tensor1D {\n  const $boxes =\n      convertToTensor(boxes, 'boxes', 'nonMaxSuppression', 'float32');\n  const $scores =\n      convertToTensor(scores, 'scores', 'nonMaxSuppression', 'float32');\n\n  const inputs = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);\n  maxOutputSize = inputs.maxOutputSize;\n  iouThreshold = inputs.iouThreshold;\n  scoreThreshold = inputs.scoreThreshold;\n\n  const attrs = {maxOutputSize, iouThreshold, scoreThreshold};\n  return ENGINE.runKernel(\n      NonMaxSuppressionV3, {boxes: $boxes, scores: $scores}, attrs);\n}\n\nexport const nonMaxSuppression = /* @__PURE__ */ op({nonMaxSuppression_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Inserts a value into a sorted array. This method allows duplicate, meaning it\n * allows inserting duplicate value, in which case, the element will be inserted\n * at the lowest index of the value.\n * @param arr The array to modify.\n * @param element The element to insert.\n * @param comparator Optional. If no comparator is specified, elements are\n * compared using array_util.defaultComparator, which is suitable for Strings\n * and Numbers in ascending arrays. If the array contains multiple instances of\n * the target value, the left-most instance will be returned. To provide a\n * comparator, it should take 2 arguments to compare and return a negative,\n * zero, or a positive number.\n */\nexport function binaryInsert<T>(\n    arr: T[], element: T, comparator?: (a: T, b: T) => number) {\n  const index = binarySearch(arr, element, comparator);\n  const insertionPoint = index < 0 ? -(index + 1) : index;\n  arr.splice(insertionPoint, 0, element);\n}\n\n/**\n * Searches the array for the target using binary search, returns the index\n * of the found element, or position to insert if element not found. If no\n * comparator is specified, elements are compared using array_\n * util.defaultComparator, which is suitable for Strings and Numbers in\n * ascending arrays. If the array contains multiple instances of the target\n * value, the left-most instance will be returned.\n * @param arr The array to be searched in.\n * @param target The target to be searched for.\n * @param comparator Should take 2 arguments to compare and return a negative,\n *    zero, or a positive number.\n * @return Lowest index of the target value if found, otherwise the insertion\n *    point where the target should be inserted, in the form of\n *    (-insertionPoint - 1).\n */\nexport function binarySearch<T>(\n    arr: T[], target: T, comparator?: (a: T, b: T) => number) {\n  return binarySearch_(arr, target, comparator || defaultComparator);\n}\n\n/**\n * Compares its two arguments for order.\n * @param a The first element to be compared.\n * @param b The second element to be compared.\n * @return A negative number, zero, or a positive number as the first\n *     argument is less than, equal to, or greater than the second.\n */\nfunction defaultComparator<T>(a: T, b: T): number {\n  return a > b ? 1 : a < b ? -1 : 0;\n}\n\nfunction binarySearch_<T>(\n    arr: T[], target: T, comparator: (a: T, b: T) => number) {\n  let left = 0;\n  let right = arr.length;\n  let middle = 0;\n  let found = false;\n  while (left < right) {\n    middle = left + ((right - left) >>> 1);\n    const compareResult = comparator(target, arr[middle]);\n    if (compareResult > 0) {\n      left = middle + 1;\n    } else {\n      right = middle;\n      // If compareResult is 0, the value is found. We record it is found,\n      // and then keep looking because there may be duplicate.\n      found = !compareResult;\n    }\n  }\n\n  return found ? left : -left - 1;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray} from '../types';\nimport {binaryInsert} from './non_max_suppression_util';\n\n/**\n * Implementation of the NonMaxSuppression kernel shared between webgl and cpu.\n */\ninterface Candidate {\n  score: number;\n  boxIndex: number;\n  suppressBeginIndex: number;\n}\n\ninterface NonMaxSuppressionResult {\n  selectedIndices: number[];\n  selectedScores?: number[];\n  validOutputs?: number;\n}\n\nexport function nonMaxSuppressionV3Impl(\n    boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number): NonMaxSuppressionResult {\n  return nonMaxSuppressionImpl_(\n      boxes, scores, maxOutputSize, iouThreshold, scoreThreshold,\n      0 /* softNmsSigma */);\n}\n\nexport function nonMaxSuppressionV4Impl(\n    boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number,\n    padToMaxOutputSize: boolean): NonMaxSuppressionResult {\n  return nonMaxSuppressionImpl_(\n      boxes, scores, maxOutputSize, iouThreshold, scoreThreshold,\n      0 /* softNmsSigma */, false /* returnScoresTensor */,\n      padToMaxOutputSize /* padToMaxOutputSize */, true\n      /* returnValidOutputs */);\n}\n\nexport function nonMaxSuppressionV5Impl(\n    boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number,\n    softNmsSigma: number): NonMaxSuppressionResult {\n  return nonMaxSuppressionImpl_(\n      boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma,\n      true /* returnScoresTensor */);\n}\n\nfunction nonMaxSuppressionImpl_(\n    boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number, softNmsSigma: number,\n    returnScoresTensor = false, padToMaxOutputSize = false,\n    returnValidOutputs = false): NonMaxSuppressionResult {\n  // The list is sorted in ascending order, so that we can always pop the\n  // candidate with the largest score in O(1) time.\n  const candidates = [];\n\n  for (let i = 0; i < scores.length; i++) {\n    if (scores[i] > scoreThreshold) {\n      candidates.push({score: scores[i], boxIndex: i, suppressBeginIndex: 0});\n    }\n  }\n\n  candidates.sort(ascendingComparator);\n\n  // If softNmsSigma is 0, the outcome of this algorithm is exactly same as\n  // before.\n  const scale = softNmsSigma > 0 ? (-0.5 / softNmsSigma) : 0.0;\n\n  const selectedIndices: number[] = [];\n  const selectedScores: number[] = [];\n\n  while (selectedIndices.length < maxOutputSize && candidates.length > 0) {\n    const candidate = candidates.pop();\n    const {score: originalScore, boxIndex, suppressBeginIndex} = candidate;\n\n    if (originalScore < scoreThreshold) {\n      break;\n    }\n\n    // Overlapping boxes are likely to have similar scores, therefore we\n    // iterate through the previously selected boxes backwards in order to\n    // see if candidate's score should be suppressed. We use\n    // suppressBeginIndex to track and ensure a candidate can be suppressed\n    // by a selected box no more than once. Also, if the overlap exceeds\n    // iouThreshold, we simply ignore the candidate.\n    let ignoreCandidate = false;\n    for (let j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {\n      const iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);\n\n      if (iou >= iouThreshold) {\n        ignoreCandidate = true;\n        break;\n      }\n\n      candidate.score =\n          candidate.score * suppressWeight(iouThreshold, scale, iou);\n\n      if (candidate.score <= scoreThreshold) {\n        break;\n      }\n    }\n\n    // At this point, if `candidate.score` has not dropped below\n    // `scoreThreshold`, then we know that we went through all of the\n    // previous selections and can safely update `suppressBeginIndex` to the\n    // end of the selected array. Then we can re-insert the candidate with\n    // the updated score and suppressBeginIndex back in the candidate list.\n    // If on the other hand, `candidate.score` has dropped below the score\n    // threshold, we will not add it back to the candidates list.\n    candidate.suppressBeginIndex = selectedIndices.length;\n\n    if (!ignoreCandidate) {\n      // Candidate has passed all the tests, and is not suppressed, so\n      // select the candidate.\n      if (candidate.score === originalScore) {\n        selectedIndices.push(boxIndex);\n        selectedScores.push(candidate.score);\n      } else if (candidate.score > scoreThreshold) {\n        // Candidate's score is suppressed but is still high enough to be\n        // considered, so add back to the candidates list.\n        binaryInsert(candidates, candidate, ascendingComparator);\n      }\n    }\n  }\n\n  // NonMaxSuppressionV4 feature: padding output to maxOutputSize.\n  const validOutputs = selectedIndices.length;\n  const elemsToPad = maxOutputSize - validOutputs;\n\n  if (padToMaxOutputSize && elemsToPad > 0) {\n    selectedIndices.push(...new Array(elemsToPad).fill(0));\n    selectedScores.push(...new Array(elemsToPad).fill(0.0));\n  }\n\n  const result: NonMaxSuppressionResult = {selectedIndices};\n\n  if (returnScoresTensor) {\n    result['selectedScores'] = selectedScores;\n  }\n\n  if (returnValidOutputs) {\n    result['validOutputs'] = validOutputs;\n  }\n\n  return result;\n}\n\nfunction intersectionOverUnion(boxes: TypedArray, i: number, j: number) {\n  const iCoord = boxes.subarray(i * 4, i * 4 + 4);\n  const jCoord = boxes.subarray(j * 4, j * 4 + 4);\n  const yminI = Math.min(iCoord[0], iCoord[2]);\n  const xminI = Math.min(iCoord[1], iCoord[3]);\n  const ymaxI = Math.max(iCoord[0], iCoord[2]);\n  const xmaxI = Math.max(iCoord[1], iCoord[3]);\n  const yminJ = Math.min(jCoord[0], jCoord[2]);\n  const xminJ = Math.min(jCoord[1], jCoord[3]);\n  const ymaxJ = Math.max(jCoord[0], jCoord[2]);\n  const xmaxJ = Math.max(jCoord[1], jCoord[3]);\n  const areaI = (ymaxI - yminI) * (xmaxI - xminI);\n  const areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);\n  if (areaI <= 0 || areaJ <= 0) {\n    return 0.0;\n  }\n  const intersectionYmin = Math.max(yminI, yminJ);\n  const intersectionXmin = Math.max(xminI, xminJ);\n  const intersectionYmax = Math.min(ymaxI, ymaxJ);\n  const intersectionXmax = Math.min(xmaxI, xmaxJ);\n  const intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0.0) *\n      Math.max(intersectionXmax - intersectionXmin, 0.0);\n  return intersectionArea / (areaI + areaJ - intersectionArea);\n}\n\n// A Gaussian penalty function, this method always returns values in [0, 1].\n// The weight is a function of similarity, the more overlap two boxes are, the\n// smaller the weight is,meaning highly overlapping boxes will be significantly\n// penalized. On the other hand, a non-overlapping box will not be penalized.\nfunction suppressWeight(iouThreshold: number, scale: number, iou: number) {\n  const weight = Math.exp(scale * iou * iou);\n  return iou <= iouThreshold ? weight : 0.0;\n}\n\nfunction ascendingComparator(c1: Candidate, c2: Candidate) {\n  // For objects with same scores, we make the object with the larger index go\n  // first. In an array that pops from the end, this means that the object with\n  // the smaller index will be popped first. This ensures the same output as\n  // the TensorFlow python version.\n  return (c1.score - c2.score) ||\n      ((c1.score === c2.score) && (c2.boxIndex - c1.boxIndex));\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {nonMaxSuppressionV3Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This is the async version of `nonMaxSuppression`\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @return A 1D tensor with the selected box indices.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionAsync_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY): Promise<Tensor1D> {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n  const inputs = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);\n  maxOutputSize = inputs.maxOutputSize;\n  iouThreshold = inputs.iouThreshold;\n  scoreThreshold = inputs.scoreThreshold;\n\n  const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);\n  const boxesVals = boxesAndScores[0];\n  const scoresVals = boxesAndScores[1];\n\n  // We call a cpu based impl directly with the typedarray data  here rather\n  // than a kernel because all kernels are synchronous (and thus cannot await\n  // .data()).\n  const {selectedIndices} = nonMaxSuppressionV3Impl(\n      boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);\n  if ($boxes !== boxes) {\n    $boxes.dispose();\n  }\n  if ($scores !== scores) {\n    $scores.dispose();\n  }\n\n  return tensor1d(selectedIndices, 'int32');\n}\n\nexport const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This op also supports a Soft-NMS mode (cf.\n * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\n * of other overlapping boxes, therefore favoring different regions of the image\n * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`\n * parameter to be larger than 0.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @param softNmsSigma A float representing the sigma parameter for Soft NMS.\n *     When sigma is 0, it falls back to nonMaxSuppression.\n * @return A map with the following properties:\n *     - selectedIndices: A 1D tensor with the selected box indices.\n *     - selectedScores: A 1D tensor with the corresponding scores for each\n *       selected box.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppressionWithScore_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY,\n    softNmsSigma = 0.0): NamedTensorMap {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\n\n  const params = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n      softNmsSigma);\n  maxOutputSize = params.maxOutputSize;\n  iouThreshold = params.iouThreshold;\n  scoreThreshold = params.scoreThreshold;\n  softNmsSigma = params.softNmsSigma;\n\n  const inputs: NonMaxSuppressionV5Inputs = {boxes: $boxes, scores: $scores};\n  const attrs: NonMaxSuppressionV5Attrs =\n      {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const result = ENGINE.runKernel(\n                     NonMaxSuppressionV5, inputs as unknown as NamedTensorMap,\n                     attrs as unknown as NamedAttrMap) as Tensor[];\n\n  return {selectedIndices: result[0], selectedScores: result[1]};\n}\n\nexport const nonMaxSuppressionWithScore = /* @__PURE__ */ op({nonMaxSuppressionWithScore_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {nonMaxSuppressionV5Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This op also supports a Soft-NMS mode (cf.\n * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\n * of other overlapping boxes, therefore favoring different regions of the image\n * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`\n * parameter to be larger than 0.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @param softNmsSigma A float representing the sigma parameter for Soft NMS.\n *     When sigma is 0, it falls back to nonMaxSuppression.\n * @return A map with the following properties:\n *     - selectedIndices: A 1D tensor with the selected box indices.\n *     - selectedScores: A 1D tensor with the corresponding scores for each\n *       selected box.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionWithScoreAsync_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY,\n    softNmsSigma = 0.0): Promise<NamedTensorMap> {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n  const params = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n      softNmsSigma);\n  maxOutputSize = params.maxOutputSize;\n  iouThreshold = params.iouThreshold;\n  scoreThreshold = params.scoreThreshold;\n  softNmsSigma = params.softNmsSigma;\n\n  const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);\n  const boxesVals = boxesAndScores[0];\n  const scoresVals = boxesAndScores[1];\n\n  // We call a cpu based impl directly with the typedarray data  here rather\n  // than a kernel because all kernels are synchronous (and thus cannot await\n  // .data()).\n  const {selectedIndices, selectedScores} = nonMaxSuppressionV5Impl(\n      boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold,\n      softNmsSigma);\n\n  if ($boxes !== boxes) {\n    $boxes.dispose();\n  }\n  if ($scores !== scores) {\n    $scores.dispose();\n  }\n\n  return {\n    selectedIndices: tensor1d(selectedIndices, 'int32'),\n    selectedScores: tensor1d(selectedScores)\n  };\n}\n\nexport const nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union), with an option to pad results.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @param padToMaxOutputSize Defaults to false. If true, size of output\n *     `selectedIndices` is padded to maxOutputSize.\n * @return A map with the following properties:\n *     - selectedIndices: A 1D tensor with the selected box indices.\n *     - validOutputs: A scalar denoting how many elements in `selectedIndices`\n *       are valid. Valid elements occur first, then padding.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppressionPadded_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY,\n    padToMaxOutputSize = false): NamedTensorMap {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\n\n  const params = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n      null /* softNmsSigma */);\n  const $maxOutputSize = params.maxOutputSize;\n  const $iouThreshold = params.iouThreshold;\n  const $scoreThreshold = params.scoreThreshold;\n\n  const inputs: NonMaxSuppressionV4Inputs = {boxes: $boxes, scores: $scores};\n  const attrs: NonMaxSuppressionV4Attrs = {\n    maxOutputSize: $maxOutputSize,\n    iouThreshold: $iouThreshold,\n    scoreThreshold: $scoreThreshold,\n    padToMaxOutputSize\n  };\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const result = ENGINE.runKernel(\n                     NonMaxSuppressionV4, inputs as unknown as NamedTensorMap,\n                     attrs as unknown as NamedAttrMap) as Tensor[];\n\n  return {selectedIndices: result[0], validOutputs: result[1]};\n}\n\nexport const nonMaxSuppressionPadded = /* @__PURE__ */ op({nonMaxSuppressionPadded_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {nonMaxSuppressionV4Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {scalar} from '../scalar';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union), with an option to pad results.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @param padToMaxOutputSize Defaults to false. If true, size of output\n *     `selectedIndices` is padded to maxOutputSize.\n * @return A map with the following properties:\n *     - selectedIndices: A 1D tensor with the selected box indices.\n *     - validOutputs: A scalar denoting how many elements in `selectedIndices`\n *       are valid. Valid elements occur first, then padding.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionPaddedAsync_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY,\n    padToMaxOutputSize = false): Promise<NamedTensorMap> {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n  const params = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n      null /* softNmsSigma */);\n  const $maxOutputSize = params.maxOutputSize;\n  const $iouThreshold = params.iouThreshold;\n  const $scoreThreshold = params.scoreThreshold;\n\n  const [boxesVals, scoresVals] =\n      await Promise.all([$boxes.data(), $scores.data()]);\n\n  // We call a cpu based impl directly with the typedarray data here rather\n  // than a kernel because all kernels are synchronous (and thus cannot await\n  // .data()).\n  const {selectedIndices, validOutputs} = nonMaxSuppressionV4Impl(\n      boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold,\n      padToMaxOutputSize);\n\n  if ($boxes !== boxes) {\n    $boxes.dispose();\n  }\n  if ($scores !== scores) {\n    $scores.dispose();\n  }\n\n  return {\n    selectedIndices: tensor1d(selectedIndices, 'int32'),\n    validOutputs: scalar(validOutputs, 'int32')\n  };\n}\n\nexport const nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Bilinear resize a single 3D image or a batch of 3D images to a new shape.\n *\n * @param images The images, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param size The new shape `[newHeight, newWidth]` to resize the\n *     images to. Each channel is resized individually.\n * @param alignCorners Defaults to `false`. If true, rescale\n *     input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4\n *     corners of images and resized images. If false, rescale by\n *     `new_height / height`. Treat similarly the width dimension.\n * @param halfPixelCenters Defaults to `false`. Whether to assume pixel centers\n *     are at 0.5, which would make the floating point coordinates of the top\n *     left pixel 0.5, 0.5.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction resizeBilinear_<T extends Tensor3D|Tensor4D>(\n    images: T|TensorLike, size: [number, number], alignCorners = false,\n    halfPixelCenters = false): T {\n  const $images = convertToTensor(images, 'images', 'resizeBilinear');\n\n  util.assert(\n      $images.rank === 3 || $images.rank === 4,\n      () => `Error in resizeBilinear: x must be rank 3 or 4, but got ` +\n          `rank ${$images.rank}.`);\n  util.assert(\n      size.length === 2,\n      () => `Error in resizeBilinear: new shape must 2D, but got shape ` +\n          `${size}.`);\n  util.assert(\n      halfPixelCenters === false || alignCorners === false,\n      () => `Error in resizeBilinear: If halfPixelCenters is true, ` +\n          `alignCorners must be false.`);\n\n  let batchImages = $images as Tensor4D;\n  let reshapedTo4D = false;\n  if ($images.rank === 3) {\n    reshapedTo4D = true;\n    batchImages = reshape(\n        $images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);\n  }\n\n  const [] = size;\n\n  const inputs: ResizeBilinearInputs = {images: batchImages};\n  const attrs: ResizeBilinearAttrs = {alignCorners, halfPixelCenters, size};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  ResizeBilinear, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const resizeBilinear = /* @__PURE__ */ op({resizeBilinear_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * NearestNeighbor resize a batch of 3D images to a new shape.\n *\n * @param images The images, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param size The new shape `[newHeight, newWidth]` to resize the\n *     images to. Each channel is resized individually.\n * @param alignCorners Defaults to False. If true, rescale\n *     input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4\n *     corners of images and resized images. If false, rescale by\n *     `new_height / height`. Treat similarly the width dimension.\n * @param halfPixelCenters Defaults to `false`. Whether to assume pixels are of\n *      half the actual dimensions, and yield more accurate resizes. This flag\n *      would also make the floating point coordinates of the top left pixel\n *      0.5, 0.5.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction resizeNearestNeighbor_<T extends Tensor3D|Tensor4D>(\n    images: T|TensorLike, size: [number, number], alignCorners = false,\n    halfPixelCenters = false): T {\n  const $images = convertToTensor(images, 'images', 'resizeNearestNeighbor');\n\n  util.assert(\n      $images.rank === 3 || $images.rank === 4,\n      () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got ` +\n          `rank ${$images.rank}.`);\n  util.assert(\n      size.length === 2,\n      () =>\n          `Error in resizeNearestNeighbor: new shape must 2D, but got shape ` +\n          `${size}.`);\n  util.assert(\n      $images.dtype === 'float32' || $images.dtype === 'int32',\n      () => '`images` must have `int32` or `float32` as dtype');\n  util.assert(\n      halfPixelCenters === false || alignCorners === false,\n      () => `Error in resizeNearestNeighbor: If halfPixelCenters is true, ` +\n          `alignCorners must be false.`);\n  let batchImages = $images as Tensor4D;\n  let reshapedTo4D = false;\n  if ($images.rank === 3) {\n    reshapedTo4D = true;\n    batchImages = reshape(\n        $images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);\n  }\n  const [] = size;\n\n  const inputs: ResizeNearestNeighborInputs = {images: batchImages};\n  const attrs:\n      ResizeNearestNeighborAttrs = {alignCorners, halfPixelCenters, size};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  ResizeNearestNeighbor, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const resizeNearestNeighbor = /* @__PURE__ */ op({resizeNearestNeighbor_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { Tensor1D, Tensor3D } from '../../tensor';\nimport { tensor1d } from '../tensor1d';\nimport { TensorLike } from '../../types';\nimport { op } from '../operation';\nimport { cast } from '../cast';\nimport { split } from '../split';\nimport { bincount } from '../bincount';\nimport { lessEqual } from '../less_equal';\nimport { greater } from '../greater';\nimport { sum } from '../sum';\nimport { add } from '../add';\nimport { mul } from '../mul';\nimport { div } from '../div';\nimport { sub } from '../sub';\nimport { round } from '../round';\nimport { where } from '../where';\nimport { fill } from '../fill';\nimport {slice} from '../slice';\nimport { range } from '../range';\nimport { tensor } from '../tensor';\nimport * as util from '../../util';\nimport { convertToTensor } from '../../tensor_util_env';\n\n/**\n * Performs image binarization with corresponding threshold\n * (depends on the method)value, which creates a binary image from a grayscale.\n * @param image 3d tensor of shape [imageHeight,imageWidth, depth],\n * where imageHeight and imageWidth must be positive.The image color\n * range should be [0, 255].\n * @param method Optional string from `'binary' | 'otsu'`\n * which specifies the method for thresholding. Defaults to 'binary'.\n * @param inverted Optional boolean whichspecifies\n * if colours should be inverted. Defaults to false.\n * @param threshValue Optional number which defines threshold value from 0 to 1.\n * Defaults to 0.5.\n * @return A 3d tensor of shape [imageHeight,imageWidth, depth], which\n * contains binarized image.\n */\n\nfunction threshold_(\n    image: Tensor3D | TensorLike,\n    method = 'binary',\n    inverted = false,\n    threshValue = 0.5\n): Tensor3D {\n    const $image = convertToTensor(image, 'image', 'threshold');\n\n    /* 0.2989, 0.5870, 0.1140 are represent luma coefficients in CCIR601.\n\tReference for converting between RGB and grayscale: https://en.wikipedia.org/wiki/Luma_%28video%29  */\n\n    const RED_INTENCITY_COEF = 0.2989;\n    const GREEN_INTENCITY_COEF = 0.5870;\n    const BLUE_INTENCITY_COEF = 0.1140;\n    const totalPixelsInImage = $image.shape[0] * $image.shape[1];\n\n    let $threshold = mul(tensor1d([threshValue]), 255);\n    let r, g, b, grayscale;\n\n    util.assert(\n        $image.rank === 3,\n        () => 'Error in threshold: image must be rank 3,' +\n            `but got rank ${$image.rank}.`);\n\n    util.assert(\n        $image.shape[2] === 3 || $image.shape[2]=== 1,\n        () => 'Error in threshold: ' +\n            'image color channel must be equal to 3 or 1' +\n            `but got ${$image.shape[2]}.`);\n\n    util.assert(\n      $image.dtype === 'int32' || $image.dtype === 'float32',\n      () => 'Error in dtype: image dtype must be int32 or float32,' +\n          `but got dtype ${$image.dtype}.`);\n\n    util.assert(\n      method === 'otsu' || method === 'binary',\n      () => `Method must be binary or otsu, but was ${method}`);\n\n    if ($image.shape[2] === 3) {\n        [r, g, b] = split($image, [1, 1, 1], -1);\n        const $r = mul(r,RED_INTENCITY_COEF);\n        const $g = mul(g,GREEN_INTENCITY_COEF);\n        const $b = mul(b,BLUE_INTENCITY_COEF);\n        grayscale = add(add($r, $g), $b);\n    } else {\n        grayscale = image;\n    }\n\n    if (method === 'otsu') {\n        const $histogram = bincount(cast(round(grayscale), 'int32') as Tensor1D,\n            tensor([]),\n            256);\n        $threshold = otsu($histogram, totalPixelsInImage);\n    }\n\n    const invCondition = inverted ?\n        lessEqual(grayscale, $threshold) : greater(grayscale, $threshold);\n\n    const result = cast(mul(invCondition,255), 'int32');\n\n    return result as Tensor3D;\n}\n\nfunction otsu(histogram: Tensor1D, total: number):Tensor1D {\n\n    let bestThresh = tensor1d([-1]);\n    let bestInBetVar = tensor1d([0]);\n    let cInBetVar = tensor1d([0]);\n    let classFirst, classSecond, meanFirst,\n        meanSec, weightForeground, weightBack;\n\n    for (let index = 0; index < histogram.size-1; index++) {\n\n        classFirst = slice(histogram, 0, index + 1);\n\n        classSecond = slice(histogram,index + 1);\n\n        weightForeground = div(sum(classFirst),total);\n\n        weightBack = div(sum(classSecond),total);\n\n        const meanFirstDivA = sum(mul(classFirst, range(0, classFirst.size)));\n\n        meanFirst = div(meanFirstDivA, sum(classFirst) );\n\n        const meanSecFill = fill(classSecond.shape, classFirst.size);\n        const meanSecAdd = add(range(0,classSecond.size),meanSecFill);\n        const meanSecMul = mul(classSecond, (meanSecAdd));\n        meanSec = div(sum(meanSecMul), sum(classSecond));\n\n        const cInBetVarSubA = sub(meanFirst, meanSec);\n        const cInBetVarSubB = sub(meanFirst, meanSec);\n        const cInBetVarMul = mul(weightForeground, weightBack);\n        cInBetVar = mul(mul(cInBetVarMul,cInBetVarSubA), cInBetVarSubB);\n\n        const condition = greater(cInBetVar, bestInBetVar);\n\n        bestInBetVar = where(condition, cInBetVar, bestInBetVar);\n\n        bestThresh = where(condition, tensor1d([index]), bestThresh);\n\n    }\n    return bestThresh;\n}\n\nexport const threshold = /* @__PURE__ */ op({ threshold_ });\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../../engine';\nimport {Transform, TransformAttrs, TransformInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor2D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Applies the given transform(s) to the image(s).\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n * @param transforms Projective transform matrix/matrices. A tensor1d of length\n *     8 or tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0,\n *     b1, b2, c0, c1], then it maps the output point (x, y) to a transformed\n *     input point (x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k),\n *     where k = c0 x + c1 y + 1. The transforms are inverted compared to the\n *     transform mapping input points to output points.\n * @param interpolation Interpolation mode.\n *     Supported values: 'nearest', 'bilinear'. Default to 'nearest'.\n * @param fillMode Points outside the boundaries of the input are filled\n *     according to the given mode, one of 'constant', 'reflect', 'wrap',\n *     'nearest'. Default to 'constant'.\n *     'reflect': (d c b a | a b c d | d c b a ) The input is extended by\n *     reflecting about the edge of the last pixel.\n *     'constant': (k k k k | a b c d | k k k k) The input is extended by\n *     filling all values beyond the edge with the same constant value k.\n *     'wrap': (a b c d | a b c d | a b c d) The input is extended by\n *     wrapping around to the opposite edge.\n *     'nearest': (a a a a | a b c d | d d d d) The input is extended by\n *     the nearest pixel.\n * @param fillValue A float represents the value to be filled outside the\n *     boundaries when fillMode is 'constant'.\n * @param Output dimension after the transform, [height, width]. If undefined,\n *     output is the same size as input image.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction transform_(\n    image: Tensor4D|TensorLike, transforms: Tensor2D|TensorLike,\n    interpolation: 'nearest'|'bilinear' = 'nearest',\n    fillMode: 'constant'|'reflect'|'wrap'|'nearest' = 'constant', fillValue = 0,\n    outputShape?: [number, number]): Tensor4D {\n  const $image = convertToTensor(image, 'image', 'transform', 'float32');\n  const $transforms =\n      convertToTensor(transforms, 'transforms', 'transform', 'float32');\n\n  util.assert(\n      $image.rank === 4,\n      () => 'Error in transform: image must be rank 4,' +\n          `but got rank ${$image.rank}.`);\n\n  util.assert(\n      $transforms.rank === 2 &&\n          ($transforms.shape[0] === $image.shape[0] ||\n           $transforms.shape[0] === 1) &&\n          $transforms.shape[1] === 8,\n      () => `Error in transform: Input transform should be batch x 8 or 1 x 8`);\n\n  util.assert(\n      outputShape == null || outputShape.length === 2,\n      () =>\n          'Error in transform: outputShape must be [height, width] or null, ' +\n          `but got ${outputShape}.`);\n\n  const inputs: TransformInputs = {image: $image, transforms: $transforms};\n  const attrs:\n      TransformAttrs = {interpolation, fillMode, fillValue, outputShape};\n\n  return ENGINE.runKernel(\n      Transform, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const transform = /* @__PURE__ */ op({transform_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assert} from '../../util';\n\nimport {greaterEqual} from '../greater_equal';\nimport {less} from '../less';\nimport {lessEqual} from '../less_equal';\nimport {logicalAnd} from '../logical_and';\nimport {minimum} from '../minimum';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {range} from '../range';\nimport {reshape} from '../reshape';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {unstack} from '../unstack';\nimport {where} from '../where';\nimport {zeros} from '../zeros';\n\n/**\n * Copy a tensor setting everything outside a central band in each innermost\n * matrix to zero.\n *\n * The band part is computed as follows: Assume input has `k` dimensions\n * `[I, J, K, ..., M, N]`, then the output is a tensor with the same shape where\n * `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.\n * The indicator function\n * `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)`\n * `&& (num_upper < 0 || (n-m) <= num_upper)`\n *\n * ```js\n * const x = tf.tensor2d([[ 0,  1,  2, 3],\n *                        [-1,  0,  1, 2],\n *                        [-2, -1,  0, 1],\n *                        [-3, -2, -1, 0]]);\n * let y = tf.linalg.bandPart(x, 1, -1);\n * y.print(); // [[ 0,  1,  2, 3],\n *            //  [-1,  0,  1, 2],\n *            //  [ 0, -1,  0, 1],\n *            //  [ 0, 0 , -1, 0]]\n * let z = tf.linalg.bandPart(x, 2, 1);\n * z.print(); // [[ 0,  1,  0, 0],\n *            //  [-1,  0,  1, 0],\n *            //  [-2, -1,  0, 1],\n *            //  [ 0, -2, -1, 0]]\n * ```\n *\n * @param x Rank `k` tensor\n * @param numLower Number of subdiagonals to keep.\n *   If negative, keep entire lower triangle.\n * @param numUpper Number of subdiagonals to keep.\n *   If negative, keep entire upper triangle.\n * @returns Rank `k` tensor of the same shape as input.\n *   The extracted banded tensor.\n *\n * @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}\n */\nfunction bandPart_<T extends Tensor>(\n    a: T|TensorLike, numLower: number|Scalar, numUpper: number|Scalar): T {\n  const $a = convertToTensor(a, 'a', 'bandPart');\n  assert(\n      $a.rank >= 2,\n      () => `bandPart(): Rank must be at least 2, got ${$a.rank}.`);\n\n  const shape = $a.shape;\n  const [M, N] = $a.shape.slice(-2);\n\n  let $numLower: Scalar;\n  let $numUpper: Scalar;\n  if (typeof numLower === 'number') {\n    assert(\n        numLower % 1 === 0,\n        () => `bandPart(): numLower must be an integer, got ${numLower}.`);\n    assert(\n        numLower <= M,\n        () => `bandPart(): numLower (${numLower})` +\n            ` must not be greater than the number of rows (${M}).`);\n    $numLower =\n        convertToTensor(numLower < 0 ? M : numLower, 'numLower', 'bandPart') as\n        Scalar;\n  } else {\n    assert(\n        numLower.dtype === 'int32',\n        () => `bandPart(): numLower's dtype must be an int32.`);\n    // If numLower is a Scalar, checking `numLower <= M` could hurt performance,\n    // but minimum(numLower, M) could avoid unexpected results.\n    $numLower = where(less(numLower, 0), M, minimum(numLower, M)) as Scalar;\n  }\n\n  if (typeof numUpper === 'number') {\n    assert(\n        numUpper % 1 === 0,\n        () => `bandPart(): numUpper must be an integer, got ${numUpper}.`);\n    assert(\n        numUpper <= N,\n        () => `bandPart(): numUpper (${numUpper})` +\n            ` must not be greater than the number of columns (${N}).`);\n    $numUpper =\n        convertToTensor(numUpper < 0 ? N : numUpper, 'numUpper', 'bandPart') as\n        Scalar;\n  } else {\n    assert(\n        numUpper.dtype === 'int32',\n        () => `bandPart(): numUpper's dtype must be an int32.`);\n    $numUpper = where(less(numUpper, 0), N, minimum(numUpper, N)) as Scalar;\n  }\n\n  const i = reshape(range(0, M, 1, 'int32'), [-1, 1]);\n  const j = range(0, N, 1, 'int32');\n  const ij = sub(i, j);\n\n  const inBand =\n      logicalAnd(lessEqual(ij, $numLower), greaterEqual(ij, neg($numUpper)));\n\n  const zero = zeros([M, N], $a.dtype);\n\n  return reshape(\n             stack(unstack(reshape($a, [-1, M, N]))\n                       .map(mat => where(inBand, mat, zero))),\n             shape) as T;\n}\n\nexport const bandPart = /* @__PURE__ */ op({bandPart_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {assert} from '../../util';\n\nimport {div} from '../div';\nimport {mul} from '../mul';\nimport {norm} from '../norm';\nimport {op} from '../operation';\nimport {split} from '../split';\nimport {squeeze} from '../squeeze';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\n/**\n * Gram-Schmidt orthogonalization.\n *\n * ```js\n * const x = tf.tensor2d([[1, 2], [3, 4]]);\n * let y = tf.linalg.gramSchmidt(x);\n * y.print();\n * console.log('Orthogonalized:');\n * y.dot(y.transpose()).print();  // should be nearly the identity matrix.\n * console.log('First row direction maintained:');\n * const data = await y.array();\n * console.log(data[0][1] / data[0][0]);  // should be nearly 2.\n * ```\n *\n * @param xs The vectors to be orthogonalized, in one of the two following\n *   formats:\n *   - An Array of `tf.Tensor1D`.\n *   - A `tf.Tensor2D`, i.e., a matrix, in which case the vectors are the rows\n *     of `xs`.\n *   In each case, all the vectors must have the same length and the length\n *   must be greater than or equal to the number of vectors.\n * @returns The orthogonalized and normalized vectors or matrix.\n *   Orthogonalization means that the vectors or the rows of the matrix\n *   are orthogonal (zero inner products). Normalization means that each\n *   vector or each row of the matrix has an L2 norm that equals `1`.\n *\n * @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}\n */\nfunction gramSchmidt_(xs: Tensor1D[]|Tensor2D): Tensor1D[]|Tensor2D {\n  let inputIsTensor2D: boolean;\n  if (Array.isArray(xs)) {\n    inputIsTensor2D = false;\n    assert(\n        xs != null && xs.length > 0,\n        () => 'Gram-Schmidt process: input must not be null, undefined, or ' +\n            'empty');\n    const dim = xs[0].shape[0];\n    for (let i = 1; i < xs.length; ++i) {\n      assert(\n          xs[i].shape[0] === dim,\n          () =>\n              'Gram-Schmidt: Non-unique lengths found in the input vectors: ' +\n              `(${(xs as Tensor1D[])[i].shape[0]} vs. ${dim})`);\n    }\n  } else {\n    inputIsTensor2D = true;\n    xs = split(xs, xs.shape[0], 0).map(x => squeeze(x, [0]));\n  }\n\n  assert(\n      xs.length <= xs[0].shape[0],\n      () => `Gram-Schmidt: Number of vectors (${\n                (xs as Tensor1D[]).length}) exceeds ` +\n          `number of dimensions (${(xs as Tensor1D[])[0].shape[0]}).`);\n\n  const ys: Tensor1D[] = [];\n  const xs1d = xs;\n  for (let i = 0; i < xs.length; ++i) {\n    ys.push(ENGINE.tidy(() => {\n      let x = xs1d[i];\n      if (i > 0) {\n        for (let j = 0; j < i; ++j) {\n          const proj = mul(sum(mul(ys[j], x)), ys[j]);\n          x = sub(x, proj);\n        }\n      }\n      return div(x, norm(x, 'euclidean'));\n    }));\n  }\n\n  if (inputIsTensor2D) {\n    return stack(ys, 0) as Tensor2D;\n  } else {\n    return ys;\n  }\n}\n\nexport const gramSchmidt = /* @__PURE__ */ op({gramSchmidt_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../../engine';\nimport {dispose} from '../../globals';\nimport {Tensor, Tensor2D} from '../../tensor';\nimport {assert} from '../../util';\n\nimport {clone} from '../clone';\nimport {concat} from '../concat';\nimport {div} from '../div';\nimport {eye} from '../eye';\nimport {greater} from '../greater';\nimport {matMul} from '../mat_mul';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {norm} from '../norm';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {tensor2d} from '../tensor2d';\nimport {transpose} from '../transpose';\nimport {unstack} from '../unstack';\nimport {where} from '../where';\n\n/**\n * Compute QR decomposition of m-by-n matrix using Householder transformation.\n *\n * Implementation based on\n *   [http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf]\n * (http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf)\n *\n * ```js\n * const a = tf.tensor2d([[1, 2], [3, 4]]);\n * let [q, r] = tf.linalg.qr(a);\n * console.log('Q');\n * q.print();\n * console.log('R');\n * r.print();\n * console.log('Orthogonalized');\n * q.dot(q.transpose()).print()  // should be nearly the identity matrix.\n * console.log('Reconstructed');\n * q.dot(r).print(); // should be nearly [[1, 2], [3, 4]];\n * ```\n *\n * @param x The `tf.Tensor` to be QR-decomposed. Must have rank >= 2. Suppose\n *   it has the shape `[..., M, N]`.\n * @param fullMatrices An optional boolean parameter. Defaults to `false`.\n *   If `true`, compute full-sized `Q`. If `false` (the default),\n *   compute only the leading N columns of `Q` and `R`.\n * @returns An `Array` of two `tf.Tensor`s: `[Q, R]`. `Q` is a unitary matrix,\n *   i.e., its columns all have unit norm and are mutually orthogonal.\n *   If `M >= N`,\n *     If `fullMatrices` is `false` (default),\n *       - `Q` has a shape of `[..., M, N]`,\n *       - `R` has a shape of `[..., N, N]`.\n *     If `fullMatrices` is `true` (default),\n *       - `Q` has a shape of `[..., M, M]`,\n *       - `R` has a shape of `[..., M, N]`.\n *   If `M < N`,\n *     - `Q` has a shape of `[..., M, M]`,\n *     - `R` has a shape of `[..., M, N]`.\n * @throws If the rank of `x` is less than 2.\n *\n * @doc {heading:'Operations',\n *       subheading:'Linear Algebra',\n *       namespace:'linalg'}\n */\nfunction qr_(x: Tensor, fullMatrices = false): [Tensor, Tensor] {\n  assert(\n      x.rank >= 2,\n      () => `qr() requires input tensor to have a rank >= 2, but got rank ${\n          x.rank}`);\n\n  if (x.rank === 2) {\n    return qr2d(x as Tensor2D, fullMatrices);\n  } else {\n    // Rank > 2.\n    // TODO(cais): Below we split the input into individual 2D tensors,\n    //   perform QR decomposition on them and then stack the results back\n    //   together. We should explore whether this can be parallelized.\n    const outerDimsProd = x.shape.slice(0, x.shape.length - 2)\n                              .reduce((value, prev) => value * prev);\n    const x2ds = unstack(\n        reshape(\n            x,\n            [\n              outerDimsProd, x.shape[x.shape.length - 2],\n              x.shape[x.shape.length - 1]\n            ]),\n        0);\n    const q2ds: Tensor2D[] = [];\n    const r2ds: Tensor2D[] = [];\n    x2ds.forEach(x2d => {\n      const [q2d, r2d] = qr2d(x2d as Tensor2D, fullMatrices);\n      q2ds.push(q2d);\n      r2ds.push(r2d);\n    });\n    const q = reshape(stack(q2ds, 0), x.shape);\n    const r = reshape(stack(r2ds, 0), x.shape);\n    return [q, r];\n  }\n}\n\nfunction qr2d(x: Tensor2D, fullMatrices = false): [Tensor2D, Tensor2D] {\n  return ENGINE.tidy(() => {\n    assert(\n        x.shape.length === 2,\n        () => `qr2d() requires a 2D Tensor, but got a ${\n            x.shape.length}D Tensor.`);\n\n    const m = x.shape[0];\n    const n = x.shape[1];\n\n    let q = eye(m);    // Orthogonal transform so far.\n    let r = clone(x);  // Transformed matrix so far.\n\n    const one2D = tensor2d([[1]], [1, 1]);\n    let w: Tensor2D = clone(one2D);\n\n    const iters = m >= n ? n : m;\n    for (let j = 0; j < iters; ++j) {\n      // This tidy within the for-loop ensures we clean up temporary\n      // tensors as soon as they are no longer needed.\n      const rTemp = r;\n      const wTemp = w;\n      const qTemp = q;\n      [w, r, q] = ENGINE.tidy((): [Tensor2D, Tensor2D, Tensor2D] => {\n        // Find H = I - tau * w * w', to put zeros below R(j, j).\n        const rjEnd1 = slice(r, [j, j], [m - j, 1]);\n        const normX = norm(rjEnd1);\n        const rjj = slice(r, [j, j], [1, 1]);\n\n        // The sign() function returns 0 on 0, which causes division by zero.\n        const s = where(greater(rjj, 0), tensor2d([[-1]]), tensor2d([[1]]));\n\n        const u1 = sub(rjj, mul(s, normX));\n        const wPre = div(rjEnd1, u1);\n        if (wPre.shape[0] === 1) {\n          w = clone(one2D);\n        } else {\n          w = concat(\n              [\n                one2D,\n                slice(wPre, [1, 0], [wPre.shape[0] - 1, wPre.shape[1]]) as\n                    Tensor2D\n              ],\n              0);\n        }\n        const tau = neg(div(matMul(s, u1), normX)) as Tensor2D;\n\n        // -- R := HR, Q := QH.\n        const rjEndAll = slice(r, [j, 0], [m - j, n]);\n        const tauTimesW: Tensor2D = mul(tau, w);\n        const wT: Tensor2D = transpose(w);\n        if (j === 0) {\n          r = sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));\n        } else {\n          const rTimesTau: Tensor2D =\n              sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));\n          r = concat([slice(r, [0, 0], [j, n]), rTimesTau], 0);\n        }\n        const tawTimesWT: Tensor2D = transpose(tauTimesW);\n        const qAllJEnd = slice(q, [0, j], [m, q.shape[1] - j]);\n        if (j === 0) {\n          q = sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));\n        } else {\n          const qTimesTau: Tensor2D =\n              sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));\n          q = concat([slice(q, [0, 0], [m, j]), qTimesTau], 1);\n        }\n        return [w, r, q];\n      });\n      dispose([rTemp, wTemp, qTemp]);\n    }\n\n    if (!fullMatrices && m > n) {\n      q = slice(q, [0, 0], [m, n]);\n      r = slice(r, [0, 0], [n, n]);\n    }\n\n    return [q, r];\n  }) as [Tensor2D, Tensor2D];\n}\n\nexport const qr = /* @__PURE__ */ op({qr_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport enum Reduction {\n  NONE,\n  MEAN,\n  SUM,\n  SUM_BY_NONZERO_WEIGHTS\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {cast} from '../cast';\nimport {div} from '../div';\nimport {Reduction} from '../loss_ops_utils';\nimport {mean} from '../mean';\nimport {mul} from '../mul';\nimport {notEqual} from '../not_equal';\nimport {ones} from '../ones';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sum} from '../sum';\n\n/**\n * Computes the weighted loss between two tensors.\n *\n * @param losses Tensor of shape `[batch_size, d1, ..., dN]`.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `losses`, and must be broadcastable to `losses` (i.e., all\n *    dimensions must be either `1`, or the same as the corresponding\n *    `losses` dimension).\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction computeWeightedLoss_<T extends Tensor, O extends Tensor>(\n    losses: T|TensorLike, weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $losses = convertToTensor(losses, 'losses', 'computeWeightedLoss');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'computeWeightedLoss');\n  }\n\n  const weightedLoss = ($weights == null) ? $losses : mul($losses, $weights);\n\n  if (reduction === Reduction.NONE) {\n    return weightedLoss as O;\n  }\n  if (reduction === Reduction.SUM) {\n    return sum(weightedLoss);\n  }\n  if (reduction === Reduction.MEAN) {\n    if ($weights == null) {\n      return mean(weightedLoss);\n    } else {\n      const broadcastFactor = $losses.size / $weights.size;\n      const result = div(sum(weightedLoss), sum($weights));\n      return broadcastFactor > 1 ? div(result, scalar(broadcastFactor)) :\n                                   result as O;\n    }\n  }\n  if (reduction === Reduction.SUM_BY_NONZERO_WEIGHTS) {\n    if ($weights == null) {\n      return div(sum(weightedLoss), scalar($losses.size));\n    } else {\n      const broadcastedWeights = mul($weights, ones($losses.shape));\n\n      const numNonZeros =\n          cast(sum(notEqual(broadcastedWeights, scalar(0))), 'float32');\n      return div(sum(weightedLoss), numNonZeros);\n    }\n  }\n\n  throw Error(`Unknown reduction: ${reduction}`);\n}\nexport const computeWeightedLoss = /* @__PURE__ */ op({computeWeightedLoss_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {Reduction} from '../loss_ops_utils';\nimport {op} from '../operation';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the absolute difference loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction absoluteDifference_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'absoluteDifference');\n  const $predictions =\n      convertToTensor(predictions, 'predictions', 'absoluteDifference');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'absoluteDifference');\n  }\n  assertShapesMatch(\n      $labels.shape, $predictions.shape, 'Error in absoluteDifference: ');\n\n  const losses = abs(sub($labels, $predictions));\n  return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const absoluteDifference = /* @__PURE__ */ op({absoluteDifference_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the cosine distance loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param axis The dimension along which the cosine distance is computed.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction cosineDistance_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike, axis: number,\n    weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'cosineDistance');\n  const $predictions =\n      convertToTensor(predictions, 'predictions', 'cosineDistance');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'cosineDistance');\n  }\n  assertShapesMatch(\n      $labels.shape, $predictions.shape, 'Error in cosineDistance: ');\n\n  const one = scalar(1);\n  const losses = sub(one, sum(mul($labels, $predictions), axis, true));\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const cosineDistance = /* @__PURE__ */ op({cosineDistance_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {relu} from '../relu';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the Hinge loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction hingeLoss_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  let $labels = convertToTensor(labels, 'labels', 'hingeLoss');\n  const $predictions = convertToTensor(predictions, 'predictions', 'hingeLoss');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'hingeLoss');\n  }\n  assertShapesMatch($labels.shape, $predictions.shape, 'Error in hingeLoss: ');\n\n  const one = scalar(1);\n  // Convert binary labels to (-1, 1)\n  $labels = sub(mul(scalar(2), $labels), one);\n  const losses = relu(sub(one, mul($labels, $predictions)));\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const hingeLoss = /* @__PURE__ */ op({hingeLoss_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {add} from '../add';\nimport {Reduction} from '../loss_ops_utils';\nimport {minimum} from '../minimum';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {square} from '../square';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the Huber loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param delta Point where Huber loss changes from quadratic to linear.\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`.\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction huberLoss_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike, delta = 1.0,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'huberLoss');\n  const $predictions = convertToTensor(predictions, 'predictions', 'huberLoss');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'huberLoss');\n  }\n  assertShapesMatch($labels.shape, $predictions.shape, 'Error in huberLoss: ');\n\n  const deltaScalar = scalar(delta);\n  const error = abs(sub($predictions, $labels));\n  const quadratic = minimum(error, deltaScalar);\n  const linear = sub(error, quadratic);\n\n  const losses =\n      add(mul(scalar(0.5), square(quadratic)), mul(deltaScalar, linear));\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const huberLoss = /* @__PURE__ */ op({huberLoss_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {add} from '../add';\nimport {log} from '../log';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the log loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param epsilon A small increment to avoid taking log of zero\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction logLoss_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike, epsilon = 1e-7,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'logLoss');\n  const $predictions = convertToTensor(predictions, 'predictions', 'logLoss');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'logLoss');\n  }\n  assertShapesMatch($labels.shape, $predictions.shape, 'Error in logLoss: ');\n\n  const one = scalar(1);\n  const epsilonScalar = scalar(epsilon);\n\n  const l1 = neg(mul($labels, log(add($predictions, epsilonScalar))));\n  const l2 =\n      mul(sub(one, $labels), log(add(sub(one, $predictions), epsilonScalar)));\n  const losses = sub(l1, l2);\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const logLoss = /* @__PURE__ */ op({logLoss_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {op} from '../operation';\nimport {squaredDifference} from '../squared_difference';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the mean squared error between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction meanSquaredError_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'meanSquaredError');\n  const $predictions =\n      convertToTensor(predictions, 'predictions', 'meanSquaredError');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'meanSquaredError');\n  }\n  assertShapesMatch(\n      $labels.shape, $predictions.shape, 'Error in meanSquaredError: ');\n\n  const losses = squaredDifference($labels, $predictions);\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const meanSquaredError = /* @__PURE__ */ op({meanSquaredError_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {add} from '../add';\nimport {exp} from '../exp';\nimport {log1p} from '../log1p';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {relu} from '../relu';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\nfunction sigmoidCrossEntropyWithLogits_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, logits: T|TensorLike): O {\n  const $labels =\n      convertToTensor(labels, 'labels', 'sigmoidCrossEntropyWithLogits');\n  const $logits =\n      convertToTensor(logits, 'logits', 'sigmoidCrossEntropyWithLogits');\n  assertShapesMatch(\n      $labels.shape, $logits.shape, 'Error in sigmoidCrossEntropyWithLogits: ');\n\n  /**\n   * Implementation Details:\n   *\n   * For brevity, let `x = logits`, `z = labels`.  The logistic loss is\n   *     z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n   *   = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))\n   *   = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))\n   *   = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))\n   *   = (1 - z) * x + log(1 + exp(-x))\n   *   = x - x * z + log(1 + exp(-x))\n   *\n   *   For x < 0, to avoid overflow in exp(-x), we reformulate the above\n   *     x - x * z + log(1 + exp(-x))\n   *   = log(exp(x)) - x * z + log(1 + exp(-x))\n   *   = - x * z + log(1 + exp(x))\n   *\n   * Hence, to ensure stability and avoid overflow, the implementation uses\n   * this equivalent formulation:\n   *     max(x, 0) - x * z + log(1 + exp(-abs(x)))\n   */\n  const maxOutput = relu($logits);\n  const outputXTarget = mul($logits, $labels);\n  const sigmoidOutput = log1p(exp(neg(abs($logits))));\n\n  return add(sub(maxOutput, outputXTarget), sigmoidOutput);\n}\n\n/**\n * Computes the sigmoid cross entropy loss between two tensors.\n *\n * If labelSmoothing is nonzero, smooth the labels towards 1/2:\n *\n *   newMulticlassLabels = multiclassLabels * (1 - labelSmoothing)\n *                         + 0.5 * labelSmoothing\n *\n * @param multiClassLabels The ground truth output tensor of shape\n * [batch_size, num_classes], same dimensions as 'predictions'.\n * @param logits The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param labelSmoothing If greater than 0, then smooth the labels.\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' }\n */\nfunction sigmoidCrossEntropy_<T extends Tensor, O extends Tensor>(\n    multiClassLabels: T|TensorLike, logits: T|TensorLike,\n    weights?: Tensor|TensorLike, labelSmoothing = 0,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  let $multiClassLabels = convertToTensor(\n      multiClassLabels, 'multiClassLabels', 'sigmoidCrossEntropy');\n  const $logits = convertToTensor(logits, 'logits', 'sigmoidCrossEntropy');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'sigmoidCrossEntropy');\n  }\n  assertShapesMatch(\n      $multiClassLabels.shape, $logits.shape, 'Error in sigmoidCrossEntropy: ');\n\n  if (labelSmoothing > 0) {\n    const labelSmoothingScalar = scalar(labelSmoothing);\n    const one = scalar(1);\n    const half = scalar(0.5);\n\n    $multiClassLabels =\n        add(mul($multiClassLabels, sub(one, labelSmoothingScalar)),\n            mul(half, labelSmoothingScalar));\n  }\n  const losses = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);\n\n  return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const sigmoidCrossEntropy = /* @__PURE__ */ op({sigmoidCrossEntropy_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {customGrad} from '../../gradients';\nimport {Tensor} from '../../tensor';\nimport {GradSaveFunc} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {add} from '../add';\nimport {expandShapeToKeepDim} from '../axis_util';\nimport {cast} from '../cast';\nimport {div} from '../div';\nimport {exp} from '../exp';\nimport {logSumExp} from '../log_sum_exp';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes softmax cross entropy between logits and labels.\n *\n * Measures the probability error in discrete classification tasks in which\n * the classes are mutually exclusive (each entry is in exactly one class).\n * For example, each CIFAR-10 image is labeled with one and only one label: an\n * image can be a dog or a truck, but not both.\n *\n * `NOTE`: While the classes are mutually exclusive, their probabilities need\n * not be. All that is required is that each row of labels is a valid\n * probability distribution. If they are not, the computation of the gradient\n * will be incorrect.\n *\n * `WARNING`: This op expects unscaled logits, since it performs a softmax on\n * logits internally for efficiency. Do not call this op with the output of\n * softmax, as it will produce incorrect results.\n *\n * logits and labels must have the same shape, e.g. [batch_size, num_classes]\n * and the same dtype.\n * @param labels The labels array.\n * @param logits The logits array.\n * @param dim The dimension softmax would be performed on. Defaults to `-1`\n *     which indicates the last dimension.\n */\nfunction softmaxCrossEntropyWithLogits_<T extends Tensor, O extends Tensor>(\n    labels: T, logits: T, dim = -1): O {\n  if (dim === -1) {\n    dim = logits.rank - 1;\n  }\n\n  if (dim !== logits.rank - 1) {\n    throw Error(\n        `Softmax cross entropy along a non-last dimension is not yet ` +\n        `supported. Labels / logits was rank ${logits.rank} ` +\n        `and dim was ${dim}`);\n  }\n  // Use a custom gradient for numerical stability.\n  const customOp =\n      customGrad((labels: Tensor, logits: Tensor, save: GradSaveFunc) => {\n        // Reference:\n        //   1. http://cs231n.github.io/linear-classify/#softmax\n        //   2. https://blog.feedly.com/tricks-of-the-trade-logsumexp/\n        const keepDims = true;\n        const lse = logSumExp(logits, [dim], keepDims);\n        const logResult = sub(cast(logits, 'float32'), lse);\n        save([labels, logResult]);\n\n        const costVector = neg(mul(logResult, labels));\n        const value: O = sum(costVector, [dim]);\n\n        const gradFunc = (dy: O, saved: Tensor[]) => {\n          const [labels, logResult] = saved;\n          const dyShape = expandShapeToKeepDim(dy.shape, [dim]);\n          return [\n            mul(reshape(dy, dyShape),\n                sub(cast(labels, 'float32'), exp(logResult))),\n            mul(reshape(dy, dyShape),\n                sub(exp(logResult), cast(labels, 'float32'))),\n          ];\n        };\n        return {value, gradFunc};\n      });\n\n  return customOp(labels, logits);\n}\n\n/**\n * Computes the softmax cross entropy loss between two tensors.\n *\n * If labelSmoothing is nonzero, smooth the labels towards 1/2:\n *\n *   newOnehotLabels = onehotLabels * (1 - labelSmoothing)\n *                         + labelSmoothing / numClasses\n *\n * @param onehotLabels One hot encoded labels\n *    [batch_size, num_classes], same dimensions as 'predictions'.\n * @param logits The predicted outputs.\n * @param weights Tensor whose rank is either 0, or 1, and must be\n *    broadcastable to `loss`  of shape [batch_size]\n * @param labelSmoothing If greater than 0, then smooth the labels.\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' }\n */\nfunction softmaxCrossEntropy_<T extends Tensor, O extends Tensor>(\n    onehotLabels: T|TensorLike, logits: T|TensorLike,\n    weights?: Tensor|TensorLike, labelSmoothing = 0,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  let $onehotLabels =\n      convertToTensor(onehotLabels, 'onehotLabels', 'softmaxCrossEntropy');\n  const $logits = convertToTensor(logits, 'logits', 'softmaxCrossEntropy');\n  let $weights: Tensor = null;\n\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'softmaxCrossEntropy');\n  }\n\n  assertShapesMatch(\n      $onehotLabels.shape, $logits.shape, 'Error in softmaxCrossEntropy: ');\n\n  if (labelSmoothing > 0) {\n    const labelSmoothingScalar = scalar(labelSmoothing);\n    const one = scalar(1);\n    const numClasses = scalar($onehotLabels.shape[1]);\n\n    $onehotLabels =\n        add(mul($onehotLabels, sub(one, labelSmoothingScalar)),\n            div(labelSmoothingScalar, numClasses));\n  }\n\n  const losses = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);\n\n  return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const softmaxCrossEntropy = /* @__PURE__ */ op({softmaxCrossEntropy_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseFillEmptyRows, SparseFillEmptyRowsInputs} from '../../kernel_names';\nimport {Scalar, Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {ScalarLike, TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * The input SparseTensor is represented via the map of inputs {`indices`,\n * `values`, `denseShape`}. The output SparseTensor has the same `denseShape`\n * but with indices `outputIndices` and values `outputValues`. This op inserts a\n * single entry for every row that doesn't have any values. The index is created\n * as `[row, 0, ..., 0]` and the inserted value is `defaultValue`.\n *\n * For example, suppose `spInput` has shape [5, 6] and non-empty values:\n * [0, 1]: a\n * [0, 3]: b\n * [2, 0]: c\n * [3, 1]: d\n *\n * Rows 1 and 4 are empty, so the output will be of shape [5, 6] with values:\n * [0, 1]: a\n * [0, 3]: b\n * [1, 0]: `defaultValue`\n * [2, 0]: c\n * [3, 1]: d\n * [4, 0]: `defaultValue`\n *\n * The output SparseTensor will be in row-major order and will have the same\n * shape as the input.\n *\n * This op also returns an indicator vector shaped [dense_shape[0]] such that\n * emptyRowIndicator[i] = True iff row i was an empty row.\n *\n * And a reverse index map vector shaped [indices.shape[0]] that is used during\n * backpropagation, reverseIndexMap[i] = outi s.t. indices[i, j] ==\n * outputIndices[outi, j] for all j\n *\n * ```js\n * const result = tf.sparse.sparseFillEmptyRows(\n *   [[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]],\n *   [0, 10, 13, 14, 32, 33], [5, 6], -1);\n * console.log(result);\n * result['outputIndices'].print(); // [[0, 0], [1, 0], [1, 3], [1, 4],\n *                                  //  [2, 0], [3, 2], [3, 3], [4, 0]]\n * result['outputValues'].print(); // [0, 10, 13, 14,-1, 32, 33, -1]\n * result['emptyRowIndicator'].print(); // [false, false, true, false, true]\n * result['reverseIndexMap'].print(); // [0, 1, 2, 3, 5, 6]\n * ```\n * @param indices: 2-D. The indices of the sparse tensor.\n * @param values: 1-D. The values of the sparse tensor.\n * @param denseShape: 1-D. The shape of the sparse tensor.\n * @param defaultValue: 0-D. Default value to insert into location [row, 0, ...,\n *     0] for rows missing from the input sparse tensor.\n * @return A map with the following properties:\n *     - outputIndices\n *     - outputValues: 1-D. The values of the filled sparse tensor.\n *     - emptyRowIndicator: 1-D. Whether the dense row was missing in the input\n * sparse tensor.\n *     - reverseIndexMap: 1-D. A map from the input indices to the output\n * indices.\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseFillEmptyRows_(\n    indices: Tensor2D|TensorLike, values: Tensor1D|TensorLike,\n    denseShape: Tensor1D|TensorLike,\n    defaultValue: Scalar|ScalarLike): NamedTensorMap {\n  const $indices =\n      convertToTensor(indices, 'indices', 'sparseFillEmptyRows', 'int32');\n  const $values = convertToTensor(values, 'values', 'sparseFillEmptyRows');\n  const $denseShape =\n      convertToTensor(denseShape, 'denseShape', 'sparseFillEmptyRows', 'int32');\n  const $defaultValue = convertToTensor(\n      defaultValue, 'defaultValue', 'sparseFillEmptyRows', $values.dtype);\n\n  if ($indices.rank !== 2) {\n    throw new Error(`Indices should be Tensor2D but received shape\n        ${$indices.shape}`);\n  }\n  if ($values.rank !== 1) {\n    throw new Error(\n        `Values should be Tensor1D but received shape ${$values.shape}`);\n  }\n  if ($denseShape.rank !== 1) {\n    throw new Error(`Dense shape should be Tensor1D but received shape ${\n        $denseShape.shape}`);\n  }\n  if ($defaultValue.rank !== 0) {\n    throw new Error(`Default value should be a scalar but received shape ${\n        $defaultValue.shape}`);\n  }\n\n  const inputs: SparseFillEmptyRowsInputs = {\n    indices: $indices,\n    values: $values,\n    denseShape: $denseShape,\n    defaultValue: $defaultValue\n  };\n\n  const result: Tensor[] = ENGINE.runKernel(SparseFillEmptyRows, inputs as {});\n  return {\n    outputIndices: result[0],\n    outputValues: result[1],\n    emptyRowIndicator: result[2],\n    reverseIndexMap: result[3]\n  };\n}\n\nexport const sparseFillEmptyRows = /* @__PURE__ */ op({sparseFillEmptyRows_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseReshape, SparseReshapeInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * This operation has the same semantics as reshape on the represented dense\n * tensor. The `inputIndices` are recomputed based on the requested `newShape`.\n * If one component of `newShape` is the special value -1, the size of that\n * dimension is computed so that the total dense size remains constant. At most\n * one component of `newShape` can be -1. The number of dense elements implied\n * by `newShape` must be the same as the number of dense elements originally\n * implied by `inputShape`. Reshaping does not affect the order of values in the\n * SparseTensor. If the input tensor has rank R_in and N non-empty values, and\n * `newShape` has length R_out, then `inputIndices` has shape [N, R_in],\n * `inputShape` has length R_in, `outputIndices` has shape [N, R_out], and\n * `outputShape` has length R_out.\n *\n * ```js\n * const result = tf.sparse.sparseReshape(\n *   [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]],\n *   [2, 3, 6], [9, -1]);\n * console.log(result);\n * result['outputIndices'].print(); //[[0, 0], [0, 1], [1, 2], [4, 2], [8, 1]]\n * result['outputShape'].print(); // [9, 4]\n * ```\n * @param inputIndices: 2-D. N x R_in matrix with the indices of non-empty\n * values in a SparseTensor.\n * @param inputShape: 1-D. R_in Tensor1D with the input SparseTensor's dense\n * shape.\n * @param newShape: 1-D. R_out Tensor1D with the requested new dense shape.\n * @return A map with the following properties:\n *     - outputIndices: 2-D. N x R_out matrix with the updated indices of\n *       non-empty values in the output SparseTensor.\n *     - outputShape: 1-D. R_out vector with the full dense shape of the output\n *       SparseTensor. This is the same as newShape but with any -1 dimensions\n *        filled in.\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseReshape_(\n    inputIndices: Tensor2D|TensorLike, inputShape: Tensor1D|TensorLike,\n    newShape: Tensor1D|TensorLike): NamedTensorMap {\n  const $inputIndices =\n      convertToTensor(inputIndices, 'inputIndices', 'sparseReshape', 'int32');\n  const $inputShape =\n      convertToTensor(inputShape, 'inputShape', 'sparseReshape', 'int32');\n  const $newShape =\n      convertToTensor(newShape, 'newShape', 'sparseReshape', 'int32');\n\n  if ($inputIndices.rank !== 2) {\n    throw new Error(`Input indices should be Tensor2D but received shape\n        ${$inputIndices.shape}`);\n  }\n  if ($inputShape.rank !== 1) {\n    throw new Error(`Input shape should be Tensor1D but received shape ${\n        $inputShape.shape}`);\n  }\n  if ($newShape.rank !== 1) {\n    throw new Error(\n        `New shape should be Tensor1D but received shape ${$newShape.shape}`);\n  }\n\n  const inputs: SparseReshapeInputs = {\n    inputIndices: $inputIndices,\n    inputShape: $inputShape,\n    newShape: $newShape\n  };\n  const result: Tensor[] = ENGINE.runKernel(SparseReshape, inputs as {});\n  return {outputIndices: result[0], outputShape: result[1]};\n}\n\nexport const sparseReshape = /* @__PURE__ */ op({sparseReshape_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseSegmentMean, SparseSegmentMeanInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Computes the mean along sparse segments of a tensor.\n *\n * ```js\n * const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [6,7,8,9]]);\n * // Select two rows, one segment.\n * const result1 = tf.sparse.sparseSegmentMean(c,\n *                                           tf.tensor1d([0, 1], 'int32'),\n *                                           tf.tensor1d([0, 0], 'int32'));\n * result1.print(); // [[0, 0, 0, 0]]\n *\n * // Select two rows, two segments.\n * const result2 = tf.sparse.sparseSegmentMean(c,\n *                                             tf.tensor1d([0, 1], 'int32'),\n *                                             tf.tensor1d([0, 1], 'int32'));\n * result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]\n *\n * // Select all rows, two segments.\n * const result3 = tf.sparse.sparseSegmentMean(c,\n *                                             tf.tensor1d([0, 1, 2], 'int32'),\n *                                             tf.tensor1d([0, 1, 1], 'int32'));\n * result3.print(); // [[1.0, 2.0, 3.0, 4.0], [2.5, 2.5, 2.5, 2.5]]\n * ```\n * @param data: A Tensor of at least one dimension with data that will be\n *     assembled in the output.\n * @param indices: A 1-D Tensor with indices into data. Has same rank as\n *     segmentIds.\n * @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values\n *     should be sorted and can be repeated.\n * @return Has same shape as data, except for dimension 0 which has equal to\n *         the number of segments.\n *\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseSegmentMean_(\n    data: Tensor|TensorLike, indices: Tensor1D|TensorLike,\n    segmentIds: Tensor1D|TensorLike): Tensor {\n  const $data = convertToTensor(data, 'data', 'sparseSegmentMean');\n  const $indices =\n      convertToTensor(indices, 'indices', 'sparseSegmentMean', 'int32');\n  const $segmentIds =\n      convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentMean', 'int32');\n\n  if ($data.rank < 1) {\n    throw new Error(\n        `Data should be at least 1 dimensional but received scalar`);\n  }\n  if ($indices.rank !== 1) {\n    throw new Error(`Indices should be Tensor1D but received shape\n          ${$indices.shape}`);\n  }\n  if ($segmentIds.rank !== 1) {\n    throw new Error(`Segment ids should be Tensor1D but received shape\n          ${$segmentIds.shape}`);\n  }\n\n  const inputs: SparseSegmentMeanInputs = {\n    data: $data,\n    indices: $indices,\n    segmentIds: $segmentIds\n  };\n\n  return ENGINE.runKernel(SparseSegmentMean, inputs as {});\n}\n\nexport const sparseSegmentMean = /* @__PURE__ */ op({sparseSegmentMean_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseSegmentSum, SparseSegmentSumInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Computes the sum along sparse segments of a tensor.\n *\n * ```js\n * const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]);\n * // Select two rows, one segment.\n * const result1 = tf.sparse.sparseSegmentSum(c,\n *                                           tf.tensor1d([0, 1], 'int32'),\n *                                           tf.tensor1d([0, 0], 'int32'));\n * result1.print(); // [[0, 0, 0, 0]]\n *\n * // Select two rows, two segments.\n * const result2 = tf.sparse.sparseSegmentSum(c,\n *                                           tf.tensor1d([0, 1], 'int32'),\n *                                           tf.tensor1d([0, 1], 'int32'));\n * result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]\n *\n * // Select all rows, two segments.\n * const result3 = tf.sparse.sparseSegmentSum(c,\n *                                           tf.tensor1d([0, 1, 2], 'int32'),\n *                                           tf.tensor1d([0, 0, 1], 'int32'));\n * result3.print(); // [[0, 0, 0, 0], [5, 6, 7, 8]]\n * ```\n * @param data: A Tensor of at least one dimension with data that will be\n *     assembled in the output.\n * @param indices: A 1-D Tensor with indices into data. Has same rank as\n *     segmentIds.\n * @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values\n *     should be sorted and can be repeated.\n * @return Has same shape as data, except for dimension 0 which has equal to\n *         the number of segments.\n *\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseSegmentSum_(\n    data: Tensor|TensorLike, indices: Tensor1D|TensorLike,\n    segmentIds: Tensor1D|TensorLike): Tensor {\n  const $data = convertToTensor(data, 'data', 'sparseSegmentSum');\n  const $indices =\n      convertToTensor(indices, 'indices', 'sparseSegmentSum', 'int32');\n  const $segmentIds =\n      convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentSum', 'int32');\n\n  if ($data.rank < 1) {\n    throw new Error(\n        `Data should be at least 1 dimensional but received scalar`);\n  }\n  if ($indices.rank !== 1) {\n    throw new Error(`Indices should be Tensor1D but received shape\n         ${$indices.shape}`);\n  }\n  if ($segmentIds.rank !== 1) {\n    throw new Error(`Segment ids should be Tensor1D but received shape\n         ${$segmentIds.shape}`);\n  }\n\n  const inputs: SparseSegmentSumInputs = {\n    data: $data,\n    indices: $indices,\n    segmentIds: $segmentIds\n  };\n\n  return ENGINE.runKernel(SparseSegmentSum, inputs as {});\n}\n\nexport const sparseSegmentSum = /* @__PURE__ */ op({sparseSegmentSum_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringNGrams, StringNGramsAttrs, StringNGramsInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Creates ngrams from ragged string data.\n *\n * This op accepts a ragged tensor with 1 ragged dimension containing only\n * strings and outputs a ragged tensor with 1 ragged dimension containing ngrams\n * of that string, joined along the innermost axis.\n *\n * ```js\n * const result = tf.string.stringNGrams(\n *   ['a', 'b', 'c', 'd'], tf.tensor1d([0, 2, 4], 'int32'),\n *   '|', [1, 2], 'LP', 'RP', -1, false);\n * result['nGrams'].print(); // ['a', 'b', 'LP|a', 'a|b', 'b|RP',\n *                           //  'c', 'd', 'LP|c', 'c|d', 'd|RP']\n * result['nGramsSplits'].print(); // [0, 5, 10]\n * ```\n * @param data: The values tensor of the ragged string tensor to make ngrams out\n *     of. Must be a 1D string tensor.\n * @param dataSplits: The splits tensor of the ragged string tensor to make\n *     ngrams out of.\n * @param separator: The string to append between elements of the token. Use \"\"\n *     for no separator.\n * @param nGramWidths: The sizes of the ngrams to create.\n * @param leftPad: The string to use to pad the left side of the ngram sequence.\n *     Only used if pad_width !== 0.\n * @param rightPad: The string to use to pad the right side of the ngram\n *     sequence. Only used if pad_width !== 0.\n * @param padWidth: The number of padding elements to add to each side of each\n *     sequence. Note that padding will never be greater than `nGramWidths`-1\n *     regardless of this value. If `padWidth`=-1, then add max(`nGramWidths`)-1\n *     elements.\n * @param preserveShortSequences: If true, then ensure that at least one ngram\n *     is generated for each input sequence. In particular, if an input sequence\n *     is shorter than min(ngramWidth) + 2*padWidth, then generate a single\n *     ngram containing the entire sequence. If false, then no ngrams are\n *     generated for these short input sequences.\n * @return A map with the following properties:\n *     - nGrams: The values tensor of the output ngrams ragged tensor.\n *     - nGramsSplits: The splits tensor of the output ngrams ragged tensor.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringNGrams_(\n    data: Tensor1D|TensorLike, dataSplits: Tensor|TensorLike, separator: string,\n    nGramWidths: number[], leftPad: string, rightPad: string, padWidth: number,\n    preserveShortSequences: boolean): NamedTensorMap {\n  const $data = convertToTensor(data, 'data', 'stringNGrams', 'string');\n  if ($data.dtype !== 'string') {\n    throw new Error('Data must be of datatype string');\n  }\n  if ($data.shape.length !== 1) {\n    throw new Error(`Data must be a vector, saw: ${$data.shape}`);\n  }\n\n  const $dataSplits = convertToTensor(dataSplits, 'dataSplits', 'stringNGrams');\n  if ($dataSplits.dtype !== 'int32') {\n    throw new Error('Data splits must be of datatype int32');\n  }\n\n  const attrs: StringNGramsAttrs = {\n    separator,\n    nGramWidths,\n    leftPad,\n    rightPad,\n    padWidth,\n    preserveShortSequences\n  };\n\n  const inputs: StringNGramsInputs = {data: $data, dataSplits: $dataSplits};\n  const result: Tensor[] =\n      ENGINE.runKernel(StringNGrams, inputs as {}, attrs as {});\n  return {nGrams: result[0], nGramsSplits: result[1]};\n}\n\nexport const stringNGrams = /* @__PURE__ */ op({stringNGrams_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringSplit, StringSplitAttrs, StringSplitInputs} from '../../kernel_names';\nimport {Scalar, Tensor, Tensor1D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {ScalarLike, TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Split elements of `input` based on `delimiter` into a SparseTensor .\n *\n * Let N be the size of source (typically N will be the batch size). Split each\n * element of `input` based on `delimiter` and return a SparseTensor containing\n * the splitted tokens. Empty tokens are ignored if `skipEmpty` is set to True.\n *\n * `delimiter` can be empty, or a string of split characters. If `delimiter` is\n * an empty string, each element of `input` is split into individual\n * character strings. Otherwise every character of `delimiter` is a potential\n * split point.\n *\n * ```js\n * const result = tf.string.stringSplit(['hello world',  'a b c'], ' ');\n * result['indices'].print(); // [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2]]\n * result['values'].print(); // ['hello', 'world', 'a', 'b', 'c']\n * result['shape'].print(); // [2, 3]\n * ```\n * @param input: 1-D. Strings to split.\n * @param delimiter: 0-D. Delimiter characters, or empty string.\n * @param skipEmpty: Optional. If true, skip the empty strings from the result.\n *     Defaults to true.\n * @return A map with the following properties:\n *     - indices: A dense matrix of int32 representing the indices of the sparse\n *       tensor.\n *     - values: A vector of strings corresponding to the splited values.\n *     - shape: a length-2 vector of int32 representing the shape of the sparse\n * tensor, where the first value is N and the second value is the maximum number\n * of tokens in a single input entry.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringSplit_(\n    input: Tensor1D|TensorLike, delimiter: Scalar|ScalarLike,\n    skipEmpty = true): NamedTensorMap {\n  const $input = convertToTensor(input, 'input', 'stringSplit', 'string');\n  const $delimiter =\n      convertToTensor(delimiter, 'delimiter', 'stringSplit', 'string');\n\n  if ($input.rank !== 1) {\n    throw new Error(\n        `Input should be Tensor1D but received shape ${$input.shape}`);\n  }\n  if ($delimiter.rank !== 0) {\n    throw new Error(\n        `Delimiter should be a scalar but received shape ${$delimiter.shape}`);\n  }\n\n  const attrs: StringSplitAttrs = {skipEmpty};\n  const inputs: StringSplitInputs = {input: $input, delimiter: $delimiter};\n  const result: Tensor[] =\n      ENGINE.runKernel(StringSplit, inputs as {}, attrs as {});\n  return {indices: result[0], values: result[1], shape: result[2]};\n}\n\nexport const stringSplit = /* @__PURE__ */ op({stringSplit_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringToHashBucketFast, StringToHashBucketFastAttrs, StringToHashBucketFastInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Converts each string in the input Tensor to its hash mod by a number of\n * buckets.\n *\n * The hash function is deterministic on the content of the string within the\n * process and will never change. However, it is not suitable for cryptography.\n * This function may be used when CPU time is scarce and inputs are trusted or\n * unimportant. There is a risk of adversaries constructing inputs that all hash\n * to the same bucket.\n *\n * ```js\n * const result = tf.string.stringToHashBucketFast(\n *   ['Hello', 'TensorFlow', '2.x'], 3);\n * result.print(); // [0, 2, 2]\n * ```\n * @param input: The strings to assign a hash bucket.\n * @param numBuckets: The number of buckets.\n * @return A Tensor of the same shape as the input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringToHashBucketFast_(\n    input: Tensor|TensorLike, numBuckets: number): Tensor {\n  const $input =\n      convertToTensor(input, 'input', 'stringToHashBucketFast', 'string');\n  const attrs: StringToHashBucketFastAttrs = {numBuckets};\n\n  if (numBuckets <= 0) {\n    throw new Error(`Number of buckets must be at least 1`);\n  }\n\n  const inputs: StringToHashBucketFastInputs = {input: $input};\n  return ENGINE.runKernel(StringToHashBucketFast, inputs as {}, attrs as {});\n}\n\nexport const stringToHashBucketFast = /* @__PURE__ */ op({stringToHashBucketFast_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StaticRegexReplace, StaticRegexReplaceAttrs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Replace the match of a `pattern` in `input` with `rewrite`.\n *\n * ```js\n * const result = tf.string.staticRegexReplace(\n *     ['format       this   spacing      better'], ' +', ' ');\n * result.print(); // ['format this spacing better']\n * ```\n * @param input: A Tensor of type string. The text to be processed.\n * @param pattern: A string. The regular expression to match the input.\n * @param rewrite: A string. The rewrite to be applied to the matched\n *     expression.\n * @param replaceGlobal: An optional bool. Defaults to True. If True, the\n *     replacement is global, otherwise the replacement is done only on the\n *     first match.\n * @return A Tensor of type string.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction staticRegexReplace_(\n  input: Tensor | TensorLike, pattern: string, rewrite: string,\n  replaceGlobal=true): Tensor {\n\n  const $input = convertToTensor(input, 'input', 'staticRegexReplace',\n                                 'string');\n  const attrs: StaticRegexReplaceAttrs = {pattern, rewrite, replaceGlobal};\n  return ENGINE.runKernel(StaticRegexReplace, {x: $input},\n                          attrs as unknown as NamedAttrMap);\n}\n\nexport const staticRegexReplace = /* @__PURE__ */ op({staticRegexReplace_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Modularized ops.\nexport {abs} from './abs';\nexport {acos} from './acos';\nexport {acosh} from './acosh';\nexport {add} from './add';\nexport {addN} from './add_n';\nexport {all} from './all';\nexport {any} from './any';\nexport {argMax} from './arg_max';\nexport {argMin} from './arg_min';\nexport {asin} from './asin';\nexport {asinh} from './asinh';\nexport {atan} from './atan';\nexport {atan2} from './atan2';\nexport {atanh} from './atanh';\nexport {avgPool} from './avg_pool';\nexport {avgPool3d} from './avg_pool_3d';\nexport {basicLSTMCell} from './basic_lstm_cell';\nexport {batchToSpaceND} from './batch_to_space_nd';\nexport {batchNorm} from './batchnorm';\nexport {batchNorm2d} from './batchnorm2d';\nexport {batchNorm3d} from './batchnorm3d';\nexport {batchNorm4d} from './batchnorm4d';\nexport {bincount} from './bincount';\nexport {bitwiseAnd} from './bitwise_and';\nexport {broadcastArgs} from './broadcast_args';\nexport {broadcastTo} from './broadcast_to';\nexport {buffer} from './buffer';\nexport {cast} from './cast';\nexport {ceil} from './ceil';\nexport {clipByValue} from './clip_by_value';\nexport {clone} from './clone';\nexport {complex} from './complex';\nexport {concat} from './concat';\nexport {concat1d} from './concat_1d';\nexport {concat2d} from './concat_2d';\nexport {concat3d} from './concat_3d';\nexport {concat4d} from './concat_4d';\nexport {conv1d} from './conv1d';\nexport {conv2d} from './conv2d';\nexport {conv2dTranspose} from './conv2d_transpose';\nexport {conv3d} from './conv3d';\nexport {conv3dTranspose} from './conv3d_transpose';\nexport {cos} from './cos';\nexport {cosh} from './cosh';\nexport {cumprod} from './cumprod';\nexport {cumsum} from './cumsum';\nexport {denseBincount} from './dense_bincount';\nexport {depthToSpace} from './depth_to_space';\nexport {depthwiseConv2d} from './depthwise_conv2d';\nexport {diag} from './diag';\nexport {dilation2d} from './dilation2d';\nexport {div} from './div';\nexport {divNoNan} from './div_no_nan';\nexport {dot} from './dot';\nexport {einsum} from './einsum';\nexport {elu} from './elu';\nexport {ensureShape} from './ensure_shape';\nexport {equal} from './equal';\nexport {erf} from './erf';\nexport {euclideanNorm} from './euclidean_norm';\nexport {exp} from './exp';\nexport {expandDims} from './expand_dims';\nexport {expm1} from './expm1';\nexport {eye} from './eye';\nexport {fill} from './fill';\nexport {floor} from './floor';\nexport {floorDiv} from './floorDiv';\nexport {gather} from './gather';\nexport {greater} from './greater';\nexport {greaterEqual} from './greater_equal';\nexport {imag} from './imag';\nexport {isFinite} from './is_finite';\nexport {isInf} from './is_inf';\nexport {isNaN} from './is_nan';\nexport {leakyRelu} from './leaky_relu';\nexport {less} from './less';\nexport {lessEqual} from './less_equal';\nexport {linspace} from './linspace';\nexport {localResponseNormalization} from './local_response_normalization';\nexport {log} from './log';\nexport {log1p} from './log1p';\nexport {logSigmoid} from './log_sigmoid';\nexport {logSoftmax} from './log_softmax';\nexport {logSumExp} from './log_sum_exp';\nexport {logicalAnd} from './logical_and';\nexport {logicalNot} from './logical_not';\nexport {logicalOr} from './logical_or';\nexport {logicalXor} from './logical_xor';\nexport {lowerBound} from './lower_bound';\nexport {matMul} from './mat_mul';\nexport {max} from './max';\nexport {maxPool} from './max_pool';\nexport {maxPool3d} from './max_pool_3d';\nexport {maxPoolWithArgmax} from './max_pool_with_argmax';\nexport {maximum} from './maximum';\nexport {mean} from './mean';\nexport {meshgrid} from './meshgrid';\nexport {min} from './min';\nexport {minimum} from './minimum';\nexport {mirrorPad} from './mirror_pad';\nexport {mod} from './mod';\nexport {moments} from './moments';\nexport {mul} from './mul';\nexport {LSTMCellFunc, multiRNNCell} from './multi_rnn_cell';\nexport {multinomial} from './multinomial';\nexport {neg} from './neg';\nexport {notEqual} from './not_equal';\nexport {oneHot} from './one_hot';\nexport {ones} from './ones';\nexport {onesLike} from './ones_like';\nexport {outerProduct} from './outer_product';\nexport {pad} from './pad';\nexport {pad1d} from './pad1d';\nexport {pad2d} from './pad2d';\nexport {pad3d} from './pad3d';\nexport {pad4d} from './pad4d';\nexport {pool} from './pool';\nexport {pow} from './pow';\nexport {prelu} from './prelu';\nexport {print} from './print';\nexport {prod} from './prod';\nexport {raggedGather} from './ragged_gather';\nexport {raggedRange} from './ragged_range';\nexport {raggedTensorToTensor} from './ragged_tensor_to_tensor';\nexport {rand} from './rand';\nexport {randomGamma} from './random_gamma';\nexport {randomNormal} from './random_normal';\nexport {randomStandardNormal} from './random_standard_normal';\nexport {randomUniform} from './random_uniform';\nexport {randomUniformInt} from './random_uniform_int';\nexport {range} from './range';\nexport {real} from './real';\nexport {reciprocal} from './reciprocal';\nexport {relu} from './relu';\nexport {relu6} from './relu6';\nexport {reshape} from './reshape';\nexport {reverse} from './reverse';\nexport {reverse1d} from './reverse_1d';\nexport {reverse2d} from './reverse_2d';\nexport {reverse3d} from './reverse_3d';\nexport {reverse4d} from './reverse_4d';\nexport {round} from './round';\nexport {rsqrt} from './rsqrt';\nexport {scalar} from './scalar';\nexport {selu} from './selu';\nexport {separableConv2d} from './separable_conv2d';\nexport {setdiff1dAsync} from './setdiff1d_async';\nexport {sigmoid} from './sigmoid';\nexport {sign} from './sign';\nexport {sin} from './sin';\nexport {sinh} from './sinh';\nexport {slice} from './slice';\nexport {slice1d} from './slice1d';\nexport {slice2d} from './slice2d';\nexport {slice3d} from './slice3d';\nexport {slice4d} from './slice4d';\nexport {softmax} from './softmax';\nexport {softplus} from './softplus';\nexport {spaceToBatchND} from './space_to_batch_nd';\nexport {fft} from './spectral/fft';\nexport {ifft} from './spectral/ifft';\nexport {irfft} from './spectral/irfft';\nexport {rfft} from './spectral/rfft';\nexport {split} from './split';\nexport {sqrt} from './sqrt';\nexport {square} from './square';\nexport {squaredDifference} from './squared_difference';\nexport {squeeze} from './squeeze';\nexport {stack} from './stack';\nexport {step} from './step';\nexport {stridedSlice} from './strided_slice';\nexport {sub} from './sub';\nexport {sum} from './sum';\nexport {tan} from './tan';\nexport {tanh} from './tanh';\nexport {tensor} from './tensor';\nexport {tensor1d} from './tensor1d';\nexport {tensor2d} from './tensor2d';\nexport {tensor3d} from './tensor3d';\nexport {tensor4d} from './tensor4d';\nexport {tensor5d} from './tensor5d';\nexport {tensor6d} from './tensor6d';\nexport {tensorScatterUpdate} from './tensor_scatter_update';\nexport {tile} from './tile';\nexport {topk} from './topk';\nexport {truncatedNormal} from './truncated_normal';\nexport {unique} from './unique';\nexport {unsortedSegmentSum} from './unsorted_segment_sum';\nexport {unstack} from './unstack';\nexport {upperBound} from './upper_bound';\nexport {variable} from './variable';\nexport {where} from './where';\nexport {whereAsync} from './where_async';\nexport {zeros} from './zeros';\nexport {zerosLike} from './zeros_like';\n\nexport * from './boolean_mask';\nexport * from './transpose';\nexport * from './norm';\nexport * from './moving_average';\nexport * from './scatter_nd';\nexport * from './search_sorted';\nexport * from './sparse_to_dense';\nexport * from './gather_nd';\nexport * from './dropout';\nexport * from './signal_ops_util';\nexport * from './in_top_k';\n\nexport {op, OP_SCOPE_SUFFIX} from './operation';\n\nimport {rfft} from './spectral/rfft';\nimport {fft} from './spectral/fft';\nimport {ifft} from './spectral/ifft';\nimport {irfft} from './spectral/irfft';\nconst spectral = {\n  fft,\n  ifft,\n  rfft,\n  irfft\n};\n\nimport * as fused from './fused_ops';\n\nimport {hammingWindow} from './signal/hamming_window';\nimport {hannWindow} from './signal/hann_window';\nimport {frame} from './signal/frame';\nimport {stft} from './signal/stft';\nconst signal = {\n  hammingWindow,\n  hannWindow,\n  frame,\n  stft,\n};\n\n// Image Ops namespace\nimport {cropAndResize} from './image/crop_and_resize';\nimport {flipLeftRight} from './image/flip_left_right';\nimport {grayscaleToRGB} from './image/grayscale_to_rgb';\nimport {rgbToGrayscale} from './image/rgb_to_grayscale';\nimport {rotateWithOffset} from './image/rotate_with_offset';\nimport {nonMaxSuppression} from './image/non_max_suppression';\nimport {nonMaxSuppressionAsync} from './image/non_max_suppression_async';\nimport {nonMaxSuppressionWithScore} from './image/non_max_suppression_with_score';\nimport {nonMaxSuppressionWithScoreAsync} from './image/non_max_suppression_with_score_async';\nimport {nonMaxSuppressionPadded} from './image/non_max_suppression_padded';\nimport {nonMaxSuppressionPaddedAsync} from './image/non_max_suppression_padded_async';\nimport {resizeBilinear} from './image/resize_bilinear';\nimport {resizeNearestNeighbor} from './image/resize_nearest_neighbor';\nimport {threshold} from './image/threshold';\nimport {transform} from './image/transform';\nconst image = {\n  flipLeftRight,\n  grayscaleToRGB,\n  resizeNearestNeighbor,\n  resizeBilinear,\n  rgbToGrayscale,\n  rotateWithOffset,\n  cropAndResize,\n  nonMaxSuppression,\n  nonMaxSuppressionAsync,\n  nonMaxSuppressionWithScore,\n  nonMaxSuppressionWithScoreAsync,\n  nonMaxSuppressionPadded,\n  nonMaxSuppressionPaddedAsync,\n  threshold,\n  transform\n};\n\n// linalg namespace\nimport {bandPart} from './linalg/band_part';\nimport {gramSchmidt} from './linalg/gram_schmidt';\nimport {qr} from './linalg/qr';\nconst linalg = {\n  bandPart,\n  gramSchmidt,\n  qr\n};\n\n// losses namespace;\nimport {absoluteDifference} from './losses/absolute_difference';\nimport {computeWeightedLoss} from './losses/compute_weighted_loss';\nimport {cosineDistance} from './losses/cosine_distance';\nimport {hingeLoss} from './losses/hinge_loss';\nimport {huberLoss} from './losses/huber_loss';\nimport {logLoss} from './losses/log_loss';\nimport {meanSquaredError} from './losses/mean_squared_error';\nimport {sigmoidCrossEntropy} from './losses/sigmoid_cross_entropy';\nimport {softmaxCrossEntropy} from './losses/softmax_cross_entropy';\nconst losses = {\n  absoluteDifference,\n  computeWeightedLoss,\n  cosineDistance,\n  hingeLoss,\n  huberLoss,\n  logLoss,\n  meanSquaredError,\n  sigmoidCrossEntropy,\n  softmaxCrossEntropy\n};\n\nimport {sparseFillEmptyRows} from './sparse/sparse_fill_empty_rows';\nimport {sparseReshape} from './sparse/sparse_reshape';\nimport {sparseSegmentMean} from './sparse/sparse_segment_mean';\nimport {sparseSegmentSum} from './sparse/sparse_segment_sum';\nconst sparse = {\n  sparseFillEmptyRows,\n  sparseReshape,\n  sparseSegmentMean,\n  sparseSegmentSum\n};\n\nimport {stringNGrams} from './string/string_n_grams';\nimport {stringSplit} from './string/string_split';\nimport {stringToHashBucketFast} from './string/string_to_hash_bucket_fast';\nimport {staticRegexReplace} from './string/static_regex_replace';\n// tslint:disable-next-line:variable-name\nconst string = {\n  stringNGrams,\n  stringSplit,\n  stringToHashBucketFast,\n  staticRegexReplace,\n};\n\n// Second level exports.\nexport {image, linalg, losses, spectral, fused, signal, sparse, string};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {assert} from './util';\n\n/**\n * Types to support JSON-esque data structures internally.\n *\n * Internally ConfigDict's use camelCase keys and values where the\n * values are class names to be instantiated.  On the python side, these\n * will be snake_case.  Internally we allow Enums into the values for better\n * type safety, but these need to be converted to raw primitives (usually\n * strings) for round-tripping with python.\n *\n * toConfig returns the TS-friendly representation. model.toJSON() returns\n * the pythonic version as that's the portable format.  If you need to\n * python-ify a non-model level toConfig output, you'll need to use a\n * convertTsToPythonic from serialization_utils in -Layers.\n *\n */\nexport declare type ConfigDictValue =\n    boolean | number | string | null | ConfigDictArray | ConfigDict;\nexport declare interface ConfigDict {\n  [key: string]: ConfigDictValue;\n}\nexport declare interface ConfigDictArray extends Array<ConfigDictValue> {}\n\n/**\n * Type to represent the class-type of Serializable objects.\n *\n * Ie the class prototype with access to the constructor and any\n * static members/methods. Instance methods are not listed here.\n *\n * Source for this idea: https://stackoverflow.com/a/43607255\n */\nexport declare type SerializableConstructor<T extends Serializable> = {\n  // tslint:disable-next-line:no-any\n  new (...args: any[]): T; className: string; fromConfig: FromConfigMethod<T>;\n};\nexport declare type FromConfigMethod<T extends Serializable> =\n    (cls: SerializableConstructor<T>, config: ConfigDict) => T;\n\n/**\n * Maps to mapping between the custom object and its name.\n *\n * After registering a custom class, these two maps will add key-value pairs\n * for the class object and the registered name.\n *\n * Therefore we can get the relative registered name by calling\n * getRegisteredName() function.\n *\n * For example:\n * GLOBAL_CUSTOM_OBJECT: {key=registeredName: value=corresponding\n * CustomObjectClass}\n *\n * GLOBAL_CUSTOM_NAMES: {key=CustomObjectClass: value=corresponding\n * registeredName}\n *\n */\nconst GLOBAL_CUSTOM_OBJECT =\n    new Map<string, SerializableConstructor<Serializable>>();\n\nconst GLOBAL_CUSTOM_NAMES =\n    new Map<SerializableConstructor<Serializable>, string>();\n\n/**\n * Serializable defines the serialization contract.\n *\n * TFJS requires serializable classes to return their className when asked\n * to avoid issues with minification.\n */\nexport abstract class Serializable {\n  /**\n   * Return the class name for this class to use in serialization contexts.\n   *\n   * Generally speaking this will be the same thing that constructor.name\n   * would have returned.  However, the class name needs to be robust\n   * against minification for serialization/deserialization to work properly.\n   *\n   * There's also places such as initializers.VarianceScaling, where\n   * implementation details between different languages led to different\n   * class hierarchies and a non-leaf node is used for serialization purposes.\n   */\n  getClassName(): string {\n    return (this.constructor as SerializableConstructor<Serializable>)\n        .className;\n  }\n\n  /**\n   * Return all the non-weight state needed to serialize this object.\n   */\n  abstract getConfig(): ConfigDict;\n\n  /**\n   * Creates an instance of T from a ConfigDict.\n   *\n   * This works for most descendants of serializable.  A few need to\n   * provide special handling.\n   * @param cls A Constructor for the class to instantiate.\n   * @param config The Configuration for the object.\n   */\n  /** @nocollapse */\n  static fromConfig<T extends Serializable>(\n      cls: SerializableConstructor<T>, config: ConfigDict): T {\n    return new cls(config);\n  }\n}\n\n/**\n * Maps string keys to class constructors.\n *\n * Used during (de)serialization from the cross-language JSON format, which\n * requires the class name in the serialization format matches the class\n * names as used in Python, should it exist.\n */\nexport class SerializationMap {\n  private static instance: SerializationMap;\n  classNameMap: {\n    [className: string]:\n        [SerializableConstructor<Serializable>, FromConfigMethod<Serializable>]\n  };\n\n  private constructor() {\n    this.classNameMap = {};\n  }\n\n  /**\n   * Returns the singleton instance of the map.\n   */\n  static getMap(): SerializationMap {\n    if (SerializationMap.instance == null) {\n      SerializationMap.instance = new SerializationMap();\n    }\n    return SerializationMap.instance;\n  }\n\n  /**\n   * Registers the class as serializable.\n   */\n  static register<T extends Serializable>(cls: SerializableConstructor<T>) {\n    SerializationMap.getMap().classNameMap[cls.className] =\n        [cls, cls.fromConfig];\n  }\n}\n\n/**\n * Register a class with the serialization map of TensorFlow.js.\n *\n * This is often used for registering custom Layers, so they can be\n * serialized and deserialized.\n *\n * Example 1. Register the class without package name and specified name.\n *\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n *   static className = 'MyCustomLayer';\n *\n *   constructor(config) {\n *     super(config);\n *   }\n * }\n * tf.serialization.registerClass(MyCustomLayer);\n * console.log(tf.serialization.GLOBALCUSTOMOBJECT.get(\"Custom>MyCustomLayer\"));\n * console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));\n * ```\n *\n * Example 2. Register the class with package name: \"Package\" and specified\n * name: \"MyLayer\".\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n *   static className = 'MyCustomLayer';\n *\n *   constructor(config) {\n *     super(config);\n *   }\n * }\n * tf.serialization.registerClass(MyCustomLayer, \"Package\", \"MyLayer\");\n * console.log(tf.serialization.GLOBALCUSTOMOBJECT.get(\"Package>MyLayer\"));\n * console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));\n * ```\n *\n * Example 3. Register the class with specified name: \"MyLayer\".\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n *   static className = 'MyCustomLayer';\n *\n *   constructor(config) {\n *     super(config);\n *   }\n * }\n * tf.serialization.registerClass(MyCustomLayer, undefined, \"MyLayer\");\n * console.log(tf.serialization.GLOBALCUSTOMOBJECT.get(\"Custom>MyLayer\"));\n * console.log(tf.serialization.GLOBALCUSTOMNAMES.get(MyCustomLayer));\n * ```\n *\n * Example 4. Register the class with specified package name: \"Package\".\n * ```js\n * class MyCustomLayer extends tf.layers.Layer {\n *   static className = 'MyCustomLayer';\n *\n *   constructor(config) {\n *     super(config);\n *   }\n * }\n * tf.serialization.registerClass(MyCustomLayer, \"Package\");\n * console.log(tf.serialization.GLOBALCUSTOMOBJECT\n * .get(\"Package>MyCustomLayer\"));\n * console.log(tf.serialization.GLOBALCUSTOMNAMES\n * .get(MyCustomLayer));\n * ```\n *\n * @param cls The class to be registered. It must have a public static member\n *   called `className` defined and the value must be a non-empty string.\n * @param pkg The package name that this class belongs to. This used to define\n *     the key in GlobalCustomObject. If not defined, it defaults to `Custom`.\n * @param name The name that user specified. It defaults to the actual name of\n *     the class as specified by its static `className` property.\n * @doc {heading: 'Models', subheading: 'Serialization', ignoreCI: true}\n */\nexport function registerClass<T extends Serializable>(\n    cls: SerializableConstructor<T>, pkg?: string, name?: string) {\n  assert(\n      cls.className != null,\n      () => `Class being registered does not have the static className ` +\n          `property defined.`);\n  assert(\n      typeof cls.className === 'string',\n      () => `className is required to be a string, but got type ` +\n          typeof cls.className);\n  assert(\n      cls.className.length > 0,\n      () => `Class being registered has an empty-string as its className, ` +\n          `which is disallowed.`);\n\n  if (typeof pkg === 'undefined') {\n    pkg = 'Custom';\n  }\n\n  if (typeof name === 'undefined') {\n    name = cls.className;\n  }\n\n  const className = name;\n  const registerName = pkg + '>' + className;\n\n  SerializationMap.register(cls);\n  GLOBAL_CUSTOM_OBJECT.set(registerName, cls);\n  GLOBAL_CUSTOM_NAMES.set(cls, registerName);\n\n  return cls;\n}\n\n/**\n * Get the registered name of a class. If the class has not been registered,\n * return the class name.\n *\n * @param cls The class we want to get register name for. It must have a public\n *     static member called `className` defined.\n * @returns registered name or class name.\n */\nexport function getRegisteredName<T extends Serializable>(\n    cls: SerializableConstructor<T>) {\n  if (GLOBAL_CUSTOM_NAMES.has(cls)) {\n    return GLOBAL_CUSTOM_NAMES.get(cls);\n  } else {\n    return cls.className;\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {dispose} from '../globals';\nimport {variableGrads} from '../gradients';\nimport {scalar} from '../ops/ops';\nimport {Serializable} from '../serialization';\nimport {Scalar, Variable} from '../tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\n/**\n * A variable that belongs to an optimizer.\n *\n * The `originalName` field is required for keeping track of the canonical\n * name of the variable, which is usually the name of the model weight that\n * the variable is related to plus a suffix, e.g., 'dense1/kernel/momentum'.\n * The name of the `Variable` object itself cannot be used directly due to\n * possible deduplication: Every `Variable` must have a unique name but more\n * than one optimizer objects of the same type may be created for the same model\n * or the same `Variable`.\n */\nexport interface OptimizerVariable {\n  originalName: string;\n  variable: Variable;\n}\n\n/** @doc {heading: 'Training', subheading: 'Classes', namespace: 'train'} */\nexport abstract class Optimizer extends Serializable {\n  protected iterations_: number;\n\n  /**\n   * Executes `f()` and minimizes the scalar output of `f()` by computing\n   * gradients of y with respect to the list of trainable variables provided by\n   * `varList`. If no list is provided, it defaults to all trainable variables.\n   *\n   * @param f The function to execute and whose output to minimize.\n   * @param returnCost Whether to return the scalar cost value produced by\n   * executing `f()`.\n   * @param varList An optional list of variables to update. If specified, only\n   * the trainable variables in varList will be updated by minimize. Defaults to\n   * all trainable variables.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers'}\n   */\n  minimize(f: () => Scalar, returnCost = false, varList?: Variable[]): Scalar\n      |null {\n    const {value, grads} = this.computeGradients(f, varList);\n\n    if (varList != null) {\n      const gradArray: NamedTensor[] =\n          varList.map(v => ({name: v.name, tensor: grads[v.name]}));\n      this.applyGradients(gradArray);\n    } else {\n      this.applyGradients(grads);\n    }\n\n    // Dispose gradients.\n    dispose(grads);\n\n    if (returnCost) {\n      return value;\n    } else {\n      value.dispose();\n      return null;\n    }\n  }\n\n  /**\n   * The number of iterations that this optimizer instance has been invoked for.\n   */\n  get iterations(): number {\n    if (this.iterations_ == null) {\n      this.iterations_ = 0;\n    }\n    return this.iterations_;\n  }\n\n  protected incrementIterations() {\n    this.iterations_ = this.iterations + 1;\n  }\n\n  /**\n   * Executes f() and computes the gradient of the scalar output of f() with\n   * respect to the list of trainable variables provided by `varList`. If no\n   * list is provided, it defaults to all trainable variables.\n   *\n   * @param f The function to execute and whose output to use for computing\n   * gradients with respect to variables.\n   * @param varList An optional list of variables to compute gradients with\n   * respect to. If specified, only the trainable variables in varList will have\n   * gradients computed with respect to. Defaults to all trainable variables.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers'}\n   */\n  computeGradients(f: () => Scalar, varList?: Variable[]):\n      {value: Scalar, grads: NamedTensorMap} {\n    return variableGrads(f, varList);\n  }\n\n  /**\n   * Updates variables by using the computed gradients.\n   *\n   * @param variableGradients A mapping of variable name to its gradient value.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers'}\n   */\n  abstract applyGradients(variableGradients: NamedTensorMap|\n                          NamedTensor[]): void;\n\n  /**\n   * Dispose the variables (if any) owned by this optimizer instance.\n   */\n  dispose(): void {\n    if (this.iterations_ != null) {\n      dispose(this.iterations_);\n    }\n  }\n\n  async saveIterations(): Promise<NamedTensor> {\n    if (this.iterations_ == null) {\n      this.iterations_ = 0;\n    }\n    return {\n      name: 'iter',  // Named for Python compatibility.\n      // TODO(cais): Use 'int64' type when available.\n      tensor: scalar(this.iterations_, 'int32')\n    };\n  }\n\n  async getWeights(): Promise<NamedTensor[]> {\n    throw new Error('getWeights() is not implemented for this optimizer yet.');\n  }\n\n  async setWeights(weightValues: NamedTensor[]): Promise<void> {\n    throw new Error(\n        `setWeights() is not implemented for this optimizer class ` +\n        `${this.getClassName()}`);\n  }\n\n  /**\n   * Extract the first element of the weight values and set it\n   * as the iterations counter variable of this instance of optimizer.\n   *\n   * @param weightValues\n   * @returns Weight values with the first element consumed and excluded.\n   */\n  protected async extractIterations(weightValues: NamedTensor[]):\n      Promise<NamedTensor[]> {\n    this.iterations_ = (await weightValues[0].tensor.data())[0];\n    return weightValues.slice(1);\n  }\n}\n\nObject.defineProperty(Optimizer, Symbol.hasInstance, {\n  value: (instance: Optimizer) => {\n    return instance.minimize != null && instance.computeGradients != null &&\n        instance.applyGradients != null;\n  }\n});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/ops';\nimport {square} from '../ops/square';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class AdadeltaOptimizer extends Optimizer {\n  /** @nocollapse */\n  static get className() {\n    // Name matters for Python compatibility.\n    // This is a getter instead of a property because when it's a property, it\n    // prevents the entire class from being tree-shaken.\n    return 'Adadelta';\n  }\n  private accumulatedGrads: OptimizerVariable[] = [];\n  private accumulatedUpdates: OptimizerVariable[] = [];\n\n  constructor(\n      protected learningRate: number, protected rho: number,\n      protected epsilon: number = null) {\n    super();\n\n    if (epsilon == null) {\n      this.epsilon = ENGINE.backend.epsilon();\n    }\n  }\n\n  applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n    const variableNames = Array.isArray(variableGradients) ?\n        variableGradients.map(item => item.name) :\n        Object.keys(variableGradients);\n\n    variableNames.forEach((name, i) => {\n      const value = ENGINE.registeredVariables[name];\n      const trainable = false;\n      if (this.accumulatedGrads[i] == null) {\n        this.accumulatedGrads[i] = {\n          originalName: `${name}/accum_grad`,\n          variable: tidy(() => zerosLike(value).variable(trainable))\n        };\n      }\n      if (this.accumulatedUpdates[i] == null) {\n        this.accumulatedUpdates[i] = {\n          originalName: `${name}/accum_var`,\n          variable: tidy(() => zerosLike(value).variable(trainable))\n        };\n      }\n\n      const gradient = Array.isArray(variableGradients) ?\n          variableGradients[i].tensor :\n          variableGradients[name];\n      if (gradient == null) {\n        return;\n      }\n\n      const accumulatedGrad = this.accumulatedGrads[i].variable;\n      const accumulatedUpdate = this.accumulatedUpdates[i].variable;\n\n      tidy(() => {\n        const newAccumulatedGrad =\n            add(mul(accumulatedGrad, this.rho),\n                mul(square(gradient), 1 - this.rho));\n\n        const updates =\n            mul(div(sqrt(add(accumulatedUpdate, this.epsilon)),\n                    sqrt(add(accumulatedGrad, this.epsilon))),\n                gradient);\n\n        const newAccumulatedUpdate =\n            add(mul(accumulatedUpdate, this.rho),\n                mul(square(updates), 1 - this.rho));\n\n        accumulatedGrad.assign(newAccumulatedGrad);\n        accumulatedUpdate.assign(newAccumulatedUpdate);\n\n        const newValue = add(mul(updates, -this.learningRate), value);\n        value.assign(newValue);\n      });\n    });\n    this.incrementIterations();\n  }\n\n  override dispose(): void {\n    if (this.accumulatedUpdates != null) {\n      dispose(this.accumulatedGrads.map(v => v.variable));\n      dispose(this.accumulatedUpdates.map(v => v.variable));\n    }\n  }\n\n  override async getWeights(): Promise<NamedTensor[]> {\n    // Order matters for Python compatibility.\n    const variables: OptimizerVariable[] =\n        [...this.accumulatedGrads, ...this.accumulatedUpdates];\n    return [await this.saveIterations()].concat(\n        variables.map(v => ({name: v.originalName, tensor: v.variable})));\n  }\n\n  override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n    weightValues = await this.extractIterations(weightValues);\n    const variableCount = weightValues.length / 2;\n    const trainable = false;\n    this.accumulatedGrads =\n        weightValues.slice(0, variableCount).map(v => ({\n                                                   originalName: v.name,\n                                                   variable: v.tensor.variable(\n                                                       trainable)\n                                                 }));\n    this.accumulatedUpdates =\n        weightValues.slice(variableCount, variableCount * 2)\n            .map(v => ({\n                   originalName: v.name,\n                   variable: v.tensor.variable(trainable)\n                 }));\n  }\n\n  getConfig(): ConfigDict {\n    return {\n      'learningRate': this.learningRate,\n      'rho': this.rho,\n      'epsilon': this.epsilon\n    };\n  }\n\n  /** @nocollapse */\n  static override fromConfig<T extends Serializable>(\n      cls: SerializableConstructor<T>, config: ConfigDict): T {\n    return new cls(config['learningRate'], config['rho'], config['epsilon']);\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {fill} from '../ops/fill';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class AdagradOptimizer extends Optimizer {\n  /** @nocollapse */\n  static get className() {\n    // Name matters for Python compatibility.\n    // This is a getter instead of a property because when it's a property, it\n    // prevents the entire class from being tree-shaken.\n    return 'Adagrad';\n  }\n\n  private accumulatedGrads: OptimizerVariable[] = [];\n\n  constructor(\n      protected learningRate: number, private initialAccumulatorValue = 0.1) {\n    super();\n  }\n\n  applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n    const variableNames = Array.isArray(variableGradients) ?\n        variableGradients.map(item => item.name) :\n        Object.keys(variableGradients);\n\n    variableNames.forEach((name, i) => {\n      const value = ENGINE.registeredVariables[name];\n      if (this.accumulatedGrads[i] == null) {\n        const trainable = false;\n        this.accumulatedGrads[i] = {\n          originalName: `${name}/accumulator`,\n          variable: tidy(\n              () => fill(value.shape, this.initialAccumulatorValue)\n                        .variable(trainable))\n        };\n      }\n\n      const gradient = Array.isArray(variableGradients) ?\n          variableGradients[i].tensor :\n          variableGradients[name];\n      if (gradient == null) {\n        return;\n      }\n\n      const accumulatedGrad = this.accumulatedGrads[i].variable;\n\n      tidy(() => {\n        const newAccumulatedGrad = add(accumulatedGrad, square(gradient));\n        accumulatedGrad.assign(newAccumulatedGrad);\n\n        const newValue = add(\n            mul(div(gradient,\n                    sqrt(add(newAccumulatedGrad, ENGINE.backend.epsilon()))),\n                -this.learningRate),\n            value);\n        value.assign(newValue);\n      });\n    });\n    this.incrementIterations();\n  }\n\n  override dispose(): void {\n    if (this.accumulatedGrads != null) {\n      dispose(this.accumulatedGrads.map(v => v.variable));\n    }\n  }\n\n  override async getWeights(): Promise<NamedTensor[]> {\n    // Order matters for Python compatibility.\n    return [await this.saveIterations()].concat(this.accumulatedGrads.map(\n        v => ({name: v.originalName, tensor: v.variable})));\n  }\n\n  override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n    weightValues = await this.extractIterations(weightValues);\n    const trainable = false;\n    this.accumulatedGrads = weightValues.map(\n        v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));\n  }\n\n  getConfig(): ConfigDict {\n    return {\n      'learningRate': this.learningRate,\n      'initialAccumulatorValue': this.initialAccumulatorValue,\n    };\n  }\n\n  /** @nocollapse */\n  static override fromConfig<T extends Serializable>(\n      cls: SerializableConstructor<T>, config: ConfigDict): T {\n    return new cls(config['learningRate'], config['initialAccumulatorValue']);\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {pow} from '../ops/pow';\nimport {scalar} from '../ops/scalar';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Variable} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\nexport class AdamOptimizer extends Optimizer {\n  /** @nocollapse */\n  static get className() {\n    // Name matters for Python compatibility.\n    // This is a getter instead of a property because when it's a property, it\n    // prevents the entire class from being tree-shaken.\n    return 'Adam';\n  }\n  private accBeta1: Variable;\n  private accBeta2: Variable;\n\n  private accumulatedFirstMoment: OptimizerVariable[] = [];\n  private accumulatedSecondMoment: OptimizerVariable[] = [];\n\n  constructor(\n      protected learningRate: number, protected beta1: number,\n      protected beta2: number, protected epsilon: number = null) {\n    super();\n    tidy(() => {\n      // accB* will be updated by batch.\n      this.accBeta1 = scalar(beta1).variable();\n      this.accBeta2 = scalar(beta2).variable();\n    });\n\n    if (epsilon == null) {\n      this.epsilon = ENGINE.backend.epsilon();\n    }\n  }\n\n  applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n    const varNames = Array.isArray(variableGradients) ?\n        variableGradients.map(v => v.name) :\n        Object.keys(variableGradients);\n    tidy(() => {\n      const oneMinusAccBeta1 = sub(1, this.accBeta1);\n      const oneMinusAccBeta2 = sub(1, this.accBeta2);\n\n      varNames.forEach((name, i) => {\n        const value = ENGINE.registeredVariables[name];\n        const trainable = false;\n        if (this.accumulatedFirstMoment[i] == null) {\n          this.accumulatedFirstMoment[i] = {\n            originalName: `${name}/m`,\n            variable: tidy(() => zerosLike(value).variable(trainable))\n          };\n        }\n        if (this.accumulatedSecondMoment[i] == null) {\n          this.accumulatedSecondMoment[i] = {\n            originalName: `${name}/v`,\n            variable: tidy(() => zerosLike(value).variable(trainable))\n          };\n        }\n\n        const gradient = Array.isArray(variableGradients) ?\n            variableGradients[i].tensor :\n            variableGradients[name];\n        if (gradient == null) {\n          return;\n        }\n\n        const firstMoment = this.accumulatedFirstMoment[i].variable;\n        const secondMoment = this.accumulatedSecondMoment[i].variable;\n\n        const newFirstMoment =\n            add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));\n        const newSecondMoment =\n            add(mul(secondMoment, this.beta2),\n                mul(square(gradient), 1 - this.beta2));\n\n        const biasCorrectedFirstMoment = div(newFirstMoment, oneMinusAccBeta1);\n        const biasCorrectedSecondMoment =\n            div(newSecondMoment, oneMinusAccBeta2);\n\n        firstMoment.assign(newFirstMoment);\n        secondMoment.assign(newSecondMoment);\n\n        const newValue =\n            add(mul(div(biasCorrectedFirstMoment,\n                        add(sqrt(biasCorrectedSecondMoment), this.epsilon)),\n                    -this.learningRate),\n                value);\n        value.assign(newValue);\n      });\n\n      this.accBeta1.assign(mul(this.accBeta1, this.beta1));\n      this.accBeta2.assign(mul(this.accBeta2, this.beta2));\n    });\n    this.incrementIterations();\n  }\n\n  override dispose(): void {\n    this.accBeta1.dispose();\n    this.accBeta2.dispose();\n\n    if (this.accumulatedFirstMoment != null) {\n      dispose(this.accumulatedFirstMoment.map(v => v.variable));\n    }\n    if (this.accumulatedSecondMoment != null) {\n      dispose(this.accumulatedSecondMoment.map(v => v.variable));\n    }\n  }\n\n  override async getWeights(): Promise<NamedTensor[]> {\n    // Order matters for Python compatibility.\n    const variables: OptimizerVariable[] =\n        [...this.accumulatedFirstMoment, ...this.accumulatedSecondMoment];\n    return [await this.saveIterations()].concat(\n        variables.map(v => ({name: v.originalName, tensor: v.variable})));\n  }\n\n  override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n    weightValues = await this.extractIterations(weightValues);\n    tidy(() => {\n      this.accBeta1.assign(pow(this.beta1, this.iterations_ + 1));\n      this.accBeta2.assign(pow(this.beta2, this.iterations_ + 1));\n    });\n\n    const variableCount = weightValues.length / 2;\n    const trainable = false;\n    this.accumulatedFirstMoment =\n        weightValues.slice(0, variableCount).map(v => ({\n                                                   originalName: v.name,\n                                                   variable: v.tensor.variable(\n                                                       trainable)\n                                                 }));\n    this.accumulatedSecondMoment =\n        weightValues.slice(variableCount, variableCount * 2)\n            .map(v => ({\n                   originalName: v.name,\n                   variable: v.tensor.variable(trainable)\n                 }));\n  }\n\n  getConfig(): ConfigDict {\n    return {\n      'learningRate': this.learningRate,\n      'beta1': this.beta1,\n      'beta2': this.beta2,\n      'epsilon': this.epsilon,\n    };\n  }\n\n  /** @nocollapse */\n  static override fromConfig<T extends Serializable>(\n      cls: SerializableConstructor<T>, config: ConfigDict): T {\n    return new cls(\n        config['learningRate'], config['beta1'], config['beta2'],\n        config['epsilon']);\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {abs} from '../ops/abs';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {maximum} from '../ops/maximum';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Variable} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\nexport class AdamaxOptimizer extends Optimizer {\n  /** @nocollapse */\n  static get className() {\n    // Name matters for Python compatibility.\n    // This is a getter instead of a property because when it's a property, it\n    // prevents the entire class from being tree-shaken.\n    return 'Adamax';\n  }\n  private accBeta1: Variable;\n  private iteration: Variable;\n\n  private accumulatedFirstMoment: OptimizerVariable[] = [];\n  private accumulatedWeightedInfNorm: OptimizerVariable[] = [];\n\n  constructor(\n      protected learningRate: number, protected beta1: number,\n      protected beta2: number, protected epsilon: number = null,\n      protected decay = 0.0) {\n    super();\n\n    tidy(() => {\n      this.iteration = scalar(0).variable();\n      this.accBeta1 = scalar(beta1).variable();\n    });\n\n    if (epsilon == null) {\n      this.epsilon = ENGINE.backend.epsilon();\n    }\n  }\n\n  applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n    const variableNames = Array.isArray(variableGradients) ?\n        variableGradients.map(item => item.name) :\n        Object.keys(variableGradients);\n\n    tidy(() => {\n      const oneMinusAccBeta1 = sub(1, this.accBeta1);\n      const lr =\n          div(-this.learningRate, add(mul(this.iteration, this.decay), 1));\n\n      variableNames.forEach((name, i) => {\n        const value = ENGINE.registeredVariables[name];\n        const trainable = false;\n        if (this.accumulatedFirstMoment[i] == null) {\n          this.accumulatedFirstMoment[i] = {\n            originalName: `${name}/m`,\n            variable: zerosLike(value).variable(trainable)\n          };\n        }\n        if (this.accumulatedWeightedInfNorm[i] == null) {\n          this.accumulatedWeightedInfNorm[i] = {\n            originalName: `${name}/v`,\n            variable: zerosLike(value).variable(trainable)\n          };\n        }\n\n        const gradient = Array.isArray(variableGradients) ?\n            variableGradients[i].tensor :\n            variableGradients[name];\n        if (gradient == null) {\n          return;\n        }\n\n        const firstMoment = this.accumulatedFirstMoment[i].variable;\n        const weightedInfNorm = this.accumulatedWeightedInfNorm[i].variable;\n\n        const newFirstMoment =\n            add(mul(firstMoment, this.beta1), mul(gradient, 1 - this.beta1));\n\n        const ut0 = mul(weightedInfNorm, this.beta2);\n        const ut1 = abs(gradient);\n\n        const newWeightedInfNorm = maximum(ut0, ut1);\n\n        firstMoment.assign(newFirstMoment);\n        weightedInfNorm.assign(newWeightedInfNorm);\n\n        const newValue =\n            add(mul(div(lr, oneMinusAccBeta1),\n                    div(newFirstMoment, add(newWeightedInfNorm, this.epsilon))),\n                value);\n\n        value.assign(newValue);\n      });\n\n      this.iteration.assign(add(this.iteration, 1));\n      this.accBeta1.assign(mul(this.accBeta1, this.beta1));\n    });\n    this.incrementIterations();\n  }\n\n  override dispose(): void {\n    this.accBeta1.dispose();\n    this.iteration.dispose();\n\n    if (this.accumulatedFirstMoment != null) {\n      dispose(this.accumulatedFirstMoment.map(v => v.variable));\n    }\n    if (this.accumulatedWeightedInfNorm != null) {\n      dispose(this.accumulatedWeightedInfNorm.map(v => v.variable));\n    }\n  }\n\n  override async getWeights(): Promise<NamedTensor[]> {\n    throw new Error('getWeights() is not implemented for Adamax yet.');\n  }\n\n  override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n    throw new Error('setWeights() is not implemented for Adamax yet.');\n  }\n\n  getConfig(): ConfigDict {\n    return {\n      'learningRate': this.learningRate,\n      'beta1': this.beta1,\n      'beta2': this.beta2,\n      'epsilon': this.epsilon,\n      'decay': this.decay\n    };\n  }\n\n  /** @nocollapse */\n  static override fromConfig<T extends Serializable>(\n      cls: SerializableConstructor<T>, config: ConfigDict): T {\n    return new cls(\n        config['learningRate'], config['beta1'], config['beta2'],\n        config['epsilon'], config['decay']);\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {keep, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Scalar} from '../tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\nimport {Optimizer} from './optimizer';\n\n/** @doclink Optimizer */\nexport class SGDOptimizer extends Optimizer {\n  /** @nocollapse */\n  static get className() {\n    // Name matters for Python compatibility.\n    // This is a getter instead of a property because when it's a property, it\n    // prevents the entire class from being tree-shaken.\n    return 'SGD';\n  }\n  protected c: Scalar;\n\n  constructor(protected learningRate: number) {\n    super();\n    this.setLearningRate(learningRate);\n  }\n\n  applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {\n    const varNames = Array.isArray(variableGradients) ?\n        variableGradients.map(v => v.name) :\n        Object.keys(variableGradients);\n    varNames.forEach((name, i) => {\n      const gradient = Array.isArray(variableGradients) ?\n          variableGradients[i].tensor :\n          variableGradients[name];\n      if (gradient == null) {\n        return;\n      }\n      const value = ENGINE.registeredVariables[name];\n      tidy(() => {\n        const newValue = add(mul(this.c, gradient), value);\n        value.assign(newValue);\n      });\n    });\n    this.incrementIterations();\n  }\n\n  /**\n   * Sets the learning rate of the optimizer.\n   */\n  setLearningRate(learningRate: number) {\n    this.learningRate = learningRate;\n    if (this.c != null) {\n      this.c.dispose();\n    }\n    this.c = keep(scalar(-learningRate));\n  }\n\n  override dispose() {\n    this.c.dispose();\n  }\n\n  override async getWeights(): Promise<NamedTensor[]> {\n    return [await this.saveIterations()];\n  }\n\n  override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n    weightValues = await this.extractIterations(weightValues);\n    if (weightValues.length !== 0) {\n      throw new Error('SGD optimizer does not have settable weights.');\n    }\n  }\n\n  getConfig(): ConfigDict {\n    return {'learningRate': this.learningRate};\n  }\n\n  /** @nocollapse */\n  static override fromConfig<T extends Serializable>(\n      cls: SerializableConstructor<T>, config: ConfigDict): T {\n    return new cls(config['learningRate']);\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {Scalar, Tensor} from '../tensor';\nimport {NamedTensor, NamedVariableMap} from '../tensor_types';\n\nimport {OptimizerVariable} from './optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\n\n/** @doclink Optimizer */\nexport class MomentumOptimizer extends SGDOptimizer {\n  /** @nocollapse */\n  // Name matters for Python compatibility.\n  static override get className() {\n    // Name matters for Python compatibility.\n    // This is a getter instead of a property because when it's a property, it\n    // prevents the entire class from being tree-shaken.\n    return 'Momentum';\n  }\n  private m: Scalar;\n  private accumulations: OptimizerVariable[] = [];\n\n  constructor(\n      protected override learningRate: number, private momentum: number,\n      private useNesterov = false) {\n    super(learningRate);\n    this.m = scalar(this.momentum);\n  }\n\n  override applyGradients(variableGradients: NamedVariableMap|NamedTensor[]) {\n    const variableNames = Array.isArray(variableGradients) ?\n        variableGradients.map(item => item.name) :\n        Object.keys(variableGradients);\n\n    variableNames.forEach((name, i) => {\n      const value = ENGINE.registeredVariables[name];\n      if (this.accumulations[i] == null) {\n        const trainable = false;\n        this.accumulations[i] = {\n          originalName: `${name}/momentum`,\n          variable: tidy(() => zerosLike(value).variable(trainable))\n        };\n      }\n\n      const accumulation = this.accumulations[i].variable;\n      const gradient = Array.isArray(variableGradients) ?\n          variableGradients[i].tensor :\n          variableGradients[name];\n      if (gradient == null) {\n        return;\n      }\n\n      tidy(() => {\n        let newValue: Tensor;\n        const newAccumulation = add(mul(this.m, accumulation), gradient);\n        if (this.useNesterov) {\n          newValue = add(\n              mul(this.c, add(gradient, mul(newAccumulation, this.m))), value);\n        } else {\n          newValue = add(mul(this.c, newAccumulation), value);\n        }\n        accumulation.assign(newAccumulation);\n        value.assign(newValue);\n      });\n    });\n    this.incrementIterations();\n  }\n\n  override dispose(): void {\n    this.m.dispose();\n    if (this.accumulations != null) {\n      dispose(this.accumulations.map(v => v.variable));\n    }\n  }\n\n  /**\n   * Sets the momentum of the optimizer.\n   *\n   * @param momentum\n   */\n  setMomentum(momentum: number) {\n    this.momentum = momentum;\n  }\n\n  override async getWeights(): Promise<NamedTensor[]> {\n    // Order matters for Python compatibility.\n    return [await this.saveIterations()].concat(this.accumulations.map(\n        v => ({name: v.originalName, tensor: v.variable})));\n  }\n\n  override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n    weightValues = await this.extractIterations(weightValues);\n    const trainable = false;\n    this.accumulations = weightValues.map(\n        v => ({originalName: v.name, variable: v.tensor.variable(trainable)}));\n  }\n\n  override getConfig(): ConfigDict {\n    return {\n      'learningRate': this.learningRate,\n      'momentum': this.momentum,\n      'useNesterov': this.useNesterov\n    };\n  }\n\n  /** @nocollapse */\n  static override fromConfig<T extends Serializable>(\n      cls: SerializableConstructor<T>, config: ConfigDict): T {\n    return new cls(\n        config['learningRate'], config['momentum'], config['useNesterov']);\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {dispose, tidy} from '../globals';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {zerosLike} from '../ops/zeros_like';\nimport {ConfigDict, Serializable, SerializableConstructor} from '../serialization';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\n\nimport {Optimizer, OptimizerVariable} from './optimizer';\n\n/** @doclink Optimizer */\nexport class RMSPropOptimizer extends Optimizer {\n  /** @nocollapse */\n  static get className() {\n    // Name matters for Python compatibility.\n    // This is a getter instead of a property because when it's a property, it\n    // prevents the entire class from being tree-shaken.\n    return 'RMSProp';\n  }\n  private centered: boolean;\n\n  private accumulatedMeanSquares: OptimizerVariable[] = [];\n  private accumulatedMoments: OptimizerVariable[] = [];\n  private accumulatedMeanGrads: OptimizerVariable[] = [];\n\n  constructor(\n      protected learningRate: number, protected decay = 0.9,\n      protected momentum = 0.0, protected epsilon: number = null,\n      centered = false) {\n    super();\n\n    this.centered = centered;\n\n    if (epsilon == null) {\n      this.epsilon = ENGINE.backend.epsilon();\n    }\n    if (learningRate == null) {\n      throw new Error(`learningRate for RMSPropOptimizer must be defined.`);\n    }\n  }\n\n  applyGradients(variableGradients: NamedTensorMap|NamedTensor[]) {\n    const variableNames = Array.isArray(variableGradients) ?\n        variableGradients.map(item => item.name) :\n        Object.keys(variableGradients);\n\n    variableNames.forEach((name, i) => {\n      const value = ENGINE.registeredVariables[name];\n      const trainable = false;\n      if (this.accumulatedMeanSquares[i] == null) {\n        this.accumulatedMeanSquares[i] = {\n          originalName: `${name}/rms`,\n          variable: tidy(() => zerosLike(value).variable(trainable))\n        };\n      }\n      if (this.accumulatedMoments[i] == null) {\n        this.accumulatedMoments[i] = {\n          originalName: `${name}/momentum`,\n          variable: tidy(() => zerosLike(value).variable(trainable))\n        };\n      }\n      if (this.accumulatedMeanGrads[i] == null && this.centered) {\n        this.accumulatedMeanGrads[i] = {\n          originalName: `${name}/mg`,\n          variable: tidy(() => zerosLike(value).variable(trainable))\n        };\n      }\n\n      const gradient = Array.isArray(variableGradients) ?\n          variableGradients[i].tensor :\n          variableGradients[name];\n      if (gradient == null) {\n        return;\n      }\n\n      const accumulatedMeanSquare = this.accumulatedMeanSquares[i].variable;\n      const accumulatedMoments = this.accumulatedMoments[i].variable;\n      tidy(() => {\n        const newAccumulatedMeanSquare =\n            add(mul(accumulatedMeanSquare, this.decay),\n                mul(square(gradient), 1 - this.decay));\n\n        if (this.centered) {\n          const accumulatedMeanGrad = this.accumulatedMeanGrads[i].variable;\n          // Centered gradient\n          const newAccumulatedMeanGrad =\n              add(mul(accumulatedMeanGrad, this.decay),\n                  mul(gradient, 1 - this.decay));\n\n          const gradContribution =\n              div(mul(gradient, this.learningRate),\n                  sqrt(\n                      sub(newAccumulatedMeanSquare,\n                          add(square(newAccumulatedMeanGrad), this.epsilon))));\n          const newAccumulatedMoments =\n              add(mul(accumulatedMoments, this.momentum), gradContribution);\n\n          accumulatedMeanSquare.assign(newAccumulatedMeanSquare);\n          accumulatedMeanGrad.assign(newAccumulatedMeanGrad);\n          accumulatedMoments.assign(newAccumulatedMoments);\n\n          const newValue = sub(value, newAccumulatedMoments);\n          value.assign(newValue);\n        } else {\n          // Plain gradient\n          const newAccumulatedMeanSquare =\n              add(mul(accumulatedMeanSquare, this.decay),\n                  mul(square(gradient), 1 - this.decay));\n\n          const newAccumulatedMoments =\n              add(mul(accumulatedMoments, this.momentum),\n                  div(mul(gradient, this.learningRate),\n                      sqrt(add(newAccumulatedMeanSquare, this.epsilon))));\n\n          accumulatedMeanSquare.assign(newAccumulatedMeanSquare);\n          accumulatedMoments.assign(newAccumulatedMoments);\n\n          const newValue = sub(value, newAccumulatedMoments);\n          value.assign(newValue);\n        }\n      });\n    });\n    this.incrementIterations();\n  }\n\n  override dispose(): void {\n    if (this.accumulatedMeanSquares != null) {\n      dispose(this.accumulatedMeanSquares.map(v => v.variable));\n    }\n    if (this.accumulatedMeanGrads != null && this.centered) {\n      dispose(this.accumulatedMeanGrads.map(v => v.variable));\n    }\n    if (this.accumulatedMoments != null) {\n      dispose(this.accumulatedMoments.map(v => v.variable));\n    }\n  }\n\n  override async getWeights(): Promise<NamedTensor[]> {\n    // Order matters for Python compatibility.\n    const variables: OptimizerVariable[] =\n        [...this.accumulatedMeanSquares, ...this.accumulatedMoments];\n    if (this.centered) {\n      variables.push(...this.accumulatedMeanGrads);\n    }\n    return [await this.saveIterations()].concat(\n        variables.map(v => ({name: v.originalName, tensor: v.variable})));\n  }\n\n  override async setWeights(weightValues: NamedTensor[]): Promise<void> {\n    weightValues = await this.extractIterations(weightValues);\n    const variableCount =\n        this.centered ? weightValues.length / 3 : weightValues.length / 2;\n    const trainable = false;\n    this.accumulatedMeanSquares =\n        weightValues.slice(0, variableCount).map(v => ({\n                                                   originalName: v.name,\n                                                   variable: v.tensor.variable(\n                                                       trainable)\n                                                 }));\n    this.accumulatedMoments =\n        weightValues.slice(variableCount, variableCount * 2)\n            .map(v => ({\n                   originalName: v.name,\n                   variable: v.tensor.variable(trainable)\n                 }));\n    if (this.centered) {\n      this.accumulatedMeanGrads =\n          weightValues.slice(variableCount * 2, variableCount * 3)\n              .map(v => ({\n                     originalName: v.name,\n                     variable: v.tensor.variable(trainable)\n                   }));\n    }\n  }\n\n  getConfig(): ConfigDict {\n    return {\n      'learningRate': this.learningRate,\n      'decay': this.decay,\n      'momentum': this.momentum,\n      'epsilon': this.epsilon,\n      'centered': this.centered\n    };\n  }\n\n  /** @nocollapse */\n  static override fromConfig<T extends Serializable>(\n      cls: SerializableConstructor<T>, config: ConfigDict): T {\n    return new cls(\n        config['learningRate'], config['decay'], config['momentum'],\n        config['epsilon'], config['centered']);\n  }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AdadeltaOptimizer} from './adadelta_optimizer';\nimport {AdagradOptimizer} from './adagrad_optimizer';\nimport {AdamOptimizer} from './adam_optimizer';\nimport {AdamaxOptimizer} from './adamax_optimizer';\nimport {MomentumOptimizer} from './momentum_optimizer';\nimport {RMSPropOptimizer} from './rmsprop_optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\nimport {registerClass} from '../serialization';\n\nconst OPTIMIZERS = [\n  AdadeltaOptimizer,\n  AdagradOptimizer,\n  AdamOptimizer,\n  AdamaxOptimizer,\n  MomentumOptimizer,\n  RMSPropOptimizer,\n  SGDOptimizer,\n];\n\nexport function registerOptimizers() {\n  for (const optimizer of OPTIMIZERS) {\n    registerClass(optimizer);\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers related to files, such as browser-triggered file downloads,\n * user-selected files in browser.\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {basename, getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelJSON, SaveResult, WeightData, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\n\nconst DEFAULT_FILE_NAME_PREFIX = 'model';\nconst DEFAULT_JSON_EXTENSION_NAME = '.json';\nconst DEFAULT_WEIGHT_DATA_EXTENSION_NAME = '.weights.bin';\n\nfunction defer<T>(f: () => T): Promise<T> {\n  return new Promise(resolve => setTimeout(resolve)).then(f);\n}\n\nexport class BrowserDownloads implements IOHandler {\n  private readonly modelJsonFileName: string;\n  private readonly weightDataFileName: string;\n  private readonly modelJsonAnchor: HTMLAnchorElement;\n  private readonly weightDataAnchor: HTMLAnchorElement;\n\n  static readonly URL_SCHEME = 'downloads://';\n\n  constructor(fileNamePrefix?: string) {\n    if (!env().getBool('IS_BROWSER')) {\n      // TODO(cais): Provide info on what IOHandlers are available under the\n      //   current environment.\n      throw new Error(\n          'browserDownloads() cannot proceed because the current environment ' +\n          'is not a browser.');\n    }\n\n    if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) {\n      fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length);\n    }\n    if (fileNamePrefix == null || fileNamePrefix.length === 0) {\n      fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;\n    }\n\n    this.modelJsonFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;\n    this.weightDataFileName =\n        fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;\n  }\n\n  async save(modelArtifacts: ModelArtifacts): Promise<SaveResult> {\n    if (typeof (document) === 'undefined') {\n      throw new Error(\n          'Browser downloads are not supported in ' +\n          'this environment since `document` is not present');\n    }\n\n    // TODO(mattsoulanille): Support saving models over 2GB that exceed\n    // Chrome's ArrayBuffer size limit.\n    const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);\n\n    const weightsURL = window.URL.createObjectURL(new Blob(\n        [weightBuffer], {type: 'application/octet-stream'}));\n\n    if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n      throw new Error(\n          'BrowserDownloads.save() does not support saving model topology ' +\n          'in binary formats yet.');\n    } else {\n      const weightsManifest: WeightsManifestConfig = [{\n        paths: ['./' + this.weightDataFileName],\n        weights: modelArtifacts.weightSpecs\n      }];\n      const modelJSON: ModelJSON =\n          getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);\n\n      const modelJsonURL = window.URL.createObjectURL(\n          new Blob([JSON.stringify(modelJSON)], {type: 'application/json'}));\n\n      // If anchor elements are not provided, create them without attaching them\n      // to parents, so that the downloaded file names can be controlled.\n      const jsonAnchor = this.modelJsonAnchor == null ?\n          document.createElement('a') :\n          this.modelJsonAnchor;\n      jsonAnchor.download = this.modelJsonFileName;\n      jsonAnchor.href = modelJsonURL;\n      // Trigger downloads by evoking a click event on the download anchors.\n      // When multiple downloads are started synchronously, Firefox will only\n      // save the last one.\n      await defer(() => jsonAnchor.dispatchEvent(new MouseEvent('click')));\n\n      if (modelArtifacts.weightData != null) {\n        const weightDataAnchor = this.weightDataAnchor == null ?\n            document.createElement('a') :\n            this.weightDataAnchor;\n        weightDataAnchor.download = this.weightDataFileName;\n        weightDataAnchor.href = weightsURL;\n        await defer(\n            () => weightDataAnchor.dispatchEvent(new MouseEvent('click')));\n      }\n\n      return {modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts)};\n    }\n  }\n}\n\nclass BrowserFiles implements IOHandler {\n  private readonly jsonFile: File;\n  private readonly weightsFiles: File[];\n\n  constructor(files: File[]) {\n    if (files == null || files.length < 1) {\n      throw new Error(\n          `When calling browserFiles, at least 1 file is required, ` +\n          `but received ${files}`);\n    }\n    this.jsonFile = files[0];\n    this.weightsFiles = files.slice(1);\n  }\n\n  async load(): Promise<ModelArtifacts> {\n    return new Promise((resolve, reject) => {\n      const jsonReader = new FileReader();\n      jsonReader.onload = (event: Event) => {\n        // tslint:disable-next-line:no-any\n        const modelJSON = JSON.parse((event.target as any).result) as ModelJSON;\n\n        const modelTopology = modelJSON.modelTopology;\n        if (modelTopology == null) {\n          reject(new Error(`modelTopology field is missing from file ${\n              this.jsonFile.name}`));\n          return;\n        }\n\n        const weightsManifest = modelJSON.weightsManifest;\n        if (weightsManifest == null) {\n          reject(new Error(`weightManifest field is missing from file ${\n              this.jsonFile.name}`));\n          return;\n        }\n\n        if (this.weightsFiles.length === 0) {\n          resolve({modelTopology});\n          return;\n        }\n\n        const modelArtifactsPromise = getModelArtifactsForJSON(\n            modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n        resolve(modelArtifactsPromise);\n      };\n\n      jsonReader.onerror = error => reject(\n          `Failed to read model topology and weights manifest JSON ` +\n          `from file '${this.jsonFile.name}'. BrowserFiles supports loading ` +\n          `Keras-style tf.Model artifacts only.`);\n      jsonReader.readAsText(this.jsonFile);\n    });\n  }\n\n  private loadWeights(weightsManifest: WeightsManifestConfig): Promise<[\n    /* weightSpecs */ WeightsManifestEntry[], WeightData,\n  ]> {\n    const weightSpecs: WeightsManifestEntry[] = [];\n    const paths: string[] = [];\n    for (const entry of weightsManifest) {\n      weightSpecs.push(...entry.weights);\n      paths.push(...entry.paths);\n    }\n\n    const pathToFile: {[path: string]: File} =\n        this.checkManifestAndWeightFiles(weightsManifest);\n\n    const promises: Array<Promise<ArrayBuffer>> =\n        paths.map(path => this.loadWeightsFile(path, pathToFile[path]));\n\n    return Promise.all(promises).then(\n        buffers => [weightSpecs, buffers]);\n  }\n\n  private loadWeightsFile(path: string, file: File): Promise<ArrayBuffer> {\n    return new Promise((resolve, reject) => {\n      const weightFileReader = new FileReader();\n      weightFileReader.onload = (event: Event) => {\n        // tslint:disable-next-line:no-any\n        const weightData = (event.target as any).result as ArrayBuffer;\n        resolve(weightData);\n      };\n      weightFileReader.onerror = error =>\n          reject(`Failed to weights data from file of path '${path}'.`);\n      weightFileReader.readAsArrayBuffer(file);\n    });\n  }\n\n  /**\n   * Check the compatibility between weights manifest and weight files.\n   */\n  private checkManifestAndWeightFiles(manifest: WeightsManifestConfig):\n      {[path: string]: File} {\n    const basenames: string[] = [];\n    const fileNames = this.weightsFiles.map(file => basename(file.name));\n    const pathToFile: {[path: string]: File} = {};\n    for (const group of manifest) {\n      group.paths.forEach(path => {\n        const pathBasename = basename(path);\n        if (basenames.indexOf(pathBasename) !== -1) {\n          throw new Error(\n              `Duplicate file basename found in weights manifest: ` +\n              `'${pathBasename}'`);\n        }\n        basenames.push(pathBasename);\n        if (fileNames.indexOf(pathBasename) === -1) {\n          throw new Error(\n              `Weight file with basename '${pathBasename}' is not provided.`);\n        } else {\n          pathToFile[path] = this.weightsFiles[fileNames.indexOf(pathBasename)];\n        }\n      });\n    }\n\n    if (basenames.length !== this.weightsFiles.length) {\n      throw new Error(\n          `Mismatch in the number of files in weights manifest ` +\n          `(${basenames.length}) and the number of weight files provided ` +\n          `(${this.weightsFiles.length}).`);\n    }\n    return pathToFile;\n  }\n}\n\nexport const browserDownloadsRouter: IORouter = (url: string|string[]) => {\n  if (!env().getBool('IS_BROWSER')) {\n    return null;\n  } else {\n    if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {\n      return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));\n    } else {\n      return null;\n    }\n  }\n};\nIORouterRegistry.registerSaveRouter(browserDownloadsRouter);\n\n/**\n * Creates an IOHandler that triggers file downloads from the browser.\n *\n * The returned `IOHandler` instance can be used as model exporting methods such\n * as `tf.Model.save` and supports only saving.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n *     {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * const saveResult = await model.save('downloads://mymodel');\n * // This will trigger downloading of two files:\n * //   'mymodel.json' and 'mymodel.weights.bin'.\n * console.log(saveResult);\n * ```\n *\n * @param fileNamePrefix Prefix name of the files to be downloaded. For use with\n *   `tf.Model`, `fileNamePrefix` should follow either of the following two\n *   formats:\n *   1. `null` or `undefined`, in which case the default file\n *      names will be used:\n *      - 'model.json' for the JSON file containing the model topology and\n *        weights manifest.\n *      - 'model.weights.bin' for the binary file containing the binary weight\n *        values.\n *   2. A single string or an Array of a single string, as the file name prefix.\n *      For example, if `'foo'` is provided, the downloaded JSON\n *      file and binary weights file will be named 'foo.json' and\n *      'foo.weights.bin', respectively.\n * @param config Additional configuration for triggering downloads.\n * @returns An instance of `BrowserDownloads` `IOHandler`.\n *\n * @doc {\n *   heading: 'Models',\n *   subheading: 'Loading',\n *   namespace: 'io',\n *   ignoreCI: true\n * }\n */\nexport function browserDownloads(fileNamePrefix = 'model'): IOHandler {\n  return new BrowserDownloads(fileNamePrefix);\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from user-selected files.\n *\n * This method can be used for loading from files such as user-selected files\n * in the browser.\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * // Note: This code snippet won't run properly without the actual file input\n * //   elements in the HTML DOM.\n *\n * // Suppose there are two HTML file input (`<input type=\"file\" ...>`)\n * // elements.\n * const uploadJSONInput = document.getElementById('upload-json');\n * const uploadWeightsInput = document.getElementById('upload-weights');\n * const model = await tf.loadLayersModel(tf.io.browserFiles(\n *     [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));\n * ```\n *\n * @param files `File`s to load from. Currently, this function supports only\n *   loading from files that contain Keras-style models (i.e., `tf.Model`s), for\n *   which an `Array` of `File`s is expected (in that order):\n *   - A JSON file containing the model topology and weight manifest.\n *   - Optionally, one or more binary files containing the binary weights.\n *     These files must have names that match the paths in the `weightsManifest`\n *     contained by the aforementioned JSON file, or errors will be thrown\n *     during loading. These weights files have the same format as the ones\n *     generated by `tensorflowjs_converter` that comes with the `tensorflowjs`\n *     Python PIP package. If no weights files are provided, only the model\n *     topology will be loaded from the JSON file above.\n * @returns An instance of `Files` `IOHandler`.\n *\n * @doc {\n *   heading: 'Models',\n *   subheading: 'Loading',\n *   namespace: 'io',\n *   ignoreCI: true\n * }\n */\nexport function browserFiles(files: File[]): IOHandler {\n  return new BrowserFiles(files);\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {assert} from '../util';\n\nimport {OnProgressCallback} from './types';\n\n/**\n * Monitor Promise.all progress, fire onProgress callback function.\n *\n * @param promises Promise list going to be monitored\n * @param onProgress Callback function. Fired when a promise resolved.\n * @param startFraction Optional fraction start. Default to 0.\n * @param endFraction Optional fraction end. Default to 1.\n */\nexport function monitorPromisesProgress<T>(\n    promises: Array<Promise<T>>, onProgress: OnProgressCallback,\n    startFraction?: number, endFraction?: number) {\n  checkPromises(promises);\n  startFraction = startFraction == null ? 0 : startFraction;\n  endFraction = endFraction == null ? 1 : endFraction;\n  checkFraction(startFraction, endFraction);\n  let resolvedPromise = 0;\n\n  const registerMonitor = (promise: Promise<T>) => {\n    promise.then(value => {\n      const fraction = startFraction +\n          ++resolvedPromise / promises.length * (endFraction - startFraction);\n      // pass fraction as parameter to callback function.\n      onProgress(fraction);\n      return value;\n    });\n    return promise;\n  };\n\n  function checkPromises(promises: Array<Promise<T>>): void {\n    assert(\n        promises != null && Array.isArray(promises) && promises.length > 0,\n        () => 'promises must be a none empty array');\n  }\n\n  function checkFraction(startFraction: number, endFraction: number): void {\n    assert(\n        startFraction >= 0 && startFraction <= 1,\n        () => `Progress fraction must be in range [0, 1], but ` +\n            `got startFraction ${startFraction}`);\n    assert(\n        endFraction >= 0 && endFraction <= 1,\n        () => `Progress fraction must be in range [0, 1], but ` +\n            `got endFraction ${endFraction}`);\n    assert(\n        endFraction >= startFraction,\n        () => `startFraction must be no more than endFraction, but ` +\n            `got startFraction ${startFraction} and endFraction ` +\n            `${endFraction}`);\n  }\n\n  return Promise.all(promises.map(registerMonitor));\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '../environment';\n\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {decodeWeights} from './io_utils';\nimport {monitorPromisesProgress} from './progress';\nimport {DTYPE_VALUE_SIZE_MAP, LoadOptions, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\n/**\n * Reads binary weights data from a number of URLs.\n *\n * @param fetchURLs URLs to send the HTTP requests at, using `fetch` calls.\n * @param requestOptions RequestInit (options) for the HTTP requests.\n * @param fetchFunc Optional overriding value for the `window.fetch` function.\n * @param onProgress Optional, progress callback function, fired periodically\n *   before the load is completed.\n * @returns A `Promise` of an Array of `ArrayBuffer`. The Array has the same\n *   length as `fetchURLs`.\n */\nexport async function loadWeightsAsArrayBuffer(\n  fetchURLs: string[], loadOptions?: LoadOptions): Promise<ArrayBuffer[]> {\n  if (loadOptions == null) {\n    loadOptions = {};\n  }\n\n  const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :\n    loadOptions.fetchFunc;\n\n  // Create the requests for all of the weights in parallel.\n  const requests = fetchURLs.map(\n    fetchURL =>\n      fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true }));\n\n  const fetchStartFraction = 0;\n  const fetchEndFraction = 0.5;\n\n  const responses = loadOptions.onProgress == null ?\n    await Promise.all(requests) :\n    await monitorPromisesProgress(\n      requests, loadOptions.onProgress, fetchStartFraction,\n      fetchEndFraction);\n\n  const bufferPromises = responses.map(response => response.arrayBuffer());\n\n  const bufferStartFraction = 0.5;\n  const bufferEndFraction = 1;\n\n  const buffers = loadOptions.onProgress == null ?\n    await Promise.all(bufferPromises) :\n    await monitorPromisesProgress(\n      bufferPromises, loadOptions.onProgress, bufferStartFraction,\n      bufferEndFraction);\n  return buffers;\n}\n\nexport function streamWeights(fetchURLs: string[], loadOptions: LoadOptions): ReadableStream<ArrayBuffer> {\n  const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :\n    loadOptions.fetchFunc;\n\n  let fetchIndex = 0;\n  let chunkReader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n  loadOptions.onProgress?.(0);\n  return new ReadableStream<Uint8Array>({\n    pull: async (controller) => {\n      while (fetchIndex < fetchURLs.length) {\n        if (!chunkReader) {\n          const body = (await fetchFunc(fetchURLs[fetchIndex],\n                                         loadOptions.requestInit,\n                                         {isBinary: true})).body;\n\n          chunkReader = body.getReader();\n        }\n\n        const {done, value} = await chunkReader.read();\n\n        if (done) {\n          fetchIndex++;\n          chunkReader = undefined;\n          loadOptions.onProgress?.(fetchIndex / fetchURLs.length);\n          continue;\n        }\n        controller.enqueue(value);\n        return;\n      }\n      controller.close();\n    },\n  });\n}\n\n/**\n * Reads a weights manifest JSON configuration, fetches the weights and\n * returns them as `Tensor`s.\n *\n * @param manifest The weights manifest JSON.\n * @param filePathPrefix The path prefix for filenames given in the manifest.\n *     Defaults to the empty string.\n * @param weightNames The names of the weights to be fetched.\n */\nexport async function loadWeights(\n  manifest: WeightsManifestConfig, filePathPrefix = '',\n  weightNames?: string[],\n  requestInit?: RequestInit): Promise<NamedTensorMap> {\n  // TODO(nsthorat): Groups are currently fetched atomically. If you need a\n  // single weight from a group, the whole group will be fetched. At a future\n  // date, we should support fetching only the individual shards within a\n  // group that are needed to reconstruct the requested weight.\n  // TODO(cais): Use `decodeWeights` for implementation.\n\n  const fetchWeights = (fetchUrls: string[]) =>\n    loadWeightsAsArrayBuffer(fetchUrls, { requestInit });\n  const loadWeights = weightsLoaderFactory(fetchWeights);\n\n  return loadWeights(manifest, filePathPrefix, weightNames);\n}\n\n/**\n * Creates a function, which reads a weights manifest JSON configuration,\n * fetches the weight files using the specified function and returns them as\n * `Tensor`s.\n *\n * ```js\n * // example for creating a nodejs weight loader, which reads the weight files\n * // from disk using fs.readFileSync\n *\n * import * as fs from 'fs'\n *\n * const fetchWeightsFromDisk = (filePaths: string[]) =>\n *   filePaths.map(filePath => fs.readFileSync(filePath).buffer)\n *\n * const loadWeights = tf.io.weightsLoaderFactory(fetchWeightsFromDisk)\n *\n * const manifest = JSON.parse(\n *   fs.readFileSync('./my_model-weights_manifest').toString()\n * )\n * const weightMap = await loadWeights(manifest, './')\n * ```\n * @param fetchWeightsFunction The function used for fetching the weight files.\n * @returns Weight loading function.\n */\nexport function weightsLoaderFactory(\n  fetchWeightsFunction: (fetchUrls: string[]) => Promise<ArrayBuffer[]>):\n  (manifest: WeightsManifestConfig, filePathPrefix?: string,\n    weightNames?: string[]) => Promise<NamedTensorMap> {\n  return async (\n    manifest: WeightsManifestConfig, filePathPrefix = '',\n    weightNames?: string[]): Promise<NamedTensorMap> => {\n    // Collect all the groups, weights, and their relative offsets to be\n    // fetched.\n    const groupIndicesToFetchMap = manifest.map(() => false);\n    const groupWeightsToFetch: {\n      [group: number]: Array<{\n        manifestEntry: WeightsManifestEntry; groupOffset: number;\n        sizeBytes: number;\n      }>\n    } = {};\n    const weightsFound =\n      weightNames != null ? weightNames.map(() => false) : [];\n    const allManifestWeightNames: string[] = [];\n    manifest.forEach((manifestGroupConfig, groupIndex) => {\n      let groupOffset = 0;\n      manifestGroupConfig.weights.forEach(weightsEntry => {\n        const rawDtype = ('quantization' in weightsEntry) ?\n          weightsEntry.quantization.dtype :\n          weightsEntry.dtype;\n\n        const weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] *\n          util.sizeFromShape(weightsEntry.shape);\n\n        const enqueueWeightsForFetchingFn = () => {\n          groupIndicesToFetchMap[groupIndex] = true;\n          if (groupWeightsToFetch[groupIndex] == null) {\n            groupWeightsToFetch[groupIndex] = [];\n          }\n\n          groupWeightsToFetch[groupIndex].push({\n            manifestEntry: weightsEntry,\n            groupOffset,\n            sizeBytes: weightsBytes\n          });\n        };\n\n        if (weightNames != null) {\n          weightNames.forEach((weightName, weightIndex) => {\n            if (weightName === weightsEntry.name) {\n              enqueueWeightsForFetchingFn();\n              weightsFound[weightIndex] = true;\n            }\n          });\n        } else {\n          enqueueWeightsForFetchingFn();\n        }\n\n        allManifestWeightNames.push(weightsEntry.name);\n        groupOffset += weightsBytes;\n      });\n    });\n\n    if (!weightsFound.every(found => found)) {\n      const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]);\n      throw new Error(\n        `Could not find weights in manifest with names: ` +\n        `${weightsNotFound.join(', ')}. \\n` +\n        `Manifest JSON has weights with names: ` +\n        `${allManifestWeightNames.join(', ')}.`);\n    }\n\n    // Convert the one-hot boolean groupId => shouldFetch map to a list of group\n    // IDs.\n    const groupIndicesToFetch =\n      groupIndicesToFetchMap.reduce((accumulator, shouldFetch, i) => {\n        if (shouldFetch) {\n          accumulator.push(i);\n        }\n        return accumulator;\n      }, []);\n\n    const fetchUrls: string[] = [];\n    groupIndicesToFetch.forEach(i => {\n      manifest[i].paths.forEach(filepath => {\n        const fetchUrl = filePathPrefix +\n          (!filePathPrefix.endsWith('/') ? '/' : '') + filepath;\n        fetchUrls.push(fetchUrl);\n      });\n    });\n    const buffers = await fetchWeightsFunction(fetchUrls);\n\n    const weightsTensorMap: NamedTensorMap = {};\n    let bufferIndexOffset = 0;\n    groupIndicesToFetch.forEach(i => {\n      const numBuffers = manifest[i].paths.length;\n\n      const weightsBuffer = new CompositeArrayBuffer(\n        buffers.slice(bufferIndexOffset, bufferIndexOffset + numBuffers));\n\n      const weightsEntries = groupWeightsToFetch[i];\n\n      weightsEntries.forEach(weightsEntry => {\n        const byteBuffer = weightsBuffer.slice(\n          weightsEntry.groupOffset,\n          weightsEntry.groupOffset + weightsEntry.sizeBytes);\n        const nameToTensorMap =\n          decodeWeights(byteBuffer, [weightsEntry.manifestEntry]);\n        for (const name in nameToTensorMap) {\n          weightsTensorMap[name] = nameToTensorMap[name];\n        }\n      });\n\n      bufferIndexOffset += numBuffers;\n    });\n\n    return weightsTensorMap;\n  };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandler implementations based on HTTP requests in the web browser.\n *\n * Uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n */\n\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts, getWeightSpecs} from './io_utils';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, LoadOptions, ModelArtifacts, ModelJSON, SaveResult, WeightData, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeightsAsArrayBuffer, streamWeights} from './weights_loader';\n\nconst OCTET_STREAM_MIME_TYPE = 'application/octet-stream';\nconst JSON_TYPE = 'application/json';\nexport class HTTPRequest implements IOHandler {\n  protected readonly path: string;\n  protected readonly requestInit: RequestInit;\n\n  private readonly fetch: typeof fetch;\n  private readonly weightUrlConverter: (weightName: string) => Promise<string>;\n\n  readonly DEFAULT_METHOD = 'POST';\n\n  static readonly URL_SCHEME_REGEX = /^https?:\\/\\//;\n\n  private readonly weightPathPrefix: string;\n  private readonly loadOptions: LoadOptions;\n\n  constructor(path: string, loadOptions?: LoadOptions) {\n    if (loadOptions == null) {\n      loadOptions = {};\n    }\n    this.weightPathPrefix = loadOptions.weightPathPrefix;\n    this.weightUrlConverter = loadOptions.weightUrlConverter;\n\n    if (loadOptions.fetchFunc != null) {\n      assert(\n          typeof loadOptions.fetchFunc === 'function',\n          () => 'Must pass a function that matches the signature of ' +\n              '`fetch` (see ' +\n              'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)');\n      this.fetch = loadOptions.fetchFunc;\n    } else {\n      this.fetch = env().platform.fetch;\n    }\n\n    assert(\n        path != null && path.length > 0,\n        () => 'URL path for http must not be null, undefined or ' +\n            'empty.');\n\n    if (Array.isArray(path)) {\n      assert(\n          path.length === 2,\n          () => 'URL paths for http must have a length of 2, ' +\n              `(actual length is ${path.length}).`);\n    }\n    this.path = path;\n\n    if (loadOptions.requestInit != null &&\n        loadOptions.requestInit.body != null) {\n      throw new Error(\n          'requestInit is expected to have no pre-existing body, but has one.');\n    }\n    this.requestInit = loadOptions.requestInit || {};\n    this.loadOptions = loadOptions;\n  }\n\n  async save(modelArtifacts: ModelArtifacts): Promise<SaveResult> {\n    if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n      throw new Error(\n          'BrowserHTTPRequest.save() does not support saving model topology ' +\n          'in binary formats yet.');\n    }\n\n    const init = Object.assign({method: this.DEFAULT_METHOD}, this.requestInit);\n    init.body = new FormData();\n\n    const weightsManifest: WeightsManifestConfig = [{\n      paths: ['./model.weights.bin'],\n      weights: modelArtifacts.weightSpecs,\n    }];\n    const modelTopologyAndWeightManifest: ModelJSON =\n        getModelJSONForModelArtifacts(modelArtifacts, weightsManifest);\n\n    init.body.append(\n        'model.json',\n        new Blob(\n            [JSON.stringify(modelTopologyAndWeightManifest)],\n            {type: JSON_TYPE}),\n        'model.json');\n\n    if (modelArtifacts.weightData != null) {\n      // TODO(mattsoulanille): Support saving models over 2GB that exceed\n      // Chrome's ArrayBuffer size limit.\n      const weightBuffer = CompositeArrayBuffer.join(modelArtifacts.weightData);\n\n      init.body.append(\n          'model.weights.bin',\n          new Blob([weightBuffer], {type: OCTET_STREAM_MIME_TYPE}),\n          'model.weights.bin');\n    }\n\n    const response = await this.fetch(this.path, init);\n\n    if (response.ok) {\n      return {\n        modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),\n        responses: [response],\n      };\n    } else {\n      throw new Error(\n          `BrowserHTTPRequest.save() failed due to HTTP response status ` +\n          `${response.status}.`);\n    }\n  }\n\n  private async loadModelJSON(): Promise<ModelJSON> {\n    const modelConfigRequest = await this.fetch(this.path, this.requestInit);\n\n    if (!modelConfigRequest.ok) {\n      throw new Error(\n          `Request to ${this.path} failed with status code ` +\n          `${modelConfigRequest.status}. Please verify this URL points to ` +\n          `the model JSON of the model to load.`);\n    }\n    let modelJSON: ModelJSON;\n    try {\n      modelJSON = await modelConfigRequest.json();\n    } catch (e) {\n      let message = `Failed to parse model JSON of response from ${this.path}.`;\n      // TODO(nsthorat): Remove this after some time when we're comfortable that\n      // .pb files are mostly gone.\n      if (this.path.endsWith('.pb')) {\n        message += ' Your path contains a .pb file extension. ' +\n            'Support for .pb models have been removed in TensorFlow.js 1.0 ' +\n            'in favor of .json models. You can re-convert your Python ' +\n            'TensorFlow model using the TensorFlow.js 1.0 conversion scripts ' +\n            'or you can convert your.pb models with the \\'pb2json\\'' +\n            'NPM script in the tensorflow/tfjs-converter repository.';\n      } else {\n        message += ' Please make sure the server is serving valid ' +\n            'JSON for this request.';\n      }\n      throw new Error(message);\n    }\n\n    // We do not allow both modelTopology and weightsManifest to be missing.\n    const modelTopology = modelJSON.modelTopology;\n    const weightsManifest = modelJSON.weightsManifest;\n    if (modelTopology == null && weightsManifest == null) {\n      throw new Error(\n          `The JSON from HTTP path ${this.path} contains neither model ` +\n          `topology or manifest for weights.`);\n    }\n\n    return modelJSON;\n  }\n\n  /**\n   * Load model artifacts via HTTP request(s).\n   *\n   * See the documentation to `tf.io.http` for details on the saved\n   * artifacts.\n   *\n   * @returns The loaded model artifacts (if loading succeeds).\n   */\n  async load(): Promise<ModelArtifacts> {\n    if (this.loadOptions.streamWeights) {\n      return this.loadStream();\n    }\n    const modelJSON = await this.loadModelJSON();\n    return getModelArtifactsForJSON(\n        modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n  }\n\n  private async loadStream(): Promise<ModelArtifacts> {\n    const modelJSON = await this.loadModelJSON();\n    const fetchURLs = await this.getWeightUrls(modelJSON.weightsManifest);\n    const weightSpecs = getWeightSpecs(modelJSON.weightsManifest);\n    const stream = () => streamWeights(fetchURLs, this.loadOptions);\n\n    return {\n      ...modelJSON,\n      weightSpecs,\n      getWeightStream: stream,\n    };\n  }\n\n  private async getWeightUrls(weightsManifest: WeightsManifestConfig):\n    Promise<string[]> {\n    const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;\n    const [prefix, suffix] = parseUrl(weightPath);\n    const pathPrefix = this.weightPathPrefix || prefix;\n\n    const fetchURLs: string[] = [];\n    const urlPromises: Array<Promise<string>> = [];\n    for (const weightsGroup of weightsManifest) {\n      for (const path of weightsGroup.paths) {\n        if (this.weightUrlConverter != null) {\n          urlPromises.push(this.weightUrlConverter(path));\n        } else {\n          fetchURLs.push(pathPrefix + path + suffix);\n        }\n      }\n    }\n\n    if (this.weightUrlConverter) {\n      fetchURLs.push(...await Promise.all(urlPromises));\n    }\n    return fetchURLs;\n  }\n\n  private async loadWeights(weightsManifest: WeightsManifestConfig):\n    Promise<[WeightsManifestEntry[], WeightData]> {\n    const fetchURLs = await this.getWeightUrls(weightsManifest);\n    const weightSpecs = getWeightSpecs(weightsManifest);\n\n    const buffers = await loadWeightsAsArrayBuffer(fetchURLs, this.loadOptions);\n    return [weightSpecs, buffers];\n  }\n}\n\n/**\n * Extract the prefix and suffix of the url, where the prefix is the path before\n * the last file, and suffix is the search params after the last file.\n * ```\n * const url = 'http://tfhub.dev/model/1/tensorflowjs_model.pb?tfjs-format=file'\n * [prefix, suffix] = parseUrl(url)\n * // prefix = 'http://tfhub.dev/model/1/'\n * // suffix = '?tfjs-format=file'\n * ```\n * @param url the model url to be parsed.\n */\nexport function parseUrl(url: string): [string, string] {\n  const lastSlash = url.lastIndexOf('/');\n  const lastSearchParam = url.lastIndexOf('?');\n  const prefix = url.substring(0, lastSlash);\n  const suffix =\n      lastSearchParam > lastSlash ? url.substring(lastSearchParam) : '';\n  return [prefix + '/', suffix];\n}\n\nexport function isHTTPScheme(url: string): boolean {\n  return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;\n}\n\nexport const httpRouter: IORouter =\n    (url: string, loadOptions?: LoadOptions) => {\n      if (typeof fetch === 'undefined' &&\n          (loadOptions == null || loadOptions.fetchFunc == null)) {\n        // `http` uses `fetch` or `node-fetch`, if one wants to use it in\n        // an environment that is not the browser or node they have to setup a\n        // global fetch polyfill.\n        return null;\n      } else {\n        let isHTTP = true;\n        if (Array.isArray(url)) {\n          isHTTP = url.every(urlItem => isHTTPScheme(urlItem));\n        } else {\n          isHTTP = isHTTPScheme(url);\n        }\n        if (isHTTP) {\n          return http(url, loadOptions);\n        }\n      }\n      return null;\n    };\nIORouterRegistry.registerSaveRouter(httpRouter);\nIORouterRegistry.registerLoadRouter(httpRouter);\n\n/**\n * Creates an IOHandler subtype that sends model artifacts to HTTP server.\n *\n * An HTTP request of the `multipart/form-data` mime type will be sent to the\n * `path` URL. The form data includes artifacts that represent the topology\n * and/or weights of the model. In the case of Keras-style `tf.Model`, two\n * blobs (files) exist in form-data:\n *   - A JSON file consisting of `modelTopology` and `weightsManifest`.\n *   - A binary weights file consisting of the concatenated weight values.\n * These files are in the same format as the one generated by\n * [tfjs_converter](https://js.tensorflow.org/tutorials/import-keras.html).\n *\n * The following code snippet exemplifies the client-side code that uses this\n * function:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n *     tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save(tf.io.http(\n *     'http://model-server:5000/upload', {requestInit: {method: 'PUT'}}));\n * console.log(saveResult);\n * ```\n *\n * If the default `POST` method is to be used, without any custom parameters\n * such as headers, you can simply pass an HTTP or HTTPS URL to `model.save`:\n *\n * ```js\n * const saveResult = await model.save('http://model-server:5000/upload');\n * ```\n *\n * The following GitHub Gist\n * https://gist.github.com/dsmilkov/1b6046fd6132d7408d5257b0976f7864\n * implements a server based on [flask](https://github.com/pallets/flask) that\n * can receive the request. Upon receiving the model artifacts via the request,\n * this particular server reconstitutes instances of [Keras\n * Models](https://keras.io/models/model/) in memory.\n *\n *\n * @param path A URL path to the model.\n *   Can be an absolute HTTP path (e.g.,\n *   'http://localhost:8000/model-upload)') or a relative path (e.g.,\n *   './model-upload').\n * @param requestInit Request configurations to be used when sending\n *    HTTP request to server using `fetch`. It can contain fields such as\n *    `method`, `credentials`, `headers`, `mode`, etc. See\n *    https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\n *    for more information. `requestInit` must not have a body, because the\n * body will be set by TensorFlow.js. File blobs representing the model\n * topology (filename: 'model.json') and the weights of the model (filename:\n * 'model.weights.bin') will be appended to the body. If `requestInit` has a\n * `body`, an Error will be thrown.\n * @param loadOptions Optional configuration for the loading. It includes the\n *   following fields:\n *   - weightPathPrefix Optional, this specifies the path prefix for weight\n *     files, by default this is calculated from the path param.\n *   - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,\n *     the `fetch` from node-fetch can be used here.\n *   - onProgress Optional, progress callback function, fired periodically\n *     before the load is completed.\n * @returns An instance of `IOHandler`.\n *\n * @doc {\n *   heading: 'Models',\n *   subheading: 'Loading',\n *   namespace: 'io',\n *   ignoreCI: true\n * }\n */\nexport function http(path: string, loadOptions?: LoadOptions): IOHandler {\n  return new HTTPRequest(path, loadOptions);\n}\n\n/**\n * Deprecated. Use `tf.io.http`.\n * @param path\n * @param loadOptions\n */\nexport function browserHTTPRequest(\n    path: string, loadOptions?: LoadOptions): IOHandler {\n  return http(path, loadOptions);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers that pass through the in-memory ModelArtifacts format.\n */\n\nimport {IOHandler, IOHandlerSync, LoadHandler, ModelArtifacts, SaveHandler, SaveResult, TrainingConfig, WeightData, WeightsManifestEntry} from './types';\n\nclass PassthroughLoader implements IOHandlerSync {\n  constructor(private readonly modelArtifacts?: ModelArtifacts) {}\n\n  load(): ModelArtifacts {\n    return this.modelArtifacts;\n  }\n}\n\nclass PassthroughSaver<R extends SaveResult | Promise<SaveResult>> {\n  constructor(\n    private readonly saveHandler: (artifacts: ModelArtifacts) => R) {}\n\n  save(modelArtifacts: ModelArtifacts): R {\n    return this.saveHandler(modelArtifacts);\n  }\n}\n\nclass PassthroughAsync implements IOHandler {\n  load?: LoadHandler;\n  save?: SaveHandler;\n\n  constructor(handler: IOHandlerSync) {\n    if (handler.load) {\n      this.load = () => Promise.resolve(handler.load());\n    }\n    if (handler.save) {\n      this.save = (modelArtifacts: ModelArtifacts) =>\n        Promise.resolve(handler.save(modelArtifacts));\n    }\n  }\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n *     modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n *   the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n *   names, shapes, types, and quantization of the weight data. Optional.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n *   concatenated in the order described by the weightSpecs. Optional.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandler` that simply loads the provided data.\n */\nexport function fromMemory(\n    modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n    weightData?: WeightData, trainingConfig?: TrainingConfig): IOHandler {\n\n  const args = arguments as unknown as Parameters<typeof fromMemory>;\n  return new PassthroughAsync(fromMemorySync(...args));\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n *     modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n *   the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n *   names, shapes, types, and quantization of the weight data. Optional.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n *   concatenated in the order described by the weightSpecs. Optional.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandlerSync` that simply loads the provided data.\n */\nexport function fromMemorySync(\n    modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n    weightData?: WeightData, trainingConfig?: TrainingConfig): IOHandlerSync {\n  if (arguments.length === 1) {\n    const isModelArtifacts =\n        (modelArtifacts as ModelArtifacts).modelTopology != null ||\n        (modelArtifacts as ModelArtifacts).weightSpecs != null;\n    if (isModelArtifacts) {\n      return new PassthroughLoader(modelArtifacts as ModelArtifacts);\n    } else {\n      // Legacy support: with only modelTopology.\n      // TODO(cais): Remove this deprecated API.\n      console.warn(\n          'Please call tf.io.fromMemory() with only one argument. ' +\n          'The argument should be of type ModelArtifacts. ' +\n          'The multi-argument signature of tf.io.fromMemory() has been ' +\n          'deprecated and will be removed in a future release.');\n      return new PassthroughLoader({modelTopology: modelArtifacts as {}});\n    }\n  } else {\n    // Legacy support.\n    // TODO(cais): Remove this deprecated API.\n    console.warn(\n        'Please call tf.io.fromMemory() with only one argument. ' +\n        'The argument should be of type ModelArtifacts. ' +\n        'The multi-argument signature of tf.io.fromMemory() has been ' +\n        'deprecated and will be removed in a future release.');\n    return new PassthroughLoader({\n      modelTopology: modelArtifacts as {},\n      weightSpecs,\n      weightData,\n      trainingConfig\n    });\n  }\n}\n\n/**\n * Creates an IOHandler that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n *   // ... do something with the artifacts ...\n *   return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n *     promise that resolves to a `SaveResult`.\n */\nexport function withSaveHandler(\n    saveHandler: (artifacts: ModelArtifacts) =>\n        Promise<SaveResult>): IOHandler {\n  return new PassthroughSaver(saveHandler);\n}\n\n/**\n * Creates an IOHandlerSync that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n *   // ... do something with the artifacts ...\n *   return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n *     `SaveResult`.\n */\nexport function withSaveHandlerSync(\n    saveHandler: (artifacts: ModelArtifacts) => SaveResult): IOHandlerSync {\n  return new PassthroughSaver<SaveResult>(saveHandler);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Importing local_storage and indexed_db is necessary for the routers to be\n// registered.\nimport './indexed_db';\nimport './local_storage';\n\nimport {browserFiles} from './browser_files';\nimport {browserHTTPRequest, http, isHTTPScheme} from './http';\nimport {concatenateArrayBuffers, decodeWeights, decodeWeightsStream, encodeWeights, getModelArtifactsForJSON, getModelArtifactsForJSONSync, getModelArtifactsInfoForJSON, getWeightSpecs} from './io_utils';\nimport {fromMemory, fromMemorySync, withSaveHandler, withSaveHandlerSync} from './passthrough';\nimport {getLoadHandlers, getSaveHandlers, registerLoadRouter, registerSaveRouter} from './router_registry';\nimport {IOHandler, IOHandlerSync, LoadHandler, LoadOptions, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, OnProgressCallback, RequestDetails, SaveConfig, SaveHandler, SaveResult, TrainingConfig, WeightGroup, WeightsManifestConfig, WeightsManifestEntry, WeightData} from './types';\nimport {loadWeights, weightsLoaderFactory} from './weights_loader';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\n\nexport {copyModel, listModels, moveModel, removeModel} from './model_management';\nexport {\n  browserFiles,\n  browserHTTPRequest,\n  CompositeArrayBuffer,\n  concatenateArrayBuffers,\n  decodeWeights,\n  decodeWeightsStream,\n  encodeWeights,\n  fromMemory,\n  fromMemorySync,\n  getLoadHandlers,\n  getModelArtifactsForJSON,\n  getModelArtifactsForJSONSync,\n  getModelArtifactsInfoForJSON,\n  getSaveHandlers,\n  getWeightSpecs,\n  http,\n  IOHandler,\n  IOHandlerSync,\n  isHTTPScheme,\n  LoadHandler,\n  LoadOptions,\n  loadWeights,\n  ModelArtifacts,\n  ModelArtifactsInfo,\n  ModelJSON,\n  ModelStoreManager,\n  OnProgressCallback,\n  registerLoadRouter,\n  registerSaveRouter,\n  RequestDetails,\n  SaveConfig,\n  SaveHandler,\n  SaveResult,\n  TrainingConfig,\n  WeightData,\n  WeightGroup,\n  weightsLoaderFactory,\n  WeightsManifestConfig,\n  WeightsManifestEntry,\n  withSaveHandler,\n  withSaveHandlerSync,\n};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {matMul} from './mat_mul';\nimport {oneHot} from './one_hot';\nimport {op} from './operation';\nimport {transpose} from './transpose';\n\n/**\n * Computes the confusion matrix from true labels and predicted labels.\n *\n * ```js\n * const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');\n * const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');\n * const numClasses = 3;\n * const out = tf.math.confusionMatrix(labels, predictions, numClasses);\n * out.print();\n * // Expected output matrix:\n * // [[2, 0, 0],\n * //  [0, 1, 1],\n * //  [0, 0, 1]]\n * ```\n *\n * @param labels The target labels, assumed to be 0-based integers\n *   for the classes. The shape is `[numExamples]`, where\n *   `numExamples` is the number of examples included.\n * @param predictions The predicted classes, assumed to be\n *   0-based integers for the classes. Must have the same shape as `labels`.\n * @param numClasses Number of all classes, as an integer.\n *   Its value must be larger than the largest element in `labels` and\n *   `predictions`.\n * @returns The confusion matrix as a int32-type 2D tensor. The value at\n *   row `r` and column `c` is the number of times examples of actual class\n *   `r` were predicted as class `c`.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function confusionMatrix_(\n    labels: Tensor1D|TensorLike, predictions: Tensor1D|TensorLike,\n    numClasses: number): Tensor2D {\n  const $labels = convertToTensor(labels, 'labels', 'confusionMatrix');\n  const $predictions =\n      convertToTensor(predictions, 'predictions', 'confusionMatrix');\n\n  util.assert(\n      numClasses == null || numClasses > 0 && Number.isInteger(numClasses),\n      () => `If provided, numClasses must be a positive integer, ` +\n          `but got ${numClasses}`);\n  util.assert(\n      $labels.rank === 1,\n      () => `Expected the rank of labels to be 1, but got ${$labels.rank}`);\n  util.assert(\n      $predictions.rank === 1,\n      () => `Expected the rank of predictions to be 1, ` +\n          `but got ${$predictions.rank}`);\n  util.assert(\n      $labels.shape[0] === $predictions.shape[0],\n      () => `Mismatch in the number of examples: ` +\n          `${$labels.shape[0]} vs. ${$predictions.shape[0]}. ` +\n          `Labels and predictions should have the same number of elements.`);\n  util.assert(\n      numClasses > 0 && Number.isInteger(numClasses),\n      () => `numClasses is required to be a positive integer, but got ` +\n          `${numClasses}`);\n  // TODO(cais): In the future, if oneHot supports tensors inputs for\n  //   `numClasses`, `confusionMatrix` can make `numClasses` optional.\n\n  const oneHotLabels = oneHot(cast($labels, 'int32'), numClasses) as Tensor2D;\n  const oneHotPredictions =\n      oneHot(cast($predictions, 'int32'), numClasses) as Tensor2D;\n  const oneHotLabelsT: Tensor2D = transpose(oneHotLabels);\n  const product: Tensor2D = matMul(oneHotLabelsT, oneHotPredictions);\n  return cast(product, 'int32');\n}\n\nexport const confusionMatrix = /* @__PURE__ */ op({confusionMatrix_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Exports under the tf.math.* namespace.\n */\n\nimport {confusionMatrix} from './ops/confusion_matrix';\n\nexport {confusionMatrix};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {env} from '../environment';\nimport {Draw, DrawAttrs, DrawInputs, FromPixels, FromPixelsAttrs, FromPixelsInputs} from '../kernel_names';\nimport {getKernel, NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor2D, Tensor3D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DrawOptions, ImageOptions, PixelData, TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\nimport {tensor3d} from './tensor3d';\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\nlet hasToPixelsWarned = false;\n\n/**\n * Creates a `tf.Tensor` from an image.\n *\n * ```js\n * const image = new ImageData(1, 1);\n * image.data[0] = 100;\n * image.data[1] = 150;\n * image.data[2] = 200;\n * image.data[3] = 255;\n *\n * tf.browser.fromPixels(image).print();\n * ```\n *\n * @param pixels The input image to construct the tensor from. The\n * supported image types are all 4-channel. You can also pass in an image\n * object with following attributes:\n * `{data: Uint8Array; width: number; height: number}`\n * @param numChannels The number of channels of the output tensor. A\n * numChannels value less than 4 allows you to ignore channels. Defaults to\n * 3 (ignores alpha channel of input image).\n *\n * @returns A Tensor3D with the shape `[height, width, numChannels]`.\n *\n * Note: fromPixels can be lossy in some cases, same image may result in\n * slightly different tensor values, if rendered by different rendering\n * engines. This means that results from different browsers, or even same\n * browser with CPU and GPU rendering engines can be different. See discussion\n * in details:\n * https://github.com/tensorflow/tfjs/issues/5482\n *\n * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}\n */\nfunction fromPixels_(\n    pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n    HTMLVideoElement|ImageBitmap,\n    numChannels = 3): Tensor3D {\n  // Sanity checks.\n  if (numChannels > 4) {\n    throw new Error(\n        'Cannot construct Tensor with more than 4 channels from pixels.');\n  }\n  if (pixels == null) {\n    throw new Error('pixels passed to tf.browser.fromPixels() can not be null');\n  }\n  let isPixelData = false;\n  let isImageData = false;\n  let isVideo = false;\n  let isImage = false;\n  let isCanvasLike = false;\n  let isImageBitmap = false;\n  if ((pixels as PixelData).data instanceof Uint8Array) {\n    isPixelData = true;\n  } else if (\n      typeof (ImageData) !== 'undefined' && pixels instanceof ImageData) {\n    isImageData = true;\n  } else if (\n      typeof (HTMLVideoElement) !== 'undefined' &&\n      pixels instanceof HTMLVideoElement) {\n    isVideo = true;\n  } else if (\n      typeof (HTMLImageElement) !== 'undefined' &&\n      pixels instanceof HTMLImageElement) {\n    isImage = true;\n    // tslint:disable-next-line: no-any\n  } else if ((pixels as any).getContext != null) {\n    isCanvasLike = true;\n  } else if (\n      typeof (ImageBitmap) !== 'undefined' && pixels instanceof ImageBitmap) {\n    isImageBitmap = true;\n  } else {\n    throw new Error(\n        'pixels passed to tf.browser.fromPixels() must be either an ' +\n        `HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData ` +\n        `in browser, or OffscreenCanvas, ImageData in webworker` +\n        ` or {data: Uint32Array, width: number, height: number}, ` +\n        `but was ${(pixels as {}).constructor.name}`);\n  }\n  // If the current backend has 'FromPixels' registered, it has a more\n  // efficient way of handling pixel uploads, so we call that.\n  const kernel = getKernel(FromPixels, ENGINE.backendName);\n  if (kernel != null) {\n    const inputs: FromPixelsInputs = {pixels};\n    const attrs: FromPixelsAttrs = {numChannels};\n    return ENGINE.runKernel(\n        FromPixels, inputs as unknown as NamedTensorMap,\n        attrs as unknown as NamedAttrMap);\n  }\n\n  const [width, height] = isVideo ?\n      [\n        (pixels as HTMLVideoElement).videoWidth,\n        (pixels as HTMLVideoElement).videoHeight\n      ] :\n      [pixels.width, pixels.height];\n  let vals: Uint8ClampedArray|Uint8Array;\n\n  if (isCanvasLike) {\n    vals =\n        // tslint:disable-next-line:no-any\n        (pixels as any).getContext('2d').getImageData(0, 0, width, height).data;\n  } else if (isImageData || isPixelData) {\n    vals = (pixels as PixelData | ImageData).data;\n  } else if (isImage || isVideo || isImageBitmap) {\n    if (fromPixels2DContext == null) {\n      if (typeof document === 'undefined') {\n        if (typeof OffscreenCanvas !== 'undefined' &&\n            typeof OffscreenCanvasRenderingContext2D !== 'undefined') {\n          // @ts-ignore\n          fromPixels2DContext = new OffscreenCanvas(1, 1).getContext('2d');\n        } else {\n          throw new Error(\n              'Cannot parse input in current context. ' +\n              'Reason: OffscreenCanvas Context2D rendering is not supported.');\n        }\n      } else {\n        fromPixels2DContext = document.createElement('canvas').getContext(\n            '2d', {willReadFrequently: true});\n      }\n    }\n    fromPixels2DContext.canvas.width = width;\n    fromPixels2DContext.canvas.height = height;\n    fromPixels2DContext.drawImage(\n        pixels as HTMLVideoElement, 0, 0, width, height);\n    vals = fromPixels2DContext.getImageData(0, 0, width, height).data;\n  }\n  let values: Int32Array;\n  if (numChannels === 4) {\n    values = new Int32Array(vals);\n  } else {\n    const numPixels = width * height;\n    values = new Int32Array(numPixels * numChannels);\n    for (let i = 0; i < numPixels; i++) {\n      for (let channel = 0; channel < numChannels; ++channel) {\n        values[i * numChannels + channel] = vals[i * 4 + channel];\n      }\n    }\n  }\n  const outShape: [number, number, number] = [height, width, numChannels];\n  return tensor3d(values, outShape, 'int32');\n}\n\n// Helper functions for |fromPixelsAsync| to check whether the input can\n// be wrapped into imageBitmap.\nfunction isPixelData(pixels: PixelData|ImageData|HTMLImageElement|\n                     HTMLCanvasElement|HTMLVideoElement|\n                     ImageBitmap): pixels is PixelData {\n  return (pixels != null) && ((pixels as PixelData).data instanceof Uint8Array);\n}\n\nfunction isImageBitmapFullySupported() {\n  return typeof window !== 'undefined' &&\n      typeof (ImageBitmap) !== 'undefined' &&\n      window.hasOwnProperty('createImageBitmap');\n}\n\nfunction isNonEmptyPixels(pixels: PixelData|ImageData|HTMLImageElement|\n                          HTMLCanvasElement|HTMLVideoElement|ImageBitmap) {\n  return pixels != null && pixels.width !== 0 && pixels.height !== 0;\n}\n\nfunction canWrapPixelsToImageBitmap(pixels: PixelData|ImageData|\n                                    HTMLImageElement|HTMLCanvasElement|\n                                    HTMLVideoElement|ImageBitmap) {\n  return isImageBitmapFullySupported() && !(pixels instanceof ImageBitmap) &&\n      isNonEmptyPixels(pixels) && !isPixelData(pixels);\n}\n\n/**\n * Creates a `tf.Tensor` from an image in async way.\n *\n * ```js\n * const image = new ImageData(1, 1);\n * image.data[0] = 100;\n * image.data[1] = 150;\n * image.data[2] = 200;\n * image.data[3] = 255;\n *\n * (await tf.browser.fromPixelsAsync(image)).print();\n * ```\n * This API is the async version of fromPixels. The API will first\n * check |WRAP_TO_IMAGEBITMAP| flag, and try to wrap the input to\n * imageBitmap if the flag is set to true.\n *\n * @param pixels The input image to construct the tensor from. The\n * supported image types are all 4-channel. You can also pass in an image\n * object with following attributes:\n * `{data: Uint8Array; width: number; height: number}`\n * @param numChannels The number of channels of the output tensor. A\n * numChannels value less than 4 allows you to ignore channels. Defaults to\n * 3 (ignores alpha channel of input image).\n *\n * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}\n */\nexport async function fromPixelsAsync(\n    pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n    HTMLVideoElement|ImageBitmap,\n    numChannels = 3) {\n  let inputs: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n      HTMLVideoElement|ImageBitmap = null;\n\n  // Check whether the backend needs to wrap |pixels| to imageBitmap and\n  // whether |pixels| can be wrapped to imageBitmap.\n  if (env().getBool('WRAP_TO_IMAGEBITMAP') &&\n      canWrapPixelsToImageBitmap(pixels)) {\n    // Force the imageBitmap creation to not do any premultiply alpha\n    // ops.\n    let imageBitmap;\n\n    try {\n      // wrap in try-catch block, because createImageBitmap may not work\n      // properly in some browsers, e.g.\n      // https://bugzilla.mozilla.org/show_bug.cgi?id=1335594\n      // tslint:disable-next-line: no-any\n      imageBitmap = await (createImageBitmap as any)(\n          pixels as ImageBitmapSource, {premultiplyAlpha: 'none'});\n    } catch (e) {\n      imageBitmap = null;\n    }\n\n    // createImageBitmap will clip the source size.\n    // In some cases, the input will have larger size than its content.\n    // E.g. new Image(10, 10) but with 1 x 1 content. Using\n    // createImageBitmap will clip the size from 10 x 10 to 1 x 1, which\n    // is not correct. We should avoid wrapping such resouce to\n    // imageBitmap.\n    if (imageBitmap != null && imageBitmap.width === pixels.width &&\n        imageBitmap.height === pixels.height) {\n      inputs = imageBitmap;\n    } else {\n      inputs = pixels;\n    }\n  } else {\n    inputs = pixels;\n  }\n\n  return fromPixels_(inputs, numChannels);\n}\n\nfunction validateImgTensor(img: Tensor2D|Tensor3D) {\n  if (img.rank !== 2 && img.rank !== 3) {\n    throw new Error(\n        `toPixels only supports rank 2 or 3 tensors, got rank ${img.rank}.`);\n  }\n  const depth = img.rank === 2 ? 1 : img.shape[2];\n\n  if (depth > 4 || depth === 2) {\n    throw new Error(\n        `toPixels only supports depth of size ` +\n        `1, 3 or 4 but got ${depth}`);\n  }\n\n  if (img.dtype !== 'float32' && img.dtype !== 'int32') {\n    throw new Error(\n        `Unsupported type for toPixels: ${img.dtype}.` +\n        ` Please use float32 or int32 tensors.`);\n  }\n}\n\nfunction validateImageOptions(imageOptions: ImageOptions) {\n  const alpha = imageOptions ?.alpha || 1;\n  if (alpha > 1 || alpha < 0) {\n    throw new Error(`Alpha value ${alpha} is suppoed to be in range [0 - 1].`);\n  }\n}\n\n/**\n * Draws a `tf.Tensor` of pixel values to a byte array or optionally a\n * canvas.\n *\n * When the dtype of the input is 'float32', we assume values in the range\n * [0-1]. Otherwise, when input is 'int32', we assume values in the range\n * [0-255].\n *\n * Returns a promise that resolves when the canvas has been drawn to.\n *\n * @param img A rank-2 tensor with shape `[height, width]`, or a rank-3 tensor\n * of shape `[height, width, numChannels]`. If rank-2, draws grayscale. If\n * rank-3, must have depth of 1, 3 or 4. When depth of 1, draws\n * grayscale. When depth of 3, we draw with the first three components of\n * the depth dimension corresponding to r, g, b and alpha = 1. When depth of\n * 4, all four components of the depth dimension correspond to r, g, b, a.\n * @param canvas The canvas to draw to.\n *\n * @doc {heading: 'Browser', namespace: 'browser'}\n */\nexport async function toPixels(\n    img: Tensor2D|Tensor3D|TensorLike,\n    canvas?: HTMLCanvasElement): Promise<Uint8ClampedArray> {\n  let $img = convertToTensor(img, 'img', 'toPixels');\n  if (!(img instanceof Tensor)) {\n    // Assume int32 if user passed a native array.\n    const originalImgTensor = $img;\n    $img = cast(originalImgTensor, 'int32');\n    originalImgTensor.dispose();\n  }\n  validateImgTensor($img);\n\n  const [height, width] = $img.shape.slice(0, 2);\n  const depth = $img.rank === 2 ? 1 : $img.shape[2];\n  const data = await $img.data();\n  const multiplier = $img.dtype === 'float32' ? 255 : 1;\n  const bytes = new Uint8ClampedArray(width * height * 4);\n\n  for (let i = 0; i < height * width; ++i) {\n    const rgba = [0, 0, 0, 255];\n\n    for (let d = 0; d < depth; d++) {\n      const value = data[i * depth + d];\n\n      if ($img.dtype === 'float32') {\n        if (value < 0 || value > 1) {\n          throw new Error(\n              `Tensor values for a float32 Tensor must be in the ` +\n              `range [0 - 1] but encountered ${value}.`);\n        }\n      } else if ($img.dtype === 'int32') {\n        if (value < 0 || value > 255) {\n          throw new Error(\n              `Tensor values for a int32 Tensor must be in the ` +\n              `range [0 - 255] but encountered ${value}.`);\n        }\n      }\n\n      if (depth === 1) {\n        rgba[0] = value * multiplier;\n        rgba[1] = value * multiplier;\n        rgba[2] = value * multiplier;\n      } else {\n        rgba[d] = value * multiplier;\n      }\n    }\n\n    const j = i * 4;\n    bytes[j + 0] = Math.round(rgba[0]);\n    bytes[j + 1] = Math.round(rgba[1]);\n    bytes[j + 2] = Math.round(rgba[2]);\n    bytes[j + 3] = Math.round(rgba[3]);\n  }\n\n  if (canvas != null) {\n    if (!hasToPixelsWarned) {\n      const kernel = getKernel(Draw, ENGINE.backendName);\n      if (kernel != null) {\n        console.warn(\n            'tf.browser.toPixels is not efficient to draw tensor on canvas. ' +\n            'Please try tf.browser.draw instead.');\n        hasToPixelsWarned = true;\n      }\n    }\n\n    canvas.width = width;\n    canvas.height = height;\n    const ctx = canvas.getContext('2d');\n    const imageData = new ImageData(bytes, width, height);\n    ctx.putImageData(imageData, 0, 0);\n  }\n  if ($img !== img) {\n    $img.dispose();\n  }\n  return bytes;\n}\n\n/**\n * Draws a `tf.Tensor` to a canvas.\n *\n * When the dtype of the input is 'float32', we assume values in the range\n * [0-1]. Otherwise, when input is 'int32', we assume values in the range\n * [0-255].\n *\n * @param image The tensor to draw on the canvas. Must match one of\n * these shapes:\n *   - Rank-2 with shape `[height, width`]: Drawn as grayscale.\n *   - Rank-3 with shape `[height, width, 1]`: Drawn as grayscale.\n *   - Rank-3 with shape `[height, width, 3]`: Drawn as RGB with alpha set in\n *     `imageOptions` (defaults to 1, which is opaque).\n *   - Rank-3 with shape `[height, width, 4]`: Drawn as RGBA.\n * @param canvas The canvas to draw to.\n * @param options The configuration arguments for image to be drawn and the\n *     canvas to draw to.\n *\n * @doc {heading: 'Browser', namespace: 'browser'}\n */\nexport function draw(\n    image: Tensor2D|Tensor3D|TensorLike, canvas: HTMLCanvasElement,\n    options?: DrawOptions): void {\n  let $img = convertToTensor(image, 'img', 'draw');\n  if (!(image instanceof Tensor)) {\n    // Assume int32 if user passed a native array.\n    const originalImgTensor = $img;\n    $img = cast(originalImgTensor, 'int32');\n    originalImgTensor.dispose();\n  }\n  validateImgTensor($img);\n  validateImageOptions(options?.imageOptions);\n\n  const inputs: DrawInputs = {image: $img};\n  const attrs: DrawAttrs = {canvas, options};\n  ENGINE.runKernel(\n      Draw, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const fromPixels = /* @__PURE__ */ op({fromPixels_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { TensorInfo } from '../tensor_info';\nimport {computeStrides, sizeFromShape} from '../util';\n\n/**\n * Validate gather nd inputs.\n *\n * @param tensor The tensor contains the source values.\n * @param indices The tensor contains the indices to slice the source.\n *\n * @returns [resultShape, numUpdates, sliceSize, strides]\n */\nexport function prepareAndValidate(tensor: TensorInfo, indices: TensorInfo):\n    [number[], number, number, number[]] {\n  const tensorRank = tensor.shape.length;\n  const indicesRank = indices.shape.length;\n  if (tensorRank < 1) {\n    throw new Error(\n        'tf.gatherND() expects the input to be rank 1 or higher,' +\n        ` but the rank was ${tensorRank}.`);\n  }\n  if (indicesRank < 1) {\n    throw new Error(\n        'tf.gatherND() expects the indices to be rank 1 or higher,' +\n        ` but the rank was ${indicesRank}.`);\n  }\n  if (indices.dtype !== 'int32') {\n    throw new Error(\n        'tf.gatherND() expects the indices to be int32 type,' +\n        ` but the dtype was ${indices.dtype}.`);\n  }\n  if (indices.shape[indicesRank - 1] > tensorRank) {\n    throw new Error(\n        'index innermost dimension length must be <= tensor rank; saw: ' +\n        `${indices.shape[indicesRank - 1]} vs. ${tensorRank}`);\n  }\n\n  if (sizeFromShape(tensor.shape) === 0) {\n    throw new Error(\n        'Requested more than 0 entries, but input is empty.' +\n        ` Input shape: ${tensor.shape}.`);\n  }\n\n  const indicesShape = indices.shape;\n  const sliceRank = indicesShape[indicesShape.length - 1];\n\n  // The result shape is\n  //   indices.shape[:-1] + params.shape[indices.shape[-1]:]\n  let nResult = 1;\n  for (let i = 0; i < indicesShape.length - 1; ++i) {\n    nResult *= indicesShape[i];\n  }\n\n  const inputShape = tensor.shape;\n\n  const resultShape = indicesShape.slice();\n  resultShape.pop();\n\n  let sliceSize = 1;\n  for (let i = sliceRank; i < tensorRank; ++i) {\n    sliceSize *= inputShape[i];\n    resultShape.push(inputShape[i]);\n  }\n\n  const strides =\n      [...computeStrides(tensor.shape).map(stride => stride / sliceSize),\n       1].slice(0, sliceRank);\n\n  return [resultShape, nResult, sliceSize, strides];\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { TensorInfo } from '../tensor_info';\nimport * as util from '../util';\n\nconst NEW_AXIS = -2;\nconst SHRINK_AXIS = -1;\n\n// Sparse slicing specification\n// if one does foo[3:5, ..., -3], the begin, end and strides will have length\n// of 3.\ninterface StridedSliceSparseSpec {\n  dims: number;\n  numAddAxisAfterEllipsis: number;\n  begin: number[];\n  end: number[];\n  strides: number[];\n  beginMask: number;\n  endMask: number;\n  ellipsisMask: number;\n  newAxisMask: number;\n  shrinkAxisMask: number;\n}\n\n// Dense slicing specification\n// all ellipses and newaxis are expanded out. So if foo[3:5, ..., -3] where foo\n// is 10 dimensional, each array of begin, end, strides will have 10 entries\n// where as the sparse can have length less than the rank of foo.\ninterface StridedSliceDenseSpec {\n  dims: number;\n  beginMask?: number;\n  endMask?: number;\n  beginValid: boolean;\n  endValid: boolean;\n  begin?: number[];\n  end?: number[];\n  strides?: number[];\n  // This array helps construct the final shape of the slice.\n  // The final tensor is reduced in rank whenever a single index e.g. foo[3]\n  // is called for. The final tensor increases in rank with newAxis entries.\n  // If an index in this array is positive, the size of the dimension is\n  // obtained from canonical end-begin.  Otherwise, if it is a NEW_AXIS, it will\n  // be 1. A shrunk dimension is skipped.\n  finalShapeGatherIndices?: number[];\n  // This array has the same size as finalShapeGatherIndices, but it remembers\n  // the sparse index that a dimension comes from, instead of dense index.\n  // A -1 in this vector means the index is not from the sparse input.\n  finalShapeGatherIndicesSparse?: number[];\n  inputShapeGatherIndicesSparse?: number[];\n  // The dense indexed shrink mask is which processing dimensions should be\n  // shrunk. For example, if foo.shape = [10, 10, 10, 10], foo[3, ..., 5] has\n  // sparseShrinkAxisMask of 5 (0101) and denseShrinkAxisMask of 9 (1001),\n  // yielding a final shape [10, 10].\n  shrinkAxisMask?: number;\n}\n\nexport type SliceInfo = {\n  finalShapeSparse: number[],\n  finalShape: number[],\n  isIdentity: boolean,\n  sliceDim0: boolean,\n  isSimpleSlice: boolean,\n  begin: number[],\n  end: number[],\n  strides: number[]\n};\n\nexport function assertParamsValid(\n    input: TensorInfo, begin: number[], size: number[]): void {\n  const inputRank = input.shape.length;\n  util.assert(\n      inputRank === begin.length,\n      () => `Error in slice${inputRank}D: Length of begin ${begin} must ` +\n          `match the rank of the array (${inputRank}).`);\n  util.assert(\n      inputRank === size.length,\n      () => `Error in slice${inputRank}D: Length of size ${size} must ` +\n          `match the rank of the array (${inputRank}).`);\n\n  for (let i = 0; i < inputRank; ++i) {\n    util.assert(\n        begin[i] + size[i] <= input.shape[i],\n        () => `Error in slice${inputRank}D: begin[${i}] + size[${i}] ` +\n            `(${begin[i] + size[i]}) would overflow input.shape[${i}] (${\n                  input.shape[i]})`);\n  }\n}\n\n/** Converts a binary mask to an array of axes. Used in stridedSlice(). */\nexport function maskToAxes(mask: number): number[] {\n  const axes = [];\n  let axis = 0;\n  while (mask > 0) {\n    if (mask & 1) {\n      axes.push(axis);\n    }\n    mask /= 2;\n    axis++;\n  }\n  return axes;\n}\n\n/** Computes the output shape given the strided slice params. */\nexport function computeOutShape(\n    begin: number[], end: number[], strides: number[]): number[] {\n  const size = [];\n  for (let axis = 0; axis < begin.length; axis++) {\n    size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);\n  }\n  return size;\n}\n\n// Creates full selection at the elided dimensions. If the dimension matches\n// the ellipsis mask, override the current stride value. Otherwise, insert.\nexport function stridesWithElidedDims(\n    strides: number[], ellipsisInsertionIndex: number, numElidedAxes: number,\n    inputShape: number[]): number[] {\n  const newStrides = [...strides];\n  for (let i = newStrides.length; i < inputShape.length; i++) {\n    newStrides.push(1);\n  }\n  for (let i = 0; i < numElidedAxes; i++) {\n    if (i === 0) {\n      newStrides[ellipsisInsertionIndex] = 1;\n    } else {\n      newStrides.splice(\n          ellipsisInsertionIndex, 0 /* num elements to delete */,\n          1 /* element to add */);\n      newStrides.pop();\n    }\n  }\n  return newStrides;\n}\n\nfunction unnormalizeAxis(\n    ellipsisInsertionIndex: number, numElidedAxes: number,\n    normalizedAxis: number): number {\n  if (normalizedAxis <= ellipsisInsertionIndex) {\n    return normalizedAxis;\n  }\n\n  return normalizedAxis - (numElidedAxes - 1);\n}\n\nfunction getElidedAxes(numElidedAxes: number, ellipsisInsertionIndex: number) {\n  const elidedAxes = [];\n  for (let i = 0; i < numElidedAxes; i++) {\n    elidedAxes.push(ellipsisInsertionIndex + i);\n  }\n  return elidedAxes;\n}\n\n// Normalize the start, end and strides.\nexport function getNormalizedAxes(\n    inputShape: number[], ellipsisAxes: number[], numInterpolatedAxes: number,\n    begin: number[], end: number[], strides: number[], beginMask: number,\n    endMask: number,\n    ellipsisMask: number): {begin: number[], end: number[], strides: number[]} {\n  const inputRank = inputShape.length;\n  let normalizedBegin = new Array(inputRank),\n      normalizedEnd = new Array(inputRank),\n      normalizedStrides = new Array(inputRank);\n  if (ellipsisAxes.length && numInterpolatedAxes > 0) {\n    const fullIndex = ellipsisAxes[0];\n\n    // The ellipsis applies to the masked index as well as any dimensions\n    // that are interpolated.\n    const numElidedAxes = numInterpolatedAxes + 1;\n    normalizedBegin = startIndicesWithElidedDims(\n        beginMask, fullIndex, numElidedAxes, begin, inputShape);\n    normalizedEnd = stopIndicesWithElidedDims(\n        endMask, fullIndex, numElidedAxes, end, inputShape);\n    normalizedStrides =\n        stridesWithElidedDims(strides, fullIndex, numElidedAxes, inputShape);\n  } else {\n    for (let axis = 0; axis < inputRank; axis++) {\n      normalizedBegin[axis] = startForAxis(\n          beginMask, begin, strides, inputShape, axis, ellipsisMask);\n      normalizedEnd[axis] =\n          stopForAxis(endMask, end, strides, inputShape, axis, ellipsisMask);\n      normalizedStrides[axis] = stridesForAxis(strides, axis, ellipsisMask);\n    }\n  }\n\n  return {\n    begin: normalizedBegin,\n    end: normalizedEnd,\n    strides: normalizedStrides\n  };\n}\n\n// Creates full selection at the elided dimensions. If the dimension matches\n// the ellipsis mask, override the current start value. Otherwise, insert.\nexport function startIndicesWithElidedDims(\n    beginMask: number, ellipsisInsertionIndex: number, numElidedAxes: number,\n    originalBegin: number[], inputShape: number[]): number[] {\n  const newIndices = [...inputShape];\n  const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);\n\n  for (let axis = 0; axis < newIndices.length; axis++) {\n    if (elidedAxes.indexOf(axis) > -1) {\n      newIndices[axis] = 0;\n    } else {\n      const originalAxis =\n          unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);\n      let originalValue = originalBegin[originalAxis];\n      if (beginMask & 1 << originalAxis) {\n        originalValue = 0;\n      }\n\n      newIndices[axis] = originalValue;\n    }\n  }\n  return newIndices;\n}\n\n// Creates full selection at the elided dimensions. If the dimension matches\n// the ellipsis mask, override the current stop value. Otherwise, insert.\nexport function stopIndicesWithElidedDims(\n    endMask: number, ellipsisInsertionIndex: number, numElidedAxes: number,\n    originalEnd: number[], inputShape: number[]): number[] {\n  const newIndices = [...inputShape];\n  const elidedAxes = getElidedAxes(numElidedAxes, ellipsisInsertionIndex);\n\n  for (let axis = 0; axis < newIndices.length; axis++) {\n    if (elidedAxes.indexOf(axis) > -1) {\n      newIndices[axis] = Number.MAX_SAFE_INTEGER;\n    } else {\n      const originalAxis =\n          unnormalizeAxis(ellipsisInsertionIndex, numElidedAxes, axis);\n      let originalValue = originalEnd[originalAxis];\n      if (endMask & 1 << originalAxis) {\n        originalValue = Number.MAX_SAFE_INTEGER;\n      }\n      newIndices[axis] = originalValue;\n    }\n  }\n\n  for (let i = 0; i < newIndices.length; i++) {\n    // Handle negative indices\n    const axisSize = inputShape[i];\n    if (newIndices[i] < 0) {\n      newIndices[i] += axisSize;\n    }\n    newIndices[i] = util.clamp(0, newIndices[i], inputShape[i]);\n  }\n  return newIndices;\n}\n\nexport function stridesForAxis(\n    strides: number[], axis: number, ellipsisMask: number): number {\n  let stride = strides[axis];\n  if (ellipsisMask & (1 << axis) || stride == null) {\n    stride = 1;\n  }\n\n  return stride;\n}\n\nexport function startForAxis(\n    beginMask: number, startIndices: number[], strides: number[],\n    inputShape: number[], axis: number, ellipsisMask: number): number {\n  // Begin with the specified index\n  let start = startIndices[axis];\n  const stride = strides[axis] || 1;\n\n  // Check the axis bit from right of masked axes, or the begin index is not set\n  // for the axis.\n  if (beginMask & 1 << axis || ellipsisMask & 1 << axis || start == null) {\n    if (stride > 0) {\n      // Forward iteration - use the first element. These values will get\n      // clamped below (Note: We could have set them to 0 and axis_size-1, but\n      // use lowest() and max() to maintain symmetry with StopForAxis())\n      start = Number.MIN_SAFE_INTEGER;\n    } else {\n      // Backward iteration - use the last element.\n      start = Number.MAX_SAFE_INTEGER;\n    }\n  }\n\n  // Handle negative indices\n  const axisSize = inputShape[axis];\n  if (start < 0) {\n    start += axisSize;\n  }\n\n  // Clamping\n  start = util.clamp(0, start, axisSize - 1);\n\n  return start;\n}\n\nexport function stopForAxis(\n    endMask: number, stopIndices: number[], strides: number[],\n    inputShape: number[], axis: number, ellipsisMask: number): number {\n  // Begin with the specified index\n  let stop = stopIndices[axis];\n  const stride = strides[axis] || 1;\n\n  // Check the axis bit from right of masked axes, or if the stop index is not\n  // set for this axis.\n  if (endMask & (1 << axis) || ellipsisMask & (1 << axis) || stop == null) {\n    if (stride > 0) {\n      // Forward iteration - use the last element. These values will get\n      // clamped below\n      stop = Number.MAX_SAFE_INTEGER;\n    } else {\n      // Backward iteration - use the first element.\n      stop = Number.MIN_SAFE_INTEGER;\n    }\n  }\n\n  // Handle negative indices\n  const axisSize = inputShape[axis];\n  if (stop < 0) {\n    stop += axisSize;\n  }\n\n  // Clamping\n  // Because the end index points one past the last element, we need slightly\n  // different clamping ranges depending on the direction.\n  if (stride > 0) {\n    // Forward iteration\n    stop = util.clamp(0, stop, axisSize);\n  } else {\n    // Backward iteration\n    stop = util.clamp(-1, stop, axisSize - 1);\n  }\n\n  return stop;\n}\n\n/**\n * Returns true if the slice occupies a continous set of elements in the\n * 'flat' space.\n */\nexport function isSliceContinous(\n    shape: number[], begin: number[], size: number[]) {\n  // Index of the first axis that has size > 1.\n  let firstNonOneAxis = size.length;\n  for (let i = 0; i < size.length; i++) {\n    if (size[i] > 1) {\n      firstNonOneAxis = i;\n      break;\n    }\n  }\n\n  for (let i = firstNonOneAxis + 1; i < size.length; i++) {\n    if (begin[i] > 0 || size[i] !== shape[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function computeFlatOffset(begin: number[], strides: number[]): number {\n  let flatOffset = begin.length > 0 ? begin[begin.length - 1] : 1;\n  for (let i = 0; i < begin.length - 1; i++) {\n    flatOffset += begin[i] * strides[i];\n  }\n  return flatOffset;\n}\n\nexport function parseSliceParams(\n    x: TensorInfo, begin: number|number[], size?: number|number[]) {\n  // The following logic allows for more ergonomic calls.\n  let begin_: number[];\n  const xRank = x.shape.length;\n  if (typeof begin === 'number') {\n    begin_ = [begin, ...new Array(xRank - 1).fill(0)];\n  } else if (begin.length < xRank) {\n    begin_ = begin.concat(new Array(xRank - begin.length).fill(0));\n  } else {\n    begin_ = begin.slice();\n  }\n  begin_.forEach(d => {\n    util.assert(\n        d !== -1, () => 'slice() does not support negative begin indexing.');\n  });\n  let size_: number[];\n  if (size == null) {\n    size_ = new Array(xRank).fill(-1);\n  } else if (typeof size === 'number') {\n    size_ = [size, ...new Array(xRank - 1).fill(-1)];\n  } else if (size.length < xRank) {\n    size_ = size.concat(new Array(xRank - size.length).fill(-1));\n  } else {\n    size_ = size;\n  }\n  size_ = size_.map((d, i) => {\n    if (d >= 0) {\n      return d;\n    } else {\n      util.assert(\n          d === -1,\n          () => `Negative size values should be exactly -1 but got ` +\n              `${d} for the slice() size at index ${i}.`);\n      return x.shape[i] - begin_[i];\n    }\n  });\n  return [begin_, size_];\n}\n\n// Convert the slicing specification from a sparse representation to a dense\n// representation. This means that all ellipses and newaxis are expanded out.\nexport function sliceInfo(\n    xShape: number[], begin: number[], end: number[], strides: number[],\n    beginMask: number, endMask: number, ellipsisMask: number,\n    newAxisMask: number, shrinkAxisMask: number): SliceInfo {\n  let stridesNonNull;\n  if (strides == null) {\n    stridesNonNull = new Array(begin.length);\n    stridesNonNull.fill(1);\n  } else {\n    stridesNonNull = strides;\n  }\n\n  // Only one non-zero bit is allowed in ellipsisMask, which means ellipsisMask\n  // is a power of 2. Use bit compares to ensure ellipsisMask is 0 or a power\n  // of 2. When i is a power of 2, i & (i - 1) is always 0.\n  // Also ref:\n  // https://stackoverflow.com/questions/600293/how-to-check-if-a-number-is-a-power-of-2\n  if (ellipsisMask != null && (ellipsisMask & (ellipsisMask - 1)) !== 0) {\n    throw new Error('Multiple ellipses in slice is not allowed.');\n  }\n\n  // Step 1: Account for ellipsis and new axis.\n  // Check for ellipsis and count how many non-newaxis there are after.\n  let ellipsisSeen = false;\n\n  const sparseSpec: StridedSliceSparseSpec = {\n    dims: stridesNonNull.length,\n    numAddAxisAfterEllipsis: 0,\n    begin: begin.slice(),\n    end: end.slice(),\n    strides: stridesNonNull.slice(),\n    beginMask,\n    endMask,\n    ellipsisMask,\n    newAxisMask,\n    shrinkAxisMask\n  };\n\n  for (let i = 0; i < sparseSpec.dims; i++) {\n    if (ellipsisSeen && ((1 << i) & newAxisMask) !== 0) {\n      sparseSpec.numAddAxisAfterEllipsis++;\n    }\n    if ((1 << i) & ellipsisMask) {\n      ellipsisSeen = true;\n    }\n  }\n  // If no ellipsis insert one at the end.\n  if (!ellipsisSeen) {\n    sparseSpec.ellipsisMask |= (1 << sparseSpec.dims);\n    sparseSpec.dims++;  // this effects loop iteration below\n  }\n\n  // Step 2: Make a sparse spec into a full index spec.\n  //\n  // The sparse spec deos not correspond to the number of dimensions.\n  // Make a dense spec that cooresponds to the number of dimensions.\n  //\n  // For example suppose foo[...,3:] on foo.shape = [2, 2, 3] then we need to\n  // produce the missing beginMask for the first two dimensions i.e. from\n  // beginMaskSpec = 0, endMaskSpec = 2, we achieve beginMask = 6 (110),\n  // endMask = 7 (111).\n  const denseSpec: StridedSliceDenseSpec = {\n    dims: xShape.length,\n    beginMask: 0,\n    endMask: 0,\n    beginValid: false,\n    endValid: false\n  };\n\n  buildDenseSpec(sparseSpec, denseSpec);\n\n  // Step 3: Make implicit ranges (non-zero beginMasks and endMasks) explicit\n  // and bounds check.\n  let isIdentity = true;\n  let sliceDim0 = true;\n  let isSimpleSlice = true;\n  const processingShape = [];\n  const finalShape = [];\n\n  for (let i = 0; i < xShape.length; ++i) {\n    if (denseSpec.strides[i] === 0) {\n      throw Error(`strides[${i}] must be non-zero`);\n    }\n    const shrinkI = !!(denseSpec.shrinkAxisMask & (1 << i));\n    const dimI = xShape[i];\n    if (dimI === -1) {\n      processingShape.push(shrinkI ? 1 : -1);\n      continue;\n    }\n\n    const masks =\n        [denseSpec.beginMask & (1 << i), denseSpec.endMask & (1 << i)];\n    const validRange = [\n      denseSpec.strides[i] > 0 ? 0 : -1,\n      denseSpec.strides[i] > 0 ? dimI : dimI - 1\n    ];\n\n    if (shrinkI && denseSpec.strides[i] <= 0) {\n      throw Error('only stride 1 allowed on non-range indexing.');\n    }\n\n    isSimpleSlice = isSimpleSlice && (denseSpec.strides[i] === 1);\n\n    const beginAndEndMasked =\n        !!((denseSpec.beginMask & (1 << i)) && (denseSpec.endMask & (1 << i)));\n\n    if (denseSpec.beginValid && denseSpec.endValid) {\n      if (shrinkI) {\n        // If we are shrinking, the end index is now possibly incorrect. In\n        // particular foo[-1] produces sparseBegin = -1, sparseEnd = 0.\n        // and canonical puts these to n-1 and 0, which implies a degenerate\n        // interval. Fortunately, it is now safe to re-create end as begin + 1.\n        const xFwd = denseSpec.begin[i] < 0 ? dimI + denseSpec.begin[i] :\n                                              denseSpec.begin[i];\n        denseSpec.begin[i] = xFwd;\n        denseSpec.end[i] = denseSpec.begin[i] + 1;\n        if (xFwd < 0 || xFwd >= dimI) {\n          throw Error(`slice index ${denseSpec.begin[i]} of dimension ${\n              i} out of bounds.`);\n        }\n      } else {\n        denseSpec.begin[i] = canonical(\n            denseSpec.begin[i], 0, denseSpec.strides[i], dimI, masks,\n            validRange);\n        denseSpec.end[i] = canonical(\n            denseSpec.end[i], 1, denseSpec.strides[i], dimI, masks, validRange);\n      }\n      // Update optimization values\n      const takeAllInDimension = denseSpec.strides[i] === 1 &&\n          denseSpec.begin[i] === 0 && denseSpec.end[i] === dimI;\n      isIdentity = isIdentity && takeAllInDimension;\n      sliceDim0 = sliceDim0 &&\n          ((i === 0 && denseSpec.strides[i] === 1) || takeAllInDimension);\n    } else {\n      isIdentity =\n          isIdentity && ((denseSpec.strides[i] === 1) && beginAndEndMasked);\n      sliceDim0 = sliceDim0 &&\n          ((i === 0 && denseSpec.strides[i] === 1) || beginAndEndMasked);\n    }\n    // Compute the processing shape (the intermediate Eigen will produce)\n    let intervalLength;\n    let knownInterval = false;\n    if (denseSpec.beginValid && denseSpec.endValid) {\n      intervalLength = denseSpec.end[i] - denseSpec.begin[i];\n      knownInterval = true;\n    } else if (shrinkI) {\n      // The dimension is still known as 1 for the processingShape, but will be\n      // discarded for the final shape.\n      intervalLength = 1;\n      knownInterval = true;\n    } else if (beginAndEndMasked) {\n      // Even if we don't have values for begin or end, we do know that this\n      // dimension covers the whole interval. If we have shape information for\n      // this dimension, that tells us the interval length.\n      if (dimI >= 0) {\n        if (denseSpec.strides[i] < 0) {\n          intervalLength = -dimI;\n        } else {\n          intervalLength = dimI;\n        }\n        knownInterval = true;\n      }\n    }\n    if (knownInterval) {\n      let sizeI;\n      // Hold zero if the interval is degenerate, otherwise account for\n      // remainder\n      if (intervalLength === 0 ||\n          ((intervalLength < 0) !== (denseSpec.strides[i] < 0))) {\n        sizeI = 0;\n      } else {\n        sizeI = Math.trunc(intervalLength / denseSpec.strides[i]) +\n            (intervalLength % denseSpec.strides[i] !== 0 ? 1 : 0);\n      }\n      processingShape.push(sizeI);\n    } else {\n      processingShape.push(-1);\n    }\n  }\n\n  // Step 4: Compute the final shape\n  //\n  // newAxis will increase dimension by 1 (with a one-size dimension)\n  // slices like foo[3, ...] will reduce dimension by 1.\n  // This cannot be done earlier, because it depends on Step 3.\n  for (let denseDim = 0; denseDim < denseSpec.finalShapeGatherIndices.length;\n       ++denseDim) {\n    const gatherIndex = denseSpec.finalShapeGatherIndices[denseDim];\n    if (gatherIndex >= 0) {\n      finalShape.push(processingShape[gatherIndex]);\n    } else if (gatherIndex === NEW_AXIS) {\n      finalShape.push(1);\n    }\n  }\n\n  const finalShapeSparse = finalShape.filter(\n      (dim, i) => denseSpec.finalShapeGatherIndices[i] !== NEW_AXIS);\n\n  return {\n    finalShapeSparse,\n    finalShape,\n    isIdentity,\n    sliceDim0,\n    isSimpleSlice,\n    begin: denseSpec.begin,\n    end: denseSpec.end,\n    strides: denseSpec.strides\n  };\n}\n\nfunction buildDenseSpec(\n    sparse: StridedSliceSparseSpec, dense: StridedSliceDenseSpec) {\n  dense.beginMask = 0;\n  dense.endMask = 0;\n  dense.shrinkAxisMask = 0;\n\n  let fullIndex = 0;\n  dense.beginValid = sparse.begin != null;\n  dense.endValid = sparse.end != null;\n\n  dense.begin = new Array(dense.dims);\n  dense.end = new Array(dense.dims);\n  dense.strides = new Array(dense.dims);\n  dense.finalShapeGatherIndices = [];\n  dense.finalShapeGatherIndicesSparse = [];\n  dense.inputShapeGatherIndicesSparse = new Array(dense.dims);\n\n  for (let i = 0; i < sparse.dims; i++) {\n    if ((1 << i) & sparse.ellipsisMask) {\n      // Only the bit that has ellipsis will fall in this condition.\n      // Expand the ellipsis into the appropriate indices\n      // Note: this only works because we guaranteed one ellipsis.\n      const nextIndex = Math.min(\n          dense.dims - (sparse.dims - i) + 1 + sparse.numAddAxisAfterEllipsis,\n          dense.dims);\n      for (; fullIndex < nextIndex; fullIndex++) {\n        // newAxis aren't real axis so you have to skip.\n        dense.begin[fullIndex] = 0;\n        dense.end[fullIndex] = 0;\n        dense.strides[fullIndex] = 1;\n        dense.beginMask |= (1 << fullIndex);\n        dense.endMask |= (1 << fullIndex);\n        dense.finalShapeGatherIndices.push(fullIndex);\n        dense.finalShapeGatherIndicesSparse.push(-1);\n        dense.inputShapeGatherIndicesSparse[fullIndex] = i;\n      }\n    } else if ((1 << i) & sparse.newAxisMask) {\n      // Only the bit that has newAxis will fall in this condition.\n      dense.finalShapeGatherIndices.push(NEW_AXIS);\n      dense.finalShapeGatherIndicesSparse.push(-1);\n    } else {\n      if (fullIndex === dense.begin.length) {\n        throw Error(\n            `Index out of range using input dim ${fullIndex}; input ` +\n            `has only ${dense.dims} dims, ${dense.begin.length}.`);\n      }\n\n      // Gather slicing spec into appropriate index.\n      if (sparse.begin != null) {\n        dense.begin[fullIndex] = sparse.begin[i];\n      }\n      if (sparse.end != null) {\n        dense.end[fullIndex] = sparse.end[i];\n      }\n      dense.strides[fullIndex] = sparse.strides[i];\n      if (sparse.beginMask & (1 << i)) {\n        dense.beginMask |= (1 << fullIndex);\n      }\n      if (sparse.endMask & (1 << i)) {\n        dense.endMask |= (1 << fullIndex);\n      }\n      // If shrink, record where to get the dimensionality from (i.e. newAxis)\n      // creates a fake 1 size dimension. Also remember shrink axis (now in\n      // dense form) so we can ignore dense.end below.\n      if (sparse.shrinkAxisMask & (1 << i)) {\n        dense.finalShapeGatherIndices.push(SHRINK_AXIS);\n        dense.finalShapeGatherIndicesSparse.push(-1);\n        dense.shrinkAxisMask |= (1 << fullIndex);\n      } else {\n        dense.finalShapeGatherIndices.push(fullIndex);\n        // Remember that where in the sparse shape the dense dim comes from.\n        dense.finalShapeGatherIndicesSparse.push(i);\n      }\n      dense.inputShapeGatherIndicesSparse[fullIndex] = i;\n      fullIndex++;\n    }\n  }\n}\n\nfunction canonical(\n    x: number, c: number, strideI: number, dimI: number, masks: number[],\n    validRange: number[]) {\n  if (masks[c]) {\n    return strideI > 0 ? validRange[c] : validRange[(c + 1) & 1];\n  } else {\n    const xFwd = x < 0 ? dimI + x : x;  // make negative indices positive\n    return xFwd < validRange[0] ? validRange[0] :\n                                  xFwd > validRange[1] ? validRange[1] : xFwd;\n  }\n}\n", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.22.0';\nexport {version};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AdadeltaOptimizer} from './adadelta_optimizer';\nimport {AdagradOptimizer} from './adagrad_optimizer';\nimport {AdamOptimizer} from './adam_optimizer';\nimport {AdamaxOptimizer} from './adamax_optimizer';\nimport {MomentumOptimizer} from './momentum_optimizer';\nimport {RMSPropOptimizer} from './rmsprop_optimizer';\nimport {SGDOptimizer} from './sgd_optimizer';\n\nexport class OptimizerConstructors {\n  /**\n   * Constructs a `tf.SGDOptimizer` that uses stochastic gradient descent.\n   *\n   * ```js\n   * // Fit a quadratic function by learning the coefficients a, b, c.\n   * const xs = tf.tensor1d([0, 1, 2, 3]);\n   * const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);\n   *\n   * const a = tf.scalar(Math.random()).variable();\n   * const b = tf.scalar(Math.random()).variable();\n   * const c = tf.scalar(Math.random()).variable();\n   *\n   * // y = a * x^2 + b * x + c.\n   * const f = x => a.mul(x.square()).add(b.mul(x)).add(c);\n   * const loss = (pred, label) => pred.sub(label).square().mean();\n   *\n   * const learningRate = 0.01;\n   * const optimizer = tf.train.sgd(learningRate);\n   *\n   * // Train the model.\n   * for (let i = 0; i < 10; i++) {\n   *   optimizer.minimize(() => loss(f(xs), ys));\n   * }\n   *\n   * // Make predictions.\n   * console.log(\n   *     `a: ${a.dataSync()}, b: ${b.dataSync()}, c: ${c.dataSync()}`);\n   * const preds = f(xs).dataSync();\n   * preds.forEach((pred, i) => {\n   *   console.log(`x: ${i}, pred: ${pred}`);\n   * });\n   * ```\n   *\n   * @param learningRate The learning rate to use for the SGD algorithm.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n   */\n  static sgd(learningRate: number): SGDOptimizer {\n    return new SGDOptimizer(learningRate);\n  }\n\n  /**\n   * Constructs a `tf.MomentumOptimizer` that uses momentum gradient\n   * descent.\n   *\n   * See\n   * [http://proceedings.mlr.press/v28/sutskever13.pdf](\n   * http://proceedings.mlr.press/v28/sutskever13.pdf)\n   *\n   * @param learningRate The learning rate to use for the Momentum gradient\n   * descent algorithm.\n   * @param momentum The momentum to use for the momentum gradient descent\n   * algorithm.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n   */\n  static momentum(learningRate: number, momentum: number, useNesterov = false):\n      MomentumOptimizer {\n    return new MomentumOptimizer(learningRate, momentum, useNesterov);\n  }\n\n  /**\n   * Constructs a `tf.RMSPropOptimizer` that uses RMSProp gradient\n   * descent. This implementation uses plain momentum and is not centered\n   * version of RMSProp.\n   *\n   * See\n   * [http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf](\n   * http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)\n   *\n   * @param learningRate The learning rate to use for the RMSProp gradient\n   * descent algorithm.\n   * @param decay The discounting factor for the history/coming gradient.\n   * @param momentum The momentum to use for the RMSProp gradient descent\n   * algorithm.\n   * @param epsilon Small value to avoid zero denominator.\n   * @param centered If true, gradients are normalized by the estimated\n   * variance of the gradient.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n   */\n  static rmsprop(\n      learningRate: number, decay = .9, momentum = 0.0, epsilon: number = null,\n      centered = false): RMSPropOptimizer {\n    return new RMSPropOptimizer(\n        learningRate, decay, momentum, epsilon, centered);\n  }\n\n  /**\n   * Constructs a `tf.AdamOptimizer` that uses the Adam algorithm.\n   * See [https://arxiv.org/abs/1412.6980](https://arxiv.org/abs/1412.6980)\n   *\n   * @param learningRate The learning rate to use for the Adam gradient\n   * descent algorithm.\n   * @param beta1 The exponential decay rate for the 1st moment estimates.\n   * @param beta2 The exponential decay rate for the 2nd moment estimates.\n   * @param epsilon A small constant for numerical stability.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n   */\n  static adam(\n      learningRate = 0.001, beta1 = 0.9, beta2 = 0.999,\n      epsilon: number = null): AdamOptimizer {\n    return new AdamOptimizer(learningRate, beta1, beta2, epsilon);\n  }\n\n  /**\n   * Constructs a `tf.AdadeltaOptimizer` that uses the Adadelta algorithm.\n   * See [https://arxiv.org/abs/1212.5701](https://arxiv.org/abs/1212.5701)\n   *\n   * @param learningRate The learning rate to use for the Adadelta gradient\n   * descent algorithm.\n   * @param rho The learning rate decay over each update.\n   * @param epsilon A constant epsilon used to better condition the grad\n   * update.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n   */\n  static adadelta(learningRate = .001, rho = .95, epsilon: number = null):\n      AdadeltaOptimizer {\n    return new AdadeltaOptimizer(learningRate, rho, epsilon);\n  }\n\n  /**\n   * Constructs a `tf.AdamaxOptimizer` that uses the Adamax algorithm.\n   * See [https://arxiv.org/abs/1412.6980](https://arxiv.org/abs/1412.6980)\n   *\n   * @param learningRate The learning rate to use for the Adamax gradient\n   * descent algorithm.\n   * @param beta1 The exponential decay rate for the 1st moment estimates.\n   * @param beta2 The exponential decay rate for the 2nd moment estimates.\n   * @param epsilon A small constant for numerical stability.\n   * @param decay The learning rate decay over each update.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n   */\n  static adamax(\n      learningRate = 0.002, beta1 = 0.9, beta2 = 0.999, epsilon: number = null,\n      decay = 0.0): AdamaxOptimizer {\n    return new AdamaxOptimizer(learningRate, beta1, beta2, epsilon, decay);\n  }\n\n  /**\n   * Constructs a `tf.AdagradOptimizer` that uses the Adagrad algorithm.\n   * See\n   * [http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf](\n   * http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)\n   * or\n   * [http://ruder.io/optimizing-gradient-descent/index.html#adagrad](\n   * http://ruder.io/optimizing-gradient-descent/index.html#adagrad)\n   *\n   * @param learningRate The learning rate to use for the Adagrad gradient\n   * descent algorithm.\n   * @param initialAccumulatorValue Starting value for the accumulators, must be\n   * positive.\n   *\n   * @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}\n   */\n  static adagrad(learningRate: number, initialAccumulatorValue = 0.1):\n      AdagradOptimizer {\n    return new AdagradOptimizer(learningRate, initialAccumulatorValue);\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OptimizerConstructors} from './optimizers/optimizer_constructors';\n\nexport const train = OptimizerConstructors;\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nconst delayCallback: Function = (() => {\n  if (typeof requestAnimationFrame !== 'undefined') {\n    return requestAnimationFrame;\n  } else if (typeof setImmediate !== 'undefined') {\n    return setImmediate;\n  }\n  return (f: Function) => f();  // no delays\n})();\n\n/**\n * Returns a promise that resolves when a requestAnimationFrame has completed.\n *\n * On Node.js this uses setImmediate instead of requestAnimationFrame.\n *\n * This is simply a sugar method so that users can do the following:\n * `await tf.nextFrame();`\n *\n * @doc {heading: 'Performance', subheading: 'Timing'}\n */\nfunction nextFrame(): Promise<void> {\n  return new Promise<void>(resolve => delayCallback(() => resolve()));\n}\n\nexport {nextFrame};\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\nexport function assertParamsConsistent(shapes: number[][], axis: number) {\n  const rank = shapes[0].length;\n  shapes.forEach((shape, i) => {\n    util.assert(\n        shape.length === rank,\n        () =>\n            `Error in concat${rank}D: rank of tensors[${i}] must be the same ` +\n            `as the rank of the rest (${rank})`);\n  });\n\n  util.assert(\n      axis >= 0 && axis < rank,\n      () => `Error in concat${rank}D: axis must be between 0 and ${rank - 1}.`);\n\n  const firstShape = shapes[0];\n  shapes.forEach((shape, i) => {\n    for (let r = 0; r < rank; r++) {\n      util.assert(\n          (r === axis) || (shape[r] === firstShape[r]),\n          () => `Error in concat${rank}D: Shape of tensors[${i}] (${shape}) ` +\n              `does not match the shape of the rest (${firstShape}) ` +\n              `along the non-concatenated axis ${i}.`);\n    }\n  });\n}\n\nexport function computeOutShape(shapes: number[][], axis: number): number[] {\n  const outputShape = shapes[0].slice();\n  for (let i = 1; i < shapes.length; i++) {\n    outputShape[axis] += shapes[i][axis];\n  }\n  return outputShape;\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport enum RowPartitionType {\n  FIRST_DIM_SIZE,\n  VALUE_ROWIDS,\n  ROW_LENGTHS,\n  ROW_SPLITS,\n  ROW_LIMITS,\n  ROW_STARTS\n}\n\nexport function combineRaggedTensorToTensorShapes(\n    raggedRank: number, shape: number[], valueShape: number[]) {\n  // Test for consistency of valueShape and shape specified.\n  // If shape is unspecified and valueShape is specified, then copy\n  // over the size from the valueShape dimension.\n\n  let outputShape: number[] = new Array();\n  if (valueShape == null && shape == null) {\n    return outputShape;\n  }\n\n  if (shape == null) {\n    // Here, value_shape must be of known size.\n    while (outputShape.length < raggedRank + valueShape.length) {\n      outputShape.push(-1);\n    }\n  } else {\n    outputShape = shape.slice();\n  }\n  if (valueShape == null) {\n    return outputShape;\n  }\n  // At this point, valueShape and output_shape have known ranks.\n  if (raggedRank + valueShape.length !== outputShape.length) {\n    throw new Error(\n        `rt input.shape and shape=${shape} are incompatible: rt input.rank = ${\n            raggedRank +\n            valueShape.length}, but shape.rank = ${outputShape.length}`);\n  }\n\n  for (let i = 1; i < valueShape.length; ++i) {\n    const valueDim = valueShape[i];\n    const outputShapeDimIndex =\n        outputShape[outputShape.length - valueShape.length + i];\n    const outputShapeDim = outputShape[outputShapeDimIndex];\n\n    if (valueDim >= 0) {\n      if (outputShapeDim >= 0) {\n        if (outputShapeDim !== valueDim) {\n          throw new Error(`rt input.shape and shape=${\n              shape} are incompatible: rt input.shape[${i + raggedRank}] = ${\n              valueDim} but shape[${i + raggedRank}] = ${outputShapeDim}`);\n        }\n      } else {\n        outputShape[outputShapeDimIndex] = valueDim;\n      }\n    }\n  }\n  return outputShape;\n}\n\nexport function getRowPartitionTypesHelper(rowPartitionTypeStrings: string[]) {\n  const stringToType = {\n    'FIRST_DIM_SIZE': RowPartitionType.FIRST_DIM_SIZE,\n    'VALUE_ROWIDS': RowPartitionType.VALUE_ROWIDS,\n    'ROW_LENGTHS': RowPartitionType.ROW_LENGTHS,\n    'ROW_SPLITS': RowPartitionType.ROW_SPLITS,\n    'ROW_LIMITS': RowPartitionType.ROW_LIMITS,\n    'ROW_STARTS': RowPartitionType.ROW_STARTS\n  };\n\n  const result: RowPartitionType[] = [];\n  for (const typeStr of rowPartitionTypeStrings) {\n    if (typeStr in stringToType) {\n      result.push(stringToType[typeStr as keyof typeof stringToType]);\n    } else {\n      break;\n    }\n  }\n\n  return result;\n}\n\nexport function getRaggedRank(rowPartitionTypes: RowPartitionType[]) {\n  if (rowPartitionTypes.length === 0) {\n    return 0;\n  }\n  if (rowPartitionTypes[0] === RowPartitionType.FIRST_DIM_SIZE) {\n    return rowPartitionTypes.length - 1;\n  }\n  return rowPartitionTypes.length;\n}\n\nexport function validateDefaultValueShape(\n    defaultValueShape: number[], valueShape: number[]) {\n  if (defaultValueShape == null || valueShape == null) {\n    return;\n  }\n\n  const defaultNDims = defaultValueShape.length;\n  const valuesNDims = valueShape.length;\n  if (defaultNDims >= valuesNDims) {\n    throw new Error(`defaultValue.shape=${\n        defaultValueShape} and ragged tensor flatValues.shape=${\n        valueShape}, are incompatible: defaultValue.rank = ${\n        defaultNDims} must be less than ragged tensor input flatValues.rank = ${\n        valuesNDims})`);\n  }\n  for (let i = 0; i < Math.min(defaultNDims, valuesNDims - 1); ++i) {\n    const defaultDim = defaultValueShape[i];\n    const valueDim = valueShape[i + 1];\n    if (defaultDim >= 0 && valueDim >= 0 && defaultDim !== 1 &&\n        defaultDim !== valueDim) {\n      throw new Error(`defaultValue.shape=${\n          defaultValueShape}, and ragged tensor input flatValues.shape=${\n          valueShape} are incompatible: defaultValue.shape[${\n          i - defaultValueShape.length}] = ${\n          defaultDim} but ragged tensor input.flatValues.shape[${\n          i - defaultValueShape.length}] = ${valueDim}`);\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Inputs of size above this threshold will be parallelized by calling multiple\n * shader programs.\n */\nimport {nearestDivisor} from '../util';\n\nexport const PARALLELIZE_THRESHOLD = 30;\n\nexport interface ReduceInfo {\n  windowSize: number;\n  batchSize: number;\n  inSize: number;\n  outSize: number;\n}\n\nexport function computeOptimalWindowSize(inSize: number): number {\n  if (inSize <= PARALLELIZE_THRESHOLD) {\n    return inSize;\n  }\n  return nearestDivisor(inSize, Math.floor(Math.sqrt(inSize)));\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Returns the image center in pixels.\nexport function getImageCenter(\n    center: number|[number, number], imageHeight: number,\n    imageWidth: number): [number, number] {\n  const centerX =\n      imageWidth * (typeof center === 'number' ? center : center[0]);\n  const centerY =\n      imageHeight * (typeof center === 'number' ? center : center[1]);\n  return [centerX, centerY];\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Gets the new shape of the input Tensor after it's been reshaped\n * to:\n * [blockShape[0], ..., blockShape[M-1], batch / prod(blockShape),\n * inputShape[1], ..., inputShape[N-1]]\n *\n * See step 1: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd\n */\nexport function getReshaped(\n    inputShape: number[], blockShape: number[], prod: number,\n    batchToSpace = true): number[] {\n  let reshaped: number[] = [];\n  if (batchToSpace) {\n    reshaped = reshaped.concat(blockShape.slice(0));\n    reshaped.push(inputShape[0] / prod);\n    reshaped = reshaped.concat(inputShape.slice(1));\n  } else {\n    reshaped = reshaped.concat(inputShape[0]);\n    const spatialLength = blockShape.length;\n    for (let i = 0; i < spatialLength; ++i) {\n      reshaped =\n          reshaped.concat([inputShape[i + 1] / blockShape[i], blockShape[i]]);\n    }\n    reshaped = reshaped.concat(inputShape.slice(spatialLength + 1));\n  }\n  return reshaped;\n}\n\n/**\n * Gets the permutation that will transpose the dimensions of the\n * reshaped tensor to shape:\n *\n * [batch / prod(block_shape),inputShape[1], blockShape[0], ...,\n * inputShape[M], blockShape[M-1],inputShape[M+1], ..., inputShape[N-1]]\n *\n * see step 2: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd\n */\nexport function getPermuted(\n    reshapedRank: number, blockShapeRank: number,\n    batchToSpace = true): number[] {\n  const permuted = [];\n  if (batchToSpace) {\n    permuted.push(blockShapeRank);\n    for (let i = blockShapeRank + 1; i < reshapedRank; ++i) {\n      if (i <= 2 * blockShapeRank) {\n        permuted.push(i);\n        permuted.push(i - (blockShapeRank + 1));\n      } else {\n        permuted.push(i);\n      }\n    }\n  } else {\n    const permutedBeforeBatch = [];\n    const permutedAfterBatch = [];\n    for (let i = 1; i < reshapedRank; ++i) {\n      if (i >= blockShapeRank * 2 + 1 || i % 2 === 1) {\n        permutedAfterBatch.push(i);\n      } else {\n        permutedBeforeBatch.push(i);\n      }\n    }\n    permuted.push(...permutedBeforeBatch);\n    permuted.push(0);\n    permuted.push(...permutedAfterBatch);\n  }\n  return permuted;\n}\n\n/**\n * Gets the shape of the reshaped and permuted input Tensor before any cropping\n * is applied.  The new shape will be:\n *\n * [batch / prod(blockShape),inputShape[1] * blockShape[0], ...,\n * inputShape[M] * blockShape[M-1],inputShape[M+1], ..., inputShape[N-1]]\n *\n * See step 3: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd\n */\nexport function getReshapedPermuted(\n    inputShape: number[], blockShape: number[], prod: number,\n    batchToSpace = true): number[] {\n  const reshapedPermuted = [];\n\n  if (batchToSpace) {\n    reshapedPermuted.push(inputShape[0] / prod);\n  } else {\n    reshapedPermuted.push(inputShape[0] * prod);\n  }\n\n  for (let i = 1; i < inputShape.length; ++i) {\n    if (i <= blockShape.length) {\n      if (batchToSpace) {\n        reshapedPermuted.push(blockShape[i - 1] * inputShape[i]);\n      } else {\n        reshapedPermuted.push(inputShape[i] / blockShape[i - 1]);\n      }\n    } else {\n      reshapedPermuted.push(inputShape[i]);\n    }\n  }\n\n  return reshapedPermuted;\n}\n\n/**\n * Converts the crops argument into the beginning coordinates of a slice\n * operation.\n */\nexport function getSliceBeginCoords(\n    crops: number[][], blockShape: number): number[] {\n  const sliceBeginCoords = [0];\n  for (let i = 0; i < blockShape; ++i) {\n    sliceBeginCoords.push(crops[i][0]);\n  }\n  return sliceBeginCoords;\n}\n\n/**\n * Converts the crops argument into the size of a slice operation.  When\n * combined with getSliceBeginCoords this function allows the reshaped and\n * permuted Tensor to be cropped to its final output shape of:\n *\n * inputShape[1] * blockShape[0] - crops[0,0] - crops[0,1], ...,\n * inputShape[M] * blockShape[M-1] -crops[M-1,0] -\n * crops[M-1,1],inputShape[M+1], ..., inputShape[N-1]]\n *\n * See step 4: https://www.tensorflow.org/api_docs/python/tf/batch_to_space_nd\n */\nexport function getSliceSize(\n    uncroppedShape: number[], crops: number[][], blockShape: number): number[] {\n  const sliceSize = uncroppedShape.slice(0, 1);\n  for (let i = 0; i < blockShape; ++i) {\n    sliceSize.push(uncroppedShape[i + 1] - crops[i][0] - crops[i][1]);\n  }\n\n  return sliceSize;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const SELU_SCALEALPHA = 1.7580993408473768599402175208123;\nexport const SELU_SCALE = 1.0507009873554804934193349852946;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport const ERF_P = 0.3275911;\nexport const ERF_A1 = 0.254829592;\nexport const ERF_A2 = -0.284496736;\nexport const ERF_A3 = 1.421413741;\nexport const ERF_A4 = -1.453152027;\nexport const ERF_A5 = 1.061405429;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray} from '../types';\n/**\n * Merges real and imaginary Float32Arrays into a single complex Float32Array.\n *\n * The memory layout is interleaved as follows:\n * real: [r0, r1, r2]\n * imag: [i0, i1, i2]\n * complex: [r0, i0, r1, i1, r2, i2]\n *\n * This is the inverse of splitRealAndImagArrays.\n *\n * @param real The real values of the complex tensor values.\n * @param imag The imag values of the complex tensor values.\n * @returns A complex tensor as a Float32Array with merged values.\n */\nexport function mergeRealAndImagArrays(\n    real: Float32Array, imag: Float32Array): Float32Array {\n  if (real.length !== imag.length) {\n    throw new Error(\n        `Cannot merge real and imag arrays of different lengths. real:` +\n        `${real.length}, imag: ${imag.length}.`);\n  }\n  const result = new Float32Array(real.length * 2);\n  for (let i = 0; i < result.length; i += 2) {\n    result[i] = real[i / 2];\n    result[i + 1] = imag[i / 2];\n  }\n  return result;\n}\n\n/**\n * Splits a complex Float32Array into real and imag parts.\n *\n * The memory layout is interleaved as follows:\n * complex: [r0, i0, r1, i1, r2, i2]\n * real: [r0, r1, r2]\n * imag: [i0, i1, i2]\n *\n * This is the inverse of mergeRealAndImagArrays.\n *\n * @param complex The complex tensor values.\n * @returns An object with real and imag Float32Array components of the complex\n *     tensor.\n */\nexport function splitRealAndImagArrays(complex: Float32Array):\n    {real: Float32Array, imag: Float32Array} {\n  const real = new Float32Array(complex.length / 2);\n  const imag = new Float32Array(complex.length / 2);\n  for (let i = 0; i < complex.length; i += 2) {\n    real[i / 2] = complex[i];\n    imag[i / 2] = complex[i + 1];\n  }\n  return {real, imag};\n}\n\n/**\n * Extracts even indexed complex values in the given array.\n * @param complex The complex tensor values\n */\nexport function complexWithEvenIndex(complex: Float32Array):\n    {real: Float32Array, imag: Float32Array} {\n  const len = Math.ceil(complex.length / 4);\n  const real = new Float32Array(len);\n  const imag = new Float32Array(len);\n  for (let i = 0; i < complex.length; i += 4) {\n    real[Math.floor(i / 4)] = complex[i];\n    imag[Math.floor(i / 4)] = complex[i + 1];\n  }\n  return {real, imag};\n}\n\n/**\n * Extracts odd indexed complete values in the given array.\n * @param complex The complex tensor values\n */\nexport function complexWithOddIndex(complex: Float32Array):\n    {real: Float32Array, imag: Float32Array} {\n  const len = Math.floor(complex.length / 4);\n  const real = new Float32Array(len);\n  const imag = new Float32Array(len);\n  for (let i = 2; i < complex.length; i += 4) {\n    real[Math.floor(i / 4)] = complex[i];\n    imag[Math.floor(i / 4)] = complex[i + 1];\n  }\n  return {real, imag};\n}\n\n/**\n * Get the map representing a complex value in the given array.\n * @param complex The complex tensor values.\n * @param index An index of the target complex value.\n */\nexport function getComplexWithIndex(\n    complex: Float32Array, index: number): {real: number, imag: number} {\n  const real = complex[index * 2];\n  const imag = complex[index * 2 + 1];\n  return {real, imag};\n}\n\n/**\n * Insert a given complex value into the TypedArray.\n * @param data The array in which the complex value is inserted.\n * @param c The complex value to be inserted.\n * @param index An index of the target complex value.\n */\nexport function assignToTypedArray(\n    data: TypedArray, real: number, imag: number, index: number) {\n  data[index * 2] = real;\n  data[index * 2 + 1] = imag;\n}\n\n/**\n * Make the list of exponent terms used by FFT.\n */\nexport function exponents(\n    n: number, inverse: boolean): {real: Float32Array, imag: Float32Array} {\n  const real = new Float32Array(n / 2);\n  const imag = new Float32Array(n / 2);\n  for (let i = 0; i < Math.ceil(n / 2); i++) {\n    const x = (inverse ? 2 : -2) * Math.PI * (i / n);\n    real[i] = Math.cos(x);\n    imag[i] = Math.sin(x);\n  }\n  return {real, imag};\n}\n\n/**\n * Make the exponent term used by FFT.\n */\nexport function exponent(\n    k: number, n: number, inverse: boolean): {real: number, imag: number} {\n  const x = (inverse ? 2 : -2) * Math.PI * (k / n);\n  const real = Math.cos(x);\n  const imag = Math.sin(x);\n  return {real, imag};\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Utility functions for computing einsum (tensor contraction and summation\n * based on Einstein summation.)\n */\n\nimport {Tensor} from '../tensor';\nimport {assert} from '../util_base';\n\nconst ARROW = '->';\nconst ARROW_REGEX = /->/g;\nconst COMMA = ',';\nconst ELLIPSIS = '...';\n\n/**\n * Parse an equation for einsum.\n *\n * @param equation The einsum equation (e.g., \"ij,jk->ik\").\n * @param numTensors Number of tensors provided along with `equation`. Used to\n *   check matching number of input tensors.\n * @returns An object consisting of the following fields:\n *   - allDims: all dimension names as strings.\n *   - summedDims: a list of all dimensions being summed over, as indices to\n *     the elements of `allDims`.\n *   - idDims: indices of the dimensions in each input tensor, as indices to\n *     the elements of `allDims.\n */\nexport function decodeEinsumEquation(equation: string, numTensors: number): {\n  allDims: string[],\n  summedDims: number[],\n  idDims: number[][],\n} {\n  equation = equation.replace(/\\s/g, '');  // Remove witespace in equation.\n  const numArrows =\n      (equation.length - equation.replace(ARROW_REGEX, '').length) /\n      ARROW.length;\n  if (numArrows < 1) {\n    throw new Error('Equations without an arrow are not supported.');\n  } else if (numArrows > 1) {\n    throw new Error(`Equation must contain exactly one arrow (\"${ARROW}\").`);\n  }\n  const [inputString, outputString] = equation.split(ARROW);\n  assert(\n      inputString.indexOf(ELLIPSIS) === -1,\n      () => `The ellipsis notation (\"${ELLIPSIS}\") is not supported yet.`);\n  const inputTerms = inputString.split(COMMA);\n  const numInputs = inputTerms.length;\n  if (numTensors !== numInputs) {\n    throw new Error(\n        `Expected ${numInputs} input tensors, received ${numTensors}`);\n  }\n  if (numInputs > 2) {\n    throw new Error(\n        'Support for more than 2 input tensors is not implemented yet.');\n  }\n\n  const allDims: string[] = [];\n  for (let i = 0; i < outputString.length; ++i) {\n    const dimName = outputString[i];\n    if (!inputTerms.some(inputTerm => inputTerm.indexOf(dimName) !== -1)) {\n      throw new Error(\n          `Output subscripts contain the label ${dimName} ` +\n          `not present in the input subscripts.`);\n    }\n    if (allDims.indexOf(dimName) === -1) {\n      allDims.push(dimName);\n    }\n  }\n  for (let i = 0; i < inputString.length; ++i) {\n    const dimName = inputString[i];\n    if (allDims.indexOf(dimName) === -1 && dimName !== COMMA) {\n      allDims.push(dimName);\n    }\n  }\n\n  const idDims: number[][] = new Array<number[]>(inputTerms.length);\n  for (let i = 0; i < numInputs; ++i) {\n    if (new Set(inputTerms[i].split('')).size !== inputTerms[i].length) {\n      throw new Error(\n          `Found duplicate axes in input component ${inputTerms[i]}. ` +\n          `Support for duplicate axes in input is not implemented yet.`);\n    }\n    idDims[i] = [];\n    for (let j = 0; j < inputTerms[i].length; ++j) {\n      idDims[i].push(allDims.indexOf(inputTerms[i][j]));\n    }\n  }\n\n  const numDims = allDims.length;          // Number of unique dimensions.\n  const numOutDims = outputString.length;  // Number of output dimensions.\n  const summedDims: number[] = [];         // Dimensions being summed over.\n  for (let i = numOutDims; i < numDims; ++i) {\n    summedDims.push(i);\n  }\n  return {allDims, summedDims, idDims};\n}\n\n/**\n * Get the permutation for a given input tensor.\n *\n * @param nDims Total number of dimension of all tensors involved in the einsum\n *   operation.\n * @param idDims Dimension indices involve in the tensor in question.\n * @returns An object consisting of the following fields:\n *   - permutationIndices: Indices to permute the axes of the tensor with.\n *   - expandDims: Indices to the dimension that need to be expanded from the\n *     tensor after permutation.\n */\nexport function getEinsumPermutation(nDims: number, idDims: number[]):\n    {permutationIndices: number[], expandDims: number[]} {\n  let permutationIndices: number[] = new Array<number>(nDims);\n  permutationIndices.fill(-1);\n  for (let i = 0; i < idDims.length; ++i) {\n    permutationIndices[idDims[i]] = i;\n  }\n  const expandDims: number[] = [];\n  for (let i = 0; i < nDims; ++i) {\n    if (permutationIndices[i] === -1) {\n      expandDims.push(i);\n    }\n  }\n  permutationIndices = permutationIndices.filter(d => d !== -1);\n  return {permutationIndices, expandDims};\n}\n\n/**\n * Checks that the dimension sizes from different input tensors match the\n * equation.\n */\nexport function checkEinsumDimSizes(\n    nDims: number, idDims: number[][], tensors: Tensor[]) {\n  const dimSizes: number[] = new Array<number>(nDims);\n  for (let i = 0; i < tensors.length; ++i) {\n    const shape: number[] = tensors[i].shape;\n    for (let j = 0; j < idDims[i].length; ++j) {\n      if (dimSizes[idDims[i][j]] === undefined) {\n        dimSizes[idDims[i][j]] = shape[j];\n      } else {\n        assert(\n            dimSizes[idDims[i][j]] === shape[j],\n            () => `Expected dimension ${dimSizes[idDims[i][j]]} at axis ${j} ` +\n                `of input shaped ${JSON.stringify(shape)}, ` +\n                `but got dimension ${shape[j]}`);\n      }\n    }\n  }\n}\n\n/**\n * Gets path of computation for einsum.\n *\n * @param summedDims indices to the dimensions being summed over.\n * @param idDims A look up table for the dimensions present in each input\n *     tensor.Each constituent array contains indices for the dimensions in the\n *     corresponding input tensor.\n *\n * @return A map with two fields:\n *   - path: The path of computation, with each element indicating the dimension\n *     being summed over after the element-wise multiplication in that step.\n *   - steps: With the same length as `path`. Each element contains the indices\n *     to the input tensors being used for element-wise multiplication in the\n *     corresponding step.\n */\nexport function getEinsumComputePath(summedDims: number[], idDims: number[][]):\n    {path: number[], steps: number[][]} {\n  const path: number[] = summedDims;\n  const steps: number[][] = [];\n  let nSteps = 0;\n  if (summedDims.length === 0) {\n    // Einsum that involes no summing: e.g., transpose and outer product.\n    path.push(-1);\n  }\n  nSteps = summedDims.length + 1;\n  for (let i = 0; i < nSteps; ++i) {\n    steps.push([]);\n  }\n  const computedTermIndices: number[] = [];\n  for (let i = 0; i < path.length; ++i) {\n    const summedDim = path[i];\n    const termIndices = findTermsWithDim(idDims, summedDim);\n    for (const termIndex of termIndices) {\n      if (computedTermIndices.indexOf(termIndex) === -1) {\n        steps[i].push(termIndex);\n        computedTermIndices.push(termIndex);\n      }\n    }\n  }\n  return {path, steps};\n}\n\n/** Determines if an axes permutation is the identity permutation. */\nexport function isIdentityPermutation(perm: number[]): boolean {\n  return perm.every((dim: number, index: number) => dim === index);\n}\n\nfunction findTermsWithDim(idDims: number[][], dim: number): number[] {\n  const termIndices: number[] = [];\n  for (let i = 0; i < idDims.length; ++i) {\n    if (idDims[i].length === 0 || idDims[i].indexOf(dim) !== -1 || dim === -1) {\n      termIndices.push(i);\n    }\n  }\n  return termIndices;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { TensorInfo } from '../tensor_info';\nimport {Tensor} from '../tensor';\nimport {assert} from '../util';\n\n/**\n * Prepare the split size array. When the input is a number, the axis is evenly\n * divided among the split size. When the input contains the negative value, the\n * rest of the axis is allocated toward that.\n */\nexport function prepareSplitSize(\n    x: Tensor|TensorInfo, numOrSizeSplits: number[]|number,\n    axis = 0): number[] {\n  let splitSizes = [];\n  if (typeof (numOrSizeSplits) === 'number') {\n    assert(\n        x.shape[axis] % numOrSizeSplits === 0,\n        () => 'Number of splits must evenly divide the axis.');\n    splitSizes =\n        new Array(numOrSizeSplits).fill(x.shape[axis] / numOrSizeSplits);\n  } else {\n    const numOfNegs = numOrSizeSplits.reduce((count, value) => {\n      if (value === -1) {\n        count += 1;\n      }\n      return count;\n    }, 0);\n    assert(\n        numOfNegs <= 1,\n        () => 'There should be only one negative value in split array.');\n    const negIndex = numOrSizeSplits.indexOf(-1);\n    // Allow the number of split array to be -1, which indicates the rest\n    // of dimension is allocated to that split.\n    if (negIndex !== -1) {\n      const total = numOrSizeSplits.reduce((a, b) => b > 0 ? a + b : a);\n      numOrSizeSplits[negIndex] = x.shape[axis] - total;\n    }\n    assert(\n        x.shape[axis] === numOrSizeSplits.reduce((a, b) => a + b),\n        () => 'The sum of sizes must match the size of the axis dimension.');\n    splitSizes = numOrSizeSplits;\n  }\n\n  return splitSizes;\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Generates sparse fill empty rows indices, dense shape mismatch error message.\n *\n * @param indicesLength The first dimension of indices.\n */\nexport function getSparseFillEmptyRowsIndicesDenseShapeMismatch(\n    indicesLength: number) {\n  return `Received SparseTensor with denseShape[0] = 0 but\n  indices.shape[0] = ${indicesLength}`;\n}\n\n/**\n * Generates sparse fill empty rows negative index error message.\n *\n * @param index The index with a negative value.\n * @param value The negative value.\n */\nexport function getSparseFillEmptyRowsNegativeIndexErrorMessage(\n    index: number, value: number) {\n  return `indices(${index}, 0) is invalid: ${value} < 0`;\n}\n\n/**\n * Generates sparse fill empty rows out of range index error message.\n *\n * @param index The index with an out of range value.\n * @param value The out of range value.\n * @param limit The upper limit for indices.\n */\nexport function getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(\n    index: number, value: number, limit: number) {\n  return `indices(${index}, 0) is invalid: ${value} >= ${limit}`;\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {sizeFromShape} from '../../util';\n\n/**\n * Generates sparse reshape multiple negative 1 output dimension error message.\n *\n * @param dim1 The first dimension with a negative 1 value.\n * @param dim2 The second dimension with a negative 1 value.\n */\nexport function getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(\n    dim1: number, dim2: number) {\n  return `only one output dimension may be -1, not both ${dim1} and ${dim2}`;\n}\n\n/**\n * Generates sparse reshape negative output dimension error message.\n *\n * @param dim The dimension with a negative value.\n * @param value The negative value.\n */\nexport function getSparseReshapeNegativeOutputDimErrorMessage(\n    dim: number, value: number) {\n  return `size ${dim} must be non-negative, not ${value}`;\n}\n\n/**\n * Generates sparse reshape empty tensor zero output dimension error message.\n *\n */\nexport function getSparseReshapeEmptyTensorZeroOutputDimErrorMessage() {\n  return 'reshape cannot infer the missing input size for an empty tensor ' +\n      'unless all specified input sizes are non-zero';\n}\n\n/**\n * Generates sparse reshape input output multiple mismatch error message.\n *\n * @param inputShape the input shape.\n * @param outputShape the requested output shape.\n */\nexport function getSparseReshapeInputOutputMultipleErrorMessage(\n    inputShape: number[], outputShape: number[]) {\n  const inputSize = sizeFromShape(inputShape);\n  const outputSize = sizeFromShape(outputShape);\n  return `Input to reshape is a SparseTensor with ${inputSize}\n  dense values, but the requested shape requires a multiple of ${\n      outputSize}. inputShape=${inputShape} outputShape= ${outputShape}`;\n}\n\n/**\n * Generates sparse reshape input output inequality error message.\n *\n * @param inputShape the input shape.\n * @param outputShape the requested output shape.\n */\nexport function getSparseReshapeInputOutputMismatchErrorMessage(\n    inputShape: number[], outputShape: number[]) {\n  const inputSize = sizeFromShape(inputShape);\n  const outputSize = sizeFromShape(outputShape);\n  return `Input to reshape is a tensor with ${\n      inputSize} dense values, but the requested shape has ${\n      outputSize}. inputShape=${inputShape} outputShape=${outputShape}`;\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Generates sparse segment reduction negative segment ids error message.\n *\n */\nexport function getSparseSegmentReductionNegativeSegmentIdsErrorMessage() {\n  return `segment ids must be >= 0`;\n}\n\n/**\n * Generates sparse segment reduction non increasing segment ids error message.\n *\n */\nexport function getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage() {\n  return `segment ids are not increasing`;\n}\n\n/**\n * Generates sparse segment reduction segment id out of range error message.\n *\n * @param segmentId The segment id index that is out of range.\n * @param outputRows Upper bound of valid segment id values.\n */\nexport function getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(\n    segmentId: number, outputRows: number) {\n  return `Segment id ${segmentId} out of range [0, ${\n      outputRows}), possibly because segmentIds input is not sorted.`;\n}\n\n/**\n * Generates sparse segment reduction input indice out of range error message.\n *\n * @param index The index that holds the out of range value.\n * @param indexValue The value that is out of range.\n * @param inputRows Upper bound of valid index values.\n */\nexport function getSparseSegmentReductionIndicesOutOfRangeErrorMessage(\n    index: number, indexValue: number, inputRows: number) {\n  return `Bad: indices[${index}] == ${indexValue} out of range [0, ${\n      inputRows})`;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { TensorInfo } from '../tensor_info';\nimport {nearestDivisor} from '../util';\n\nimport {PARALLELIZE_THRESHOLD} from './reduce_util';\n\nexport interface SegOpInfo {\n  windowSize: number;\n  batchSize: number;\n  inSize: number;\n  numSegments: number;\n}\n\nexport function segOpComputeOptimalWindowSize(\n    inSize: number, numSegments: number): number {\n  let done = false;\n  let res;\n\n  if (inSize <= PARALLELIZE_THRESHOLD) {\n    res = inSize;\n    done = true;\n  } else {\n    res = nearestDivisor(inSize, Math.floor(Math.sqrt(inSize)));\n  }\n\n  while (!done) {\n    if (res > numSegments || res === inSize) {\n      done = true;\n    } else {\n      res = nearestDivisor(inSize, res + 1);\n    }\n  }\n  return res;\n}\n\nexport function computeOutShape(\n    aShape: number[], axis: number, numSegments: number): number[] {\n  const outShape = [];\n  const rank = aShape.length;\n  for (let dim = 0; dim < rank; dim++) {\n    if (dim !== axis) {\n      outShape.push(aShape[dim]);\n    } else {\n      outShape.push(numSegments);\n    }\n  }\n  return outShape;\n}\n\nexport interface GatherOpShapeInfo {\n  batchSize: number;\n  sliceSize: number;\n  outerSize: number;\n  dimSize: number;\n  outputShape: number[];\n}\n\nexport function collectGatherOpShapeInfo(\n    x: TensorInfo, indices: TensorInfo, axis: number,\n    batchDims: number): GatherOpShapeInfo {\n  const indicesRank = indices.shape.length;\n  const xRank = x.shape.length;\n\n  if (batchDims !== 0) {\n    if (batchDims < -indicesRank || batchDims > indicesRank) {\n      throw new Error(`Expect batchDims in the range of [-${indicesRank}, ${\n          indicesRank}], but got ${batchDims}`);\n    }\n  }\n\n  if (batchDims < 0) {\n    batchDims += indicesRank;\n  }\n\n  if (batchDims > xRank) {\n    throw new Error(`batchDims (${batchDims}) must be less than rank(x) (\n    ${xRank}).`);\n  }\n\n  if (axis < batchDims) {\n    throw new Error(`batchDims (${\n        batchDims}) must be less than or equal to axis (${axis}).`);\n  }\n\n  for (let i = 0; i < batchDims; ++i) {\n    if (x.shape[i] !== indices.shape[i]) {\n      throw new Error(\n          `x.shape[${i}]: ${x.shape[i]} should be equal to indices.shape[${\n              i}]: ${indices.shape[i]}.`);\n    }\n  }\n  const dimSize = x.shape[axis];\n\n  const outputShape: number[] = [];\n  let batchSize = 1;\n  let outerSize = 1;\n  let sliceSize = 1;\n\n  for (let i = 0; i < batchDims; ++i) {\n    outputShape.push(x.shape[i]);\n    batchSize *= x.shape[i];\n  }\n\n  for (let i = batchDims; i < axis; i++) {\n    outputShape.push(x.shape[i]);\n    outerSize *= x.shape[i];\n  }\n\n  for (let i = batchDims; i < indicesRank; i++) {\n    outputShape.push(indices.shape[i]);\n  }\n\n  for (let i = axis + 1; i < xRank; i++) {\n    outputShape.push(x.shape[i]);\n    sliceSize *= x.shape[i];\n  }\n\n  return {batchSize, sliceSize, outerSize, dimSize, outputShape};\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {decodeString, encodeString} from '../util';\n\n// Utilities needed by backend consumers of tf-core.\nexport * from '../ops/axis_util';\nexport * from '../ops/broadcast_util';\nexport * from '../ops/concat_util';\nexport * from '../ops/conv_util';\nexport * from '../ops/fused_util';\nexport * from '../ops/fused_types';\nexport * from '../ops/ragged_to_dense_util';\nexport * from '../ops/reduce_util';\n\nimport * as slice_util from '../ops/slice_util';\nexport {slice_util};\n\nexport {BackendValues, TypedArray, upcastType, PixelData} from '../types';\nexport {MemoryInfo, TimingInfo} from '../engine';\nexport * from '../ops/rotate_util';\nexport * from '../ops/array_ops_util';\nexport * from '../ops/gather_nd_util';\nexport * from '../ops/scatter_nd_util';\nexport * from '../ops/selu_util';\nexport * from '../ops/fused_util';\nexport * from '../ops/erf_util';\nexport * from '../log';\nexport * from '../backends/complex_util';\nexport * from '../backends/einsum_util';\nexport * from '../ops/split_util';\nexport * from '../ops/sparse/sparse_fill_empty_rows_util';\nexport * from '../ops/sparse/sparse_reshape_util';\nexport * from '../ops/sparse/sparse_segment_reduction_util';\n\nimport * as segment_util from '../ops/segment_util';\nexport {segment_util};\n\nexport function fromUint8ToStringArray(vals: Uint8Array[]) {\n  try {\n    // Decode the bytes into string.\n    return vals.map(val => decodeString(val));\n  } catch (err) {\n    throw new Error(\n        `Failed to decode encoded string bytes into utf-8, error: ${err}`);\n  }\n}\n\nexport function fromStringArrayToUint8(strings: string[]) {\n  return strings.map(s => encodeString(s));\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport {nonMaxSuppressionV3Impl, nonMaxSuppressionV4Impl, nonMaxSuppressionV5Impl} from './non_max_suppression_impl';\nexport {whereImpl} from './where_impl';\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code.\nimport './base_side_effects';\n\n// TODO(mattSoulanille): Move this to base_side_effects.ts\n// It is here for now because custom bundles need to avoid calling it, and they\n// only replace the index.js file, not the base_side_effects file.\nimport {registerOptimizers} from './optimizers/register_optimizers';\nregisterOptimizers();\n\n// All exports from this package should be in base.\nexport * from './base';\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '@tensorflow/tfjs-core';\n\nconst ENV = env();\n\n/** Whether to keep intermediate tensors. */\nENV.registerFlag('KEEP_INTERMEDIATE_TENSORS', () => false, debugValue => {\n  if (debugValue) {\n    console.warn(\n        'Keep intermediate tensors is ON. This will print the values of all ' +\n        'intermediate tensors during model inference. Not all models ' +\n        'support this mode. For details, check e2e/benchmarks/ ' +\n        'model_config.js. This significantly impacts performance.');\n  }\n});\n", "/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n    extendStatics = Object.setPrototypeOf ||\r\n        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n    return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n    if (typeof b !== \"function\" && b !== null)\r\n        throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n    extendStatics(d, b);\r\n    function __() { this.constructor = d; }\r\n    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n    __assign = Object.assign || function __assign(t) {\r\n        for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n            s = arguments[i];\r\n            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n        }\r\n        return t;\r\n    }\r\n    return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n    var t = {};\r\n    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n        t[p] = s[p];\r\n    if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n                t[p[i]] = s[p[i]];\r\n        }\r\n    return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n    if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n    return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n    return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n    if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n    return new (P || (P = Promise))(function (resolve, reject) {\r\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n    });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n    return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n    function verb(n) { return function (v) { return step([n, v]); }; }\r\n    function step(op) {\r\n        if (f) throw new TypeError(\"Generator is already executing.\");\r\n        while (_) try {\r\n            if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n            if (y = 0, t) op = [op[0] & 2, t.value];\r\n            switch (op[0]) {\r\n                case 0: case 1: t = op; break;\r\n                case 4: _.label++; return { value: op[1], done: false };\r\n                case 5: _.label++; y = op[1]; op = [0]; continue;\r\n                case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n                default:\r\n                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n                    if (t[2]) _.ops.pop();\r\n                    _.trys.pop(); continue;\r\n            }\r\n            op = body.call(thisArg, _);\r\n        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n    }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    var desc = Object.getOwnPropertyDescriptor(m, k);\r\n    if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n        desc = { enumerable: true, get: function() { return m[k]; } };\r\n    }\r\n    Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n    if (k2 === undefined) k2 = k;\r\n    o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n    for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n    var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n    if (m) return m.call(o);\r\n    if (o && typeof o.length === \"number\") return {\r\n        next: function () {\r\n            if (o && i >= o.length) o = void 0;\r\n            return { value: o && o[i++], done: !o };\r\n        }\r\n    };\r\n    throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n    var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n    if (!m) return o;\r\n    var i = m.call(o), r, ar = [], e;\r\n    try {\r\n        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n    }\r\n    catch (error) { e = { error: error }; }\r\n    finally {\r\n        try {\r\n            if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n        }\r\n        finally { if (e) throw e.error; }\r\n    }\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n    for (var ar = [], i = 0; i < arguments.length; i++)\r\n        ar = ar.concat(__read(arguments[i]));\r\n    return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n    for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n            r[k] = a[j];\r\n    return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n        if (ar || !(i in from)) {\r\n            if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n            ar[i] = from[i];\r\n        }\r\n    }\r\n    return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n    return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n    return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n    function fulfill(value) { resume(\"next\", value); }\r\n    function reject(value) { resume(\"throw\", value); }\r\n    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n    var i, p;\r\n    return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n    if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n    var m = o[Symbol.asyncIterator], i;\r\n    return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n    if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n    return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n    Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n    o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n    if (mod && mod.__esModule) return mod;\r\n    var result = {};\r\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n    __setModuleDefault(result, mod);\r\n    return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n    return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n    if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n    return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * =============================================================================\n */\n\n/* tslint:disable */\n\n/** Properties of an Any. */\nexport declare interface IAny {\n  /** Any typeUrl */\n  typeUrl?: (string|null);\n\n  /** Any value */\n  value?: (Uint8Array|null);\n}\n\n/** DataType enum. */\nexport enum DataType {\n  // These properties must be quoted since they are used by parseDtypeParam\n  // in tfjs-converter/src/operations/operation_mapper.ts to look up dtypes\n  // by string name. If they are not quoted, Closure will mangle their names.\n\n  // Not a legal value for DataType.  Used to indicate a DataType field\n  // has not been set.\n  'DT_INVALID' = 0,\n\n  // Data types that all computation devices are expected to be\n  // capable to support.\n  'DT_FLOAT' = 1,\n  'DT_DOUBLE' = 2,\n  'DT_INT32' = 3,\n  'DT_UINT8' = 4,\n  'DT_INT16' = 5,\n  'DT_INT8' = 6,\n  'DT_STRING' = 7,\n  'DT_COMPLEX64' = 8,  // Single-precision complex\n  'DT_INT64' = 9,\n  'DT_BOOL' = 10,\n  'DT_QINT8' = 11,     // Quantized int8\n  'DT_QUINT8' = 12,    // Quantized uint8\n  'DT_QINT32' = 13,    // Quantized int32\n  'DT_BFLOAT16' = 14,  // Float32 truncated to 16 bits.  Only for cast ops.\n  'DT_QINT16' = 15,    // Quantized int16\n  'DT_QUINT16' = 16,   // Quantized uint16\n  'DT_UINT16' = 17,\n  'DT_COMPLEX128' = 18,  // Double-precision complex\n  'DT_HALF' = 19,\n  'DT_RESOURCE' = 20,\n  'DT_VARIANT' = 21,  // Arbitrary C++ data types\n  'DT_UINT32' = 22,\n  'DT_UINT64' = 23,\n\n  // Do not use!  These are only for parameters.  Every enum above\n  // should have a corresponding value below (verified by types_test).\n  'DT_FLOAT_REF' = 101,\n  'DT_DOUBLE_REF' = 102,\n  'DT_INT32_REF' = 103,\n  'DT_UINT8_REF' = 104,\n  'DT_INT16_REF' = 105,\n  'DT_INT8_REF' = 106,\n  'DT_STRING_REF' = 107,\n  'DT_COMPLEX64_REF' = 108,\n  'DT_INT64_REF' = 109,\n  'DT_BOOL_REF' = 110,\n  'DT_QINT8_REF' = 111,\n  'DT_QUINT8_REF' = 112,\n  'DT_QINT32_REF' = 113,\n  'DT_BFLOAT16_REF' = 114,\n  'DT_QINT16_REF' = 115,\n  'DT_QUINT16_REF' = 116,\n  'DT_UINT16_REF' = 117,\n  'DT_COMPLEX128_REF' = 118,\n  'DT_HALF_REF' = 119,\n  'DT_RESOURCE_REF' = 120,\n  'DT_VARIANT_REF' = 121,\n  'DT_UINT32_REF' = 122,\n  'DT_UINT64_REF' = 123,\n}\n\n/** Properties of a TensorShape. */\nexport declare interface ITensorShape {\n  /** TensorShape dim */\n  dim?: (TensorShape.IDim[]|null);\n\n  /** TensorShape unknownRank */\n  unknownRank?: (boolean|null);\n}\n\nexport namespace TensorShape {\n  /** Properties of a Dim. */\n  export declare interface IDim {\n    /** Dim size */\n    size?: (number|string|null);\n\n    /** Dim name */\n    name?: (string|null);\n  }\n}\n\n/** Properties of a Tensor. */\nexport declare interface ITensor {\n  /** Tensor dtype */\n  dtype?: (DataType|null);\n\n  /** Tensor tensorShape */\n  tensorShape?: (ITensorShape|null);\n\n  /** Tensor versionNumber */\n  versionNumber?: (number|null);\n\n  /** Tensor tensorContent */\n  tensorContent?: (Uint8Array|null);\n\n  /** Tensor floatVal */\n  floatVal?: (number[]|null);\n\n  /** Tensor doubleVal */\n  doubleVal?: (number[]|null);\n\n  /** Tensor intVal */\n  intVal?: (number[]|null);\n\n  /** Tensor stringVal */\n  stringVal?: (Uint8Array[]|null);\n\n  /** Tensor scomplexVal */\n  scomplexVal?: (number[]|null);\n\n  /** Tensor int64Val */\n  int64Val?: ((number | string)[]|null);\n\n  /** Tensor boolVal */\n  boolVal?: (boolean[]|null);\n\n  /** Tensor uint32Val */\n  uint32Val?: (number[]|null);\n\n  /** Tensor uint64Val */\n  uint64Val?: ((number | string)[]|null);\n}\n\n/** Properties of an AttrValue. */\nexport declare interface IAttrValue {\n  /** AttrValue list */\n  list?: (AttrValue.IListValue|null);\n\n  /** AttrValue s */\n  s?: (string|null);\n\n  /** AttrValue i */\n  i?: (number|string|null);\n\n  /** AttrValue f */\n  f?: (number|null);\n\n  /** AttrValue b */\n  b?: (boolean|null);\n\n  /** AttrValue type */\n  type?: (DataType|null);\n\n  /** AttrValue shape */\n  shape?: (ITensorShape|null);\n\n  /** AttrValue tensor */\n  tensor?: (ITensor|null);\n\n  /** AttrValue placeholder */\n  placeholder?: (string|null);\n\n  /** AttrValue func */\n  func?: (INameAttrList|null);\n}\n\nexport namespace AttrValue {\n  /** Properties of a ListValue. */\n  export declare interface IListValue {\n    /** ListValue s */\n    s?: (string[]|null);\n\n    /** ListValue i */\n    i?: ((number | string)[]|null);\n\n    /** ListValue f */\n    f?: (number[]|null);\n\n    /** ListValue b */\n    b?: (boolean[]|null);\n\n    /** ListValue type */\n    type?: (DataType[]|null);\n\n    /** ListValue shape */\n    shape?: (ITensorShape[]|null);\n\n    /** ListValue tensor */\n    tensor?: (ITensor[]|null);\n\n    /** ListValue func */\n    func?: (INameAttrList[]|null);\n  }\n}\n\n/** Properties of a NameAttrList. */\nexport declare interface INameAttrList {\n  /** NameAttrList name */\n  name?: (string|null);\n\n  /** NameAttrList attr */\n  attr?: ({[k: string]: IAttrValue}|null);\n}\n\n/** Properties of a NodeDef. */\nexport declare interface INodeDef {\n  /** NodeDef name */\n  name?: (string|null);\n\n  /** NodeDef op */\n  op?: (string|null);\n\n  /** NodeDef input */\n  input?: (string[]|null);\n\n  /** NodeDef device */\n  device?: (string|null);\n\n  /** NodeDef attr */\n  attr?: ({[k: string]: IAttrValue}|null);\n}\n\n/** Properties of a VersionDef. */\nexport declare interface IVersionDef {\n  /** VersionDef producer */\n  producer?: (number|null);\n\n  /** VersionDef minConsumer */\n  minConsumer?: (number|null);\n\n  /** VersionDef badConsumers */\n  badConsumers?: (number[]|null);\n}\n\n/** Properties of a GraphDef. */\nexport declare interface IGraphDef {\n  /** GraphDef node */\n  node?: (INodeDef[]|null);\n\n  /** GraphDef versions */\n  versions?: (IVersionDef|null);\n\n  /** GraphDef library */\n  library?: (IFunctionDefLibrary|null);\n}\n\n/** Properties of a CollectionDef. */\nexport declare interface ICollectionDef {\n  /** CollectionDef nodeList */\n  nodeList?: (CollectionDef.INodeList|null);\n\n  /** CollectionDef bytesList */\n  bytesList?: (CollectionDef.IBytesList|null);\n\n  /** CollectionDef int64List */\n  int64List?: (CollectionDef.IInt64List|null);\n\n  /** CollectionDef floatList */\n  floatList?: (CollectionDef.IFloatList|null);\n\n  /** CollectionDef anyList */\n  anyList?: (CollectionDef.IAnyList|null);\n}\n\nexport namespace CollectionDef {\n  /** Properties of a NodeList. */\n  export declare interface INodeList {\n    /** NodeList value */\n    value?: (string[]|null);\n  }\n\n  /** Properties of a BytesList. */\n  export declare interface IBytesList {\n    /** BytesList value */\n    value?: (Uint8Array[]|null);\n  }\n\n  /** Properties of an Int64List. */\n  export declare interface IInt64List {\n    /** Int64List value */\n    value?: ((number | string)[]|null);\n  }\n\n  /** Properties of a FloatList. */\n  export declare interface IFloatList {\n    /** FloatList value */\n    value?: (number[]|null);\n  }\n\n  /** Properties of an AnyList. */\n  export declare interface IAnyList {\n    /** AnyList value */\n    value?: (IAny[]|null);\n  }\n}\n\n/** Properties of a SaverDef. */\nexport declare interface ISaverDef {\n  /** SaverDef filenameTensorName */\n  filenameTensorName?: (string|null);\n\n  /** SaverDef saveTensorName */\n  saveTensorName?: (string|null);\n\n  /** SaverDef restoreOpName */\n  restoreOpName?: (string|null);\n\n  /** SaverDef maxToKeep */\n  maxToKeep?: (number|null);\n\n  /** SaverDef sharded */\n  sharded?: (boolean|null);\n\n  /** SaverDef keepCheckpointEveryNHours */\n  keepCheckpointEveryNHours?: (number|null);\n\n  /** SaverDef version */\n  version?: (SaverDef.CheckpointFormatVersion|null);\n}\n\nexport namespace SaverDef {\n  /** CheckpointFormatVersion enum. */\n  export enum CheckpointFormatVersion {'LEGACY' = 0, 'V1' = 1, 'V2' = 2}\n}\n\n/** Properties of a TensorInfo. */\nexport declare interface ITensorInfo {\n  /** TensorInfo name */\n  name?: (string|null);\n\n  /** TensorInfo cooSparse */\n  cooSparse?: (TensorInfo.ICooSparse|null);\n\n  /** TensorInfo dtype */\n  dtype?: (DataType|string|null);\n\n  /** TensorInfo tensorShape */\n  tensorShape?: (ITensorShape|null);\n\n  /** Resource id tensor was originally assigned to.  */\n  resourceId?: (number|null);\n}\n\nexport namespace TensorInfo {\n  /** Properties of a CooSparse. */\n  export declare interface ICooSparse {\n    /** CooSparse valuesTensorName */\n    valuesTensorName?: (string|null);\n\n    /** CooSparse indicesTensorName */\n    indicesTensorName?: (string|null);\n\n    /** CooSparse denseShapeTensorName */\n    denseShapeTensorName?: (string|null);\n  }\n}\n\n/** Properties of a SignatureDef. */\nexport declare interface ISignatureDef {\n  /** SignatureDef inputs */\n  inputs?: ({[k: string]: ITensorInfo}|null);\n\n  /** SignatureDef outputs */\n  outputs?: ({[k: string]: ITensorInfo}|null);\n\n  /** SignatureDef methodName */\n  methodName?: (string|null);\n}\n\n/** Properties of an AssetFileDef. */\nexport declare interface IAssetFileDef {\n  /** AssetFileDef tensorInfo */\n  tensorInfo?: (ITensorInfo|null);\n\n  /** AssetFileDef filename */\n  filename?: (string|null);\n}\n\n/** Properties of an OpDef. */\nexport declare interface IOpDef {\n  /** OpDef name */\n  name?: (string|null);\n\n  /** OpDef inputArg */\n  inputArg?: (OpDef.IArgDef[]|null);\n\n  /** OpDef outputArg */\n  outputArg?: (OpDef.IArgDef[]|null);\n\n  /** OpDef attr */\n  attr?: (OpDef.IAttrDef[]|null);\n\n  /** OpDef deprecation */\n  deprecation?: (OpDef.IOpDeprecation|null);\n\n  /** OpDef summary */\n  summary?: (string|null);\n\n  /** OpDef description */\n  description?: (string|null);\n\n  /** OpDef isCommutative */\n  isCommutative?: (boolean|null);\n\n  /** OpDef isAggregate */\n  isAggregate?: (boolean|null);\n\n  /** OpDef isStateful */\n  isStateful?: (boolean|null);\n\n  /** OpDef allowsUninitializedInput */\n  allowsUninitializedInput?: (boolean|null);\n}\n\nexport namespace OpDef {\n  /** Properties of an ArgDef. */\n  export declare interface IArgDef {\n    /** ArgDef name */\n    name?: (string|null);\n\n    /** ArgDef description */\n    description?: (string|null);\n\n    /** ArgDef type */\n    type?: (DataType|null);\n\n    /** ArgDef typeAttr */\n    typeAttr?: (string|null);\n\n    /** ArgDef numberAttr */\n    numberAttr?: (string|null);\n\n    /** ArgDef typeListAttr */\n    typeListAttr?: (string|null);\n\n    /** ArgDef isRef */\n    isRef?: (boolean|null);\n  }\n\n  /** Properties of an AttrDef. */\n  export declare interface IAttrDef {\n    /** AttrDef name */\n    name?: (string|null);\n\n    /** AttrDef type */\n    type?: (string|null);\n\n    /** AttrDef defaultValue */\n    defaultValue?: (IAttrValue|null);\n\n    /** AttrDef description */\n    description?: (string|null);\n\n    /** AttrDef hasMinimum */\n    hasMinimum?: (boolean|null);\n\n    /** AttrDef minimum */\n    minimum?: (number|string|null);\n\n    /** AttrDef allowedValues */\n    allowedValues?: (IAttrValue|null);\n  }\n\n  /** Properties of an OpDeprecation. */\n  export declare interface IOpDeprecation {\n    /** OpDeprecation version */\n    version?: (number|null);\n\n    /** OpDeprecation explanation */\n    explanation?: (string|null);\n  }\n}\n\n/** Properties of an OpList. */\nexport declare interface IOpList {\n  /** OpList op */\n  op?: (IOpDef[]|null);\n}\n\n/** Properties of a MetaGraphDef. */\nexport declare interface IMetaGraphDef {\n  /** MetaGraphDef metaInfoDef */\n  metaInfoDef?: (MetaGraphDef.IMetaInfoDef|null);\n\n  /** MetaGraphDef graphDef */\n  graphDef?: (IGraphDef|null);\n\n  /** MetaGraphDef saverDef */\n  saverDef?: (ISaverDef|null);\n\n  /** MetaGraphDef collectionDef */\n  collectionDef?: ({[k: string]: ICollectionDef}|null);\n\n  /** MetaGraphDef signatureDef */\n  signatureDef?: ({[k: string]: ISignatureDef}|null);\n\n  /** MetaGraphDef assetFileDef */\n  assetFileDef?: (IAssetFileDef[]|null);\n}\n\nexport namespace MetaGraphDef {\n  /** Properties of a MetaInfoDef. */\n  export declare interface IMetaInfoDef {\n    /** MetaInfoDef metaGraphVersion */\n    metaGraphVersion?: (string|null);\n\n    /** MetaInfoDef strippedOpList */\n    strippedOpList?: (IOpList|null);\n\n    /** MetaInfoDef anyInfo */\n    anyInfo?: (IAny|null);\n\n    /** MetaInfoDef tags */\n    tags?: (string[]|null);\n\n    /** MetaInfoDef tensorflowVersion */\n    tensorflowVersion?: (string|null);\n\n    /** MetaInfoDef tensorflowGitVersion */\n    tensorflowGitVersion?: (string|null);\n  }\n}\n\n/** Properties of a SavedModel. */\nexport declare interface ISavedModel {\n  /** SavedModel savedModelSchemaVersion */\n  savedModelSchemaVersion?: (number|string|null);\n\n  /** SavedModel metaGraphs */\n  metaGraphs?: (IMetaGraphDef[]|null);\n}\n\n/** Properties of a FunctionDefLibrary. */\nexport declare interface IFunctionDefLibrary {\n  /** FunctionDefLibrary function */\n  'function'?: (IFunctionDef[]|null);\n\n  /** FunctionDefLibrary gradient */\n  gradient?: (IGradientDef[]|null);\n}\n\n/** Properties of a FunctionDef. */\nexport declare interface IFunctionDef {\n  /** FunctionDef signature */\n  signature?: (IOpDef|null);\n\n  /** FunctionDef attr */\n  attr?: ({[k: string]: IAttrValue}|null);\n\n  /** FunctionDef nodeDef */\n  nodeDef?: (INodeDef[]|null);\n\n  /** FunctionDef ret */\n  ret?: ({[k: string]: string}|null);\n}\n\n/** Properties of a GradientDef. */\nexport declare interface IGradientDef {\n  /** GradientDef functionName */\n  functionName?: (string|null);\n\n  /** GradientDef gradientFunc */\n  gradientFunc?: (string|null);\n}\n", "\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpExecutor, OpMapper} from '../types';\n\nconst CUSTOM_OPS: {[key: string]: OpMapper} = {};\n\n/**\n * Register an Op for graph model executor. This allows you to register\n * TensorFlow custom op or override existing op.\n *\n * Here is an example of registering a new MatMul Op.\n * ```js\n * const customMatmul = (node) =>\n *    tf.matMul(\n *        node.inputs[0], node.inputs[1],\n *        node.attrs['transpose_a'], node.attrs['transpose_b']);\n *\n * tf.registerOp('MatMul', customMatmul);\n * ```\n * The inputs and attrs of the node object are based on the TensorFlow op\n * registry.\n *\n * @param name The Tensorflow Op name.\n * @param opFunc An op function which is called with the current graph node\n * during execution and needs to return a tensor or a list of tensors. The node\n * has the following attributes:\n *    - attr: A map from attribute name to its value\n *    - inputs: A list of input tensors\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function registerOp(name: string, opFunc: OpExecutor) {\n  const opMapper: OpMapper = {\n    tfOpName: name,\n    category: 'custom',\n    inputs: [],\n    attrs: [],\n    customExecutor: opFunc\n  };\n\n  CUSTOM_OPS[name] = opMapper;\n}\n\n/**\n * Retrieve the OpMapper object for the registered op.\n *\n * @param name The Tensorflow Op name.\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function getRegisteredOp(name: string): OpMapper {\n  return CUSTOM_OPS[name];\n}\n\n/**\n * Deregister the Op for graph model executor.\n *\n * @param name The Tensorflow Op name.\n *\n * @doc {heading: 'Models', subheading: 'Op Registry'}\n */\nexport function deregisterOp(name: string) {\n  delete CUSTOM_OPS[name];\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {clone, Tensor, util} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {ResourceManager} from '../../executor/resource_manager';\nimport {Node, ValueType} from '../types';\n\nexport function getParamValue(\n    paramName: string, node: Node, tensorMap: NamedTensorsMap,\n    context: ExecutionContext, resourceManager?: ResourceManager): ValueType {\n  const inputParam = node.inputParams[paramName];\n  if (inputParam && inputParam.inputIndexStart !== undefined) {\n    const start = inputParam.inputIndexStart;\n    const end = inputParam.inputIndexEnd === 0 ?\n        undefined :\n        (inputParam.inputIndexEnd === undefined ? start + 1 :\n                                                  inputParam.inputIndexEnd);\n    const shiftedStart = start < 0 ? node.inputNames.length + start : start;\n    if (inputParam.type === 'tensor') {\n      return getTensor(\n          node.inputNames[shiftedStart], tensorMap, context, resourceManager);\n    }\n    if (inputParam.type === 'tensors') {\n      // TODO(mattSoulanille): This filters out NoOp nodes during execution, but\n      // these should really never be in the execution graph in the first place.\n      // They're necessary for ordering the graph, but should not be visible\n      // during execution. Perhaps have different sets of children, one for\n      // control dependencies and another for real dependencies.\n      const inputs = node.inputs.slice(start, end);\n      const inputNames = node.inputNames.slice(start, end)\n        .filter((_name, index) => inputs[index]?.op !== 'NoOp');\n\n      return inputNames.map(\n          name => getTensor(name, tensorMap, context, resourceManager));\n    }\n    const tensor = getTensor(\n        node.inputNames[shiftedStart], tensorMap, context, resourceManager);\n    const data = tensor.dataSync();\n    return inputParam.type === 'number' ?\n        data[0] :\n        util.toNestedArray(tensor.shape, data);\n  }\n  const attrParam = node.attrParams[paramName];\n  return attrParam && attrParam.value;\n}\n\n/**\n * Retrieve the tensor from tensorsMap based on input name.\n * @param name Node input name\n * @param tensorsMap Tensors map keyed by the node\n * @param context contains tensors and information for running the current node.\n * @param resourceManager Optional. Contains global resources of the model.\n */\nexport function getTensor(\n    name: string, tensorsMap: NamedTensorsMap, context: ExecutionContext,\n    resourceManager?: ResourceManager): Tensor {\n  const [nodeName, index] = parseNodeName(name, context);\n\n  if (resourceManager != null) {\n    const tensor = resourceManager.getHashTableHandleByName(nodeName);\n    if (tensor != null) {\n      return tensor;\n    }\n  }\n\n  const contextId = context.currentContextIds.find(contextId => {\n    return !!tensorsMap[getNodeNameWithContextId(nodeName, contextId)];\n  });\n\n  return contextId !== undefined ?\n      tensorsMap[getNodeNameWithContextId(nodeName, contextId)][index] :\n      undefined;\n}\n\n/**\n * Retrieve the tensors based on input name for current context.\n * @param name Node input name\n * @param tensorsMap Tensors map keyed by the node\n */\nexport function getTensorsForCurrentContext(\n    name: string, tensorsMap: NamedTensorsMap,\n    context: ExecutionContext): Tensor[] {\n  return tensorsMap[getNodeNameWithContextId(name, context.currentContextId)];\n}\n\n/**\n * Returns the node name, outputName and index from the Node input name.\n * @param inputName The input name of the node, in format of\n * node_name:output_index, i.e. MatMul:0, if the output_index is not set, it is\n * default to 0.\n * If the input name contains output name i.e. StringSplit:indices:0, it will\n * return ['StringSplit', 0, 'indices'].\n */\nexport function getNodeNameAndIndex(\n    inputName: string, context?: ExecutionContext): [string, number, string] {\n  const [nodeName, index, outputName] = parseNodeName(inputName, context);\n\n  return [\n    getNodeNameWithContextId(nodeName, context && context.currentContextId),\n    index, outputName\n  ];\n}\n\nfunction getNodeNameWithContextId(name: string, contextId?: string): string {\n  return !!contextId ? `${name}-${contextId}` : name;\n}\n\nexport function parseNodeName(\n    name: string, context?: ExecutionContext): [string, number, string?] {\n  if (name === '') {\n    return ['', 0, undefined];\n  }\n\n  const isCacheEnabled = context != null && context.parseNodeNameCache != null;\n  if (isCacheEnabled) {\n    const cachedResult = context.parseNodeNameCache.get(name);\n    if (cachedResult != null) {\n      return cachedResult;\n    }\n  }\n  const parts = name.split(':');\n  let result: [string, number, string?];\n  if (parts.length === 1) {\n    result = [name, 0, undefined];\n  } else {\n    const nodeName = parts[0];\n    const outputName = parts.length === 3 ? parts[1] : undefined;\n    const index = Number(parts[parts.length - 1]);\n    result = [nodeName, index, outputName];\n  }\n  if (isCacheEnabled) {\n    context.parseNodeNameCache.set(name, result);\n  }\n  return result;\n}\n\nexport function split(arr: number[], size: number) {\n  const res = [];\n  for (let i = 0; i < arr.length; i += size) {\n    res.push(arr.slice(i, i + size));\n  }\n  return res;\n}\nexport function getPadding(\n    node: Node, tensorMap: NamedTensorsMap,\n    context: ExecutionContext): ValueType {\n  let pad = getParamValue('pad', node, tensorMap, context);\n  if (pad === 'explicit') {\n    // This is 1d array, we need to convert it to 2d array\n    pad = getParamValue('explicitPaddings', node, tensorMap, context);\n    const explicitPadding: [\n      [number, number], [number, number], [number, number], [number, number]\n    ] = [[0, 0], [0, 0], [0, 0], [0, 0]];\n    for (let i = 0; i < 4; i++) {\n      explicitPadding[i][0] = (pad as number[])[i * 2];\n      explicitPadding[i][1] = (pad as number[])[i * 2 + 1];\n    }\n    return explicitPadding;\n  }\n  return pad;\n}\n\n/**\n *  Reuse the tensor if it is marked as keep, otherwise clone the tensor to\n *  avoid disposal. This is important for TensorArray and TensorList ops, since\n *  internally they use a tensor as the id for TensorArray and TensorList, and\n * to simplify lookup, they also use Tensor.id as the key to the internal map.\n * These id tensors have been marked as kept in the backend, we need avoid clone\n * them in order to create new Tensor.id.\n * @param tensor\n */\nexport function cloneTensor(tensor: Tensor): Tensor {\n  return tensor.kept ? tensor : clone(tensor);\n}\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'Add',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'AddV2',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'AddN',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'end': 0,\n        'name': 'tensors',\n        'type': 'tensors'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'BiasAdd',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Sub',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'RealDiv',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Div',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'DivNoNan',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'FloorDiv',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Mul',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Maximum',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Minimum',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Pow',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'SquaredDifference',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Mod',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'FloorMod',\n    'category': 'arithmetic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  }\n];\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'Abs',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Acos',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Asin',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Atan',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Atan2',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'y',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Ceil',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ClipByValue',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'clipValueMin',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'clipValueMax',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Complex',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'real',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'imag',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ComplexAbs',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Cos',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Cosh',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Elu',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Exp',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Floor',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Log',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Imag',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'Tout',\n        'name': 'outputType',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Neg',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Real',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'Tout',\n        'name': 'outputType',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Prelu',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'alpha',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Relu',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Relu6',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Selu',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Sigmoid',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Sin',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Sinh',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Sqrt',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Rsqrt',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Square',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Tan',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Tanh',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Sign',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Round',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Expm1',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Log1p',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Reciprocal',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Softplus',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Asinh',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Acosh',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Atanh',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Erf',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LeakyRelu',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'alpha',\n        'name': 'alpha',\n        'type': 'number',\n        'defaultValue': 0.2\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'IsNan',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'IsFinite',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'IsInf',\n    'category': 'basic_math',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'EmptyTensorList',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'elementShape',\n        'type': 'shape'\n      },\n      {\n        'start': 1,\n        'name': 'maxNumElements',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LoopCond',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'pred',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Switch',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'data',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'pred',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Merge',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'end': 0,\n        'name': 'tensors',\n        'type': 'tensors'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Enter',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'frame_name',\n        'name': 'frameName',\n        'type': 'string'\n      },\n      {\n        'tfName': 'is_constant',\n        'name': 'isConstant',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Exit',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'NextIteration',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArrayV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'size',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'element_shape',\n        'name': 'elementShape',\n        'type': 'shape'\n      },\n      {\n        'tfName': 'dynamic_size',\n        'name': 'dynamicSize',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'clear_after_read',\n        'name': 'clearAfterRead',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'identical_element_shapes',\n        'name': 'identicalElementShapes',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'tensor_array_name',\n        'name': 'name',\n        'type': 'string'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArrayWriteV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorArrayId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'index',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'tensor',\n        'type': 'tensor'\n      },\n      {\n        'start': 3,\n        'name': 'flowIn',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArrayReadV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorArrayId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'index',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'flowIn',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArrayGatherV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorArrayId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'flowIn',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'element_shape',\n        'name': 'elementShape',\n        'type': 'shape'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArrayScatterV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorArrayId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'tensor',\n        'type': 'tensor'\n      },\n      {\n        'start': 3,\n        'name': 'flowIn',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArrayConcatV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorArrayId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'flowIn',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'element_shape_except0',\n        'name': 'elementShapeExcept0',\n        'type': 'shape',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArraySplitV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorArrayId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'tensor',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'lengths',\n        'type': 'number[]'\n      },\n      {\n        'start': 3,\n        'name': 'flowIn',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArraySizeV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorArrayId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'flowIn',\n        'type': 'number'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorArrayCloseV3',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorArrayId',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'StatelessIf',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'cond',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'end': 0,\n        'name': 'args',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'then_branch',\n        'name': 'thenBranch',\n        'type': 'func'\n      },\n      {\n        'tfName': 'else_branch',\n        'name': 'elseBranch',\n        'type': 'func'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'If',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'cond',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'end': 0,\n        'name': 'args',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'then_branch',\n        'name': 'thenBranch',\n        'type': 'func'\n      },\n      {\n        'tfName': 'else_branch',\n        'name': 'elseBranch',\n        'type': 'func'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'StatelessWhile',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'end': 0,\n        'name': 'args',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'cond',\n        'name': 'cond',\n        'type': 'func'\n      },\n      {\n        'tfName': 'body',\n        'name': 'body',\n        'type': 'func'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'While',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'end': 0,\n        'name': 'args',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'cond',\n        'name': 'cond',\n        'type': 'func'\n      },\n      {\n        'tfName': 'body',\n        'name': 'body',\n        'type': 'func'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListScatter',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'elementShape',\n        'type': 'shape'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListScatterV2',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'elementShape',\n        'type': 'shape'\n      },\n      {\n        'start': 3,\n        'name': 'numElements',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListGather',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'elementShape',\n        'type': 'shape'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListGetItem',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'index',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'elementShape',\n        'type': 'shape'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListSetItem',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'index',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'tensor',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListReserve',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'elementShape',\n        'type': 'shape'\n      },\n      {\n        'start': 1,\n        'name': 'numElements',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListFromTensor',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'elementShape',\n        'type': 'shape'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListStack',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'elementShape',\n        'type': 'shape'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'num_elements',\n        'name': 'numElements',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListSplit',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'elementShape',\n        'type': 'shape'\n      },\n      {\n        'start': 2,\n        'name': 'lengths',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListConcat',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_shape',\n        'name': 'elementShape',\n        'type': 'shape'\n      },\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListConcatV2',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_shape',\n        'name': 'elementShape',\n        'type': 'shape'\n      },\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListPopBack',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'elementShape',\n        'type': 'shape'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListPushBack',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'tensor',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'element_dtype',\n        'name': 'elementDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListLength',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorListResize',\n    'category': 'control',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensorListId',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'size',\n        'type': 'number'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'AvgPool',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      },\n      {\n        'tfName': 'ksize',\n        'name': 'kernelSize',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'MaxPool',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      },\n      {\n        'tfName': 'ksize',\n        'name': 'kernelSize',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'explicit_paddings',\n        'name': 'explicitPaddings',\n        'type': 'number[]',\n        'defaultValue': [],\n        'notSupported': true\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'MaxPoolWithArgmax',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'ksize',\n        'name': 'kernelSize',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'include_batch_in_index',\n        'name': 'includeBatchInIndex',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'AvgPool3D',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      },\n      {\n        'tfName': 'ksize',\n        'name': 'kernelSize',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'MaxPool3D',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      },\n      {\n        'tfName': 'ksize',\n        'name': 'kernelSize',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Conv1D',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'stride',\n        'name': 'stride',\n        'type': 'number'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'defaultValue': 'NWC'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'dilation',\n        'name': 'dilation',\n        'type': 'number',\n        'defaultValue': 1\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Conv2D',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'useCudnnOnGpu',\n        'name': 'useCudnnOnGpu',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'defaultValue': 'NHWC'\n      },\n      {\n        'tfName': 'explicit_paddings',\n        'name': 'explicitPaddings',\n        'type': 'number[]',\n        'defaultValue': []\n      },\n      {\n        'tfName': 'dilations',\n        'name': 'dilations',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': '_FusedConv2D',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'end': 0,\n        'name': 'args',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'num_args',\n        'name': 'numArgs',\n        'type': 'number'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'explicit_paddings',\n        'name': 'explicitPaddings',\n        'type': 'number[]',\n        'defaultValue': []\n      },\n      {\n        'tfName': 'use_cudnn_on_gpu',\n        'name': 'useCudnnOnGpu',\n        'type': 'bool',\n        'defaultValue': true\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'defaultValue': 'NHWC'\n      },\n      {\n        'tfName': 'dilations',\n        'name': 'dilations',\n        'type': 'number[]',\n        'defaultValue': [\n          1,\n          1,\n          1,\n          1\n        ]\n      },\n      {\n        'tfName': 'fused_ops',\n        'name': 'fusedOps',\n        'type': 'string[]',\n        'defaultValue': []\n      },\n      {\n        'tfName': 'epsilon',\n        'name': 'epsilon',\n        'type': 'number',\n        'defaultValue': 0.0001\n      },\n      {\n        'tfName': 'leakyrelu_alpha',\n        'name': 'leakyreluAlpha',\n        'type': 'number',\n        'defaultValue': 0.2\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Conv2DBackpropInput',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 2,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      },\n      {\n        'start': 0,\n        'name': 'outputShape',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      },\n      {\n        'tfName': 'explicit_paddings',\n        'name': 'explicitPaddings',\n        'type': 'number[]',\n        'defaultValue': []\n      },\n      {\n        'tfName': 'dilations',\n        'name': 'dilations',\n        'type': 'number[]',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'DepthwiseConv2d',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'input',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'defaultValue': 'NHWC'\n      },\n      {\n        'tfName': 'explicit_paddings',\n        'name': 'explicitPaddings',\n        'type': 'number[]',\n        'defaultValue': []\n      },\n      {\n        'tfName': 'dilations',\n        'name': 'dilations',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'DepthwiseConv2dNative',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'input',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'defaultValue': 'NHWC'\n      },\n      {\n        'tfName': 'explicit_paddings',\n        'name': 'explicitPaddings',\n        'type': 'number[]',\n        'defaultValue': []\n      },\n      {\n        'tfName': 'dilations',\n        'name': 'dilations',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'FusedDepthwiseConv2dNative',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'end': 0,\n        'name': 'args',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'num_args',\n        'name': 'numArgs',\n        'type': 'number'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'defaultValue': 'NHWC'\n      },\n      {\n        'tfName': 'dilations',\n        'name': 'dilations',\n        'type': 'number[]',\n        'defaultValue': [\n          1,\n          1,\n          1,\n          1\n        ]\n      },\n      {\n        'tfName': 'fused_ops',\n        'name': 'fusedOps',\n        'type': 'string[]',\n        'defaultValue': []\n      },\n      {\n        'tfName': 'explicit_paddings',\n        'name': 'explicitPaddings',\n        'type': 'number[]',\n        'defaultValue': []\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Conv3D',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'defaultValue': 'NHWC'\n      },\n      {\n        'tfName': 'dilations',\n        'name': 'dilations',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Dilation2D',\n    'category': 'convolution',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'filter',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'strides',\n        'name': 'strides',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'rates',\n        'name': 'dilations',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'padding',\n        'name': 'pad',\n        'type': 'string'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'Fill',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'shape',\n        'type': 'number[]'\n      },\n      {\n        'start': 1,\n        'name': 'value',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LinSpace',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'start',\n        'type': 'number'\n      },\n      {\n        'start': 1,\n        'name': 'stop',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'num',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'OneHot',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'indices',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'depth',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'onValue',\n        'type': 'number',\n        'defaultValue': 1\n      },\n      {\n        'start': 3,\n        'name': 'offValue',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'axis',\n        'name': 'axis',\n        'type': 'number',\n        'notSupported': true\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Ones',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'OnesLike',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'RandomStandardNormal',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'seed',\n        'name': 'seed',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'seed2',\n        'name': 'seed2',\n        'type': 'number',\n        'defaultValue': 0,\n        'notSupported': true\n      },\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'T',\n        'name': 'T',\n        'type': 'number',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'RandomUniform',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'minval',\n        'name': 'minval',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'maxval',\n        'name': 'maxval',\n        'type': 'number',\n        'defaultValue': 1\n      },\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'seed',\n        'name': 'seed',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'seed2',\n        'name': 'seed2',\n        'type': 'number',\n        'defaultValue': 0,\n        'notSupported': true\n      },\n      {\n        'tfName': 'T',\n        'name': 'T',\n        'type': 'number',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'RandomUniformInt',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'minval',\n        'name': 'minval',\n        'type': 'number'\n      },\n      {\n        'tfName': 'maxval',\n        'name': 'maxval',\n        'type': 'number'\n      },\n      {\n        'tfName': 'seed',\n        'name': 'seed',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'seed2',\n        'name': 'seed2',\n        'type': 'number',\n        'defaultValue': 0,\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Range',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'start',\n        'type': 'number'\n      },\n      {\n        'start': 1,\n        'name': 'stop',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'step',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'Tidx',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TruncatedNormal',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'means',\n        'name': 'mean',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'stddev',\n        'name': 'stdDev',\n        'type': 'number',\n        'defaultValue': 1\n      },\n      {\n        'tfName': 'seed',\n        'name': 'seed',\n        'type': 'number'\n      },\n      {\n        'tfName': 'seed2',\n        'name': 'seed2',\n        'type': 'number',\n        'defaultValue': 0,\n        'notSupported': true\n      },\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'T',\n        'name': 'T',\n        'type': 'number',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Zeros',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ZerosLike',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Multinomial',\n    'category': 'creation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'logits',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'numSamples',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'seed',\n        'name': 'seed',\n        'type': 'number'\n      },\n      {\n        'tfName': 'seed2',\n        'name': 'seed2',\n        'type': 'number'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'output_dtype',\n        'name': 'output_dtype',\n        'type': 'dtype'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'NonMaxSuppressionV2',\n    'category': 'dynamic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'boxes',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'scores',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'maxOutputSize',\n        'type': 'number'\n      },\n      {\n        'start': 3,\n        'name': 'iouThreshold',\n        'type': 'number'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'NonMaxSuppressionV3',\n    'category': 'dynamic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'boxes',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'scores',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'maxOutputSize',\n        'type': 'number'\n      },\n      {\n        'start': 3,\n        'name': 'iouThreshold',\n        'type': 'number'\n      },\n      {\n        'start': 4,\n        'name': 'scoreThreshold',\n        'type': 'number'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'NonMaxSuppressionV4',\n    'category': 'dynamic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'boxes',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'scores',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'maxOutputSize',\n        'type': 'number'\n      },\n      {\n        'start': 3,\n        'name': 'iouThreshold',\n        'type': 'number'\n      },\n      {\n        'start': 4,\n        'name': 'scoreThreshold',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'T_threshold',\n        'name': 'threshold',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'pad_to_max_output_size',\n        'name': 'padToMaxOutputSize',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'NonMaxSuppressionV5',\n    'category': 'dynamic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'boxes',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'scores',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'maxOutputSize',\n        'type': 'number'\n      },\n      {\n        'start': 3,\n        'name': 'iouThreshold',\n        'type': 'number'\n      },\n      {\n        'start': 4,\n        'name': 'scoreThreshold',\n        'type': 'number'\n      },\n      {\n        'start': 5,\n        'name': 'softNmsSigma',\n        'type': 'number'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Where',\n    'category': 'dynamic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'condition',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ListDiff',\n    'category': 'dynamic',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'y',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  }\n];\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'LowerBound',\n    'category': 'evaluation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'sortedSequence',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'values',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TopKV2',\n    'category': 'evaluation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'k',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'sorted',\n        'name': 'sorted',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'UpperBound',\n    'category': 'evaluation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'sortedSequence',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'values',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Unique',\n    'category': 'evaluation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'UniqueV2',\n    'category': 'evaluation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'PlaceholderWithDefault',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'default',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'shape',\n        'name': 'shape',\n        'type': 'shape'\n      },\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Placeholder',\n    'category': 'graph',\n    'attrs': [\n      {\n        'tfName': 'shape',\n        'name': 'shape',\n        'type': 'shape'\n      },\n      {\n        'tfName': 'dtype',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Const',\n    'category': 'graph'\n  },\n  {\n    'tfOpName': 'Identity',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'IdentityN',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'end': 0,\n        'name': 'x',\n        'type': 'tensors'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Snapshot',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Rank',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Size',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Shape',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ShapeN',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'end': 0,\n        'name': 'x',\n        'type': 'tensors'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Print',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'data',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'message',\n        'name': 'message',\n        'type': 'string'\n      },\n      {\n        'tfName': 'first_n',\n        'name': 'firstN',\n        'type': 'number',\n        'notSupported': true\n      },\n      {\n        'tfName': 'summarize',\n        'name': 'summarize',\n        'type': 'number',\n        'defaultValue': 3\n      }\n    ]\n  },\n  {\n    'tfOpName': 'NoOp',\n    'category': 'graph',\n    'inputs': []\n  },\n  {\n    'tfOpName': 'StopGradient',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'FakeQuantWithMinMaxVars',\n    'category': 'graph',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'min',\n        'name': 'min',\n        'type': 'number'\n      },\n      {\n        'tfName': 'max',\n        'name': 'max',\n        'type': 'number'\n      }\n    ]\n  }\n];\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'HashTable',\n    'category': 'hash_table',\n    'inputs': [],\n    'attrs': [\n      {\n        'tfName': 'shared_name',\n        'name': 'sharedName',\n        'type': 'string'\n      },\n      {\n        'tfName': 'use_node_name_sharing',\n        'name': 'useNodeNameSharing',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'key_dtype',\n        'name': 'keyDType',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'value_dtype',\n        'name': 'valueDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'HashTableV2',\n    'category': 'hash_table',\n    'inputs': [],\n    'attrs': [\n      {\n        'tfName': 'shared_name',\n        'name': 'sharedName',\n        'type': 'string'\n      },\n      {\n        'tfName': 'use_node_name_sharing',\n        'name': 'useNodeNameSharing',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'key_dtype',\n        'name': 'keyDType',\n        'type': 'dtype'\n      },\n      {\n        'tfName': 'value_dtype',\n        'name': 'valueDType',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LookupTableImport',\n    'category': 'hash_table',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tableHandle',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'keys',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'values',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'Tin',\n        'name': 'tIn',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'Tout',\n        'name': 'tOut',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LookupTableImportV2',\n    'category': 'hash_table',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tableHandle',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'keys',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'values',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'Tin',\n        'name': 'tIn',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'Tout',\n        'name': 'tOut',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LookupTableFind',\n    'category': 'hash_table',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tableHandle',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'keys',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'defaultValue',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'Tin',\n        'name': 'tIn',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'Tout',\n        'name': 'tOut',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LookupTableFindV2',\n    'category': 'hash_table',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tableHandle',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'keys',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'defaultValue',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'Tin',\n        'name': 'tIn',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'Tout',\n        'name': 'tOut',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LookupTableSize',\n    'category': 'hash_table',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tableHandle',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LookupTableSizeV2',\n    'category': 'hash_table',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tableHandle',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'InitializeTable',\n    'category': 'hash_table',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tableHandle',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'keys',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'values',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'InitializeTableV2',\n    'category': 'hash_table',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tableHandle',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'keys',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'values',\n        'type': 'tensor'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'ResizeBilinear',\n    'category': 'image',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'images',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'size',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'align_corners',\n        'name': 'alignCorners',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'half_pixel_centers',\n        'name': 'halfPixelCenters',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ResizeNearestNeighbor',\n    'category': 'image',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'images',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'size',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'align_corners',\n        'name': 'alignCorners',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'half_pixel_centers',\n        'name': 'halfPixelCenters',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'CropAndResize',\n    'category': 'image',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'image',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'boxes',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'boxInd',\n        'type': 'tensor'\n      },\n      {\n        'start': 3,\n        'name': 'cropSize',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'method',\n        'name': 'method',\n        'type': 'string'\n      },\n      {\n        'tfName': 'extrapolation_value',\n        'name': 'extrapolationValue',\n        'type': 'number'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ImageProjectiveTransformV3',\n    'category': 'image',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'images',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'transforms',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'outputShape',\n        'type': 'number[]'\n      },\n      {\n        'start': 3,\n        'name': 'fillValue',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'interpolation',\n        'name': 'interpolation',\n        'type': 'string'\n      },\n      {\n        'tfName': 'fill_mode',\n        'name': 'fillMode',\n        'type': 'string'\n      }\n    ]\n  }\n];\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'Equal',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'NotEqual',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Greater',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'GreaterEqual',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Less',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LessEqual',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LogicalAnd',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LogicalNot',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LogicalOr',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Select',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'condition',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'SelectV2',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'condition',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'BitwiseAnd',\n    'category': 'logical',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'y',\n        'type': 'tensor'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': '_FusedMatMul',\n    'category': 'matrices',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'end': 0,\n        'name': 'args',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'num_args',\n        'name': 'numArgs',\n        'type': 'number'\n      },\n      {\n        'tfName': 'fused_ops',\n        'name': 'fusedOps',\n        'type': 'string[]',\n        'defaultValue': []\n      },\n      {\n        'tfName': 'epsilon',\n        'name': 'epsilon',\n        'type': 'number',\n        'defaultValue': 0.0001\n      },\n      {\n        'tfName': 'transpose_a',\n        'name': 'transposeA',\n        'type': 'bool',\n        'defaultValue': false\n      },\n      {\n        'tfName': 'transpose_b',\n        'name': 'transposeB',\n        'type': 'bool',\n        'defaultValue': false\n      },\n      {\n        'tfName': 'leakyrelu_alpha',\n        'name': 'leakyreluAlpha',\n        'type': 'number',\n        'defaultValue': 0.2\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'MatMul',\n    'category': 'matrices',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'transpose_a',\n        'name': 'transposeA',\n        'type': 'bool',\n        'defaultValue': false\n      },\n      {\n        'tfName': 'transpose_b',\n        'name': 'transposeB',\n        'type': 'bool',\n        'defaultValue': false\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'BatchMatMul',\n    'category': 'matrices',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'adj_x',\n        'name': 'transposeA',\n        'type': 'bool',\n        'defaultValue': false\n      },\n      {\n        'tfName': 'adj_y',\n        'name': 'transposeB',\n        'type': 'bool',\n        'defaultValue': false\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'BatchMatMulV2',\n    'category': 'matrices',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'b',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'adj_x',\n        'name': 'transposeA',\n        'type': 'bool',\n        'defaultValue': false\n      },\n      {\n        'tfName': 'adj_y',\n        'name': 'transposeB',\n        'type': 'bool',\n        'defaultValue': false\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Transpose',\n    'category': 'matrices',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'perm',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Einsum',\n    'category': 'matrices',\n    'inputs': [\n      {\n        'start': 0,\n        'end': 0,\n        'name': 'tensors',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'equation',\n        'name': 'equation',\n        'type': 'string'\n      },\n      {\n        'tfName': 'N',\n        'name': 'n',\n        'type': 'number',\n        'defaultValue': 2\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'MatrixBandPart',\n    'category': 'matrices',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'a',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'numLower',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'numUpper',\n        'type': 'tensor'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'EuclideanNorm',\n    'category': 'normalization',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'keep_dims',\n        'name': 'keepDims',\n        'type': 'bool',\n        'defaultValue': false\n      }\n    ]\n  },\n  {\n    'tfOpName': 'FusedBatchNorm',\n    'category': 'normalization',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'scale',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'offset',\n        'type': 'tensor'\n      },\n      {\n        'start': 3,\n        'name': 'mean',\n        'type': 'tensor'\n      },\n      {\n        'start': 4,\n        'name': 'variance',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'epsilon',\n        'name': 'epsilon',\n        'type': 'number',\n        'defaultValue': 0.001\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'FusedBatchNormV2',\n    'category': 'normalization',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'scale',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'offset',\n        'type': 'tensor'\n      },\n      {\n        'start': 3,\n        'name': 'mean',\n        'type': 'tensor'\n      },\n      {\n        'start': 4,\n        'name': 'variance',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'epsilon',\n        'name': 'epsilon',\n        'type': 'number',\n        'defaultValue': 0.001\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'FusedBatchNormV3',\n    'category': 'normalization',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'scale',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'offset',\n        'type': 'tensor'\n      },\n      {\n        'start': 3,\n        'name': 'mean',\n        'type': 'tensor'\n      },\n      {\n        'start': 4,\n        'name': 'variance',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'epsilon',\n        'name': 'epsilon',\n        'type': 'number',\n        'defaultValue': 0.001\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LRN',\n    'category': 'normalization',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'depth_radius',\n        'name': 'radius',\n        'type': 'number',\n        'defaultValue': 5\n      },\n      {\n        'tfName': 'bias',\n        'name': 'bias',\n        'type': 'number',\n        'defaultValue': 1\n      },\n      {\n        'tfName': 'alpha',\n        'name': 'alpha',\n        'type': 'number',\n        'defaultValue': 1\n      },\n      {\n        'tfName': 'beta',\n        'name': 'beta',\n        'type': 'number',\n        'defaultValue': 0.5\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Softmax',\n    'category': 'normalization',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'LogSoftmax',\n    'category': 'normalization',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'Bincount',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'size',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'weights',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'DenseBincount',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'size',\n        'type': 'number'\n      },\n      {\n        'start': 2,\n        'name': 'weights',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'binary_output',\n        'name': 'binaryOutput',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Max',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'keep_dims',\n        'name': 'keepDims',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Mean',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'keep_dims',\n        'name': 'keepDims',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Min',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'keep_dims',\n        'name': 'keepDims',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Sum',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'keep_dims',\n        'name': 'keepDims',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'All',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'keep_dims',\n        'name': 'keepDims',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Any',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'keep_dims',\n        'name': 'keepDims',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ArgMax',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ArgMin',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Prod',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'keep_dims',\n        'name': 'keepDims',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Cumprod',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'exclusive',\n        'name': 'exclusive',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'reverse',\n        'name': 'reverse',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Cumsum',\n    'category': 'reduction',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'exclusive',\n        'name': 'exclusive',\n        'type': 'bool'\n      },\n      {\n        'tfName': 'reverse',\n        'name': 'reverse',\n        'type': 'bool'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'ConcatV2',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'end': -1,\n        'name': 'tensors',\n        'type': 'tensors'\n      },\n      {\n        'start': -1,\n        'name': 'axis',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'N',\n        'name': 'n',\n        'type': 'number',\n        'defaultValue': 2\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Concat',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 1,\n        'end': 0,\n        'name': 'tensors',\n        'type': 'tensors'\n      },\n      {\n        'start': 0,\n        'name': 'axis',\n        'type': 'number'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'N',\n        'name': 'n',\n        'type': 'number',\n        'defaultValue': 2\n      }\n    ]\n  },\n  {\n    'tfOpName': 'GatherV2',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'axis',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'batch_dims',\n        'name': 'batchDims',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Gather',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'validate_indices',\n        'name': 'validateIndices',\n        'type': 'bool',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Reverse',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'dims',\n        'type': 'bool[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ReverseV2',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Slice',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'begin',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'size',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'StridedSlice',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'begin',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'end',\n        'type': 'number[]'\n      },\n      {\n        'start': 3,\n        'name': 'strides',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'begin_mask',\n        'name': 'beginMask',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'end_mask',\n        'name': 'endMask',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'new_axis_mask',\n        'name': 'newAxisMask',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'ellipsis_mask',\n        'name': 'ellipsisMask',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'shrink_axis_mask',\n        'name': 'shrinkAxisMask',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Pack',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'end': 0,\n        'name': 'tensors',\n        'type': 'tensors'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'axis',\n        'name': 'axis',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Unpack',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'axis',\n        'name': 'axis',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'tfName': 'num',\n        'name': 'num',\n        'type': 'number',\n        'defaultValue': 0,\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Tile',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'reps',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Split',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'axis',\n        'type': 'number',\n        'defaultValue': 0\n      },\n      {\n        'start': 1,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'num_split',\n        'name': 'numOrSizeSplits',\n        'type': 'number',\n        'defaultValue': 1\n      }\n    ]\n  },\n  {\n    'tfOpName': 'SplitV',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'numOrSizeSplits',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'axis',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ScatterNd',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'indices',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'values',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'GatherNd',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'SparseToDense',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'sparseIndices',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'outputShape',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'sparseValues',\n        'type': 'tensor'\n      },\n      {\n        'start': 3,\n        'name': 'defaultValue',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'validate_indices',\n        'name': 'validateIndices',\n        'type': 'bool',\n        'defaultValue': false,\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'TensorScatterUpdate',\n    'category': 'slice_join',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'tensor',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'values',\n        'type': 'tensor'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'SparseFillEmptyRows',\n    'category': 'sparse',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'indices',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'values',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'denseShape',\n        'type': 'tensor'\n      },\n      {\n        'start': 3,\n        'name': 'defaultValue',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'SparseReshape',\n    'category': 'sparse',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'inputIndices',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'inputShape',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'newShape',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'T',\n        'name': 'dtype',\n        'type': 'dtype',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'SparseSegmentMean',\n    'category': 'sparse',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'data',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'segmentIds',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'SparseSegmentSum',\n    'category': 'sparse',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'data',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'indices',\n        'type': 'tensor'\n      },\n      {\n        'start': 2,\n        'name': 'segmentIds',\n        'type': 'tensor'\n      }\n    ]\n  }\n];\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'FFT',\n    'category': 'spectral',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'IFFT',\n    'category': 'spectral',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'RFFT',\n    'category': 'spectral',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'fft_length',\n        'type': 'number',\n        'notSupported': true\n      }\n    ]\n  },\n  {\n    'tfOpName': 'IRFFT',\n    'category': 'spectral',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'fft_length',\n        'type': 'number',\n        'notSupported': true\n      }\n    ]\n  }\n];\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'StaticRegexReplace',\n    'category': 'string',\n    'inputs': [\n      {\n      'start': 0,\n        'name': 'input',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'pattern',\n        'name': 'pattern',\n        'type': 'string'\n      },\n      {\n        'tfName': 'rewrite',\n        'name': 'rewrite',\n        'type': 'string'\n      },\n      {\n        'tfName': 'replace_global',\n        'name': 'replaceGlobal',\n        'type': 'bool'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'StringNGrams',\n    'category': 'string',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'data',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'dataSplits',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'separator',\n        'name': 'separator',\n        'type': 'string'\n      },\n      {\n        'tfName': 'ngram_widths',\n        'name': 'nGramWidths',\n        'type': 'number[]'\n      },\n      {\n        'tfName': 'left_pad',\n        'name': 'leftPad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'right_pad',\n        'name': 'rightPad',\n        'type': 'string'\n      },\n      {\n        'tfName': 'pad_width',\n        'name': 'padWidth',\n        'type': 'number'\n      },\n      {\n        'tfName': 'preserve_short_sequences',\n        'name': 'preserveShortSequences',\n        'type': 'bool'\n      }\n    ],\n    'outputs': [\n      'ngrams',\n      'ngrams_splits'\n    ]\n  },\n  {\n    'tfOpName': 'StringSplit',\n    'category': 'string',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'input',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'delimiter',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'skip_empty',\n        'name': 'skipEmpty',\n        'type': 'bool'\n      }\n    ],\n    'outputs': [\n      'indices',\n      'values',\n      'shape'\n    ]\n  },\n  {\n    'tfOpName': 'StringToHashBucketFast',\n    'category': 'string',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'input',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'num_buckets',\n        'name': 'numBuckets',\n        'type': 'number'\n      }\n    ]\n  }\n]\n;\n", "\n/**\n * @license\n * Copyright 2023 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n  {\n    'tfOpName': 'Cast',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'SrcT',\n        'name': 'sdtype',\n        'type': 'dtype',\n        'notSupported': true\n      },\n      {\n        'tfName': 'DstT',\n        'name': 'dtype',\n        'type': 'dtype'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'ExpandDims',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'axis',\n        'type': 'number'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'MirrorPad',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'padding',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'mode',\n        'name': 'mode',\n        'type': 'string'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Pad',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'padding',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'constant_value',\n        'name': 'constantValue',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ]\n  },\n  {\n    'tfOpName': 'PadV2',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'padding',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'constantValue',\n        'type': 'number',\n        'defaultValue': 0\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Reshape',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'EnsureShape',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'Squeeze',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'axis',\n        'tfDeprecatedName': 'squeeze_dims',\n        'name': 'axis',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'SpaceToBatchND',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'blockShape',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'paddings',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'BatchToSpaceND',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'blockShape',\n        'type': 'number[]'\n      },\n      {\n        'start': 2,\n        'name': 'crops',\n        'type': 'number[]'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'DepthToSpace',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': [\n      {\n        'tfName': 'block_size',\n        'name': 'blockSize',\n        'type': 'number'\n      },\n      {\n        'tfName': 'data_format',\n        'name': 'dataFormat',\n        'type': 'string'\n      }\n    ]\n  },\n  {\n    'tfOpName': 'BroadcastTo',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 'x',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 'shape',\n        'type': 'number[]'\n      }\n    ],\n    'attrs': []\n  },\n  {\n    'tfOpName': 'BroadcastArgs',\n    'category': 'transformation',\n    'inputs': [\n      {\n        'start': 0,\n        'name': 's0',\n        'type': 'tensor'\n      },\n      {\n        'start': 1,\n        'name': 's1',\n        'type': 'tensor'\n      }\n    ],\n    'attrs': []\n  }\n]\n;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, env} from '@tensorflow/tfjs-core';\n\nimport * as tensorflow from '../data/compiled_api';\n\nimport {getRegisteredOp} from './custom_op/register';\nimport {getNodeNameAndIndex} from './executors/utils';\nimport * as arithmetic from './op_list/arithmetic';\nimport * as basicMath from './op_list/basic_math';\nimport * as control from './op_list/control';\nimport * as convolution from './op_list/convolution';\nimport * as creation from './op_list/creation';\nimport * as dynamic from './op_list/dynamic';\nimport * as evaluation from './op_list/evaluation';\nimport * as graph from './op_list/graph';\nimport * as hashTable from './op_list/hash_table';\nimport * as image from './op_list/image';\nimport * as logical from './op_list/logical';\nimport * as matrices from './op_list/matrices';\nimport * as normalization from './op_list/normalization';\nimport * as reduction from './op_list/reduction';\nimport * as sliceJoin from './op_list/slice_join';\nimport * as sparse from './op_list/sparse';\nimport * as spectral from './op_list/spectral';\nimport * as string from './op_list/string';\nimport * as transformation from './op_list/transformation';\nimport {Graph, InputParamValue, Node, OpMapper, ParamValue} from './types';\n\nexport class OperationMapper {\n  private static _instance: OperationMapper;\n\n  private opMappers: {[key: string]: OpMapper};\n\n  // Singleton instance for the mapper\n  public static get Instance() {\n    return this._instance || (this._instance = new this());\n  }\n\n  // Loads the op mapping from the JSON file.\n  private constructor() {\n    const ops = [\n      arithmetic, basicMath, control, convolution, creation, dynamic,\n      evaluation, graph, hashTable, image, logical, matrices, normalization,\n      reduction, sliceJoin, sparse, spectral, string, transformation\n    ];\n    const mappersJson: OpMapper[] = [].concat(...ops.map(op => op.json));\n\n    this.opMappers = mappersJson.reduce<{[key: string]: OpMapper}>(\n        (map, mapper: OpMapper) => {\n          map[mapper.tfOpName] = mapper;\n          return map;\n        },\n        {});\n  }\n\n  // Converts the model inference graph from Tensorflow GraphDef to local\n  // representation for TensorFlow.js API\n  transformGraph(\n      graph: tensorflow.IGraphDef,\n      signature: tensorflow.ISignatureDef = {}): Graph {\n    const tfNodes = graph.node;\n    const placeholders: Node[] = [];\n    const weights: Node[] = [];\n    const initNodes: Node[] = [];\n    const nodes = tfNodes.reduce<{[key: string]: Node}>((map, node) => {\n      map[node.name] = this.mapNode(node);\n      if (node.op.startsWith('Placeholder')) {\n        placeholders.push(map[node.name]);\n      } else if (node.op === 'Const') {\n        weights.push(map[node.name]);\n      } else if (node.input == null || node.input.length === 0) {\n        initNodes.push(map[node.name]);\n      }\n      return map;\n    }, {});\n\n    let inputs: Node[] = [];\n    const outputs: Node[] = [];\n    let inputNodeNameToKey: {[key: string]: string} = {};\n    let outputNodeNameToKey: {[key: string]: string} = {};\n    if (signature != null) {\n      inputNodeNameToKey = this.mapSignatureEntries(signature.inputs);\n      outputNodeNameToKey = this.mapSignatureEntries(signature.outputs);\n    }\n    const allNodes = Object.keys(nodes);\n    allNodes.forEach(key => {\n      const node = nodes[key];\n      node.inputNames.forEach((name, index) => {\n        const [nodeName, , outputName] = getNodeNameAndIndex(name);\n        const inputNode = nodes[nodeName];\n        if (inputNode.outputs != null) {\n          const outputIndex = inputNode.outputs.indexOf(outputName);\n          if (outputIndex !== -1) {\n            const inputName = `${nodeName}:${outputIndex}`;\n            // update the input name to use the mapped output index directly.\n            node.inputNames[index] = inputName;\n          }\n        }\n        node.inputs.push(inputNode);\n        inputNode.children.push(node);\n      });\n    });\n\n    // if signature has not outputs set, add any node that does not have\n    // outputs.\n    if (Object.keys(outputNodeNameToKey).length === 0) {\n      allNodes.forEach(key => {\n        const node = nodes[key];\n        if (node.children.length === 0) {\n          outputs.push(node);\n        }\n      });\n    } else {\n      Object.keys(outputNodeNameToKey).forEach(name => {\n        const [nodeName, ] = getNodeNameAndIndex(name);\n        const node = nodes[nodeName];\n        if (node != null) {\n          node.signatureKey = outputNodeNameToKey[name];\n          outputs.push(node);\n        }\n      });\n    }\n\n    if (Object.keys(inputNodeNameToKey).length > 0) {\n      Object.keys(inputNodeNameToKey).forEach(name => {\n        const [nodeName, ] = getNodeNameAndIndex(name);\n        const node = nodes[nodeName];\n        if (node) {\n          node.signatureKey = inputNodeNameToKey[name];\n          inputs.push(node);\n        }\n      });\n    } else {\n      inputs = placeholders;\n    }\n\n    let functions = {};\n    if (graph.library != null && graph.library.function != null) {\n      functions = graph.library.function.reduce((functions, func) => {\n        functions[func.signature.name] = this.mapFunction(func);\n        return functions;\n      }, {} as {[key: string]: Graph});\n    }\n\n    const result: Graph =\n        {nodes, inputs, outputs, weights, placeholders, signature, functions};\n\n    if (initNodes.length > 0) {\n      result.initNodes = initNodes;\n    }\n\n    return result;\n  }\n\n  private mapSignatureEntries(entries: {[k: string]: tensorflow.ITensorInfo}) {\n    return Object.keys(entries || {})\n        .reduce<{[key: string]: string}>((prev, curr) => {\n          prev[entries[curr].name] = curr;\n          return prev;\n        }, {});\n  }\n\n  private mapNode(node: tensorflow.INodeDef): Node {\n    // Unsupported ops will cause an error at run-time (not parse time), since\n    // they may not be used by the actual execution subgraph.\n    const mapper =\n        getRegisteredOp(node.op) || this.opMappers[node.op] || {} as OpMapper;\n    if (node.attr == null) {\n      node.attr = {};\n    }\n\n    const newNode: Node = {\n      name: node.name,\n      op: node.op,\n      category: mapper.category,\n      inputNames:\n          (node.input ||\n           []).map(input => input.startsWith('^') ? input.slice(1) : input),\n      inputs: [],\n      children: [],\n      inputParams: {},\n      attrParams: {},\n      rawAttrs: node.attr,\n      outputs: mapper.outputs\n    };\n\n    if (mapper.inputs != null) {\n      newNode.inputParams =\n          mapper.inputs.reduce<{[key: string]: InputParamValue}>(\n              (map, param) => {\n                map[param.name] = {\n                  type: param.type,\n                  inputIndexStart: param.start,\n                  inputIndexEnd: param.end\n                };\n                return map;\n              },\n              {});\n    }\n    if (mapper.attrs != null) {\n      newNode.attrParams =\n          mapper.attrs.reduce<{[key: string]: ParamValue}>((map, param) => {\n            const type = param.type;\n            let value = undefined;\n            switch (param.type) {\n              case 'string':\n                value = getStringParam(\n                    node.attr, param.tfName, param.defaultValue as string);\n\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getStringParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as string);\n                }\n                break;\n              case 'string[]':\n                value = getStringArrayParam(\n                    node.attr, param.tfName, param.defaultValue as string[]);\n\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getStringArrayParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as string[]);\n                }\n                break;\n              case 'number':\n                value = getNumberParam(\n                    node.attr, param.tfName,\n                    (param.defaultValue || 0) as number);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getNumberParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as number);\n                }\n                break;\n              case 'number[]':\n                value = getNumericArrayParam(\n                    node.attr, param.tfName, param.defaultValue as number[]);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getNumericArrayParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as number[]);\n                }\n                break;\n              case 'bool':\n                value = getBoolParam(\n                    node.attr, param.tfName, param.defaultValue as boolean);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getBoolParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as boolean);\n                }\n                break;\n              case 'bool[]':\n                value = getBoolArrayParam(\n                    node.attr, param.tfName, param.defaultValue as boolean[]);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getBoolArrayParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as boolean[]);\n                }\n                break;\n              case 'shape':\n                value = getTensorShapeParam(\n                    node.attr, param.tfName, param.defaultValue as number[]);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getTensorShapeParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as number[]);\n                }\n                break;\n              case 'shape[]':\n                value = getTensorShapeArrayParam(\n                    node.attr, param.tfName, param.defaultValue as number[][]);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getTensorShapeArrayParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as number[][]);\n                }\n                break;\n              case 'dtype':\n                value = getDtypeParam(\n                    node.attr, param.tfName, param.defaultValue as DataType);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getDtypeParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as DataType);\n                }\n                break;\n              case 'dtype[]':\n                value = getDtypeArrayParam(\n                    node.attr, param.tfName, param.defaultValue as DataType[]);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getDtypeArrayParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as DataType[]);\n                }\n                break;\n              case 'func':\n                value = getFuncParam(\n                    node.attr, param.tfName, param.defaultValue as string);\n                if (value === undefined && !!param.tfDeprecatedName) {\n                  value = getFuncParam(\n                      node.attr, param.tfDeprecatedName,\n                      param.defaultValue as string);\n                }\n                break;\n              case 'tensor':\n              case 'tensors':\n                break;\n              default:\n                throw new Error(\n                    `Unsupported param type: ${param.type} for op: ${node.op}`);\n            }\n            map[param.name] = {value, type};\n            return map;\n          }, {});\n    }\n    return newNode;\n  }\n\n  // map the TFunctionDef to TFJS graph object\n  private mapFunction(functionDef: tensorflow.IFunctionDef): Graph {\n    const tfNodes = functionDef.nodeDef;\n    const placeholders: Node[] = [];\n    const weights: Node[] = [];\n    let nodes: {[key: string]: Node} = {};\n    if (tfNodes != null) {\n      nodes = tfNodes.reduce<{[key: string]: Node}>((map, node) => {\n        map[node.name] = this.mapNode(node);\n        if (node.op === 'Const') {\n          weights.push(map[node.name]);\n        }\n        return map;\n      }, {});\n    }\n    const inputs: Node[] = [];\n    const outputs: Node[] = [];\n\n    functionDef.signature.inputArg.forEach(arg => {\n      const [nodeName, ] = getNodeNameAndIndex(arg.name);\n      const node: Node = {\n        name: nodeName,\n        op: 'Placeholder',\n        inputs: [],\n        inputNames: [],\n        category: 'graph',\n        inputParams: {},\n        attrParams: {dtype: {value: parseDtypeParam(arg.type), type: 'dtype'}},\n        children: []\n      };\n      node.signatureKey = arg.name;\n      inputs.push(node);\n      nodes[nodeName] = node;\n    });\n\n    const allNodes = Object.keys(nodes);\n    allNodes.forEach(key => {\n      const node = nodes[key];\n      node.inputNames.forEach((name, index) => {\n        const [nodeName, , outputName] = getNodeNameAndIndex(name);\n        const inputNode = nodes[nodeName];\n        if (inputNode.outputs != null) {\n          const outputIndex = inputNode.outputs.indexOf(outputName);\n          if (outputIndex !== -1) {\n            const inputName = `${nodeName}:${outputIndex}`;\n            // update the input name to use the mapped output index directly.\n            node.inputNames[index] = inputName;\n          }\n        }\n        node.inputs.push(inputNode);\n        inputNode.children.push(node);\n      });\n    });\n\n    const returnNodeMap = functionDef.ret;\n\n    functionDef.signature.outputArg.forEach(output => {\n      const [nodeName, index] = getNodeNameAndIndex(returnNodeMap[output.name]);\n      const node = nodes[nodeName];\n      if (node != null) {\n        node.defaultOutput = index;\n        outputs.push(node);\n      }\n    });\n\n    const signature = this.mapArgsToSignature(functionDef);\n    return {nodes, inputs, outputs, weights, placeholders, signature};\n  }\n\n  private mapArgsToSignature(functionDef: tensorflow.IFunctionDef):\n      tensorflow.ISignatureDef {\n    return {\n      methodName: functionDef.signature.name,\n      inputs: functionDef.signature.inputArg.reduce(\n          (map, arg) => {\n            map[arg.name] = this.mapArgToTensorInfo(arg);\n            return map;\n          },\n          {} as {[key: string]: tensorflow.ITensorInfo}),\n      outputs: functionDef.signature.outputArg.reduce(\n          (map, arg) => {\n            map[arg.name] = this.mapArgToTensorInfo(arg, functionDef.ret);\n            return map;\n          },\n          {} as {[key: string]: tensorflow.ITensorInfo}),\n    };\n  }\n\n  private mapArgToTensorInfo(\n      arg: tensorflow.OpDef.IArgDef,\n      nameMap?: {[key: string]: string}): tensorflow.ITensorInfo {\n    let name = arg.name;\n    if (nameMap != null) {\n      name = nameMap[name];\n    }\n    return {name, dtype: arg.type};\n  }\n}\n\nexport function decodeBase64(text: string): string {\n  const global = env().global;\n  if (typeof global.atob !== 'undefined') {\n    return global.atob(text);\n  } else if (typeof Buffer !== 'undefined') {\n    return new Buffer(text, 'base64').toString();\n  } else {\n    throw new Error(\n        'Unable to decode base64 in this environment. ' +\n        'Missing built-in atob() or Buffer()');\n  }\n}\n\nexport function parseStringParam(s: []|string, keepCase: boolean): string {\n  const value =\n      Array.isArray(s) ? String.fromCharCode.apply(null, s) : decodeBase64(s);\n  return keepCase ? value : value.toLowerCase();\n}\n\nexport function getStringParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string, def: string,\n    keepCase = false): string {\n  const param = attrs[name];\n  if (param != null) {\n    return parseStringParam(param.s, keepCase);\n  }\n  return def;\n}\n\nexport function getBoolParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def: boolean): boolean {\n  const param = attrs[name];\n  return param ? param.b : def;\n}\n\nexport function getNumberParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def: number): number {\n  const param = attrs[name] || {};\n  const value =\n      param['i'] != null ? param['i'] : (param['f'] != null ? param['f'] : def);\n  return (typeof value === 'number') ? value : parseInt(value, 10);\n}\n\nexport function parseDtypeParam(value: string|tensorflow.DataType): DataType {\n  if (typeof (value) === 'string') {\n    // tslint:disable-next-line:no-any\n    value = tensorflow.DataType[value as any];\n  }\n  switch (value) {\n    case tensorflow.DataType.DT_FLOAT:\n    case tensorflow.DataType.DT_HALF:\n      return 'float32';\n    case tensorflow.DataType.DT_INT32:\n    case tensorflow.DataType.DT_INT64:\n    case tensorflow.DataType.DT_INT8:\n    case tensorflow.DataType.DT_UINT8:\n      return 'int32';\n    case tensorflow.DataType.DT_BOOL:\n      return 'bool';\n    case tensorflow.DataType.DT_DOUBLE:\n      return 'float32';\n    case tensorflow.DataType.DT_STRING:\n      return 'string';\n    case tensorflow.DataType.DT_COMPLEX64:\n    case tensorflow.DataType.DT_COMPLEX128:\n      return 'complex64';\n    default:\n      // Unknown dtype error will happen at runtime (instead of parse time),\n      // since these nodes might not be used by the actual subgraph execution.\n      return null;\n  }\n}\n\nexport function getFuncParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def: string): string {\n  const param = attrs[name];\n  if (param && param.func) {\n    return param.func.name;\n  }\n  return def;\n}\n\nexport function getDtypeParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def: DataType): DataType {\n  const param = attrs[name];\n  if (param && param.type) {\n    return parseDtypeParam(param.type);\n  }\n  return def;\n}\n\nexport function getDtypeArrayParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def: DataType[]): DataType[] {\n  const param = attrs[name];\n  if (param && param.list && param.list.type) {\n    return param.list.type.map(v => parseDtypeParam(v));\n  }\n  return def;\n}\n\nexport function parseTensorShapeParam(shape: tensorflow.ITensorShape): number[]|\n    undefined {\n  if (shape.unknownRank) {\n    return undefined;\n  }\n  if (shape.dim != null) {\n    return shape.dim.map(\n        dim =>\n            (typeof dim.size === 'number') ? dim.size : parseInt(dim.size, 10));\n  }\n  return [];\n}\n\nexport function getTensorShapeParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def?: number[]): number[]|undefined {\n  const param = attrs[name];\n  if (param && param.shape) {\n    return parseTensorShapeParam(param.shape);\n  }\n  return def;\n}\n\nexport function getNumericArrayParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def: number[]): number[] {\n  const param = attrs[name];\n  if (param) {\n    return ((param.list.f && param.list.f.length ? param.list.f :\n                                                   param.list.i) ||\n            [])\n        .map(v => (typeof v === 'number') ? v : parseInt(v, 10));\n  }\n  return def;\n}\n\nexport function getStringArrayParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string, def: string[],\n    keepCase = false): string[] {\n  const param = attrs[name];\n  if (param && param.list && param.list.s) {\n    return param.list.s.map((v) => {\n      return parseStringParam(v, keepCase);\n    });\n  }\n  return def;\n}\n\nexport function getTensorShapeArrayParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def: number[][]): number[][] {\n  const param = attrs[name];\n  if (param && param.list && param.list.shape) {\n    return param.list.shape.map((v) => {\n      return parseTensorShapeParam(v);\n    });\n  }\n  return def;\n}\n\nexport function getBoolArrayParam(\n    attrs: {[key: string]: tensorflow.IAttrValue}, name: string,\n    def: boolean[]): boolean[] {\n  const param = attrs[name];\n  if (param && param.list && param.list.b) {\n    return param.list.b;\n  }\n  return def;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {getTensor} from '../executors/utils';\nimport {getBoolArrayParam, getBoolParam, getDtypeArrayParam, getDtypeParam, getNumberParam, getNumericArrayParam, getStringArrayParam, getStringParam, getTensorShapeArrayParam, getTensorShapeParam} from '../operation_mapper';\nimport {GraphNode, Node, ValueType} from '../types';\n\n/**\n * Helper class for lookup inputs and params for nodes in the model graph.\n */\nexport class NodeValueImpl implements GraphNode {\n  public readonly inputs: Tensor[] = [];\n  public readonly attrs: {[key: string]: ValueType} = {};\n  constructor(\n      private node: Node, private tensorMap: NamedTensorsMap,\n      private context: ExecutionContext) {\n    this.inputs = node.inputNames.map(name => this.getInput(name));\n    if (node.rawAttrs != null) {\n      this.attrs = Object.keys(node.rawAttrs)\n                       .reduce((attrs: {[key: string]: ValueType}, key) => {\n                         attrs[key] = this.getAttr(key);\n                         return attrs;\n                       }, {});\n    }\n  }\n\n  /**\n   * Return the value of the attribute or input param.\n   * @param name String: name of attribute or input param.\n   */\n  private getInput(name: string): Tensor {\n    return getTensor(name, this.tensorMap, this.context);\n  }\n\n  /**\n   * Return the value of the attribute or input param.\n   * @param name String: name of attribute or input param.\n   */\n  private getAttr(name: string, defaultValue?: ValueType): ValueType {\n    const value = this.node.rawAttrs[name];\n    if (value.tensor != null) {\n      return getTensor(name, this.tensorMap, this.context);\n    }\n    if (value.i != null || value.f != null) {\n      return getNumberParam(this.node.rawAttrs, name, defaultValue as number);\n    }\n    if (value.s != null) {\n      return getStringParam(this.node.rawAttrs, name, defaultValue as string);\n    }\n    if (value.b != null) {\n      return getBoolParam(this.node.rawAttrs, name, defaultValue as boolean);\n    }\n    if (value.shape != null) {\n      return getTensorShapeParam(\n          this.node.rawAttrs, name, defaultValue as number[]);\n    }\n    if (value.type != null) {\n      return getDtypeParam(this.node.rawAttrs, name, defaultValue as DataType);\n    }\n    if (value.list != null) {\n      if (value.list.i != null || value.list.f != null) {\n        return getNumericArrayParam(\n            this.node.rawAttrs, name, defaultValue as number[]);\n      }\n      if (value.list.s != null) {\n        return getStringArrayParam(\n            this.node.rawAttrs, name, defaultValue as string[]);\n      }\n      if (value.list.shape != null) {\n        return getTensorShapeArrayParam(\n            this.node.rawAttrs, name, defaultValue as number[][]);\n      }\n      if (value.list.b != null) {\n        return getBoolArrayParam(\n            this.node.rawAttrs, name, defaultValue as boolean[]);\n      }\n      if (value.list.type != null) {\n        return getDtypeArrayParam(\n            this.node.rawAttrs, name, defaultValue as DataType[]);\n      }\n    }\n\n    return defaultValue;\n  }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Backend, DataToGPUOptions, GPUData, Tensor} from '../tensor';\nimport {DataId} from '../tensor_info';\nimport {BackendValues, DataType, WebGLData, WebGPUData} from '../types';\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\n// Required information for all backends.\nexport interface BackendTimingInfo {\n  kernelMs: number|{error: string};\n  getExtraProfileInfo?(): string;  // a field for additional timing information\n                                   // e.g. packing / unpacking for WebGL backend\n}\n\nexport interface TensorStorage {\n  read(dataId: DataId): Promise<BackendValues>;\n  readSync(dataId: DataId): BackendValues;\n  disposeData(dataId: DataId, force?: boolean): boolean;\n  write(values: BackendValues, shape: number[], dtype: DataType): DataId;\n  move(\n      dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n      refCount: number): void;\n  memory(): {unreliable: boolean;};  // Backend-specific information.\n  /** Returns number of data ids currently in the storage. */\n  numDataIds(): number;\n  refCount(dataId: DataId): number;\n}\n\n/** Convenient class for storing tensor-related data. */\nexport class DataStorage<T> {\n  private data = new WeakMap<DataId, T>();\n  private dataIdsCount = 0;\n\n  constructor(private backend: KernelBackend, private dataMover: DataMover) {}\n\n  get(dataId: DataId) {\n    if (!this.data.has(dataId)) {\n      this.dataMover.moveData(this.backend, dataId);\n    }\n    return this.data.get(dataId);\n  }\n\n  set(dataId: DataId, value: T): void {\n    this.dataIdsCount++;\n    this.data.set(dataId, value);\n  }\n\n  has(dataId: DataId): boolean {\n    return this.data.has(dataId);\n  }\n\n  delete(dataId: DataId): boolean {\n    this.dataIdsCount--;\n    return this.data.delete(dataId);\n  }\n\n  numDataIds(): number {\n    return this.dataIdsCount;\n  }\n}\n\nexport interface DataMover {\n  /**\n   * To be called by backends whenever they see a dataId that they don't own.\n   * Upon calling this method, the mover will fetch the tensor from another\n   * backend and register it with the current active backend.\n   */\n  moveData(backend: KernelBackend, dataId: DataId): void;\n}\n\nexport interface BackendTimer {\n  // check if backend timer is available\n  timerAvailable(): boolean;\n  time(f: () => void): Promise<BackendTimingInfo>;\n}\n\n/**\n * The interface that defines the kernels that should be implemented when\n * adding a new backend. New backends don't need to implement every one of the\n * methods, this can be done gradually (throw an error for unimplemented\n * methods).\n */\nexport class KernelBackend implements TensorStorage, Backend, BackendTimer {\n  refCount(dataId: DataId): number {\n    return notYetImplemented('refCount');\n  }\n  incRef(dataId: DataId): void {\n    return notYetImplemented('incRef');\n  }\n  timerAvailable(): boolean {\n    return true;\n  }\n  time(f: () => void): Promise<BackendTimingInfo> {\n    return notYetImplemented('time');\n  }\n  read(dataId: object): Promise<BackendValues> {\n    return notYetImplemented('read');\n  }\n  readSync(dataId: object): BackendValues {\n    return notYetImplemented('readSync');\n  }\n  readToGPU(dataId: object, options?: DataToGPUOptions): GPUData {\n    return notYetImplemented('readToGPU');\n  }\n  numDataIds(): number {\n    return notYetImplemented('numDataIds');\n  }\n  disposeData(dataId: object, force?: boolean): boolean {\n    return notYetImplemented('disposeData');\n  }\n  write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n    return notYetImplemented('write');\n  }\n  move(\n      dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n      refCount: number): void {\n    return notYetImplemented('move');\n  }\n\n  createTensorFromGPUData(\n      values: WebGLData|WebGPUData, shape: number[], dtype: DataType): Tensor {\n    return notYetImplemented('createTensorFromGPUData');\n  }\n\n  memory(): {unreliable: boolean; reasons?: string[]} {\n    return notYetImplemented('memory');\n  }\n  /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n  floatPrecision(): 16|32 {\n    return notYetImplemented('floatPrecision');\n  }\n  /** Returns the smallest representable number.  */\n  epsilon(): number {\n    return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n  }\n  dispose(): void {\n    return notYetImplemented('dispose');\n  }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n  throw new Error(\n      `'${kernelName}' not yet implemented or not found in the registry. ` +\n      `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendValues, DataType, DataTypeMap, FlatVector, NumericDataType, TensorLike, TypedArray, WebGLData, WebGPUData} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n                        Float32Array): void {\n  let counter = array.length;\n  let index = 0;\n  // While there are elements in the array\n  while (counter > 0) {\n    // Pick a random index\n    index = (Math.random() * counter) | 0;\n    // Decrease counter by 1\n    counter--;\n    // And swap the last element with it\n    swap(array, counter, index);\n  }\n}\n\n/**\n * Shuffles two arrays in-place the same way using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1,2,3,4,5];\n * const b = [11,22,33,44,55];\n * tf.util.shuffleCombo(a, b);\n * console.log(a, b);\n * ```\n *\n * @param array The first array to shuffle in-place.\n * @param array2 The second array to shuffle in-place with the same permutation\n *     as the first array.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function shuffleCombo(\n    // tslint:disable-next-line:no-any\n    array: any[]|Uint32Array|Int32Array|Float32Array,\n    // tslint:disable-next-line:no-any\n    array2: any[]|Uint32Array|Int32Array|Float32Array): void {\n  if (array.length !== array2.length) {\n    throw new Error(\n        `Array sizes must match to be shuffled together ` +\n        `First array length was ${array.length}` +\n        `Second array length was ${array2.length}`);\n  }\n  let counter = array.length;\n  let index = 0;\n  // While there are elements in the array\n  while (counter > 0) {\n    // Pick a random index\n    index = (Math.random() * counter) | 0;\n    // Decrease counter by 1\n    counter--;\n    // And swap the last element of each array with it\n    swap(array, counter, index);\n    swap(array2, counter, index);\n  }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n  return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n  return val % 2 === 0 ? val : val + 1;\n}\n\nexport function swap<T>(\n    object: {[index: number]: T}, left: number, right: number) {\n  const temp = object[left];\n  object[left] = object[right];\n  object[right] = temp;\n}\n\nexport function sum(arr: number[]): number {\n  let sum = 0;\n  for (let i = 0; i < arr.length; i++) {\n    sum += arr[i];\n  }\n  return sum;\n}\n\n/**\n * Returns a sample from a uniform [a, b) distribution.\n *\n * @param a The minimum support (inclusive).\n * @param b The maximum support (exclusive).\n * @return A pseudorandom number on the half-open interval [a,b).\n */\nexport function randUniform(a: number, b: number) {\n  const r = Math.random();\n  return (b * r) + (1 - r) * a;\n}\n\n/** Returns the squared Euclidean distance between two vectors. */\nexport function distSquared(a: FlatVector, b: FlatVector): number {\n  let result = 0;\n  for (let i = 0; i < a.length; i++) {\n    const diff = Number(a[i]) - Number(b[i]);\n    result += diff * diff;\n  }\n  return result;\n}\n\n/**\n * Asserts that the expression is true. Otherwise throws an error with the\n * provided message.\n *\n * ```js\n * const x = 2;\n * tf.util.assert(x === 2, 'x is not 2');\n * ```\n *\n * @param expr The expression to assert (as a boolean).\n * @param msg A function that returns the message to report when throwing an\n *     error. We use a function for performance reasons.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function assert(expr: boolean, msg: () => string) {\n  if (!expr) {\n    throw new Error(typeof msg === 'string' ? msg : msg());\n  }\n}\n\nexport function assertShapesMatch(\n    shapeA: number[], shapeB: number[], errorMessagePrefix = ''): void {\n  assert(\n      arraysEqual(shapeA, shapeB),\n      () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n}\n\nexport function assertNonNull(a: TensorLike): void {\n  assert(\n      a != null,\n      () => `The input to the tensor constructor must be a non-null value.`);\n}\n\n/**\n * Returns the size (number of elements) of the tensor given its shape.\n *\n * ```js\n * const shape = [3, 4, 2];\n * const size = tf.util.sizeFromShape(shape);\n * console.log(size);\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function sizeFromShape(shape: number[]): number {\n  if (shape.length === 0) {\n    // Scalar.\n    return 1;\n  }\n  let size = shape[0];\n  for (let i = 1; i < shape.length; i++) {\n    size *= shape[i];\n  }\n  return size;\n}\n\nexport function isScalarShape(shape: number[]): boolean {\n  return shape.length === 0;\n}\n\nexport function arraysEqualWithNull(n1: number[], n2: number[]) {\n  if (n1 === n2) {\n    return true;\n  }\n\n  if (n1 == null || n2 == null) {\n    return false;\n  }\n\n  if (n1.length !== n2.length) {\n    return false;\n  }\n\n  for (let i = 0; i < n1.length; i++) {\n    if (n1[i] !== null && n2[i] !== null && n1[i] !== n2[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function arraysEqual(n1: FlatVector, n2: FlatVector) {\n  if (n1 === n2) {\n    return true;\n  }\n  if (n1 == null || n2 == null) {\n    return false;\n  }\n\n  if (n1.length !== n2.length) {\n    return false;\n  }\n  for (let i = 0; i < n1.length; i++) {\n    if (n1[i] !== n2[i]) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function isInt(a: number): boolean {\n  return a % 1 === 0;\n}\n\nexport function tanh(x: number): number {\n  // tslint:disable-next-line:no-any\n  if ((Math as any).tanh != null) {\n    // tslint:disable-next-line:no-any\n    return (Math as any).tanh(x);\n  }\n  if (x === Infinity) {\n    return 1;\n  } else if (x === -Infinity) {\n    return -1;\n  } else {\n    const e2x = Math.exp(2 * x);\n    return (e2x - 1) / (e2x + 1);\n  }\n}\n\nexport function sizeToSquarishShape(size: number): [number, number] {\n  const width = Math.ceil(Math.sqrt(size));\n  return [width, Math.ceil(size / width)];\n}\n\n/**\n * Creates a new array with randomized indices to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indices to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n  const shuffledIndices = new Uint32Array(n);\n  for (let i = 0; i < n; ++i) {\n    shuffledIndices[i] = i;\n  }\n  shuffle(shuffledIndices);\n  return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n  if (size <= a.length) {\n    return a;\n  }\n  return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n    checkFn: () => boolean, delayFn = (counter: number) => 0,\n    maxCounter?: number,\n    scheduleFn?: (functionRef: Function, delay: number) =>\n        void): Promise<void> {\n  return new Promise<void>((resolve, reject) => {\n    let tryCount = 0;\n\n    const tryFn = () => {\n      if (checkFn()) {\n        resolve();\n        return;\n      }\n\n      tryCount++;\n\n      const nextBackoff = delayFn(tryCount);\n\n      if (maxCounter != null && tryCount >= maxCounter) {\n        reject();\n        return;\n      }\n\n      if (scheduleFn != null) {\n        scheduleFn(tryFn, nextBackoff);\n      } else {\n        // google3 does not allow assigning another variable to setTimeout.\n        // Don't refactor this so scheduleFn has a default value of setTimeout.\n        setTimeout(tryFn, nextBackoff);\n      }\n    };\n\n    tryFn();\n  });\n}\n\n/**\n * Given the full size of the array and a shape that may contain -1 as the\n * implicit dimension, returns the inferred shape where -1 is replaced.\n * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].\n *\n * @param shape The shape, which may contain -1 in some dimension.\n * @param size The full size (number of elements) of the array.\n * @return The inferred shape where -1 is replaced with the inferred size.\n */\nexport function inferFromImplicitShape(\n    shape: number[], size: number): number[] {\n  let shapeProd = 1;\n  let implicitIdx = -1;\n\n  for (let i = 0; i < shape.length; ++i) {\n    if (shape[i] >= 0) {\n      shapeProd *= shape[i];\n    } else if (shape[i] === -1) {\n      if (implicitIdx !== -1) {\n        throw Error(\n            `Shapes can only have 1 implicit size. ` +\n            `Found -1 at dim ${implicitIdx} and dim ${i}`);\n      }\n      implicitIdx = i;\n    } else if (shape[i] < 0) {\n      throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);\n    }\n  }\n\n  if (implicitIdx === -1) {\n    if (size > 0 && size !== shapeProd) {\n      throw Error(`Size(${size}) must match the product of shape ${shape}`);\n    }\n    return shape;\n  }\n\n  if (shapeProd === 0) {\n    throw Error(\n        `Cannot infer the missing size in [${shape}] when ` +\n        `there are 0 elements`);\n  }\n  if (size % shapeProd !== 0) {\n    throw Error(\n        `The implicit shape can't be a fractional number. ` +\n        `Got ${size} / ${shapeProd}`);\n  }\n\n  const newShape = shape.slice();\n  newShape[implicitIdx] = size / shapeProd;\n  return newShape;\n}\n\nexport function parseAxisParam(\n    axis: number|number[], shape: number[]): number[] {\n  const rank = shape.length;\n\n  // Normalize input\n  axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);\n\n  // Check for valid range\n  assert(\n      axis.every(ax => ax >= -rank && ax < rank),\n      () =>\n          `All values in axis param must be in range [-${rank}, ${rank}) but ` +\n          `got axis ${axis}`);\n\n  // Check for only integers\n  assert(\n      axis.every(ax => isInt(ax)),\n      () => `All values in axis param must be integers but ` +\n          `got axis ${axis}`);\n\n  // Handle negative axis.\n  return axis.map(a => a < 0 ? rank + a : a);\n}\n\n/** Reduces the shape by removing all dimensions of shape 1. */\nexport function squeezeShape(shape: number[], axis?: number[]):\n    {newShape: number[], keptDims: number[]} {\n  const newShape: number[] = [];\n  const keptDims: number[] = [];\n  const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;\n  const axes = (axis == null || isEmptyArray) ?\n      null :\n      parseAxisParam(axis, shape).sort();\n  let j = 0;\n  for (let i = 0; i < shape.length; ++i) {\n    if (axes != null) {\n      if (axes[j] === i && shape[i] !== 1) {\n        throw new Error(\n            `Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);\n      }\n      if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {\n        newShape.push(shape[i]);\n        keptDims.push(i);\n      }\n      if (axes[j] <= i) {\n        j++;\n      }\n    }\n    if (shape[i] !== 1) {\n      newShape.push(shape[i]);\n      keptDims.push(i);\n    }\n  }\n  return {newShape, keptDims};\n}\n\nexport function getTypedArrayFromDType<D extends NumericDataType>(\n    dtype: D, size: number): DataTypeMap[D] {\n  return getArrayFromDType<D>(dtype, size);\n}\n\nexport function getArrayFromDType<D extends DataType>(\n    dtype: D, size: number): DataTypeMap[D] {\n  let values = null;\n  if (dtype == null || dtype === 'float32') {\n    values = new Float32Array(size);\n  } else if (dtype === 'int32') {\n    values = new Int32Array(size);\n  } else if (dtype === 'bool') {\n    values = new Uint8Array(size);\n  } else if (dtype === 'string') {\n    values = new Array<string>(size);\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n  return values as DataTypeMap[D];\n}\n\nexport function checkConversionForErrors<D extends DataType>(\n    vals: DataTypeMap[D]|number[], dtype: D): void {\n  for (let i = 0; i < vals.length; i++) {\n    const num = vals[i] as number;\n    if (isNaN(num) || !isFinite(num)) {\n      throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);\n    }\n  }\n}\n\n/** Returns true if the dtype is valid. */\nexport function isValidDtype(dtype: DataType): boolean {\n  return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||\n      dtype === 'int32' || dtype === 'string';\n}\n\n/**\n * Returns true if the new type can't encode the old type without loss of\n * precision.\n */\nexport function hasEncodingLoss(oldType: DataType, newType: DataType): boolean {\n  if (newType === 'complex64') {\n    return false;\n  }\n  if (newType === 'float32' && oldType !== 'complex64') {\n    return false;\n  }\n  if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {\n    return false;\n  }\n  if (newType === 'bool' && oldType === 'bool') {\n    return false;\n  }\n  return true;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n  if (dtype === 'float32' || dtype === 'int32') {\n    return 4;\n  } else if (dtype === 'complex64') {\n    return 8;\n  } else if (dtype === 'bool') {\n    return 1;\n  } else {\n    throw new Error(`Unknown dtype ${dtype}`);\n  }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS\n * is not possible since it depends on the encoding of the html page that\n * serves the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n  if (arr == null) {\n    return 0;\n  }\n  let bytes = 0;\n  arr.forEach(x => bytes += x.length);\n  return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n  return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n  return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n  return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike|WebGLData|WebGPUData): DataType {\n  if (Array.isArray(values)) {\n    return inferDtype(values[0]);\n  }\n  if (values instanceof Float32Array) {\n    return 'float32';\n  } else if (\n      values instanceof Int32Array || values instanceof Uint8Array ||\n      values instanceof Uint8ClampedArray) {\n    return 'int32';\n  } else if (isNumber(values)) {\n    return 'float32';\n  } else if (isString(values)) {\n    return 'string';\n  } else if (isBoolean(values)) {\n    return 'bool';\n  }\n  return 'float32';\n}\n\nexport function isFunction(f: Function) {\n  return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n  for (let i = start; i < size; ++i) {\n    if (size % i === 0) {\n      return i;\n    }\n  }\n  return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n  const rank = shape.length;\n  if (rank < 2) {\n    return [];\n  }\n\n  // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n  // strides.\n  const strides = new Array(rank - 1);\n  strides[rank - 2] = shape[rank - 1];\n  for (let i = rank - 3; i >= 0; --i) {\n    strides[i] = strides[i + 1] * shape[i + 1];\n  }\n  return strides;\n}\n\nfunction createNestedArray(\n    offset: number, shape: number[], a: TypedArray, isComplex = false) {\n  const ret = new Array();\n  if (shape.length === 1) {\n    const d = shape[0] * (isComplex ? 2 : 1);\n    for (let i = 0; i < d; i++) {\n      ret[i] = a[offset + i];\n    }\n  } else {\n    const d = shape[0];\n    const rest = shape.slice(1);\n    const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n    for (let i = 0; i < d; i++) {\n      ret[i] = createNestedArray(offset + i * len, rest, a, isComplex);\n    }\n  }\n  return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(\n    shape: number[], a: TypedArray, isComplex = false) {\n  if (shape.length === 0) {\n    // Scalar type should return a single number.\n    return a[0];\n  }\n  const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1);\n  if (size === 0) {\n    // A tensor with shape zero should be turned into empty list.\n    return [];\n  }\n  if (size !== a.length) {\n    throw new Error(`[${shape}] does not match the input size ${a.length}${\n        isComplex ? ' for a complex tensor' : ''}.`);\n  }\n\n  return createNestedArray(0, shape, a, isComplex);\n}\n\nexport function convertBackendValuesAndArrayBuffer(\n    data: BackendValues|ArrayBuffer, dtype: DataType) {\n  // If is type Uint8Array[], return it directly.\n  if (Array.isArray(data)) {\n    return data;\n  }\n  if (dtype === 'float32') {\n    return data instanceof Float32Array ? data : new Float32Array(data);\n  } else if (dtype === 'int32') {\n    return data instanceof Int32Array ? data : new Int32Array(data);\n  } else if (dtype === 'bool' || dtype === 'string') {\n    return Uint8Array.from(new Int32Array(data));\n  } else {\n    throw new Error(`Unknown dtype ${dtype}`);\n  }\n}\n\nexport function makeOnesTypedArray<D extends DataType>(\n    size: number, dtype: D): DataTypeMap[D] {\n  const array = makeZerosTypedArray(size, dtype);\n  for (let i = 0; i < array.length; i++) {\n    array[i] = 1;\n  }\n  return array;\n}\n\nexport function makeZerosTypedArray<D extends DataType>(\n    size: number, dtype: D): DataTypeMap[D] {\n  if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n    return new Float32Array(size) as DataTypeMap[D];\n  } else if (dtype === 'int32') {\n    return new Int32Array(size) as DataTypeMap[D];\n  } else if (dtype === 'bool') {\n    return new Uint8Array(size) as DataTypeMap[D];\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n}\n\n/**\n * Make nested `TypedArray` filled with zeros.\n * @param shape The shape information for the nested array.\n * @param dtype dtype of the array element.\n */\nexport function makeZerosNestedTypedArray<D extends DataType>(\n    shape: number[], dtype: D) {\n  const size = shape.reduce((prev, curr) => prev * curr, 1);\n  if (dtype == null || dtype === 'float32') {\n    return toNestedArray(shape, new Float32Array(size));\n  } else if (dtype === 'int32') {\n    return toNestedArray(shape, new Int32Array(size));\n  } else if (dtype === 'bool') {\n    return toNestedArray(shape, new Uint8Array(size));\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n  shape.forEach(dimSize => {\n    assert(\n        Number.isInteger(dimSize) && dimSize >= 0,\n        () =>\n            `Tensor must have a shape comprised of positive integers but got ` +\n            `shape [${shape}].`);\n  });\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n    locs: number[], rank: number, strides: number[]): number {\n  if (rank === 0) {\n    return 0;\n  } else if (rank === 1) {\n    return locs[0];\n  }\n  let index = locs[locs.length - 1];\n  for (let i = 0; i < locs.length - 1; ++i) {\n    index += strides[i] * locs[i];\n  }\n  return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a\n * tensor/multidimentional array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n    index: number, rank: number, strides: number[]): number[] {\n  if (rank === 0) {\n    return [];\n  } else if (rank === 1) {\n    return [index];\n  }\n  const locs: number[] = new Array(rank);\n  for (let i = 0; i < locs.length - 1; ++i) {\n    locs[i] = Math.floor(index / strides[i]);\n    index -= locs[i] * strides[i];\n  }\n  locs[locs.length - 1] = index;\n  return locs;\n}\n\n/**\n * This method asserts whether an object is a Promise instance.\n * @param object\n */\n// tslint:disable-next-line: no-any\nexport function isPromise(object: any): object is Promise<unknown> {\n  //  We chose to not use 'obj instanceOf Promise' for two reasons:\n  //  1. It only reliably works for es6 Promise, not other Promise\n  //  implementations.\n  //  2. It doesn't work with framework that uses zone.js. zone.js monkey\n  //  patch the async calls, so it is possible the obj (patched) is\n  //  comparing to a pre-patched Promise.\n  return object && object.then && typeof object.then === 'function';\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\nimport {isPromise} from './util_base';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean|string;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise<FlagValue>);\nexport type Flags = {\n  [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n  evaluationFn: FlagEvaluationFn;\n  setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n  private flags: Flags = {};\n  private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n  private urlFlags: Flags = {};\n\n  platformName: string;\n  platform: Platform;\n\n  // Jasmine spies on this in 'environment_test.ts'\n  getQueryParams = getQueryParams;\n\n  // tslint:disable-next-line: no-any\n  constructor(public global: any) {\n    this.populateURLFlags();\n  }\n\n  setPlatform(platformName: string, platform: Platform) {\n    if (this.platform != null) {\n      if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n        console.warn(\n            `Platform ${this.platformName} has already been set. ` +\n            `Overwriting the platform with ${platformName}.`);\n      }\n    }\n    this.platformName = platformName;\n    this.platform = platform;\n  }\n\n  registerFlag(\n      flagName: string, evaluationFn: FlagEvaluationFn,\n      setHook?: (value: FlagValue) => void) {\n    this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n    // Override the flag value from the URL. This has to happen here because\n    // the environment is initialized before flags get registered.\n    if (this.urlFlags[flagName] != null) {\n      const flagValue = this.urlFlags[flagName];\n      if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n        console.warn(\n            `Setting feature override from URL ${flagName}: ${flagValue}.`);\n      }\n      this.set(flagName, flagValue);\n    }\n  }\n\n  async getAsync(flagName: string): Promise<FlagValue> {\n    if (flagName in this.flags) {\n      return this.flags[flagName];\n    }\n\n    this.flags[flagName] = await this.evaluateFlag(flagName);\n    return this.flags[flagName];\n  }\n\n  get(flagName: string): FlagValue {\n    if (flagName in this.flags) {\n      return this.flags[flagName];\n    }\n\n    const flagValue = this.evaluateFlag(flagName);\n    if (isPromise(flagValue)) {\n      throw new Error(\n          `Flag ${flagName} cannot be synchronously evaluated. ` +\n          `Please use getAsync() instead.`);\n    }\n\n    this.flags[flagName] = flagValue;\n    return this.flags[flagName];\n  }\n\n  getNumber(flagName: string): number {\n    return this.get(flagName) as number;\n  }\n\n  getBool(flagName: string): boolean {\n    return this.get(flagName) as boolean;\n  }\n\n  getString(flagName: string): string {\n    return this.get(flagName) as string;\n  }\n\n  getFlags(): Flags {\n    return this.flags;\n  }\n  // For backwards compatibility.\n  get features(): Flags {\n    return this.flags;\n  }\n\n  set(flagName: string, value: FlagValue): void {\n    if (this.flagRegistry[flagName] == null) {\n      throw new Error(\n          `Cannot set flag ${flagName} as it has not been registered.`);\n    }\n    this.flags[flagName] = value;\n    if (this.flagRegistry[flagName].setHook != null) {\n      this.flagRegistry[flagName].setHook(value);\n    }\n  }\n\n  private evaluateFlag(flagName: string): FlagValue|Promise<FlagValue> {\n    if (this.flagRegistry[flagName] == null) {\n      throw new Error(\n          `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n    }\n    return this.flagRegistry[flagName].evaluationFn();\n  }\n\n  setFlags(flags: Flags) {\n    this.flags = Object.assign({}, flags);\n  }\n\n  reset() {\n    this.flags = {};\n    this.urlFlags = {};\n    this.populateURLFlags();\n  }\n\n  private populateURLFlags(): void {\n    if (typeof this.global === 'undefined' ||\n        typeof this.global.location === 'undefined' ||\n        typeof this.global.location.search === 'undefined') {\n      return;\n    }\n\n    const urlParams = this.getQueryParams(this.global.location.search);\n    if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n      const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n      keyValues.forEach(keyValue => {\n        const [key, value] = keyValue.split(':') as [string, string];\n        this.urlFlags[key] = parseValue(key, value);\n      });\n    }\n  }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n  const params = {};\n  queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n    decodeParam(params, t[0], t[1]);\n    return t.join('=');\n  });\n  return params;\n}\n\nfunction decodeParam(\n    params: {[key: string]: string}, name: string, value?: string) {\n  params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n  const lowerCaseValue = value.toLowerCase();\n  if (lowerCaseValue === 'true' || lowerCaseValue === 'false') {\n    return lowerCaseValue === 'true';\n  } else if (`${+ lowerCaseValue}` === lowerCaseValue) {\n    return +lowerCaseValue;\n  } else {\n    return value;\n  }\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n  return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n  ENV = environment;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map<string, any>};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map<string, any>} {\n  if (globalNameSpace == null) {\n    // tslint:disable-next-line:no-any\n    let ns: any;\n    if (typeof (window) !== 'undefined') {\n      ns = window;\n    } else if (typeof (global) !== 'undefined') {\n      ns = global;\n    } else if (typeof (process) !== 'undefined') {\n      ns = process;\n    } else if (typeof (self) !== 'undefined') {\n      ns = self;\n    } else {\n      throw new Error('Could not find a global object');\n    }\n    globalNameSpace = ns;\n  }\n  return globalNameSpace;\n}\n\n// tslint:disable-next-line:no-any\nfunction getGlobalMap(): Map<string, any> {\n  const ns = getGlobalNamespace();\n  if (ns._tfGlobals == null) {\n    ns._tfGlobals = new Map();\n  }\n  return ns._tfGlobals;\n}\n\n/**\n * Returns a globally accessible 'singleton' object.\n *\n * @param key the name of the object\n * @param init a function to initialize to initialize this object\n *             the first time it is fetched.\n */\nexport function getGlobal<T>(key: string, init: () => T): T {\n  const globalMap = getGlobalMap();\n  if (globalMap.has(key)) {\n    return globalMap.get(key);\n  } else {\n    const singleton = init();\n    globalMap.set(key, singleton);\n    return globalMap.get(key);\n  }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {TensorInfo} from './tensor_info';\nimport {DataType, DrawOptions, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AllAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AnyAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ArgMaxAttrs {\n  axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ArgMinAttrs {\n  axis: number;\n}\n\nexport const Asin = 'Asin';\nexport type AsinInputs = UnaryInputs;\n\nexport const Asinh = 'Asinh';\nexport type AsinhInputs = UnaryInputs;\n\nexport const Atan = 'Atan';\nexport type AtanInputs = UnaryInputs;\n\nexport const Atanh = 'Atanh';\nexport type AtanhInputs = UnaryInputs;\n\nexport const Atan2 = 'Atan2';\nexport type Atan2Inputs = BinaryInputs;\n\nexport const AvgPool = 'AvgPool';\nexport type AvgPoolInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AvgPoolAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const AvgPoolGrad = 'AvgPoolGrad';\nexport type AvgPoolGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'>;\nexport interface AvgPoolGradAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n}\n\nexport const AvgPool3D = 'AvgPool3D';\nexport type AvgPool3DInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface AvgPool3DAttrs {\n  filterSize: [number, number, number]|number;\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same'|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  dataFormat: 'NDHWC'|'NCDHW';\n}\n\nexport const AvgPool3DGrad = 'AvgPool3DGrad';\nexport type AvgPool3DGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'>;\nexport interface AvgPool3DGradAttrs {\n  filterSize: [number, number, number]|number;\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same'|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const BatchMatMul = 'BatchMatMul';\nexport type BatchMatMulInputs = Pick<NamedTensorInfoMap, 'a'|'b'>;\nexport interface BatchMatMulAttrs {\n  transposeA: boolean;\n  transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BatchToSpaceNDAttrs {\n  blockShape: number[];\n  crops: number[][];\n}\n\nexport type BinaryInputs = Pick<NamedTensorInfoMap, 'a'|'b'>;\n\nexport const Bincount = 'Bincount';\nexport type BincountInputs = Pick<NamedTensorInfoMap, 'x'|'weights'>;\nexport interface BincountAttrs {\n  size: number;\n}\n\nexport const BitwiseAnd = 'BitwiseAnd';\nexport type BitwiseAndInputs = BinaryInputs;\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BroadCastToAttrs {\n  shape: number[];\n  inputShape: number[];  // for gradient\n}\n\nexport const BroadcastArgs = 'BroadcastArgs';\nexport type BroadcastArgsInputs = Pick<NamedTensorInfoMap, 's0'|'s1'>;\n\nexport const Cast = 'Cast';\nexport type CastInputs = UnaryInputs;\nexport interface CastAttrs {\n  dtype: DataType;\n}\n\nexport const Ceil = 'Ceil';\nexport type CeilInputs = UnaryInputs;\n\nexport const ClipByValue = 'ClipByValue';\nexport type ClipByValueInputs = UnaryInputs;\nexport interface ClipByValueAttrs {\n  clipValueMin: number;\n  clipValueMax: number;\n}\n\nexport const Complex = 'Complex';\nexport type ComplexInputs = Pick<NamedTensorInfoMap, 'real'|'imag'>;\n\nexport const ComplexAbs = 'ComplexAbs';\nexport type ComplexAbsInputs = UnaryInputs;\n\nexport const Concat = 'Concat';\nexport type ConcatInputs = TensorInfo[];\nexport interface ConcatAttrs {\n  axis: number;\n}\n\nexport const Conv2D = 'Conv2D';\nexport type Conv2DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Conv2DAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dilations: [number, number]|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropFilter = 'Conv2DBackpropFilter';\nexport type Conv2DBackpropFilterInputs = Pick<NamedTensorInfoMap, 'x'|'dy'>;\nexport interface Conv2DBackpropFilterAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  filterShape: [number, number, number, number];\n}\n\nexport const Conv2DBackpropInput = 'Conv2DBackpropInput';\nexport type Conv2DBackpropInputInputs = Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface Conv2DBackpropInputAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  inputShape: [number, number, number, number];\n}\n\nexport const Conv3D = 'Conv3D';\nexport type Conv3DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Conv3DAttrs {\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same';\n  dataFormat: 'NDHWC'|'NCDHW';\n  dilations: [number, number, number]|number;\n}\n\nexport const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';\nexport type Conv3DBackpropFilterV2Inputs = Pick<NamedTensorInfoMap, 'x'|'dy'>;\n\nexport interface Conv3DBackpropFilterV2Attrs {\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same';\n  filterShape: [number, number, number, number, number];\n}\n\nexport const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';\nexport type Conv3DBackpropInputV2Inputs =\n    Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface Conv3DBackpropInputV2Attrs {\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same';\n  inputShape: [number, number, number, number, number];\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumprod = 'Cumprod';\nexport type CumprodInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface CumprodAttrs {\n  axis: number;\n  exclusive: boolean;\n  reverse: boolean;\n}\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface CumsumAttrs {\n  axis: number;\n  exclusive: boolean;\n  reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n    Pick<NamedTensorInfoMap, 'image'|'boxes'|'boxInd'>;\nexport interface CropAndResizeAttrs {\n  cropSize: [number, number];\n  method: 'bilinear'|'nearest';\n  extrapolationValue: number;\n}\n\nexport const DenseBincount = 'DenseBincount';\nexport type DenseBincountInputs = Pick<NamedTensorInfoMap, 'x'|'weights'>;\nexport interface DenseBincountAttrs {\n  size: number;\n  binaryOutput?: boolean;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface DepthToSpaceAttrs {\n  blockSize: number;\n  dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n    Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface DepthwiseConv2dNativeAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dilations: [number, number]|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const DepthwiseConv2dNativeBackpropFilter =\n    'DepthwiseConv2dNativeBackpropFilter';\nexport type DepthwiseConv2dNativeBackpropFilterInputs =\n    Pick<NamedTensorInfoMap, 'x'|'dy'>;\nexport interface DepthwiseConv2dNativeBackpropFilterAttrs {\n  strides: [number, number]|number;\n  dilations: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  filterShape: [number, number, number, number];\n}\n\nexport const DepthwiseConv2dNativeBackpropInput =\n    'DepthwiseConv2dNativeBackpropInput';\nexport type DepthwiseConv2dNativeBackpropInputInputs =\n    Pick<NamedTensorInfoMap, 'dy'|'filter'>;\nexport interface DepthwiseConv2dNativeBackpropInputAttrs {\n  strides: [number, number]|number;\n  dilations: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n  inputShape: [number, number, number, number];\n}\n\nexport const Diag = 'Diag';\nexport type DiagInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick<NamedTensorInfoMap, 'x'|'filter'>;\nexport interface Dilation2DAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number;\n  dilations: [number, number]|number;\n}\n\nexport const Dilation2DBackpropInput = 'Dilation2DBackpropInput';\nexport type Dilation2DBackpropInputInputs =\n    Pick<NamedTensorInfoMap, 'x'|'filter'|'dy'>;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n    Pick<NamedTensorInfoMap, 'x'|'filter'|'dy'>;\n\nexport const Draw = 'Draw';\nexport type DrawInputs = Pick<NamedTensorInfoMap, 'image'>;\nexport interface DrawAttrs {\n  canvas: HTMLCanvasElement;\n  options?: DrawOptions;\n}\n\nexport const RealDiv = 'RealDiv';\nexport type RealDivInputs = BinaryInputs;\n\nexport const Einsum = 'Einsum';\nexport type EinsumInputs = TensorInfo[];\nexport interface EinsumAttrs {\n  equation: string;\n}\n\nexport const Elu = 'Elu';\nexport type EluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick<NamedTensorInfoMap, 'dy'|'y'>;\n\nexport const Erf = 'Erf';\nexport type ErfInputs = UnaryInputs;\n\nexport const Equal = 'Equal';\nexport type EqualInputs = BinaryInputs;\n\nexport const Exp = 'Exp';\nexport type ExpInputs = UnaryInputs;\n\nexport const ExpandDims = 'ExpandDims';\nexport type ExpandDimsInputs = Pick<NamedTensorInfoMap, 'input'>;\nexport interface ExpandDimsAttrs {\n  dim: number;\n}\n\nexport const Expm1 = 'Expm1';\nexport type Expm1Inputs = UnaryInputs;\n\nexport const FFT = 'FFT';\nexport type FFTInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Fill = 'Fill';\nexport interface FillAttrs {\n  shape: number[];\n  value: number|string;\n  dtype: DataType;\n}\n\nexport const FlipLeftRight = 'FlipLeftRight';\nexport type FlipLeftRightInputs = Pick<NamedTensorInfoMap, 'image'>;\n\nexport const Floor = 'Floor';\nexport type FloorInputs = UnaryInputs;\n\nexport const FloorDiv = 'FloorDiv';\nexport type FloorDivInputs = BinaryInputs;\n\nexport const FusedBatchNorm = 'FusedBatchNorm';\nexport type FusedBatchNormInputs =\n    Pick<NamedTensorInfoMap, 'x'|'scale'|'offset'|'mean'|'variance'>;\nexport interface FusedBatchNormAttrs {\n  varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick<NamedTensorInfoMap, 'x'|'indices'>;\nexport interface GatherV2Attrs {\n  axis: number;\n  batchDims: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick<NamedTensorInfoMap, 'params'|'indices'>;\n\nexport const Greater = 'Greater';\nexport type GreaterInputs = BinaryInputs;\n\nexport const GreaterEqual = 'GreaterEqual';\nexport type GreaterEqualInputs = BinaryInputs;\n\nexport const Identity = 'Identity';\nexport type IdentityInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const IsFinite = 'IsFinite';\nexport type IsFiniteInputs = UnaryInputs;\n\nexport const IsInf = 'IsInf';\nexport type IsInfInputs = UnaryInputs;\n\nexport const IsNan = 'IsNan';\nexport type IsNanInputs = UnaryInputs;\n\nexport const LeakyRelu = 'LeakyRelu';\nexport type LeakyReluInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface LeakyReluAttrs {\n  alpha: number;\n}\n\nexport const Less = 'Less';\nexport type LessInputs = BinaryInputs;\n\nexport const LessEqual = 'LessEqual';\nexport type LessEqualInputs = BinaryInputs;\n\nexport const LinSpace = 'LinSpace';\nexport interface LinSpaceAttrs {\n  start: number;\n  stop: number;\n  num: number;\n}\nexport const Log = 'Log';\nexport type LogInputs = UnaryInputs;\n\nexport const Log1p = 'Log1p';\nexport type Log1pInputs = UnaryInputs;\n\nexport const LogicalAnd = 'LogicalAnd';\nexport type LogicalAndInputs = BinaryInputs;\n\nexport const LogicalNot = 'LogicalNot';\nexport type LogicalNotInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogicalXor = 'LogicalXor';\nexport type LogicalXorInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface LogSoftmaxAttrs {\n  axis: number;\n}\n\nexport const LowerBound = 'LowerBound';\nexport type LowerBoundInputs =\n    Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface LRNAttrs {\n  depthRadius: number;\n  bias: number;\n  alpha: number;\n  beta: number;\n}\n\nexport const LRNGrad = 'LRNGrad';\nexport type LRNGradInputs = Pick<NamedTensorInfoMap, 'x'|'y'|'dy'>;\nexport interface LRNGradAttrs {\n  depthRadius: number;\n  bias: number;\n  alpha: number;\n  beta: number;\n}\n\nexport const MatrixBandPart = 'MatrixBandPart';\nexport type MatrixBandPartInputs =\n    Pick<NamedTensorInfoMap, 'input'|'numLower'|'numUpper'>;\nexport interface MatrixBandPartAttrs {}\n\nexport const Max = 'Max';\nexport type MaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxAttrs {\n  reductionIndices: number|number[];\n  keepDims: boolean;\n}\n\nexport const Maximum = 'Maximum';\nexport type MaximumInputs = BinaryInputs;\n\nexport const MaxPool = 'MaxPool';\nexport type MaxPoolInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPoolAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolGrad = 'MaxPoolGrad';\nexport type MaxPoolGradInputs = Pick<NamedTensorInfoMap, 'dy'|'input'|'output'>;\nexport interface MaxPoolGradAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3D = 'MaxPool3D';\nexport type MaxPool3DInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPool3DAttrs {\n  filterSize: [number, number, number]|number;\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same'|number;\n  dataFormat: 'NDHWC'|'NCDHW';\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3DGrad = 'MaxPool3DGrad';\nexport type MaxPool3DGradInputs =\n    Pick<NamedTensorInfoMap, 'dy'|'input'|'output'>;\nexport interface MaxPool3DGradAttrs {\n  filterSize: [number, number, number]|number;\n  strides: [number, number, number]|number;\n  pad: 'valid'|'same'|number;\n  dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolWithArgmax = 'MaxPoolWithArgmax';\nexport type MaxPoolWithArgmaxInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MaxPoolWithArgmaxAttrs {\n  filterSize: [number, number]|number;\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number;\n  includeBatchInIndex: boolean;\n}\n\nexport const Mean = 'Mean';\nexport type MeanInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MeanAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MinAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const Minimum = 'Minimum';\nexport type MinimumInputs = BinaryInputs;\n\nexport const MirrorPad = 'MirrorPad';\nexport type MirrorPadInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface MirrorPadAttrs {\n  paddings: Array<[number, number]>;\n  mode: 'reflect'|'symmetric';\n}\n\nexport const Mod = 'Mod';\nexport type ModInputs = BinaryInputs;\n\nexport const Multinomial = 'Multinomial';\nexport type MultinomialInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface MultinomialAttrs {\n  numSamples: number;\n  seed: number;\n  normalized: boolean;\n}\n\nexport const Multiply = 'Multiply';\nexport type MultiplyInputs = BinaryInputs;\n\nexport const Neg = 'Neg';\nexport type NegInputs = UnaryInputs;\n\nexport const NotEqual = 'NotEqual';\nexport type NotEqualInputs = BinaryInputs;\n\nexport const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';\nexport type NonMaxSuppressionV3Inputs =\n    Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV3Attrs {\n  maxOutputSize: number;\n  iouThreshold: number;\n  scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n    Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV4Attrs {\n  maxOutputSize: number;\n  iouThreshold: number;\n  scoreThreshold: number;\n  padToMaxOutputSize: boolean;\n}\n\nexport const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';\nexport type NonMaxSuppressionV5Inputs =\n    Pick<NamedTensorInfoMap, 'boxes'|'scores'>;\nexport interface NonMaxSuppressionV5Attrs {\n  maxOutputSize: number;\n  iouThreshold: number;\n  scoreThreshold: number;\n  softNmsSigma: number;\n}\n\nexport const OnesLike = 'OnesLike';\nexport type OnesLikeInputs = UnaryInputs;\n\nexport const OneHot = 'OneHot';\nexport type OneHotInputs = Pick<NamedTensorInfoMap, 'indices'>;\nexport interface OneHotAttrs {\n  depth: number;\n  onValue: number;\n  offValue: number;\n  dtype: DataType;\n}\n\nexport const Pack = 'Pack';\nexport type PackInputs = TensorInfo[];\nexport interface PackAttrs {\n  axis: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface PadV2Attrs {\n  paddings: Array<[number, number]>;\n  constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick<NamedTensorInfoMap, 'x'|'alpha'>;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ProdAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const RaggedGather = 'RaggedGather';\nexport type RaggedGatherInputs = {\n  paramsNestedSplits: TensorInfo[]\n}&Pick<NamedTensorInfoMap, 'paramsDenseValues'|'indices'>;\nexport interface RaggedGatherAttrs {\n  outputRaggedRank: number;\n}\n\nexport const RaggedRange = 'RaggedRange';\nexport type RaggedRangeInputs =\n    Pick<NamedTensorInfoMap, 'starts'|'limits'|'deltas'>;\n\nexport const RaggedTensorToTensor = 'RaggedTensorToTensor';\nexport type RaggedTensorToTensorInputs =\n    Pick<NamedTensorInfoMap, 'shape'|'values'|'defaultValue'>&\n    {rowPartitionTensors: TensorInfo[]};\nexport interface RaggedTensorToTensorAttrs {\n  rowPartitionTypes: string[];\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n  start: number;\n  stop: number;\n  step: number;\n  dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick<NamedTensorInfoMap, 'input'>;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ReshapeAttrs {\n  shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick<NamedTensorInfoMap, 'images'>;\nexport interface ResizeNearestNeighborAttrs {\n  alignCorners: boolean;\n  halfPixelCenters: boolean;\n  size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n    Pick<NamedTensorInfoMap, 'images'|'dy'>;\nexport type ResizeNearestNeighborGradAttrs = ResizeNearestNeighborAttrs;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick<NamedTensorInfoMap, 'images'>;\nexport interface ResizeBilinearAttrs {\n  alignCorners: boolean;\n  halfPixelCenters: boolean;\n  size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick<NamedTensorInfoMap, 'images'|'dy'>;\nexport type ResizeBilinearGradAttrs = ResizeBilinearAttrs;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface ReverseAttrs {\n  dims: number|number[];\n}\n\nexport const Round = 'Round';\nexport type RoundInputs = UnaryInputs;\n\nexport const Rsqrt = 'Rsqrt';\nexport type RsqrtInputs = UnaryInputs;\n\nexport const ScatterNd = 'ScatterNd';\nexport type ScatterNdInputs = Pick<NamedTensorInfoMap, 'indices'|'updates'>;\nexport interface ScatterNdAttrs {\n  shape: number[];\n}\n\nexport const TensorScatterUpdate = 'TensorScatterUpdate';\nexport type TensorScatterUpdateInputs =\n    Pick<NamedTensorInfoMap, 'tensor'|'indices'|'updates'>;\nexport interface TensorScatterUpdateAttrs {}\n\nexport const SearchSorted = 'SearchSorted';\nexport type SearchSortedInputs =\n    Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\nexport interface SearchSortedAttrs {\n  side: 'left'|'right';\n}\n\nexport const Select = 'Select';\nexport type SelectInputs = Pick<NamedTensorInfoMap, 'condition'|'t'|'e'>;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SliceAttrs {\n  begin: number|number[];\n  size: number|number[];\n}\nexport const Sin = 'Sin';\nexport type SinInputs = UnaryInputs;\n\nexport const Sinh = 'Sinh';\nexport type SinhInputs = UnaryInputs;\n\nexport const Sign = 'Sign';\nexport type SignInputs = UnaryInputs;\n\nexport const Sigmoid = 'Sigmoid';\nexport type SigmoidInputs = UnaryInputs;\n\nexport const Softplus = 'Softplus';\nexport type SoftplusInputs = UnaryInputs;\n\nexport const Sqrt = 'Sqrt';\nexport type SqrtInputs = UnaryInputs;\n\nexport const Sum = 'Sum';\nexport type SumInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SumAttrs {\n  axis: number|number[];\n  keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SpaceToBatchNDAttrs {\n  blockShape: number[];\n  paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface SplitVAttrs {\n  numOrSizeSplits: number[]|number;\n  axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface SoftmaxAttrs {\n  dim: number;\n}\n\nexport const SparseFillEmptyRows = 'SparseFillEmptyRows';\nexport type SparseFillEmptyRowsInputs =\n    Pick<NamedTensorInfoMap, 'indices'|'values'|'denseShape'|'defaultValue'>;\n\nexport const SparseReshape = 'SparseReshape';\nexport type SparseReshapeInputs =\n    Pick<NamedTensorInfoMap, 'inputIndices'|'inputShape'|'newShape'>;\n\nexport const SparseSegmentMean = 'SparseSegmentMean';\nexport type SparseSegmentMeanInputs =\n    Pick<NamedTensorInfoMap, 'data'|'indices'|'segmentIds'>;\n\nexport const SparseSegmentSum = 'SparseSegmentSum';\nexport type SparseSegmentSumInputs =\n    Pick<NamedTensorInfoMap, 'data'|'indices'|'segmentIds'>;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n    Pick<NamedTensorInfoMap, 'sparseIndices'|'sparseValues'|'defaultValue'>;\nexport interface SparseToDenseAttrs {\n  outputShape: number[];\n}\n\nexport const SquaredDifference = 'SquaredDifference';\nexport type SquaredDifferenceInputs = BinaryInputs;\n\nexport const Square = 'Square';\nexport type SquareInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const StaticRegexReplace = 'StaticRegexReplace';\nexport type StaticRegexReplaceInputs = UnaryInputs;\nexport interface StaticRegexReplaceAttrs {\n  pattern: string;\n  rewrite: string;\n  replaceGlobal: boolean;\n}\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface StridedSliceAttrs {\n  begin: number[];\n  end: number[];\n  strides: number[];\n  beginMask: number;\n  endMask: number;\n  ellipsisMask: number;\n  newAxisMask: number;\n  shrinkAxisMask: number;\n}\n\nexport const StringNGrams = 'StringNGrams';\nexport type StringNGramsInputs = Pick<NamedTensorInfoMap, 'data'|'dataSplits'>;\nexport interface StringNGramsAttrs {\n  separator: string;\n  nGramWidths: number[];\n  leftPad: string;\n  rightPad: string;\n  padWidth: number;\n  preserveShortSequences: boolean;\n}\n\nexport const StringSplit = 'StringSplit';\nexport type StringSplitInputs = Pick<NamedTensorInfoMap, 'input'|'delimiter'>;\nexport interface StringSplitAttrs {\n  skipEmpty: boolean;\n}\n\nexport const StringToHashBucketFast = 'StringToHashBucketFast';\nexport type StringToHashBucketFastInputs = Pick<NamedTensorInfoMap, 'input'>;\nexport interface StringToHashBucketFastAttrs {\n  numBuckets: number;\n}\n\nexport const Sub = 'Sub';\nexport type SubInputs = BinaryInputs;\n\nexport const Tan = 'Tan';\nexport type TanInputs = UnaryInputs;\n\nexport const Tanh = 'Tanh';\nexport type TanhInputs = UnaryInputs;\n\nexport const Tile = 'Tile';\nexport type TileInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TileAttrs {\n  reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TopKAttrs {\n  k: number;\n  sorted: boolean;\n}\n\nexport const Transform = 'Transform';\nexport type TransformInputs = Pick<NamedTensorInfoMap, 'image'|'transforms'>;\nexport interface TransformAttrs {\n  interpolation: 'nearest'|'bilinear';\n  fillMode: 'constant'|'reflect'|'wrap'|'nearest';\n  fillValue: number;\n  outputShape?: [number, number];\n}\n\nexport const Transpose = 'Transpose';\nexport type TransposeInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface TransposeAttrs {\n  perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface UniqueAttrs {\n  axis: number;\n}\n\nexport type UnaryInputs = Pick<NamedTensorInfoMap, 'x'>;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick<NamedTensorInfoMap, 'value'>;\nexport interface UnpackAttrs {\n  axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n    Pick<NamedTensorInfoMap, 'x'|'segmentIds'>;\nexport interface UnsortedSegmentSumAttrs {\n  numSegments: number;\n}\n\nexport const UpperBound = 'UpperBound';\nexport type UpperBoundInputs =\n    Pick<NamedTensorInfoMap, 'sortedSequence'|'values'>;\n\nexport const ZerosLike = 'ZerosLike';\nexport type ZerosLikeInputs = UnaryInputs;\n\n/**\n * TensorFlow.js-only kernels\n */\nexport const Step = 'Step';\nexport type StepInputs = UnaryInputs;\nexport interface StepAttrs {\n  alpha: number;\n}\n\nexport const FromPixels = 'FromPixels';\nexport interface FromPixelsInputs {\n  pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n      HTMLVideoElement|ImageBitmap;\n}\nexport interface FromPixelsAttrs {\n  numChannels: number;\n}\n\nexport const RotateWithOffset = 'RotateWithOffset';\nexport type RotateWithOffsetInputs = Pick<NamedTensorInfoMap, 'image'>;\nexport interface RotateWithOffsetAttrs {\n  radians: number;\n  fillValue: number|[number, number, number];\n  center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n  a: TensorInfo;\n  b: TensorInfo;\n  bias?: TensorInfo;\n  preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n  transposeA: boolean;\n  transposeB: boolean;\n  activation: Activation;\n  leakyreluAlpha?: number;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n  x: TensorInfo;\n  filter: TensorInfo;\n  bias?: TensorInfo;\n  preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dilations: [number, number]|number;\n  dimRoundingMode: 'floor'|'round'|'ceil';\n  activation: Activation;\n  leakyreluAlpha?: number;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n  x: TensorInfo;\n  filter: TensorInfo;\n  bias?: TensorInfo;\n  preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n  strides: [number, number]|number;\n  pad: 'valid'|'same'|number|ExplicitPadding;\n  dataFormat: 'NHWC'|'NCHW';\n  dilations: [number, number]|number;\n  dimRoundingMode: 'floor'|'round'|'ceil';\n  activation: Activation;\n  leakyreluAlpha?: number;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\n\nexport function warn(...msg: Array<{}>): void {\n  if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n    console.warn(...msg);\n  }\n}\n\nexport function log(...msg: Array<{}>): void {\n  if (!(env().getBool('IS_TEST') || env().getBool('PROD'))) {\n    console.log(...msg);\n  }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\nimport {getGlobal} from './global_util';\nimport * as log from './log';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {TensorInfo} from './tensor_info';\nimport {RecursiveArray} from './types';\n\nconst kernelRegistry =\n  getGlobal('kernelRegistry', () => new Map<`${string}_${string}`,\n    KernelConfig>());\nconst gradRegistry =\n  getGlobal('gradRegistry', () => new Map<string, GradConfig>());\n\ntype AttributeValue =\n  number | number[] | boolean | boolean[] | string | string[] | NamedAttrMap;\n\n/** These are extra non-tensor/primitive params passed to kernel functions. */\nexport type Attribute = AttributeValue | RecursiveArray<AttributeValue>;\n\n/** Specifies the code to run when executing a kernel. */\nexport type KernelFunc = (params: {\n  inputs: NamedTensorInfoMap,\n  backend: {},\n  attrs?: NamedAttrMap,\n}) => TensorInfo | TensorInfo[];\n\n/** The function to run when computing a gradient during backprop. */\nexport type GradFunc =\n  (dy: Tensor | Tensor[], saved: Tensor[], attrs: NamedAttrMap) =>\n    NamedGradientMap;\n\n/** Function that gets called after the backend initializes. */\nexport type KernelSetupFunc = (backend: {}) => void;\n/** Function that gets called right before the backend is disposed. */\nexport type KernelDisposeFunc = KernelSetupFunc;\n\n/** Config object for registering a kernel in the global registry. */\nexport interface KernelConfig {\n  kernelName: string;\n  backendName: string;\n  kernelFunc: KernelFunc;\n  setupFunc?: KernelSetupFunc;\n  disposeFunc?: KernelDisposeFunc;\n}\n\n/** Config object for registering a gradient in the global registry. */\nexport interface GradConfig {\n  kernelName: string;\n  inputsToSave?: string[];\n  // When saveAllInputs is true, all inputs will be saved. Only use this flag\n  // if inputs is an array of Tensors.\n  saveAllInputs?: boolean;\n  outputsToSave?: boolean[];\n  gradFunc: GradFunc;\n}\n\nexport interface NamedTensorInfoMap {\n  [name: string]: TensorInfo|undefined;\n}\n\nexport interface NamedAttrMap {\n  [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n    kernelName: string, backendName: string): KernelConfig {\n  const key = makeKey(kernelName, backendName);\n  return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n  return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n  const it = kernelRegistry.entries();\n  const result: KernelConfig[] = [];\n\n  while (true) {\n    const {done, value} = it.next();\n    if (done) {\n      break;\n    }\n    const [key, config] = value;\n    const [backend, ] = key.split('_');\n    if (backend === backendName) {\n      result.push(config);\n    }\n  }\n  return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n  const {kernelName, backendName} = config;\n  const key = makeKey(kernelName, backendName);\n  if (kernelRegistry.has(key)) {\n    log.warn(\n        `The kernel '${kernelName}' for backend ` +\n        `'${backendName}' is already registered`);\n  }\n  kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n  const {kernelName} = config;\n\n  if (gradRegistry.has(kernelName)) {\n    // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n    // to debug mode.\n    if (env().getBool('DEBUG')) {\n      log.warn(`Overriding the gradient for '${kernelName}'`);\n    }\n  }\n  gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n    kernelName: string, backendName: string): void {\n  const key = makeKey(kernelName, backendName);\n  if (!kernelRegistry.has(key)) {\n    throw new Error(\n        `The kernel '${kernelName}' for backend ` +\n        `'${backendName}' is not registered`);\n  }\n  kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n  if (!gradRegistry.has(kernelName)) {\n    throw new Error(\n        `The gradient '${kernelName}' for backend is not registered`);\n  }\n  gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n    registeredBackendName: string, newBackendName: string): void {\n  const kernels = getKernelsForBackend(registeredBackendName);\n  kernels.forEach(kernelConfig => {\n    const newKernelConfig =\n        Object.assign({}, kernelConfig, {backendName: newBackendName});\n    registerKernel(newKernelConfig);\n  });\n}\n\nfunction makeKey(kernelName: string,\n                 backendName: string): `${string}_${string}` {\n  return `${backendName}_${kernelName}`;\n}\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport function isTypedArrayBrowser(a: unknown): a is Uint8Array\n  | Float32Array | Int32Array | Uint8ClampedArray {\n  return a instanceof Float32Array || a instanceof Int32Array ||\n    a instanceof Uint8Array || a instanceof Uint8ClampedArray;\n}\n", "module.exports = Long;\r\n\r\n/**\r\n * wasm optimizations, to do native i64 multiplication and divide\r\n */\r\nvar wasm = null;\r\n\r\ntry {\r\n  wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([\r\n    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\r\n  ])), {}).exports;\r\n} catch (e) {\r\n  // no wasm support :(\r\n}\r\n\r\n/**\r\n * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.\r\n *  See the from* functions below for more convenient ways of constructing Longs.\r\n * @exports Long\r\n * @class A Long class for representing a 64 bit two's-complement integer value.\r\n * @param {number} low The low (signed) 32 bits of the long\r\n * @param {number} high The high (signed) 32 bits of the long\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @constructor\r\n */\r\nfunction Long(low, high, unsigned) {\r\n\r\n    /**\r\n     * The low 32 bits as a signed value.\r\n     * @type {number}\r\n     */\r\n    this.low = low | 0;\r\n\r\n    /**\r\n     * The high 32 bits as a signed value.\r\n     * @type {number}\r\n     */\r\n    this.high = high | 0;\r\n\r\n    /**\r\n     * Whether unsigned or not.\r\n     * @type {boolean}\r\n     */\r\n    this.unsigned = !!unsigned;\r\n}\r\n\r\n// The internal representation of a long is the two given signed, 32-bit values.\r\n// We use 32-bit pieces because these are the size of integers on which\r\n// Javascript performs bit-operations.  For operations like addition and\r\n// multiplication, we split each number into 16 bit pieces, which can easily be\r\n// multiplied within Javascript's floating-point representation without overflow\r\n// or change in sign.\r\n//\r\n// In the algorithms below, we frequently reduce the negative case to the\r\n// positive case by negating the input(s) and then post-processing the result.\r\n// Note that we must ALWAYS check specially whether those values are MIN_VALUE\r\n// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as\r\n// a positive number, it overflows back into a negative).  Not handling this\r\n// case would often result in infinite recursion.\r\n//\r\n// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*\r\n// methods on which they depend.\r\n\r\n/**\r\n * An indicator used to reliably determine if an object is a Long or not.\r\n * @type {boolean}\r\n * @const\r\n * @private\r\n */\r\nLong.prototype.__isLong__;\r\n\r\nObject.defineProperty(Long.prototype, \"__isLong__\", { value: true });\r\n\r\n/**\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n * @inner\r\n */\r\nfunction isLong(obj) {\r\n    return (obj && obj[\"__isLong__\"]) === true;\r\n}\r\n\r\n/**\r\n * Tests if the specified object is a Long.\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n */\r\nLong.isLong = isLong;\r\n\r\n/**\r\n * A cache of the Long representations of small integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar INT_CACHE = {};\r\n\r\n/**\r\n * A cache of the Long representations of small unsigned integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar UINT_CACHE = {};\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromInt(value, unsigned) {\r\n    var obj, cachedObj, cache;\r\n    if (unsigned) {\r\n        value >>>= 0;\r\n        if (cache = (0 <= value && value < 256)) {\r\n            cachedObj = UINT_CACHE[value];\r\n            if (cachedObj)\r\n                return cachedObj;\r\n        }\r\n        obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);\r\n        if (cache)\r\n            UINT_CACHE[value] = obj;\r\n        return obj;\r\n    } else {\r\n        value |= 0;\r\n        if (cache = (-128 <= value && value < 128)) {\r\n            cachedObj = INT_CACHE[value];\r\n            if (cachedObj)\r\n                return cachedObj;\r\n        }\r\n        obj = fromBits(value, value < 0 ? -1 : 0, false);\r\n        if (cache)\r\n            INT_CACHE[value] = obj;\r\n        return obj;\r\n    }\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given 32 bit integer value.\r\n * @function\r\n * @param {number} value The 32 bit integer in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromInt = fromInt;\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromNumber(value, unsigned) {\r\n    if (isNaN(value))\r\n        return unsigned ? UZERO : ZERO;\r\n    if (unsigned) {\r\n        if (value < 0)\r\n            return UZERO;\r\n        if (value >= TWO_PWR_64_DBL)\r\n            return MAX_UNSIGNED_VALUE;\r\n    } else {\r\n        if (value <= -TWO_PWR_63_DBL)\r\n            return MIN_VALUE;\r\n        if (value + 1 >= TWO_PWR_63_DBL)\r\n            return MAX_VALUE;\r\n    }\r\n    if (value < 0)\r\n        return fromNumber(-value, unsigned).neg();\r\n    return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.\r\n * @function\r\n * @param {number} value The number in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromNumber = fromNumber;\r\n\r\n/**\r\n * @param {number} lowBits\r\n * @param {number} highBits\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromBits(lowBits, highBits, unsigned) {\r\n    return new Long(lowBits, highBits, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is\r\n *  assumed to use 32 bits.\r\n * @function\r\n * @param {number} lowBits The low 32 bits\r\n * @param {number} highBits The high 32 bits\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromBits = fromBits;\r\n\r\n/**\r\n * @function\r\n * @param {number} base\r\n * @param {number} exponent\r\n * @returns {number}\r\n * @inner\r\n */\r\nvar pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)\r\n\r\n/**\r\n * @param {string} str\r\n * @param {(boolean|number)=} unsigned\r\n * @param {number=} radix\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromString(str, unsigned, radix) {\r\n    if (str.length === 0)\r\n        throw Error('empty string');\r\n    if (str === \"NaN\" || str === \"Infinity\" || str === \"+Infinity\" || str === \"-Infinity\")\r\n        return ZERO;\r\n    if (typeof unsigned === 'number') {\r\n        // For goog.math.long compatibility\r\n        radix = unsigned,\r\n        unsigned = false;\r\n    } else {\r\n        unsigned = !! unsigned;\r\n    }\r\n    radix = radix || 10;\r\n    if (radix < 2 || 36 < radix)\r\n        throw RangeError('radix');\r\n\r\n    var p;\r\n    if ((p = str.indexOf('-')) > 0)\r\n        throw Error('interior hyphen');\r\n    else if (p === 0) {\r\n        return fromString(str.substring(1), unsigned, radix).neg();\r\n    }\r\n\r\n    // Do several (8) digits each time through the loop, so as to\r\n    // minimize the calls to the very expensive emulated div.\r\n    var radixToPower = fromNumber(pow_dbl(radix, 8));\r\n\r\n    var result = ZERO;\r\n    for (var i = 0; i < str.length; i += 8) {\r\n        var size = Math.min(8, str.length - i),\r\n            value = parseInt(str.substring(i, i + size), radix);\r\n        if (size < 8) {\r\n            var power = fromNumber(pow_dbl(radix, size));\r\n            result = result.mul(power).add(fromNumber(value));\r\n        } else {\r\n            result = result.mul(radixToPower);\r\n            result = result.add(fromNumber(value));\r\n        }\r\n    }\r\n    result.unsigned = unsigned;\r\n    return result;\r\n}\r\n\r\n/**\r\n * Returns a Long representation of the given string, written using the specified radix.\r\n * @function\r\n * @param {string} str The textual representation of the Long\r\n * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {number=} radix The radix in which the text is written (2-36), defaults to 10\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromString = fromString;\r\n\r\n/**\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromValue(val, unsigned) {\r\n    if (typeof val === 'number')\r\n        return fromNumber(val, unsigned);\r\n    if (typeof val === 'string')\r\n        return fromString(val, unsigned);\r\n    // Throws for non-objects, converts non-instanceof Long:\r\n    return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);\r\n}\r\n\r\n/**\r\n * Converts the specified value to a Long using the appropriate from* function for its type.\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long}\r\n */\r\nLong.fromValue = fromValue;\r\n\r\n// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be\r\n// no runtime penalty for these.\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_16_DBL = 1 << 16;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24_DBL = 1 << 24;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;\r\n\r\n/**\r\n * @type {!Long}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ZERO = fromInt(0);\r\n\r\n/**\r\n * Signed zero.\r\n * @type {!Long}\r\n */\r\nLong.ZERO = ZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UZERO = fromInt(0, true);\r\n\r\n/**\r\n * Unsigned zero.\r\n * @type {!Long}\r\n */\r\nLong.UZERO = UZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ONE = fromInt(1);\r\n\r\n/**\r\n * Signed one.\r\n * @type {!Long}\r\n */\r\nLong.ONE = ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UONE = fromInt(1, true);\r\n\r\n/**\r\n * Unsigned one.\r\n * @type {!Long}\r\n */\r\nLong.UONE = UONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar NEG_ONE = fromInt(-1);\r\n\r\n/**\r\n * Signed negative one.\r\n * @type {!Long}\r\n */\r\nLong.NEG_ONE = NEG_ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);\r\n\r\n/**\r\n * Maximum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_VALUE = MAX_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);\r\n\r\n/**\r\n * Maximum unsigned value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MIN_VALUE = fromBits(0, 0x80000000|0, false);\r\n\r\n/**\r\n * Minimum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MIN_VALUE = MIN_VALUE;\r\n\r\n/**\r\n * @alias Long.prototype\r\n * @inner\r\n */\r\nvar LongPrototype = Long.prototype;\r\n\r\n/**\r\n * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.\r\n * @returns {number}\r\n */\r\nLongPrototype.toInt = function toInt() {\r\n    return this.unsigned ? this.low >>> 0 : this.low;\r\n};\r\n\r\n/**\r\n * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).\r\n * @returns {number}\r\n */\r\nLongPrototype.toNumber = function toNumber() {\r\n    if (this.unsigned)\r\n        return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);\r\n    return this.high * TWO_PWR_32_DBL + (this.low >>> 0);\r\n};\r\n\r\n/**\r\n * Converts the Long to a string written in the specified radix.\r\n * @param {number=} radix Radix (2-36), defaults to 10\r\n * @returns {string}\r\n * @override\r\n * @throws {RangeError} If `radix` is out of range\r\n */\r\nLongPrototype.toString = function toString(radix) {\r\n    radix = radix || 10;\r\n    if (radix < 2 || 36 < radix)\r\n        throw RangeError('radix');\r\n    if (this.isZero())\r\n        return '0';\r\n    if (this.isNegative()) { // Unsigned Longs are never negative\r\n        if (this.eq(MIN_VALUE)) {\r\n            // We need to change the Long value before it can be negated, so we remove\r\n            // the bottom-most digit in this base and then recurse to do the rest.\r\n            var radixLong = fromNumber(radix),\r\n                div = this.div(radixLong),\r\n                rem1 = div.mul(radixLong).sub(this);\r\n            return div.toString(radix) + rem1.toInt().toString(radix);\r\n        } else\r\n            return '-' + this.neg().toString(radix);\r\n    }\r\n\r\n    // Do several (6) digits each time through the loop, so as to\r\n    // minimize the calls to the very expensive emulated div.\r\n    var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),\r\n        rem = this;\r\n    var result = '';\r\n    while (true) {\r\n        var remDiv = rem.div(radixToPower),\r\n            intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,\r\n            digits = intval.toString(radix);\r\n        rem = remDiv;\r\n        if (rem.isZero())\r\n            return digits + result;\r\n        else {\r\n            while (digits.length < 6)\r\n                digits = '0' + digits;\r\n            result = '' + digits + result;\r\n        }\r\n    }\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as a signed integer.\r\n * @returns {number} Signed high bits\r\n */\r\nLongPrototype.getHighBits = function getHighBits() {\r\n    return this.high;\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned high bits\r\n */\r\nLongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {\r\n    return this.high >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as a signed integer.\r\n * @returns {number} Signed low bits\r\n */\r\nLongPrototype.getLowBits = function getLowBits() {\r\n    return this.low;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned low bits\r\n */\r\nLongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {\r\n    return this.low >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the number of bits needed to represent the absolute value of this Long.\r\n * @returns {number}\r\n */\r\nLongPrototype.getNumBitsAbs = function getNumBitsAbs() {\r\n    if (this.isNegative()) // Unsigned Longs are never negative\r\n        return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();\r\n    var val = this.high != 0 ? this.high : this.low;\r\n    for (var bit = 31; bit > 0; bit--)\r\n        if ((val & (1 << bit)) != 0)\r\n            break;\r\n    return this.high != 0 ? bit + 33 : bit + 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isZero = function isZero() {\r\n    return this.high === 0 && this.low === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eqz = LongPrototype.isZero;\r\n\r\n/**\r\n * Tests if this Long's value is negative.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isNegative = function isNegative() {\r\n    return !this.unsigned && this.high < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is positive.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isPositive = function isPositive() {\r\n    return this.unsigned || this.high >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is odd.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isOdd = function isOdd() {\r\n    return (this.low & 1) === 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is even.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isEven = function isEven() {\r\n    return (this.low & 1) === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.equals = function equals(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)\r\n        return false;\r\n    return this.high === other.high && this.low === other.low;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eq = LongPrototype.equals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.notEquals = function notEquals(other) {\r\n    return !this.eq(/* validates */ other);\r\n};\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.neq = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ne = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThan = function lessThan(other) {\r\n    return this.comp(/* validates */ other) < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lt = LongPrototype.lessThan;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {\r\n    return this.comp(/* validates */ other) <= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lte = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.le = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThan = function greaterThan(other) {\r\n    return this.comp(/* validates */ other) > 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gt = LongPrototype.greaterThan;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {\r\n    return this.comp(/* validates */ other) >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gte = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ge = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Compares this Long's value with the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n *  if the given one is greater\r\n */\r\nLongPrototype.compare = function compare(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    if (this.eq(other))\r\n        return 0;\r\n    var thisNeg = this.isNegative(),\r\n        otherNeg = other.isNegative();\r\n    if (thisNeg && !otherNeg)\r\n        return -1;\r\n    if (!thisNeg && otherNeg)\r\n        return 1;\r\n    // At this point the sign bits are the same\r\n    if (!this.unsigned)\r\n        return this.sub(other).isNegative() ? -1 : 1;\r\n    // Both are positive if at least one is unsigned\r\n    return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;\r\n};\r\n\r\n/**\r\n * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n *  if the given one is greater\r\n */\r\nLongPrototype.comp = LongPrototype.compare;\r\n\r\n/**\r\n * Negates this Long's value.\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.negate = function negate() {\r\n    if (!this.unsigned && this.eq(MIN_VALUE))\r\n        return MIN_VALUE;\r\n    return this.not().add(ONE);\r\n};\r\n\r\n/**\r\n * Negates this Long's value. This is an alias of {@link Long#negate}.\r\n * @function\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.neg = LongPrototype.negate;\r\n\r\n/**\r\n * Returns the sum of this and the specified Long.\r\n * @param {!Long|number|string} addend Addend\r\n * @returns {!Long} Sum\r\n */\r\nLongPrototype.add = function add(addend) {\r\n    if (!isLong(addend))\r\n        addend = fromValue(addend);\r\n\r\n    // Divide each number into 4 chunks of 16 bits, and then sum the chunks.\r\n\r\n    var a48 = this.high >>> 16;\r\n    var a32 = this.high & 0xFFFF;\r\n    var a16 = this.low >>> 16;\r\n    var a00 = this.low & 0xFFFF;\r\n\r\n    var b48 = addend.high >>> 16;\r\n    var b32 = addend.high & 0xFFFF;\r\n    var b16 = addend.low >>> 16;\r\n    var b00 = addend.low & 0xFFFF;\r\n\r\n    var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n    c00 += a00 + b00;\r\n    c16 += c00 >>> 16;\r\n    c00 &= 0xFFFF;\r\n    c16 += a16 + b16;\r\n    c32 += c16 >>> 16;\r\n    c16 &= 0xFFFF;\r\n    c32 += a32 + b32;\r\n    c48 += c32 >>> 16;\r\n    c32 &= 0xFFFF;\r\n    c48 += a48 + b48;\r\n    c48 &= 0xFFFF;\r\n    return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long.\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.subtract = function subtract(subtrahend) {\r\n    if (!isLong(subtrahend))\r\n        subtrahend = fromValue(subtrahend);\r\n    return this.add(subtrahend.neg());\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.\r\n * @function\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.sub = LongPrototype.subtract;\r\n\r\n/**\r\n * Returns the product of this and the specified Long.\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.multiply = function multiply(multiplier) {\r\n    if (this.isZero())\r\n        return ZERO;\r\n    if (!isLong(multiplier))\r\n        multiplier = fromValue(multiplier);\r\n\r\n    // use wasm support if present\r\n    if (wasm) {\r\n        var low = wasm.mul(this.low,\r\n                           this.high,\r\n                           multiplier.low,\r\n                           multiplier.high);\r\n        return fromBits(low, wasm.get_high(), this.unsigned);\r\n    }\r\n\r\n    if (multiplier.isZero())\r\n        return ZERO;\r\n    if (this.eq(MIN_VALUE))\r\n        return multiplier.isOdd() ? MIN_VALUE : ZERO;\r\n    if (multiplier.eq(MIN_VALUE))\r\n        return this.isOdd() ? MIN_VALUE : ZERO;\r\n\r\n    if (this.isNegative()) {\r\n        if (multiplier.isNegative())\r\n            return this.neg().mul(multiplier.neg());\r\n        else\r\n            return this.neg().mul(multiplier).neg();\r\n    } else if (multiplier.isNegative())\r\n        return this.mul(multiplier.neg()).neg();\r\n\r\n    // If both longs are small, use float multiplication\r\n    if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))\r\n        return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);\r\n\r\n    // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.\r\n    // We can skip products that would overflow.\r\n\r\n    var a48 = this.high >>> 16;\r\n    var a32 = this.high & 0xFFFF;\r\n    var a16 = this.low >>> 16;\r\n    var a00 = this.low & 0xFFFF;\r\n\r\n    var b48 = multiplier.high >>> 16;\r\n    var b32 = multiplier.high & 0xFFFF;\r\n    var b16 = multiplier.low >>> 16;\r\n    var b00 = multiplier.low & 0xFFFF;\r\n\r\n    var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n    c00 += a00 * b00;\r\n    c16 += c00 >>> 16;\r\n    c00 &= 0xFFFF;\r\n    c16 += a16 * b00;\r\n    c32 += c16 >>> 16;\r\n    c16 &= 0xFFFF;\r\n    c16 += a00 * b16;\r\n    c32 += c16 >>> 16;\r\n    c16 &= 0xFFFF;\r\n    c32 += a32 * b00;\r\n    c48 += c32 >>> 16;\r\n    c32 &= 0xFFFF;\r\n    c32 += a16 * b16;\r\n    c48 += c32 >>> 16;\r\n    c32 &= 0xFFFF;\r\n    c32 += a00 * b32;\r\n    c48 += c32 >>> 16;\r\n    c32 &= 0xFFFF;\r\n    c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;\r\n    c48 &= 0xFFFF;\r\n    return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.\r\n * @function\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.mul = LongPrototype.multiply;\r\n\r\n/**\r\n * Returns this Long divided by the specified. The result is signed if this Long is signed or\r\n *  unsigned if this Long is unsigned.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.divide = function divide(divisor) {\r\n    if (!isLong(divisor))\r\n        divisor = fromValue(divisor);\r\n    if (divisor.isZero())\r\n        throw Error('division by zero');\r\n\r\n    // use wasm support if present\r\n    if (wasm) {\r\n        // guard against signed division overflow: the largest\r\n        // negative number / -1 would be 1 larger than the largest\r\n        // positive number, due to two's complement.\r\n        if (!this.unsigned &&\r\n            this.high === -0x80000000 &&\r\n            divisor.low === -1 && divisor.high === -1) {\r\n            // be consistent with non-wasm code path\r\n            return this;\r\n        }\r\n        var low = (this.unsigned ? wasm.div_u : wasm.div_s)(\r\n            this.low,\r\n            this.high,\r\n            divisor.low,\r\n            divisor.high\r\n        );\r\n        return fromBits(low, wasm.get_high(), this.unsigned);\r\n    }\r\n\r\n    if (this.isZero())\r\n        return this.unsigned ? UZERO : ZERO;\r\n    var approx, rem, res;\r\n    if (!this.unsigned) {\r\n        // This section is only relevant for signed longs and is derived from the\r\n        // closure library as a whole.\r\n        if (this.eq(MIN_VALUE)) {\r\n            if (divisor.eq(ONE) || divisor.eq(NEG_ONE))\r\n                return MIN_VALUE;  // recall that -MIN_VALUE == MIN_VALUE\r\n            else if (divisor.eq(MIN_VALUE))\r\n                return ONE;\r\n            else {\r\n                // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.\r\n                var halfThis = this.shr(1);\r\n                approx = halfThis.div(divisor).shl(1);\r\n                if (approx.eq(ZERO)) {\r\n                    return divisor.isNegative() ? ONE : NEG_ONE;\r\n                } else {\r\n                    rem = this.sub(divisor.mul(approx));\r\n                    res = approx.add(rem.div(divisor));\r\n                    return res;\r\n                }\r\n            }\r\n        } else if (divisor.eq(MIN_VALUE))\r\n            return this.unsigned ? UZERO : ZERO;\r\n        if (this.isNegative()) {\r\n            if (divisor.isNegative())\r\n                return this.neg().div(divisor.neg());\r\n            return this.neg().div(divisor).neg();\r\n        } else if (divisor.isNegative())\r\n            return this.div(divisor.neg()).neg();\r\n        res = ZERO;\r\n    } else {\r\n        // The algorithm below has not been made for unsigned longs. It's therefore\r\n        // required to take special care of the MSB prior to running it.\r\n        if (!divisor.unsigned)\r\n            divisor = divisor.toUnsigned();\r\n        if (divisor.gt(this))\r\n            return UZERO;\r\n        if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true\r\n            return UONE;\r\n        res = UZERO;\r\n    }\r\n\r\n    // Repeat the following until the remainder is less than other:  find a\r\n    // floating-point that approximates remainder / other *from below*, add this\r\n    // into the result, and subtract it from the remainder.  It is critical that\r\n    // the approximate value is less than or equal to the real value so that the\r\n    // remainder never becomes negative.\r\n    rem = this;\r\n    while (rem.gte(divisor)) {\r\n        // Approximate the result of division. This may be a little greater or\r\n        // smaller than the actual value.\r\n        approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));\r\n\r\n        // We will tweak the approximate result by changing it in the 48-th digit or\r\n        // the smallest non-fractional digit, whichever is larger.\r\n        var log2 = Math.ceil(Math.log(approx) / Math.LN2),\r\n            delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),\r\n\r\n        // Decrease the approximation until it is smaller than the remainder.  Note\r\n        // that if it is too large, the product overflows and is negative.\r\n            approxRes = fromNumber(approx),\r\n            approxRem = approxRes.mul(divisor);\r\n        while (approxRem.isNegative() || approxRem.gt(rem)) {\r\n            approx -= delta;\r\n            approxRes = fromNumber(approx, this.unsigned);\r\n            approxRem = approxRes.mul(divisor);\r\n        }\r\n\r\n        // We know the answer can't be zero... and actually, zero would cause\r\n        // infinite recursion since we would make no progress.\r\n        if (approxRes.isZero())\r\n            approxRes = ONE;\r\n\r\n        res = res.add(approxRes);\r\n        rem = rem.sub(approxRem);\r\n    }\r\n    return res;\r\n};\r\n\r\n/**\r\n * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.div = LongPrototype.divide;\r\n\r\n/**\r\n * Returns this Long modulo the specified.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.modulo = function modulo(divisor) {\r\n    if (!isLong(divisor))\r\n        divisor = fromValue(divisor);\r\n\r\n    // use wasm support if present\r\n    if (wasm) {\r\n        var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(\r\n            this.low,\r\n            this.high,\r\n            divisor.low,\r\n            divisor.high\r\n        );\r\n        return fromBits(low, wasm.get_high(), this.unsigned);\r\n    }\r\n\r\n    return this.sub(this.div(divisor).mul(divisor));\r\n};\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.mod = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.rem = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns the bitwise NOT of this Long.\r\n * @returns {!Long}\r\n */\r\nLongPrototype.not = function not() {\r\n    return fromBits(~this.low, ~this.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise AND of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.and = function and(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    return fromBits(this.low & other.low, this.high & other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise OR of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.or = function or(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    return fromBits(this.low | other.low, this.high | other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise XOR of this Long and the given one.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.xor = function xor(other) {\r\n    if (!isLong(other))\r\n        other = fromValue(other);\r\n    return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftLeft = function shiftLeft(numBits) {\r\n    if (isLong(numBits))\r\n        numBits = numBits.toInt();\r\n    if ((numBits &= 63) === 0)\r\n        return this;\r\n    else if (numBits < 32)\r\n        return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);\r\n    else\r\n        return fromBits(0, this.low << (numBits - 32), this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shl = LongPrototype.shiftLeft;\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRight = function shiftRight(numBits) {\r\n    if (isLong(numBits))\r\n        numBits = numBits.toInt();\r\n    if ((numBits &= 63) === 0)\r\n        return this;\r\n    else if (numBits < 32)\r\n        return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);\r\n    else\r\n        return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr = LongPrototype.shiftRight;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {\r\n    if (isLong(numBits))\r\n        numBits = numBits.toInt();\r\n    numBits &= 63;\r\n    if (numBits === 0)\r\n        return this;\r\n    else {\r\n        var high = this.high;\r\n        if (numBits < 32) {\r\n            var low = this.low;\r\n            return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);\r\n        } else if (numBits === 32)\r\n            return fromBits(high, 0, this.unsigned);\r\n        else\r\n            return fromBits(high >>> (numBits - 32), 0, this.unsigned);\r\n    }\r\n};\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shru = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr_u = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Converts this Long to signed.\r\n * @returns {!Long} Signed long\r\n */\r\nLongPrototype.toSigned = function toSigned() {\r\n    if (!this.unsigned)\r\n        return this;\r\n    return fromBits(this.low, this.high, false);\r\n};\r\n\r\n/**\r\n * Converts this Long to unsigned.\r\n * @returns {!Long} Unsigned long\r\n */\r\nLongPrototype.toUnsigned = function toUnsigned() {\r\n    if (this.unsigned)\r\n        return this;\r\n    return fromBits(this.low, this.high, true);\r\n};\r\n\r\n/**\r\n * Converts this Long to its byte representation.\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {!Array.<number>} Byte representation\r\n */\r\nLongPrototype.toBytes = function toBytes(le) {\r\n    return le ? this.toBytesLE() : this.toBytesBE();\r\n};\r\n\r\n/**\r\n * Converts this Long to its little endian byte representation.\r\n * @returns {!Array.<number>} Little endian byte representation\r\n */\r\nLongPrototype.toBytesLE = function toBytesLE() {\r\n    var hi = this.high,\r\n        lo = this.low;\r\n    return [\r\n        lo        & 0xff,\r\n        lo >>>  8 & 0xff,\r\n        lo >>> 16 & 0xff,\r\n        lo >>> 24       ,\r\n        hi        & 0xff,\r\n        hi >>>  8 & 0xff,\r\n        hi >>> 16 & 0xff,\r\n        hi >>> 24\r\n    ];\r\n};\r\n\r\n/**\r\n * Converts this Long to its big endian byte representation.\r\n * @returns {!Array.<number>} Big endian byte representation\r\n */\r\nLongPrototype.toBytesBE = function toBytesBE() {\r\n    var hi = this.high,\r\n        lo = this.low;\r\n    return [\r\n        hi >>> 24       ,\r\n        hi >>> 16 & 0xff,\r\n        hi >>>  8 & 0xff,\r\n        hi        & 0xff,\r\n        lo >>> 24       ,\r\n        lo >>> 16 & 0xff,\r\n        lo >>>  8 & 0xff,\r\n        lo        & 0xff\r\n    ];\r\n};\r\n\r\n/**\r\n * Creates a Long from its byte representation.\r\n * @param {!Array.<number>} bytes Byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytes = function fromBytes(bytes, unsigned, le) {\r\n    return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);\r\n};\r\n\r\n/**\r\n * Creates a Long from its little endian byte representation.\r\n * @param {!Array.<number>} bytes Little endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesLE = function fromBytesLE(bytes, unsigned) {\r\n    return new Long(\r\n        bytes[0]       |\r\n        bytes[1] <<  8 |\r\n        bytes[2] << 16 |\r\n        bytes[3] << 24,\r\n        bytes[4]       |\r\n        bytes[5] <<  8 |\r\n        bytes[6] << 16 |\r\n        bytes[7] << 24,\r\n        unsigned\r\n    );\r\n};\r\n\r\n/**\r\n * Creates a Long from its big endian byte representation.\r\n * @param {!Array.<number>} bytes Big endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesBE = function fromBytesBE(bytes, unsigned) {\r\n    return new Long(\r\n        bytes[4] << 24 |\r\n        bytes[5] << 16 |\r\n        bytes[6] <<  8 |\r\n        bytes[7],\r\n        bytes[0] << 24 |\r\n        bytes[1] << 16 |\r\n        bytes[2] <<  8 |\r\n        bytes[3],\r\n        unsigned\r\n    );\r\n};\r\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Workaround for allowing cjs module to be included in bundle created by\n// rollup.\nimport * as LongExports from 'long';\n// tslint:disable-next-line\nconst Long: LongExports.LongConstructor =\n    // tslint:disable-next-line\n    (LongExports as any).default || LongExports;\n\nexport function hexToLong(hex: string): Long {\n  return Long.fromString(hex, true, 16);\n}\n\n// Some primes between 2^63 and 2^64 for various uses.\n// Hex 0xc3a5c85c97cb3127\nconst k0: Long = hexToLong('c3a5c85c97cb3127');\n// Hex 0xb492b66fbe98f273\nconst k1: Long = hexToLong('b492b66fbe98f273');\n// Hex 0x9ae16a3b2f90404f\nconst k2: Long = hexToLong('9ae16a3b2f90404f');\n\nfunction shiftMix(val: Long): Long {\n  return val.xor(val.shru(47));\n}\n\nfunction fetch(s: Uint8Array, offset: number, numBytes: number): Long {\n  const bytes = s.slice(offset, offset + numBytes);\n  return Long.fromBytes(Array.from(bytes), true, true);\n}\n\nfunction fetch64(s: Uint8Array, offset: number): Long {\n  return fetch(s, offset, 8);\n}\n\nfunction fetch32(s: Uint8Array, offset: number): Long {\n  return fetch(s, offset, 4);\n}\n\nfunction rotate64(val: Long, shift: number): Long {\n  // Avoid shifting by 64: doing so yields an undefined result.\n  return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));\n}\n\nfunction hashLen16(u: Long, v: Long, mul = hexToLong('9ddfea08eb382d69')) {\n  // Murmur-inspired hashing.\n  let a = u.xor(v).mul(mul);\n  a = a.xor(a.shru(47));\n  let b = v.xor(a).mul(mul);\n  b = b.xor(b.shru(47));\n  b = b.mul(mul);\n  return b;\n}\n\n// Return a 16-byte hash for 48 bytes.  Quick and dirty.\n// Callers do best to use \"random-looking\" values for a and b.\nfunction weakHashLen32WithSeeds(\n    w: Long, x: Long, y: Long, z: Long, a: Long, b: Long) {\n  a = a.add(w);\n  b = rotate64(b.add(a).add(z), 21);\n  const c = a;\n  a = a.add(x);\n  a = a.add(y);\n  b = b.add(rotate64(a, 44));\n  return [a.add(z), b.add(c)];\n}\n\nfunction weakHashLen32WithSeedsStr(\n    s: Uint8Array, offset: number, a: Long, b: Long) {\n  return weakHashLen32WithSeeds(\n      fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16),\n      fetch64(s, offset + 24), a, b);\n}\n\nfunction hashLen0to16(s: Uint8Array, len = s.length): Long {\n  if (len >= 8) {\n    const mul = k2.add(len * 2);\n    const a = fetch64(s, 0).add(k2);\n    const b = fetch64(s, len - 8);\n    const c = rotate64(b, 37).mul(mul).add(a);\n    const d = rotate64(a, 25).add(b).mul(mul);\n    return hashLen16(c, d, mul);\n  }\n  if (len >= 4) {\n    const mul = k2.add(len * 2);\n    const a = fetch32(s, 0);\n    return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul);\n  }\n  if (len > 0) {\n    const a = s[0];\n    const b = s[len >> 1];\n    const c = s[len - 1];\n    const y = a + (b << 8);\n    const z = len + (c << 2);\n    return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);\n  }\n  return k2;\n}\n\nfunction hashLen17to32(s: Uint8Array, len = s.length): Long {\n  const mul = k2.add(len * 2);\n  const a = fetch64(s, 0).mul(k1);\n  const b = fetch64(s, 8);\n  const c = fetch64(s, len - 8).mul(mul);\n  const d = fetch64(s, len - 16).mul(k2);\n  return hashLen16(\n      rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d),\n      a.add(rotate64(b.add(k2), 18)).add(c), mul);\n}\n\nfunction hashLen33to64(s: Uint8Array, len = s.length): Long {\n  const mul = k2.add(len * 2);\n  const a = fetch64(s, 0).mul(k2);\n  const b = fetch64(s, 8);\n  const c = fetch64(s, len - 8).mul(mul);\n  const d = fetch64(s, len - 16).mul(k2);\n  const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);\n  const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul);\n  const e = fetch64(s, 16).mul(mul);\n  const f = fetch64(s, 24);\n  const g = y.add(fetch64(s, len - 32)).mul(mul);\n  const h = z.add(fetch64(s, len - 24)).mul(mul);\n  return hashLen16(\n      rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h),\n      e.add(rotate64(f.add(a), 18)).add(g), mul);\n}\n\nexport function fingerPrint64(s: Uint8Array, len = s.length): Long {\n  const seed: Long = Long.fromNumber(81, true);\n  if (len <= 32) {\n    if (len <= 16) {\n      return hashLen0to16(s, len);\n    } else {\n      return hashLen17to32(s, len);\n    }\n  } else if (len <= 64) {\n    return hashLen33to64(s, len);\n  }\n\n  // For strings over 64 bytes we loop.  Internal state consists of\n  // 56 bytes: v, w, x, y, and z.\n  let x = seed;\n  let y = seed.mul(k1).add(113);\n\n  let z = shiftMix(y.mul(k2).add(113)).mul(k2);\n  let v = [Long.UZERO, Long.UZERO];\n  let w = [Long.UZERO, Long.UZERO];\n  x = x.mul(k2).add(fetch64(s, 0));\n\n  let offset = 0;\n  // Set end so that after the loop we have 1 to 64 bytes left to process.\n  const end = ((len - 1) >> 6) * 64;\n  const last64 = end + ((len - 1) & 63) - 63;\n\n  do {\n    x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);\n    y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);\n    x = x.xor(w[1]);\n    y = y.add(v[0]).add(fetch64(s, offset + 40));\n    z = rotate64(z.add(w[0]), 33).mul(k1);\n    v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));\n    w = weakHashLen32WithSeedsStr(\n        s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n    [z, x] = [x, z];\n    offset += 64;\n  } while (offset !== end);\n  const mul = k1.add(z.and(0xff).shl(1));\n  // Point to the last 64 bytes of input.\n  offset = last64;\n\n  w[0] = w[0].add((len - 1) & 63);\n  v[0] = v[0].add(w[0]);\n  w[0] = w[0].add(v[0]);\n\n  x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul);\n  y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul);\n  x = x.xor(w[1].mul(9));\n  y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));\n  z = rotate64(z.add(w[0]), 33).mul(mul);\n  v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul), x.add(w[0]));\n  w = weakHashLen32WithSeedsStr(\n      s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n  [z, x] = [x, z];\n\n  return hashLen16(\n      hashLen16(v[0], w[0], mul).add(shiftMix(y).mul(k0)).add(z),\n      hashLen16(v[1], w[1], mul).add(x), mul);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {isTypedArrayBrowser} from './platforms/is_typed_array_browser';\nimport {BackendValues, DataType, RecursiveArray, TensorLike, TypedArray} from './types';\nimport * as base from './util_base';\nexport * from './util_base';\nexport * from './hash_util';\n\n/**\n * Create typed array for scalar value. Used for storing in `DataStorage`.\n */\nexport function createScalarValue(\n    value: DataType, dtype: DataType): BackendValues {\n  if (dtype === 'string') {\n    return encodeString(value);\n  }\n\n  return toTypedArray([value], dtype);\n}\n\nfunction noConversionNeeded(a: TensorLike, dtype: DataType): boolean {\n  return (a instanceof Float32Array && dtype === 'float32') ||\n      (a instanceof Int32Array && dtype === 'int32') ||\n      (a instanceof Uint8Array && dtype === 'bool');\n}\n\nexport function toTypedArray(a: TensorLike, dtype: DataType): TypedArray {\n  if (dtype === 'string') {\n    throw new Error('Cannot convert a string[] to a TypedArray');\n  }\n  if (Array.isArray(a)) {\n    a = flatten(a);\n  }\n\n  if (env().getBool('DEBUG')) {\n    base.checkConversionForErrors(a as number[], dtype);\n  }\n  if (noConversionNeeded(a, dtype)) {\n    return a as TypedArray;\n  }\n  if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n    return new Float32Array(a as number[]);\n  } else if (dtype === 'int32') {\n    return new Int32Array(a as number[]);\n  } else if (dtype === 'bool') {\n    const bool = new Uint8Array((a as number[]).length);\n    for (let i = 0; i < bool.length; ++i) {\n      if (Math.round((a as number[])[i]) !== 0) {\n        bool[i] = 1;\n      }\n    }\n    return bool;\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n}\n\n/**\n * Returns the current high-resolution time in milliseconds relative to an\n * arbitrary time in the past. It works across different platforms (node.js,\n * browsers).\n *\n * ```js\n * console.log(tf.util.now());\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function now(): number {\n  return env().platform.now();\n}\n\n/**\n * Returns a platform-specific implementation of\n * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * If `fetch` is defined on the global object (`window`, `process`, etc.),\n * `tf.util.fetch` returns that function.\n *\n * If not, `tf.util.fetch` returns a platform-specific solution.\n *\n * ```js\n * const resource = await tf.util.fetch('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs');\n * // handle response\n * ```\n *\n * @doc {heading: 'Util'}\n */\nexport function fetch(\n    path: string, requestInits?: RequestInit): Promise<Response> {\n  return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n  encoding = encoding || 'utf-8';\n  return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n  encoding = encoding || 'utf-8';\n  return env().platform.decode(bytes, encoding);\n}\n\nexport function isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array|\n    Uint8ClampedArray {\n  // TODO(mattsoulanille): Remove this fallback in 5.0.0\n  if (env().platform.isTypedArray != null) {\n    return env().platform.isTypedArray(a);\n  } else {\n    return isTypedArrayBrowser(a);\n  }\n}\n\n// NOTE: We explicitly type out what T extends instead of any so that\n// util.flatten on a nested array of number doesn't try to infer T as a\n// number[][], causing us to explicitly type util.flatten<number>().\n/**\n *  Flattens an arbitrarily nested array.\n *\n * ```js\n * const a = [[1, 2], [3, 4], [5, [6, [7]]]];\n * const flat = tf.util.flatten(a);\n * console.log(flat);\n * ```\n *\n *  @param arr The nested array to flatten.\n *  @param result The destination array which holds the elements.\n *  @param skipTypedArray If true, avoids flattening the typed arrays. Defaults\n *      to false.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function\nflatten<T extends number|boolean|string|Promise<number>|TypedArray>(\n    arr: T|RecursiveArray<T>, result: T[] = [], skipTypedArray = false): T[] {\n  if (result == null) {\n    result = [];\n  }\n  if (typeof arr === 'boolean' || typeof arr === 'number' ||\n    typeof arr === 'string' || base.isPromise(arr) || arr == null ||\n      isTypedArray(arr) && skipTypedArray) {\n    result.push(arr as T);\n  } else if (Array.isArray(arr) || isTypedArray(arr)) {\n    for (let i = 0; i < arr.length; ++i) {\n      flatten(arr[i], result, skipTypedArray);\n    }\n  } else {\n    let maxIndex = -1;\n    for (const key of Object.keys(arr)) {\n      // 0 or positive integer.\n      if (/^([1-9]+[0-9]*|0)$/.test(key)) {\n        maxIndex = Math.max(maxIndex, Number(key));\n      }\n    }\n    for (let i = 0; i <= maxIndex; i++) {\n      // tslint:disable-next-line: no-unnecessary-type-assertion\n      flatten((arr as RecursiveArray<T>)[i], result, skipTypedArray);\n    }\n  }\n  return result;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimer, BackendTimingInfo} from './backends/backend';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {DataType, DataTypeMap, TypedArray} from './types';\nimport * as util from './util';\n\nexport type KernelProfile = {\n  kernelName: string,\n  outputs: Tensor[],\n  inputs: NamedTensorMap,\n  timeMs: Promise<number|{error: string}>,\n  extraInfo: Promise<string>\n};\n\nexport class Profiler {\n  constructor(private backendTimer: BackendTimer, private logger?: Logger) {\n    if (logger == null) {\n      this.logger = new Logger();\n    }\n  }\n\n  profileKernel(kernelName: string, inputs: NamedTensorMap, f: () => Tensor[]):\n      KernelProfile {\n    let outputs: Tensor[];\n    const holdResultWrapperFn = () => {\n      outputs = f();\n    };\n    let timer: Promise<BackendTimingInfo>;\n    const start = util.now();\n    if (this.backendTimer.timerAvailable()) {\n      timer = this.backendTimer.time(holdResultWrapperFn);\n    } else {\n      holdResultWrapperFn();\n      for (const output of outputs) {\n        output.dataSync();\n      }\n      timer = Promise.resolve({kernelMs: util.now() - start});\n    }\n    if (env().getBool('CHECK_COMPUTATION_FOR_ERRORS')) {\n      for (let i = 0; i < outputs.length; i++) {\n        const output = outputs[i];\n        // Dangling promise here because we don't want to propagate up\n        // asynchronicity.\n        output.data().then(tensorVals => {\n          checkComputationForErrors(tensorVals, output.dtype, kernelName);\n        });\n      }\n    }\n\n    const kernelProfile = {\n      kernelName,\n      outputs,\n      inputs,\n      timeMs: timer.then(timing => timing.kernelMs),\n      extraInfo: timer.then(\n          timing => timing.getExtraProfileInfo != null ?\n              timing.getExtraProfileInfo() :\n              '')\n    };\n    return kernelProfile;\n  }\n\n  logKernelProfile(kernelProfile: KernelProfile): void {\n    const {kernelName, outputs, timeMs, inputs, extraInfo} = kernelProfile;\n\n    outputs.forEach(result => {\n      Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {\n        this.logger.logKernelProfile(\n            kernelName, result, valueContainer[0], valueContainer[1], inputs,\n            valueContainer[2]);\n      });\n    });\n  }\n}\n\nexport function checkComputationForErrors<D extends DataType>(\n    vals: DataTypeMap[D], dtype: D, kernelName: string): boolean {\n  if (dtype !== 'float32') {\n    // Only floating point computations will generate NaN values\n    return false;\n  }\n  for (let i = 0; i < vals.length; i++) {\n    const num = vals[i] as number;\n    if (isNaN(num) || !isFinite(num)) {\n      // Throwing custom exception so behavior is testable.\n      console.warn(`Found ${num} in the result of '${kernelName}'`);\n      return true;\n    }\n  }\n  return false;\n}\n\nexport class Logger {\n  logKernelProfile(\n      name: string, result: Tensor, vals: TypedArray,\n      timeMs: number|{error: string}, inputs: NamedTensorMap,\n      extraInfo?: string) {\n    const time = typeof timeMs === 'number' ? util.rightPad(`${timeMs}ms`, 9) :\n                                              timeMs['error'];\n    const paddedName = util.rightPad(name, 25);\n    const rank = result.rank;\n    const size = result.size;\n    const shape = util.rightPad(result.shape.toString(), 14);\n    let inputShapesDescription = '';\n\n    for (const name in inputs) {\n      const input = inputs[name];\n      if (input != null) {\n        // The input might be a non-tensor (e.g HTMLImageElement), in which case\n        // we claim the output shape as input shape.\n        const inputShape = input.shape || result.shape;\n        const inputRank = inputShape.length;\n        inputShapesDescription +=\n            `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;\n      }\n    }\n\n    console.log(\n        `%c${paddedName}\\t%c${time}\\t%c${rank}D ${shape}\\t%c${size}\\t%c${\n            inputShapesDescription}\\t%c${extraInfo}`,\n        'font-weight:bold', 'color:red', 'color:blue', 'color: orange',\n        'color: green', 'color: steelblue');\n  }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport * as util from './util';\n\nexport interface TapeNode {\n  id: number;\n  kernelName: string;\n  outputs: Tensor[];\n  inputs: NamedTensorMap;\n  // Optional params, defined only for ops with gradient impl.\n  gradient?: (dys: Tensor[]) => NamedGradientMap;\n  saved?: Tensor[];\n}\n\nexport type NamedGradientMap = {\n  [inputName: string]: () => Tensor;\n};\n\n/**\n * Computes a list of TapeNodes that connect x to y, filtering everything else\n * out and preserving the order of the original tape elements.\n *\n * @param tape The tape elements to filter.\n * @param xs The input Tensors.\n * @param y The output Tensor.\n */\nexport function getFilteredNodesXToY(\n    tape: TapeNode[], xs: Tensor[], y: Tensor): TapeNode[] {\n  // Forward pass to compute all the nodes and Tensors that are transitively a\n  // function of x.\n  const tensorsFromX: {[tensorId: number]: boolean} = {};\n  const nodesFromX: {[nodeId: number]: boolean} = {};\n  for (let i = 0; i < xs.length; i++) {\n    tensorsFromX[xs[i].id] = true;\n  }\n\n  for (let i = 0; i < tape.length; i++) {\n    const node = tape[i];\n    const nodeInputs = node.inputs;\n    for (const inputName in nodeInputs) {\n      const input = nodeInputs[inputName];\n\n      let anyInputFromX = false;\n      for (let j = 0; j < xs.length; j++) {\n        if (tensorsFromX[input.id]) {\n          node.outputs.forEach(output => tensorsFromX[output.id] = true);\n          anyInputFromX = true;\n          nodesFromX[node.id] = true;\n          break;\n        }\n      }\n\n      if (anyInputFromX) {\n        break;\n      }\n    }\n  }\n\n  // Backward pass to find all of the nodes and Tensors that lead to y.\n  const tensorsLeadToY: {[tensorId: number]: boolean} = {};\n  tensorsLeadToY[y.id] = true;\n  const nodesToY: {[nodeId: number]: boolean} = {};\n\n  for (let i = tape.length - 1; i >= 0; i--) {\n    const node = tape[i];\n    const nodeInputs = node.inputs;\n\n    // If any of the outputs lead to y, mark all of the inputs as leading to y.\n    for (let j = 0; j < node.outputs.length; j++) {\n      if (tensorsLeadToY[node.outputs[j].id]) {\n        for (const inputName in nodeInputs) {\n          tensorsLeadToY[nodeInputs[inputName].id] = true;\n          nodesToY[node.id] = true;\n        }\n        break;\n      }\n    }\n  }\n\n  // Return the paths that come from x and lead to y.\n  const filteredTape: TapeNode[] = [];\n  for (let i = 0; i < tape.length; i++) {\n    const node = tape[i];\n\n    if (nodesFromX[node.id] && nodesToY[node.id]) {\n      // Prune the inputs from the node that aren't a function of x.\n      const prunedInputs: {[inputName: string]: Tensor} = {};\n      for (const inputName in node.inputs) {\n        const nodeInput = node.inputs[inputName];\n        if (tensorsFromX[nodeInput.id]) {\n          prunedInputs[inputName] = nodeInput;\n        }\n      }\n\n      // Copy the node and overwrite inputsAndArgs to the pruned version.\n      const prunedNode = Object.assign({}, node);\n      prunedNode.inputs = prunedInputs;\n      prunedNode.outputs = node.outputs;\n\n      filteredTape.push(prunedNode);\n    }\n  }\n\n  return filteredTape;\n}\n\n/**\n * Backpropagate gradients through the filtered TapeNodes.\n *\n * @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map\n * is mutated by this method.\n * @param filteredTape The filtered TapeNodes to backprop through.\n */\nexport function backpropagateGradients(\n    tensorAccumulatedGradientMap: {[tensorId: number]: Tensor},\n    filteredTape: TapeNode[], tidy: (f: Function) => Tensor,\n    add: (a: Tensor, b: Tensor) => Tensor) {\n  // Walk the tape backward and keep a map of Tensor to its gradient.\n  for (let i = filteredTape.length - 1; i >= 0; i--) {\n    const node = filteredTape[i];\n\n    const dys: Tensor[] = [];\n    node.outputs.forEach(o => {\n      const gradTensor = tensorAccumulatedGradientMap[o.id];\n      if (gradTensor != null) {\n        dys.push(gradTensor);\n      } else {\n        // This particular output is not in the back-propagation subgraph, so it\n        // does not affect the final output, thus we put null for its dy.\n        dys.push(null);\n      }\n    });\n\n    if (node.gradient == null) {\n      throw new Error(\n          `Cannot compute gradient: gradient function not found ` +\n          `for ${node.kernelName}.`);\n    }\n\n    // Backprop dy through this node and accumulate gradients over the inputs.\n    const inputGradients = node.gradient(dys);\n\n    for (const inputName in node.inputs) {\n      if (!(inputName in inputGradients)) {\n        throw new Error(\n            `Cannot backprop through input ${inputName}. ` +\n            `Available gradients found: ${Object.keys(inputGradients)}.`);\n      }\n\n      // Call the gradient function.\n      const dx = tidy(() => inputGradients[inputName]());\n      if (dx.dtype !== 'float32') {\n        throw new Error(\n            `Error in gradient for op ${\n                node.kernelName}. The gradient of input ` +\n            `${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);\n      }\n      const x = node.inputs[inputName];\n      if (!util.arraysEqual(dx.shape, x.shape)) {\n        throw new Error(\n            `Error in gradient for op ${\n                node.kernelName}. The gradient of input ` +\n            `'${inputName}' has shape '${dx.shape}', which does not match ` +\n            `the shape of the input '${x.shape}'`);\n      }\n\n      if (tensorAccumulatedGradientMap[x.id] == null) {\n        tensorAccumulatedGradientMap[x.id] = dx;\n      } else {\n        const curGradient = tensorAccumulatedGradientMap[x.id];\n        tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);\n        curGradient.dispose();\n      }\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray} from './types';\nimport {computeStrides, isString, rightPad, sizeFromShape} from './util';\n\n// Maximum number of values before we decide to show ellipsis.\nconst FORMAT_LIMIT_NUM_VALS = 20;\n// Number of first and last values to show when displaying a, b,...,y, z.\nconst FORMAT_NUM_FIRST_LAST_VALS = 3;\n// Number of significant digits to show.\nconst FORMAT_NUM_SIG_DIGITS = 7;\n\nexport function tensorToString(\n    vals: TypedArray|string[], shape: number[], dtype: DataType,\n    verbose: boolean) {\n  const strides = computeStrides(shape);\n  const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);\n  const rank = shape.length;\n  const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);\n  const lines = ['Tensor'];\n  if (verbose) {\n    lines.push(`  dtype: ${dtype}`);\n    lines.push(`  rank: ${rank}`);\n    lines.push(`  shape: [${shape}]`);\n    lines.push(`  values:`);\n  }\n  lines.push(valsLines.map(l => '    ' + l).join('\\n'));\n  return lines.join('\\n');\n}\n\nfunction computeMaxSizePerColumn(\n    vals: TypedArray|string[], shape: number[], dtype: DataType,\n    strides: number[]): number[] {\n  const n = sizeFromShape(shape);\n  const numCols = strides[strides.length - 1];\n  const padPerCol = new Array(numCols).fill(0);\n  const rank = shape.length;\n  const valuesOrTuples =\n      dtype === 'complex64' ? createComplexTuples(vals) : vals;\n\n  if (rank > 1) {\n    for (let row = 0; row < n / numCols; row++) {\n      const offset = row * numCols;\n      for (let j = 0; j < numCols; j++) {\n        padPerCol[j] = Math.max(\n            padPerCol[j],\n            valToString(valuesOrTuples[offset + j], 0, dtype).length);\n      }\n    }\n  }\n  return padPerCol;\n}\n\nfunction valToString(\n    val: number|string|[number, number], pad: number, dtype: DataType) {\n  let valStr: string;\n  if (Array.isArray(val)) {\n    valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +\n        `${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;\n  } else if (isString(val)) {\n    valStr = `'${val}'`;\n  } else if (dtype === 'bool') {\n    valStr = boolNumToString(val);\n  } else {\n    valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();\n  }\n\n  return rightPad(valStr, pad);\n}\n\nfunction boolNumToString(v: number): string {\n  return v === 0 ? 'false' : 'true';\n}\n\nfunction subTensorToString(\n    vals: TypedArray|string[], shape: number[], dtype: DataType,\n    strides: number[], padPerCol: number[], isLast = true): string[] {\n  const storagePerElement = dtype === 'complex64' ? 2 : 1;\n\n  const size = shape[0];\n  const rank = shape.length;\n  if (rank === 0) {\n    if (dtype === 'complex64') {\n      const complexTuple = createComplexTuples(vals);\n      return [valToString(complexTuple[0], 0, dtype)];\n    }\n    if (dtype === 'bool') {\n      return [boolNumToString(vals[0] as number)];\n    }\n    return [vals[0].toString()];\n  }\n\n  if (rank === 1) {\n    if (size > FORMAT_LIMIT_NUM_VALS) {\n      const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;\n\n      let firstVals = Array.from<number|string|[number, number]>(\n          vals.slice(0, firstValsSize));\n      let lastVals = Array.from<number|string|[number, number]>(vals.slice(\n          (size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement,\n          size * storagePerElement));\n      if (dtype === 'complex64') {\n        firstVals = createComplexTuples(firstVals);\n        lastVals = createComplexTuples(lastVals);\n      }\n      return [\n        '[' +\n        firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n            .join(', ') +\n        ', ..., ' +\n        lastVals\n            .map(\n                (x, i) => valToString(\n                    x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))\n            .join(', ') +\n        ']'\n      ];\n    }\n    const displayVals: Array<number|string|[number, number]> =\n        dtype === 'complex64' ? createComplexTuples(vals) :\n                                Array.from<number|string>(vals);\n\n    return [\n      '[' +\n      displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n          .join(', ') +\n      ']'\n    ];\n  }\n\n  // The array is rank 2 or more.\n  const subshape = shape.slice(1);\n  const substrides = strides.slice(1);\n  const stride = strides[0] * storagePerElement;\n  const lines: string[] = [];\n  if (size > FORMAT_LIMIT_NUM_VALS) {\n    for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {\n      const start = i * stride;\n      const end = start + stride;\n      lines.push(...subTensorToString(\n          vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n          false /* isLast */));\n    }\n    lines.push('...');\n    for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {\n      const start = i * stride;\n      const end = start + stride;\n      lines.push(...subTensorToString(\n          vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n          i === size - 1 /* isLast */));\n    }\n  } else {\n    for (let i = 0; i < size; i++) {\n      const start = i * stride;\n      const end = start + stride;\n      lines.push(...subTensorToString(\n          vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n          i === size - 1 /* isLast */));\n    }\n  }\n  const sep = rank === 2 ? ',' : '';\n  lines[0] = '[' + (size > 0 ? lines[0] + sep : '');\n  for (let i = 1; i < lines.length - 1; i++) {\n    lines[i] = ' ' + lines[i] + sep;\n  }\n  let newLineSep = ',\\n';\n  for (let i = 2; i < rank; i++) {\n    newLineSep += '\\n';\n  }\n  lines[lines.length - 1] =\n      ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);\n  return lines;\n}\n\nfunction createComplexTuples(vals: Array<{}>|\n                             TypedArray): Array<[number, number]> {\n  const complexTuples: Array<[number, number]> = [];\n  for (let i = 0; i < vals.length; i += 2) {\n    complexTuples.push([vals[i], vals[i + 1]] as [number, number]);\n  }\n  return complexTuples;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265\n/// <reference types=\"@webgpu/types/dist\" />\n\nimport {getGlobal} from './global_util';\nimport {tensorToString} from './tensor_format';\nimport {DataId, TensorInfo} from './tensor_info';\nimport {ArrayMap, BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, Rank, ShapeMap, SingleValueMap, TypedArray} from './types';\nimport * as util from './util';\nimport {computeStrides, toNestedArray} from './util';\n\nexport interface TensorData<D extends DataType> {\n  dataId?: DataId;\n  values?: DataTypeMap[D];\n}\n\n// This interface mimics KernelBackend (in backend.ts), which would create a\n// circular dependency if imported.\nexport interface Backend {}\n\n/**\n * A mutable object, similar to `tf.Tensor`, that allows users to set values\n * at locations before converting to an immutable `tf.Tensor`.\n *\n * See `tf.buffer` for creating a tensor buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class TensorBuffer<R extends Rank, D extends DataType = 'float32'> {\n  size: number;\n  shape: ShapeMap[R];\n  strides: number[];\n  values: DataTypeMap[D];\n\n  constructor(shape: ShapeMap[R], public dtype: D, values?: DataTypeMap[D]) {\n    this.shape = shape.slice() as ShapeMap[R];\n    this.size = util.sizeFromShape(shape);\n\n    if (values != null) {\n      const n = values.length;\n      util.assert(\n          n === this.size,\n          () => `Length of values '${n}' does not match the size ` +\n              `inferred by the shape '${this.size}'.`);\n    }\n    if (dtype === 'complex64') {\n      throw new Error(\n          `complex64 dtype TensorBuffers are not supported. Please create ` +\n          `a TensorBuffer for the real and imaginary parts separately and ` +\n          `call tf.complex(real, imag).`);\n    }\n    this.values = values || util.getArrayFromDType(dtype, this.size);\n    this.strides = computeStrides(shape);\n  }\n\n  /**\n   * Sets a value in the buffer at a given location.\n   *\n   * @param value The value to set.\n   * @param locs  The location indices.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Creation'}\n   */\n  set(value: SingleValueMap[D], ...locs: number[]): void {\n    if (locs.length === 0) {\n      locs = [0];\n    }\n    util.assert(\n        locs.length === this.rank,\n        () => `The number of provided coordinates (${locs.length}) must ` +\n            `match the rank (${this.rank})`);\n\n    const index = this.locToIndex(locs);\n    this.values[index] = value as number;\n  }\n\n  /**\n   * Returns the value in the buffer at the provided location.\n   *\n   * @param locs The location indices.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Creation'}\n   */\n  get(...locs: number[]): SingleValueMap[D] {\n    if (locs.length === 0) {\n      locs = [0];\n    }\n    let i = 0;\n    for (const loc of locs) {\n      if (loc < 0 || loc >= this.shape[i]) {\n        const msg = `Requested out of range element at ${locs}. ` +\n            `  Buffer shape=${this.shape}`;\n        throw new Error(msg);\n      }\n      i++;\n    }\n    let index = locs[locs.length - 1];\n    for (let i = 0; i < locs.length - 1; ++i) {\n      index += this.strides[i] * locs[i];\n    }\n    return this.values[index] as SingleValueMap[D];\n  }\n\n  locToIndex(locs: number[]): number {\n    if (this.rank === 0) {\n      return 0;\n    } else if (this.rank === 1) {\n      return locs[0];\n    }\n    let index = locs[locs.length - 1];\n    for (let i = 0; i < locs.length - 1; ++i) {\n      index += this.strides[i] * locs[i];\n    }\n    return index;\n  }\n\n  indexToLoc(index: number): number[] {\n    if (this.rank === 0) {\n      return [];\n    } else if (this.rank === 1) {\n      return [index];\n    }\n    const locs: number[] = new Array(this.shape.length);\n    for (let i = 0; i < locs.length - 1; ++i) {\n      locs[i] = Math.floor(index / this.strides[i]);\n      index -= locs[i] * this.strides[i];\n    }\n    locs[locs.length - 1] = index;\n    return locs;\n  }\n\n  get rank() {\n    return this.shape.length;\n  }\n\n  /**\n   * Creates an immutable `tf.Tensor` object from the buffer.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Creation'}\n   */\n  toTensor(): Tensor<R> {\n    return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n        Tensor<R>;\n  }\n}\n\nexport interface DataToGPUWebGLOption {\n  customTexShape?: [number, number];\n}\n\nexport type DataToGPUOptions = DataToGPUWebGLOption;\n\nexport interface GPUData {\n  tensorRef: Tensor;\n  texture?: WebGLTexture;\n  buffer?: GPUBuffer;\n  texShape?: [number, number];\n}\n\nexport interface TensorTracker {\n  makeTensor(\n      values: DataValues, shape: number[], dtype: DataType,\n      backend?: Backend): Tensor;\n  makeVariable(\n      initialValue: Tensor, trainable?: boolean, name?: string,\n      dtype?: DataType): Variable;\n  incRef(a: Tensor, backend: Backend): void;\n  disposeTensor(t: Tensor): void;\n  disposeVariable(v: Variable): void;\n  read(dataId: DataId): Promise<BackendValues>;\n  readSync(dataId: DataId): BackendValues;\n  readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n  cast<T extends Tensor>(x: T, dtype: DataType): T;\n  buffer<R extends Rank, D extends DataType>(\n      shape: ShapeMap[R], dtype: D,\n      values?: DataTypeMap[D]): TensorBuffer<R, D>;\n  print<T extends Tensor>(x: T, verbose: boolean): void;\n  clone<T extends Tensor>(x: T): T;\n  // TODO(yassogba) bring reshape back?\n}\n\n// For tracking tensor creation and disposal.\nlet trackerFn: () => TensorTracker = null;\n// Used by chaining methods to call into ops.\nlet opHandler: OpHandler = null;\n// Used to warn about deprecated methods.\nlet deprecationWarningFn: (msg: string) => void = null;\n// This here so that we can use this method on dev branches and keep the\n// functionality at master.\n// tslint:disable-next-line:no-unused-expression\n[deprecationWarningFn];\n\n/**\n * An external consumer can register itself as the tensor tracker. This way\n * the Tensor class can notify the tracker for every tensor created and\n * disposed.\n */\nexport function setTensorTracker(fn: () => TensorTracker) {\n  trackerFn = fn;\n}\n\n/**\n * An external consumer can register itself as the op handler. This way the\n * Tensor class can have chaining methods that call into ops via the op\n * handler.\n */\nexport function setOpHandler(handler: OpHandler) {\n  opHandler = handler;\n}\n\n/**\n * Sets the deprecation warning function to be used by this file. This way the\n * Tensor class can be a leaf but still use the environment.\n */\nexport function setDeprecationWarningFn(fn: (msg: string) => void) {\n  deprecationWarningFn = fn;\n}\n\n// Declare this namespace to make Tensor class augmentation work in google3.\nexport declare namespace Tensor {}\n/**\n * A `tf.Tensor` object represents an immutable, multidimensional array of\n * numbers that has a shape and a data type.\n *\n * For performance reasons, functions that create tensors do not necessarily\n * perform a copy of the data passed to them (e.g. if the data is passed as a\n * `Float32Array`), and changes to the data will change the tensor. This is not\n * a feature and is not supported. To avoid this behavior, use the tensor before\n * changing the input data or create a copy with `copy = tf.add(yourTensor, 0)`.\n *\n * See `tf.tensor` for details on how to create a `tf.Tensor`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Tensor<R extends Rank = Rank> implements TensorInfo {\n  /** Unique id of this tensor. */\n  readonly id: number;\n  /**\n   * Id of the bucket holding the data for this tensor. Multiple arrays can\n   * point to the same bucket (e.g. when calling array.reshape()).\n   */\n  dataId: DataId;\n  /** The shape of the tensor. */\n  readonly shape: ShapeMap[R];\n  /** Number of elements in the tensor. */\n  readonly size: number;\n  /** The data type for the array. */\n  readonly dtype: DataType;\n  /** The rank type for the array (see `Rank` enum). */\n  readonly rankType: R;\n\n  /** Whether this tensor has been globally kept. */\n  kept = false;\n  /** The id of the scope this tensor is being tracked in. */\n  scopeId: number;\n  /** The keras mask that some keras layers attach to the tensor */\n  kerasMask?: Tensor;\n\n  /**\n   * Number of elements to skip in each dimension when indexing. See\n   * https://docs.scipy.org/doc/numpy/reference/generated/\\\n   * numpy.ndarray.strides.html\n   */\n  readonly strides: number[];\n\n  constructor(shape: ShapeMap[R], dtype: DataType, dataId: DataId, id: number) {\n    this.shape = shape.slice() as ShapeMap[R];\n    this.dtype = dtype || 'float32';\n    this.size = util.sizeFromShape(shape);\n    this.strides = computeStrides(shape);\n    this.dataId = dataId;\n    this.id = id;\n    this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher') as R;\n  }\n\n  get rank(): number {\n    return this.shape.length;\n  }\n\n  /**\n   * Returns a promise of `tf.TensorBuffer` that holds the underlying data.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  async buffer<D extends DataType = 'float32'>(): Promise<TensorBuffer<R, D>> {\n    const vals = await this.data<D>();\n    return opHandler.buffer(this.shape, this.dtype as D, vals);\n  }\n\n  /**\n   * Returns a `tf.TensorBuffer` that holds the underlying data.\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  bufferSync<D extends DataType = 'float32'>(): TensorBuffer<R, D> {\n    return opHandler.buffer(this.shape, this.dtype as D, this.dataSync());\n  }\n\n  /**\n   * Returns the tensor data as a nested array. The transfer of data is done\n   * asynchronously.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  async array(): Promise<ArrayMap[R]> {\n    const vals = await this.data();\n    return toNestedArray(this.shape, vals, this.dtype === 'complex64') as\n        ArrayMap[R];\n  }\n\n  /**\n   * Returns the tensor data as a nested array. The transfer of data is done\n   * synchronously.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  arraySync(): ArrayMap[R] {\n    return toNestedArray(\n               this.shape, this.dataSync(), this.dtype === 'complex64') as\n        ArrayMap[R];\n  }\n\n  /**\n   * Asynchronously downloads the values from the `tf.Tensor`. Returns a\n   * promise of `TypedArray` that resolves when the computation has finished.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  async data<D extends DataType = NumericDataType>(): Promise<DataTypeMap[D]> {\n    this.throwIfDisposed();\n    const data = trackerFn().read(this.dataId);\n    if (this.dtype === 'string') {\n      const bytes = await data as Uint8Array[];\n      try {\n        return bytes.map(b => util.decodeString(b)) as DataTypeMap[D];\n      } catch {\n        throw new Error(\n            'Failed to decode the string bytes into utf-8. ' +\n            'To get the original bytes, call tensor.bytes().');\n      }\n    }\n    return data as Promise<DataTypeMap[D]>;\n  }\n\n  /**\n   * Copy the tensor's data to a new GPU resource. Comparing to the `dataSync()`\n   * and `data()`, this method prevents data from being downloaded to CPU.\n   *\n   * For WebGL backend, the data will be stored on a densely packed texture.\n   * This means that the texture will use the RGBA channels to store value.\n   *\n   * For WebGPU backend, the data will be stored on a buffer. There is no\n   * parameter, so can not use a user-defined size to create the buffer.\n   *\n   * @param options:\n   *     For WebGL,\n   *         - customTexShape: Optional. If set, will use the user defined\n   *     texture shape to create the texture.\n   *\n   * @returns For WebGL backend, a GPUData contains the new texture and\n   *     its information.\n   *     {\n   *        tensorRef: The tensor that is associated with this texture,\n   *        texture: WebGLTexture,\n   *        texShape: [number, number] // [height, width]\n   *     }\n   *\n   *     For WebGPU backend, a GPUData contains the new buffer.\n   *     {\n   *        tensorRef: The tensor that is associated with this buffer,\n   *        buffer: GPUBuffer,\n   *     }\n   *\n   *     Remember to dispose the GPUData after it is used by\n   *     `res.tensorRef.dispose()`.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  dataToGPU(options?: DataToGPUOptions): GPUData {\n    this.throwIfDisposed();\n    return trackerFn().readToGPU(this.dataId, options);\n  }\n\n  /**\n   * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n   * UI thread until the values are ready, which can cause performance issues.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  dataSync<D extends DataType = NumericDataType>(): DataTypeMap[D] {\n    this.throwIfDisposed();\n    const data = trackerFn().readSync(this.dataId);\n    if (this.dtype === 'string') {\n      try {\n        return (data as Uint8Array[]).map(b => util.decodeString(b)) as\n            DataTypeMap[D];\n      } catch {\n        throw new Error(\n            'Failed to decode the string bytes into utf-8. ' +\n            'To get the original bytes, call tensor.bytes().');\n      }\n    }\n    return data as DataTypeMap[D];\n  }\n\n  /** Returns the underlying bytes of the tensor's data. */\n  async bytes(): Promise<Uint8Array[]|Uint8Array> {\n    this.throwIfDisposed();\n    const data = await trackerFn().read(this.dataId);\n    if (this.dtype === 'string') {\n      return data as Uint8Array[];\n    } else {\n      return new Uint8Array((data as TypedArray).buffer);\n    }\n  }\n\n  /**\n   * Disposes `tf.Tensor` from memory.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  dispose(): void {\n    if (this.isDisposed) {\n      return;\n    }\n    if (this.kerasMask) {\n      this.kerasMask.dispose();\n    }\n    trackerFn().disposeTensor(this);\n    this.isDisposedInternal = true;\n  }\n\n  protected isDisposedInternal = false;\n  get isDisposed(): boolean {\n    return this.isDisposedInternal;\n  }\n\n  throwIfDisposed() {\n    if (this.isDisposed) {\n      throw new Error(`Tensor is disposed.`);\n    }\n  }\n\n  /**\n   * Prints the `tf.Tensor`. See `tf.print` for details.\n   *\n   * @param verbose Whether to print verbose information about the tensor,\n   *    including dtype and size.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  print(verbose = false): void {\n    return opHandler.print(this, verbose);\n  }\n\n  /**\n   * Returns a copy of the tensor. See `tf.clone` for details.\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  clone<T extends Tensor>(this: T): T {\n    this.throwIfDisposed();\n    return opHandler.clone(this);\n  }\n\n  /**\n   * Returns a human-readable description of the tensor. Useful for logging.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  toString(verbose = false): string {\n    const vals = this.dataSync();\n    return tensorToString(vals, this.shape, this.dtype, verbose);\n  }\n\n  cast<T extends this>(dtype: DataType): T {\n    this.throwIfDisposed();\n    return opHandler.cast(this as T, dtype);\n  }\n  variable(trainable = true, name?: string, dtype?: DataType): Variable<R> {\n    this.throwIfDisposed();\n    return trackerFn().makeVariable(this, trainable, name, dtype) as\n        Variable<R>;\n  }\n}\n\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n  value: (instance: Tensor) => {\n    // Implementation note: we should use properties of the object that will be\n    // defined before the constructor body has finished executing (methods).\n    // This is because when this code is transpiled by babel, babel will call\n    // classCallCheck before the constructor body is run.\n    // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n    return !!instance && instance.data != null && instance.dataSync != null &&\n        instance.throwIfDisposed != null;\n  }\n});\n\nexport function getGlobalTensorClass() {\n  // Use getGlobal so that we can augment the Tensor class across package\n  // boundaries because the node resolution alg may result in different modules\n  // being returned for this file depending on the path they are loaded from.\n  return getGlobal('Tensor', () => {\n    return Tensor;\n  });\n}\n\n// Global side effect. Cache global reference to Tensor class\ngetGlobalTensorClass();\n\nexport interface NumericTensor<R extends Rank = Rank> extends Tensor<R> {\n  dtype: NumericDataType;\n  dataSync<D extends DataType = NumericDataType>(): DataTypeMap[D];\n  data<D extends DataType = NumericDataType>(): Promise<DataTypeMap[D]>;\n  dataToGPU(options?: DataToGPUOptions): GPUData;\n}\n\nexport interface StringTensor<R extends Rank = Rank> extends Tensor<R> {\n  dtype: 'string';\n  dataSync<D extends DataType = 'string'>(): DataTypeMap[D];\n  data<D extends DataType = 'string'>(): Promise<DataTypeMap[D]>;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor<Rank.R0>;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor<Rank.R1>;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor<Rank.R2>;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor<Rank.R3>;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor<Rank.R4>;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor<Rank.R5>;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor<Rank.R6>;\n\n/**\n * A mutable `tf.Tensor`, useful for persisting state, e.g. for training.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Variable<R extends Rank = Rank> extends Tensor<R> {\n  name: string;\n\n  constructor(\n      initialValue: Tensor<R>, public trainable: boolean, name: string,\n      tensorId: number) {\n    super(\n        initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);\n    this.name = name;\n  }\n\n  /**\n   * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have\n   * the same shape and dtype as the old `tf.Tensor`.\n   *\n   * @param newValue New tensor to be assigned to this variable.\n   *\n   * @doc {heading: 'Tensors', subheading: 'Classes'}\n   */\n  assign(newValue: Tensor<R>): void {\n    if (newValue.dtype !== this.dtype) {\n      throw new Error(\n          `dtype of the new value (${newValue.dtype}) and ` +\n          `previous value (${this.dtype}) must match`);\n    }\n    if (!util.arraysEqual(newValue.shape, this.shape)) {\n      throw new Error(\n          `shape of the new value (${newValue.shape}) and ` +\n          `previous value (${this.shape}) must match`);\n    }\n    trackerFn().disposeTensor(this);\n    this.dataId = newValue.dataId;\n    trackerFn().incRef(this, null /* backend */);\n  }\n\n  override dispose(): void {\n    trackerFn().disposeVariable(this);\n    this.isDisposedInternal = true;\n  }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n  value: (instance: Variable) => {\n    return instance instanceof Tensor && instance.assign != null &&\n        instance.assign instanceof Function;\n  }\n});\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** @docalias number[] */\nexport interface ShapeMap {\n  R0: number[];\n  R1: [number];\n  R2: [number, number];\n  R3: [number, number, number];\n  R4: [number, number, number, number];\n  R5: [number, number, number, number, number];\n  R6: [number, number, number, number, number, number];\n}\n\n/** @docalias number[] */\nexport interface ArrayMap {\n  R0: number;\n  R1: number[];\n  R2: number[][];\n  R3: number[][][];\n  R4: number[][][][];\n  R5: number[][][][][];\n  R6: number[][][][][][];\n}\n\nexport interface DataTypeMap {\n  float32: Float32Array;\n  int32: Int32Array;\n  bool: Uint8Array;\n  complex64: Float32Array;\n  string: string[];\n}\n\nexport interface SingleValueMap {\n  bool: boolean;\n  int32: number;\n  float32: number;\n  complex64: number;\n  string: string;\n}\n\n/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */\nexport type DataType = keyof DataTypeMap;\nexport type NumericDataType = 'float32'|'int32'|'bool'|'complex64';\n\nexport type DataTypeFor<T extends number|string|boolean> =\n    T extends number|boolean ? NumericDataType : T extends string ? 'string' :\n                                                                    never;\n\nexport type TypedArray = Float32Array|Int32Array|Uint8Array;\n/** Tensor data used in tensor creation and user-facing API. */\nexport type DataValues = DataTypeMap[DataType];\n/** The underlying tensor data that gets stored in a backend. */\nexport type BackendValues = Float32Array|Int32Array|Uint8Array|Uint8Array[];\n\nexport enum Rank {\n  R0 = 'R0',\n  R1 = 'R1',\n  R2 = 'R2',\n  R3 = 'R3',\n  R4 = 'R4',\n  R5 = 'R5',\n  R6 = 'R6'\n}\n\nexport type FlatVector = boolean[]|number[]|TypedArray;\nexport type RegularArray<T> =\n    T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray<T extends any> {\n  [index: number]: T|RecursiveArray<T>;\n}\n\n// Looks for upcasting types. Used, for example, in operations with mixed dtype\n// inputs.\nenum UpcastInt32AndMap {\n  'float32' = 'float32',\n  'int32' = 'int32',\n  'bool' = 'int32',\n  'complex64' = 'complex64'\n}\n\nenum UpcastBoolAndMap {\n  'float32' = 'float32',\n  'int32' = 'int32',\n  'bool' = 'bool',\n  'complex64' = 'complex64'\n}\n\nenum UpcastFloat32AndMap {\n  'float32' = 'float32',\n  'int32' = 'float32',\n  'bool' = 'float32',\n  'complex64' = 'complex64'\n}\n\nenum UpcastComplex64AndMap {\n  'float32' = 'complex64',\n  'int32' = 'complex64',\n  'bool' = 'complex64',\n  'complex64' = 'complex64'\n}\n\nconst upcastTypeMap = {\n  'float32': UpcastFloat32AndMap,\n  'int32': UpcastInt32AndMap,\n  'bool': UpcastBoolAndMap,\n  'complex64': UpcastComplex64AndMap\n};\n\nexport function upcastType(typeA: DataType, typeB: DataType): DataType {\n  if (typeA === 'string' || typeB === 'string') {\n    if (typeA === 'string' && typeB === 'string') {\n      return 'string';\n    }\n    throw new Error(`Can not upcast ${typeA} with ${typeB}`);\n  }\n  return upcastTypeMap[typeA][typeB];\n}\n\n/** Returns the output type after summation. */\nexport function sumOutType(type: DataType): DataType {\n  return upcastType(type, 'int32');\n}\n\n/** @docalias TypedArray|Array */\nexport type TensorLike =\n    TypedArray|number|boolean|string|RecursiveArray<number|number[]|TypedArray>|\n    RecursiveArray<boolean>|RecursiveArray<string>|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n    string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n    boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n    boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n    TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n    string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n    TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n    string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image data in Uint8Array type. */\nexport interface PixelData {\n  width: number;\n  height: number;\n  data: Uint8Array;\n}\n\n/**\n * Type for representing all permutations and combinations of 'RGBA' channels.\n */\nexport type WebGLChannels = 'A'|'B'|'G'|'R'|'AB'|'AG'|'AR'|'BA'|'BG'|'BR'|'GA'|\n    'GB'|'GR'|'RA'|'RB'|'RG'|'ABG'|'ABR'|'AGB'|'AGR'|'ARB'|'ARG'|'BAG'|'BAR'|\n    'BGA'|'BGR'|'BRA'|'BRG'|'GAB'|'GAR'|'GBA'|'GBR'|'GRA'|'GRB'|'RAB'|'RAG'|\n    'RBA'|'RBG'|'RGA'|'RGB'|'ABGR'|'ABRG'|'AGBR'|'AGRB'|'ARBG'|'ARGB'|'BAGR'|\n    'BARG'|'BGAR'|'BGRA'|'BRAG'|'BRGA'|'GABR'|'GARB'|'GBAR'|'GBRA'|'GRAB'|\n    'GRBA'|'RABG'|'RAGB'|'RBAG'|'RBGA'|'RGAB'|'RGBA';\n\n/** Type for representing a texture data to create a tensor. */\nexport interface WebGLData {\n  texture: WebGLTexture;\n  height: number;\n  width: number;\n  channels: WebGLChannels;\n}\n\n/**\n * Type for representing a buffer data to create a tensor. Buffer usage should\n * at least support GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC. When\n * zeroCopy is false or undefined (default), this GPUBuffer will be copied to\n * the tensor's resource buffer. When zeroCopy is true, tensor will use this\n * GPUBuffer as tensor's resource buffer, user should not destroy this GPUBuffer\n * until all access is done. If not specified at creating a tensor, tensor type\n * is float32.\n */\nexport interface WebGPUData {\n  buffer: GPUBuffer;\n  zeroCopy?: boolean;\n}\n\nexport function isWebGLData(values: unknown): values is WebGLData {\n  return values != null && typeof values === 'object' && 'texture' in values &&\n      values.texture instanceof WebGLTexture;\n}\nexport function isWebGPUData(values: unknown): values is WebGPUData {\n  return typeof GPUBuffer !== 'undefined' && values != null &&\n      typeof values === 'object' && 'buffer' in values &&\n      values.buffer instanceof GPUBuffer;\n}\n\nexport interface ImageOptions {\n  /**\n   * Optional. A number in range [0-1]. If the image is a 2D tensor or a 3D\n   * tensor with 1 or 3 channels, the alpha channels would set as its value;\n   * otherwise, it would not make effects.\n   */\n  alpha?: number;\n}\n\nexport interface ContextOptions {\n  /**\n   * Optional.  If the canvas has created a context, it would not make effects.\n   * If it is not set, it would be variable based on the current backend.\n   */\n  contextType?: string;\n  /**\n   * Optional. A WebGLContextAttributes configuration. If the canvas has created\n   * a context, it would not make effects.\n   */\n  contextAttributes?: WebGLContextAttributes;\n}\n\nexport interface DrawOptions {\n  /**\n   * Optional. An object of options to customize the values of image tensor.\n   */\n  imageOptions?: ImageOptions;\n  /**\n   * Optional. An object to configure the context of the canvas to draw to.\n   */\n  contextOptions?: ContextOptions;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch<T extends Tensor>(a: T, b: T): [T, T] {\n  if (a.dtype === b.dtype) {\n    return [a, b];\n  }\n  const dtype = upcastType(a.dtype, b.dtype);\n  return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n  assert(\n      a.dtype === b.dtype,\n      () => `The dtypes of the first(${a.dtype}) and` +\n          ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n  return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n *   `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n *   is safe to pass any object here, except that `Promise`s are not\n *   supported.\n * @returns An array of `Tensors` found within the passed object. If the\n *   argument is simply a `Tensor', a list containing that `Tensor` is\n *   returned. If the object is not a `Tensor` or does not\n *   contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n  const list: Tensor[] = [];\n  const seen = new Set<{}|void>();\n  walkTensorContainer(result, list, seen);\n  return list;\n}\n\nfunction walkTensorContainer(\n    container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n  if (container == null) {\n    return;\n  }\n  if (container instanceof Tensor) {\n    list.push(container);\n    return;\n  }\n  if (!isIterable(container)) {\n    return;\n  }\n  // Iteration over keys works also for arrays.\n  const iterable = container as TensorContainerArray;\n  for (const k in iterable) {\n    const val = iterable[k];\n    if (!seen.has(val)) {\n      seen.add(val);\n      walkTensorContainer(val, list, seen);\n    }\n  }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n  return Array.isArray(obj) || typeof obj === 'object';\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast, Identity} from './kernel_names';\nimport { getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap } from './kernel_registry';\nimport { TensorInfo } from './tensor_info';\nimport * as log from './log';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataToGPUOptions, GPUData, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\nimport {DataId} from './tensor_info';\nimport {GradSaveFunc, NamedTensorMap, NamedVariableMap, TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\nimport {BackendValues, DataType, DataValues} from './types';\nimport * as util from './util';\nimport {bytesFromStringArray, makeOnesTypedArray, now, sizeFromShape} from './util';\n\n/**\n * A function that computes an output. The save function is for saving tensors\n * computed in the forward pass, that we need in the backward pass.\n */\nexport type ForwardFunc<T> = (backend: KernelBackend, save?: GradSaveFunc) => T;\n\n/**\n * @docalias (a: Tensor, b: Tensor,..., save?: Function) => {\n *   value: Tensor,\n *   gradFunc: (dy: Tensor, saved?: NamedTensorMap) => Tensor | Tensor[]\n * }\n */\nexport type CustomGradientFunc<T extends Tensor> =\n    (...inputs: Array<Tensor|GradSaveFunc>) => {\n      value: T;\n      gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[];\n    };\n\nexport type MemoryInfo = {\n  numTensors: number; numDataBuffers: number; numBytes: number;\n  unreliable?: boolean; reasons: string[];\n};\n\ntype KernelInfo = {\n  name: string; bytesAdded: number; totalBytesSnapshot: number;\n  tensorsAdded: number;\n  totalTensorsSnapshot: number;\n  inputShapes: number[][];\n  outputShapes: number[][];\n  kernelTimeMs: number | {error: string} | Promise<number|{error: string}>;\n  extraInfo: string | Promise<string>;\n};\n\nexport type ProfileInfo = {\n  newBytes: number; newTensors: number; peakBytes: number;\n  kernels: KernelInfo[];\n  result: TensorContainer;\n  kernelNames: string[];\n};\n\nexport interface TimingInfo extends BackendTimingInfo {\n  wallMs: number;\n}\n\n/** @docalias Function */\nexport type ScopeFn<T extends TensorContainer> = () => T;\n\ninterface ScopeState {\n  track: Tensor[];\n  name: string;\n  id: number;\n}\n\ninterface RegisteredKernelInvocation<I extends NamedTensorMap> {\n  kernelName: string;\n  inputs: I;\n  attrs?: NamedAttrMap;\n}\n\ninterface CustomGradKernelInvocation<T extends Tensor|Tensor[],\n                                               I extends NamedTensorMap> {\n  forwardFunc: ForwardFunc<T>;\n  backwardsFunc: (dy: T, saved: Tensor[]) => {\n    [P in keyof I]: () => I[P]\n  };\n  inputs: I;\n  attrs?: NamedAttrMap;\n}\n\nfunction isRegisteredKernelInvocation<T extends Tensor|Tensor[],\n                                                I extends NamedTensorMap>(\n    kernelInvocation: RegisteredKernelInvocation<I>|\n    CustomGradKernelInvocation<T, I>):\n    kernelInvocation is RegisteredKernelInvocation<I> {\n  return (kernelInvocation as RegisteredKernelInvocation<I>).kernelName != null;\n}\n\nclass EngineState {\n  // Public since optimizers will use it.\n  registeredVariables: NamedVariableMap = {};\n\n  nextTapeNodeId = 0;\n  numBytes = 0;\n  numTensors = 0;\n  numStringTensors = 0;\n  numDataBuffers = 0;\n\n  activeTape: TapeNode[];\n  // Number of nested tf.grad() statements when computing higher-order\n  // gradients. E.g. `1` for first-order gradients and `2` for second-order\n  // gradients. Used to track if the tape should be removed after a backprop.\n  gradientDepth = 0;\n  // Number of nested kernel calls. When kernel depth is greater than 1, we turn\n  // off the tape.\n  kernelDepth = 0;\n\n  // Keep Tensors that parallel the tapes.\n  activeScope: ScopeState;\n  scopeStack: ScopeState[] = [];\n  /**\n   * Keeps track of the number of data moves during a kernel execution. We\n   * maintain a stack since kernels can call other kernels, recursively.\n   */\n  numDataMovesStack: number[] = [];\n  nextScopeId = 0;\n\n  tensorInfo = new WeakMap<DataId, {\n    backend: KernelBackend,\n    bytes: number,\n    dtype: DataType,\n    shape: number[]\n  }>();\n\n  profiling = false;\n  activeProfile: ProfileInfo = {\n    newBytes: 0,\n    newTensors: 0,\n    peakBytes: 0,\n    kernels: [],\n    result: null,\n    get kernelNames():\n        string[] {\n          return Array.from(new Set(this.kernels.map(k => k.name)));\n        }\n  };\n\n  dispose() {\n    for (const variableName in this.registeredVariables) {\n      this.registeredVariables[variableName].dispose();\n    }\n  }\n}\n\nexport class Engine implements TensorTracker, DataMover {\n  state: EngineState;\n  backendName: string;\n  registry: {[id: string]: KernelBackend} = {};\n  registryFactory: {\n    [id: string]: {\n      factory: () => KernelBackend | Promise<KernelBackend>,\n      priority: number\n    }\n  } = {};\n\n  private profiler: Profiler;\n  private backendInstance: KernelBackend;\n  private pendingBackendInit: Promise<boolean>;\n  private pendingBackendInitId = 0;\n\n  constructor(public ENV: Environment) {\n    this.state = new EngineState();\n  }\n\n  async ready(): Promise<void> {\n    if (this.pendingBackendInit != null) {\n      return this.pendingBackendInit.then(() => {});\n    }\n    if (this.backendInstance != null) {\n      return;\n    }\n    const sortedBackends = this.getSortedBackends();\n\n    for (let i = 0; i < sortedBackends.length; i++) {\n      const backendName = sortedBackends[i];\n      const success = await this.initializeBackend(backendName).success;\n      if (success) {\n        await this.setBackend(backendName);\n        return;\n      }\n    }\n\n    throw new Error(\n        `Could not initialize any backends, all backend initializations ` +\n        `failed.`);\n  }\n\n  get backend(): KernelBackend {\n    if (this.pendingBackendInit != null) {\n      throw new Error(\n          `Backend '${this.backendName}' has not yet been initialized. Make ` +\n          `sure to await tf.ready() or await tf.setBackend() before calling ` +\n          `other methods`);\n    }\n    if (this.backendInstance == null) {\n      const {name, asyncInit} = this.initializeBackendsAndReturnBest();\n      if (asyncInit) {\n        throw new Error(\n            `The highest priority backend '${name}' has not yet been ` +\n            `initialized. Make sure to await tf.ready() or ` +\n            `await tf.setBackend() before calling other methods`);\n      }\n      this.setBackend(name);\n    }\n    return this.backendInstance;\n  }\n\n  backendNames(): string[] {\n    return Object.keys(this.registryFactory);\n  }\n\n  findBackend(backendName: string): KernelBackend {\n    if (!(backendName in this.registry)) {\n      // If the backend hasn't been initialized but we have a registry entry for\n      // it, initialize it and return it.\n      if (backendName in this.registryFactory) {\n        const {asyncInit} = this.initializeBackend(backendName);\n        if (asyncInit) {\n          // Backend is not ready yet.\n          return null;\n        }\n      } else {\n        return null;\n      }\n    }\n    return this.registry[backendName];\n  }\n\n  findBackendFactory(backendName: string):\n      () => KernelBackend | Promise<KernelBackend> {\n    if (!(backendName in this.registryFactory)) {\n      return null;\n    }\n    return this.registryFactory[backendName].factory;\n  }\n\n  registerBackend(\n      backendName: string,\n      factory: () => KernelBackend | Promise<KernelBackend>,\n      priority = 1): boolean {\n    if (backendName in this.registryFactory) {\n      log.warn(\n          `${backendName} backend was already registered. ` +\n          `Reusing existing backend factory.`);\n      return false;\n    }\n    this.registryFactory[backendName] = {factory, priority};\n    return true;\n  }\n\n  async setBackend(backendName: string): Promise<boolean> {\n    if (this.registryFactory[backendName] == null) {\n      throw new Error(`Backend name '${backendName}' not found in registry`);\n    }\n    this.backendName = backendName;\n    if (this.registry[backendName] == null) {\n      this.backendInstance = null;\n      const {success, asyncInit} = this.initializeBackend(backendName);\n      const result = asyncInit ? await success : success;\n      if (!result) {\n        return false;\n      }\n    }\n    this.backendInstance = this.registry[backendName];\n    this.setupRegisteredKernels();\n    // Reset the profiler.\n    this.profiler = new Profiler(this.backendInstance);\n\n    return true;\n  }\n\n  private setupRegisteredKernels(): void {\n    const kernels = getKernelsForBackend(this.backendName);\n    kernels.forEach(kernel => {\n      if (kernel.setupFunc != null) {\n        kernel.setupFunc(this.backendInstance);\n      }\n    });\n  }\n\n  private disposeRegisteredKernels(backendName: string): void {\n    const kernels = getKernelsForBackend(backendName);\n    kernels.forEach(kernel => {\n      if (kernel.disposeFunc != null) {\n        kernel.disposeFunc(this.registry[backendName]);\n      }\n    });\n  }\n\n  /**\n   * Initializes a backend by looking up the backend name in the factory\n   * registry and calling the factory method. Returns a boolean representing\n   * whether the initialization of the backend succeeded. Throws an error if\n   * there is no backend in the factory registry.\n   */\n  private initializeBackend(backendName: string):\n      {success: boolean|Promise<boolean>, asyncInit: boolean} {\n    const registryFactoryEntry = this.registryFactory[backendName];\n    if (registryFactoryEntry == null) {\n      throw new Error(\n          `Cannot initialize backend ${backendName}, no registration found.`);\n    }\n\n    try {\n      const backend = registryFactoryEntry.factory();\n      /* Test if the factory returns a promise.\n      Done in a more liberal way than\n      previous 'Promise.resolve(backend)===backend'\n      as we needed to account for custom Promise\n      implementations (e.g. Angular) */\n      if (backend && !(backend instanceof KernelBackend) &&\n          typeof backend.then === 'function') {\n        const promiseId = ++this.pendingBackendInitId;\n        const success =\n            backend\n                .then(backendInstance => {\n                  // Outdated promise. Another backend was set in the meantime.\n                  if (promiseId < this.pendingBackendInitId) {\n                    return false;\n                  }\n                  this.registry[backendName] = backendInstance;\n                  this.pendingBackendInit = null;\n                  return true;\n                })\n                .catch(err => {\n                  // Outdated promise. Another backend was set in the meantime.\n                  if (promiseId < this.pendingBackendInitId) {\n                    return false;\n                  }\n                  this.pendingBackendInit = null;\n                  log.warn(`Initialization of backend ${backendName} failed`);\n                  log.warn(err.stack || err.message);\n                  return false;\n                });\n        this.pendingBackendInit = success;\n        return {success, asyncInit: true};\n      } else {\n        this.registry[backendName] = backend as KernelBackend;\n        return {success: true, asyncInit: false};\n      }\n    } catch (err) {\n      log.warn(`Initialization of backend ${backendName} failed`);\n      log.warn(err.stack || err.message);\n      return {success: false, asyncInit: false};\n    }\n  }\n\n  removeBackend(backendName: string): void {\n    if (!(backendName in this.registryFactory)) {\n      throw new Error(`${backendName} backend not found in registry`);\n    }\n    if (this.backendName === backendName && this.pendingBackendInit != null) {\n      // There is a pending promise of the backend we want to remove. Make it\n      // obsolete.\n      this.pendingBackendInitId++;\n    }\n\n    if (backendName in this.registry) {\n      this.disposeRegisteredKernels(backendName);\n      this.registry[backendName].dispose();\n      delete this.registry[backendName];\n    }\n\n    delete this.registryFactory[backendName];\n\n    // Unset the backend if it is active.\n    if (this.backendName === backendName) {\n      this.pendingBackendInit = null;\n      this.backendName = null;\n      this.backendInstance = null;\n    }\n  }\n\n  private getSortedBackends(): string[] {\n    if (Object.keys(this.registryFactory).length === 0) {\n      throw new Error('No backend found in registry.');\n    }\n    return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n      // Highest priority comes first.\n      return this.registryFactory[b].priority -\n          this.registryFactory[a].priority;\n    });\n  }\n\n  private initializeBackendsAndReturnBest():\n      {name: string, asyncInit: boolean} {\n    const sortedBackends = this.getSortedBackends();\n\n    for (let i = 0; i < sortedBackends.length; i++) {\n      const backendName = sortedBackends[i];\n      const {success, asyncInit} = this.initializeBackend(backendName);\n      if (asyncInit || success) {\n        return {name: backendName, asyncInit};\n      }\n    }\n    throw new Error(\n        `Could not initialize any backends, all backend initializations ` +\n        `failed.`);\n  }\n\n  moveData(backend: KernelBackend, dataId: DataId) {\n    const info = this.state.tensorInfo.get(dataId);\n    const srcBackend = info.backend;\n    const values = this.readSync(dataId);\n    const refCount = srcBackend.refCount(dataId);\n    // Delete the tensor from the old backend and move it to the new\n    // backend.\n    srcBackend.disposeData(dataId, true);\n    info.backend = backend;\n    backend.move(dataId, values, info.shape, info.dtype, refCount);\n    if (this.shouldCheckForMemLeaks()) {\n      // Track the number of moves during a kernel execution to correctly\n      // detect memory leaks.\n      this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n    }\n  }\n\n  tidy<T extends TensorContainer>(nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>):\n      T {\n    let name: string = null;\n    if (fn == null) {\n      // Called with only 1 argument.\n      if (typeof nameOrFn !== 'function') {\n        throw new Error('Please provide a function to tidy()');\n      }\n      fn = nameOrFn;\n    } else {\n      // Called with 2 arguments.\n      if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {\n        throw new Error(\n            'When calling with two arguments, the first argument ' +\n            'to tidy() must be a string');\n      }\n      if (typeof fn !== 'function') {\n        throw new Error(\n            'When calling with two arguments, the 2nd argument ' +\n            'to tidy() must be a function');\n      }\n      name = nameOrFn as string;\n      // TODO(nsthorat,smilkov): Do operation logging and performance\n      // profiling.\n    }\n    let result: T;\n    return this.scopedRun(\n        () => this.startScope(name), () => this.endScope(result), () => {\n          result = fn();\n          if (result instanceof Promise) {\n            console.error('Cannot return a Promise inside of tidy.');\n          }\n          return result;\n        });\n  }\n\n  private scopedRun<T>(start: () => void, end: () => void, f: () => T): T {\n    start();\n    try {\n      const res = f();\n      end();\n      return res;\n    } catch (ex) {\n      end();\n      throw ex;\n    }\n  }\n\n  private static nextTensorId = 0;\n  private nextTensorId(): number {\n    return Engine.nextTensorId++;\n  }\n\n  private static nextVariableId = 0;\n  private nextVariableId(): number {\n    return Engine.nextVariableId++;\n  }\n\n  /**\n   * This method is called instead of the public-facing tensor.clone() when\n   * saving a tensor for backwards pass. It makes sure to add the clone\n   * operation to the tape regardless of being called inside a kernel\n   * execution.\n   */\n  private clone(x: Tensor): Tensor {\n    const y: Tensor = ENGINE.runKernel(Identity,\n                                       {x} as unknown as NamedTensorMap);\n    const inputs = {x};\n    const grad = (dy: Tensor) => ({\n      x: () => {\n        const dtype = 'float32';\n        const gradInputs = {x: dy};\n        const attrs = {dtype};\n\n        return ENGINE.runKernel(\n                   Cast, gradInputs as unknown as NamedTensorMap,\n                   // tslint:disable-next-line: no-unnecessary-type-assertion\n                   attrs as unknown as NamedAttrMap) as Tensor;\n      }\n    });\n    const saved: Tensor[] = [];\n    this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});\n    return y;\n  }\n\n  /**\n   * Execute a kernel with the given name and return the output tensor.\n   *\n   * @param kernelName The name of the kernel to execute.\n   * @param inputs A map of input names to tensors.\n   * @param attrs A map of attribute names to their values. An attribute is a\n   *     primitive (non-tensor) input to the kernel.\n   * @param inputsToSave A list of tensors, inputs to save for the backprop\n   *     computation.\n   * @param outputsToSave A list of booleans, specifying which output to save\n   *     for the backprop computation. These are booleans since the output\n   * tensors are not visible to the user.\n   */\n  runKernel<T extends Tensor|Tensor[]>(\n      kernelName: string, inputs: NamedTensorMap, attrs?: NamedAttrMap): T {\n    if (this.backendName == null) {\n      // backend has not been initialized yet (backend initialization is lazy\n      // can be deferred until an op/ kernel is run).\n      // The below getter has side effects that will try to initialize the\n      // backend and set properties like this.backendName\n      // tslint:disable-next-line: no-unused-expression\n      this.backend;\n    }\n    const hasKernel = getKernel(kernelName, this.backendName) != null;\n    if (!hasKernel) {\n      throw new Error(`Kernel '${kernelName}' not registered for backend '${\n          this.backendName}'`);\n    }\n    return this.runKernelFunc({kernelName, inputs, attrs});\n  }\n\n  private shouldCheckForMemLeaks(): boolean {\n    return this.ENV.getBool('IS_TEST');\n  }\n\n  private checkKernelForMemLeak(\n      kernelName: string, numDataIdsBefore: number,\n      outInfos: TensorInfo[]): void {\n    const numDataIdsAfter = this.backend.numDataIds();\n\n    // Count the number of data ids associated with the result of the kernel.\n    let numOutputDataIds = 0;\n    outInfos.forEach(info => {\n      // Complex numbers allocate 3 data ids, one for 'real', one for\n      // 'imaginary', and one for the container that holds the former two.\n      numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);\n    });\n\n    // Account for the number of moves during kernel execution. A \"data move\"\n    // can happen in the middle of a kernel execution, placing a new (key,value)\n    // pair in the data storage. Since data moves have net zero effect (we\n    // always remove the data from the old backend), we have to cancel them out\n    // when detecting memory leaks.\n    const numMoves =\n        this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];\n    const dataIdsLeaked =\n        numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;\n    if (dataIdsLeaked > 0) {\n      throw new Error(\n          `Backend '${this.backendName}' has an internal memory leak ` +\n          `(${dataIdsLeaked} data ids) after running '${kernelName}'`);\n    }\n  }\n\n  /**\n   * Internal helper method to execute a kernel Func\n   *\n   * Use `runKernel` to execute kernels from outside of engine.\n   */\n  private runKernelFunc<T extends Tensor|Tensor[], I extends NamedTensorMap>(\n      kernelParams: RegisteredKernelInvocation<I>|\n      CustomGradKernelInvocation<T, I>): T {\n    let outputs: Tensor[];\n    let saved: Tensor[] = [];\n    const isTapeOn = this.isTapeOn();\n\n    const startingBytecount = this.state.numBytes;\n    const startingNumTensors = this.state.numTensors;\n\n    if (this.shouldCheckForMemLeaks()) {\n      this.state.numDataMovesStack.push(0);\n    }\n\n    let kernelFunc: () => Tensor[];\n    if (this.backendName == null) {\n      // backend has not been initialized yet (backend initialization is lazy\n      // can be deferred until an op/ kernel is run).\n      // The below getter has side effects that will try to initialize the\n      // backend and set properties like this.backendName\n      // tslint:disable-next-line: no-unused-expression\n      this.backend;\n    }\n\n    let out: TensorInfo|TensorInfo[];\n\n    const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ?\n        kernelParams.kernelName :\n        this.state.activeScope != null ? this.state.activeScope.name : '';\n\n    // Create the kernelFunc from either a registered kernel OR passed in\n    // forward/backward functions (used by custom grad). In this context a\n    // kernelFunc wraps a kernel implementation with some bookkeeping.\n\n    if (isRegisteredKernelInvocation(kernelParams)) {\n      const {kernelName, inputs, attrs} = kernelParams;\n      if (this.backendName == null) {\n        // backend has not been initialized yet (backend initialization is lazy\n        // can be deferred until an op/ kernel is run).\n        // The below getter has side effects that will try to initialize the\n        // backend and set properties like this.backendName\n        // tslint:disable-next-line: no-unused-expression\n        this.backend;\n      }\n      const kernel = getKernel(kernelName, this.backendName);\n      util.assert(\n          kernel != null,\n          () => `Cannot find registered kernel '${kernelName}' for backend '${\n              this.backendName}'`);\n\n      kernelFunc = () => {\n        const numDataIdsBefore = this.backend.numDataIds();\n        out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n        const outInfos = Array.isArray(out) ? out : [out];\n        if (this.shouldCheckForMemLeaks()) {\n          this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n        }\n\n        const outTensors = outInfos.map((outInfo: TensorInfo|Tensor) => {\n          // todo (yassogba) remove this option (Tensor) when node backend\n          // methods have been modularized and they all return tensorInfo.\n          // TensorInfos do not have a rank attribute.\n          if ((outInfo as Tensor).rank != null) {\n            return outInfo as Tensor;\n          }\n          return this.makeTensorFromTensorInfo(outInfo);\n        });\n\n        // Save any required inputs and outputs.\n\n        // Do not save unless we are recording to the tape. Otherwise it would\n        // cause a mem leak since there would be no backprop for these tensors\n        // (which would otherwise dispose them).\n        if (isTapeOn) {\n          const tensorsToSave =\n              this.getTensorsForGradient(kernelName, inputs, outTensors);\n          saved = this.saveTensorsForBackwardMode(tensorsToSave);\n        }\n        return outTensors;\n      };\n    } else {\n      const {forwardFunc} = kernelParams;\n      // Running a customGrad op.\n      const saveFunc: GradSaveFunc = (tensors) => {\n        // Do not save unless we are recording to the tape. Otherwise it would\n        // cause a mem leak since we would never run backprop, which disposes\n        // the kept tensors.\n        if (!isTapeOn) {\n          return;\n        }\n        saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n      };\n\n      kernelFunc = () => {\n        const numDataIdsBefore = this.backend.numDataIds();\n        out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n        const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n        if (this.shouldCheckForMemLeaks()) {\n          // Scope name is used to print a more helpful error message if needed.\n          this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs);\n        }\n        return outs;\n      };\n    }\n\n    //\n    // Run the kernelFunc. Optionally profiling it.\n    //\n    const {inputs, attrs} = kernelParams;\n    const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ?\n        null :\n        kernelParams.backwardsFunc;\n\n    let kernelProfile: KernelProfile;\n    this.scopedRun(\n        // Stop recording to a tape when running a kernel.\n        () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n          if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n            outputs = kernelFunc();\n          } else {\n            kernelProfile = this.profiler.profileKernel(\n                kernelOrScopeName, inputs, () => kernelFunc());\n            if (this.ENV.getBool('DEBUG')) {\n              this.profiler.logKernelProfile(kernelProfile);\n            }\n            outputs = kernelProfile.outputs;\n          }\n        });\n\n    if (isTapeOn) {\n      this.addTapeNode(\n          kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs);\n    }\n\n    if (this.state.profiling) {\n      this.state.activeProfile.kernels.push({\n        name: kernelOrScopeName,\n        bytesAdded: this.state.numBytes - startingBytecount,\n        totalBytesSnapshot: this.state.numBytes,\n        tensorsAdded: this.state.numTensors - startingNumTensors,\n        totalTensorsSnapshot: this.state.numTensors,\n        inputShapes: Object.keys(inputs).map(\n            key => inputs[key] != null ? inputs[key].shape : null),\n        outputShapes: outputs.map(item => item.shape),\n        kernelTimeMs: kernelProfile.timeMs,\n        extraInfo: kernelProfile.extraInfo\n      });\n    }\n    return (Array.isArray(out) ? outputs : outputs[0]) as T;\n  }\n\n  /**\n   * Saves tensors used in forward mode for use in backward mode.\n   *\n   * @param tensors the list of tensors to save.\n   */\n  private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n    const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n    return saved;\n  }\n\n  /**\n   * Returns a list of tensors to save for a given gradient calculation.\n   *\n   * @param kernelName name of kernel to look up gradient for.\n   * @param inputs a map of input tensors.\n   * @param outputs an array of output tensors from forward mode of kernel.\n   */\n  private getTensorsForGradient(\n      kernelName: string, inputs: NamedTensorMap,\n      outputs: Tensor[]): Tensor[]|null {\n    const gradConfig = getGradient(kernelName);\n    if (gradConfig != null) {\n      const inputsToSave: string[] = gradConfig.inputsToSave || [];\n      const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n      // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n      // specified in inputsToSave will be saved.\n      let inputTensorsToSave: Tensor[];\n      if (gradConfig.saveAllInputs) {\n        util.assert(\n            Array.isArray(inputs),\n            () => 'saveAllInputs is true, expected inputs to be an array.');\n\n        inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n      } else {\n        inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n      }\n\n      const outputTensorsToSave: Tensor[] =\n          outputs.filter((_, i) => outputsToSave[i]);\n\n      return inputTensorsToSave.concat(outputTensorsToSave);\n    }\n    // We return an empty list rather than throw an error because the kernel we\n    // are looking up may not actually be relevant to backproping through the\n    // overall function\n    //\n    // See 'does not error if irrelevant (pruned) ops are missing grads' test\n    // in gradients_test.ts for an example.\n    return [];\n  }\n\n  /**\n   * Internal method used by public APIs for tensor creation. Makes a new\n   * tensor with the provided shape, dtype and values. It always\n   * creates a new data id and writes the values to the underlying backend.\n   */\n  makeTensor(\n      values: DataValues, shape: number[], dtype: DataType,\n      backend?: KernelBackend): Tensor {\n    if (values == null) {\n      throw new Error('Values passed to engine.makeTensor() are null');\n    }\n    dtype = dtype || 'float32';\n    backend = backend || this.backend;\n    let backendVals = values as BackendValues;\n    if (dtype === 'string' && util.isString(values[0])) {\n      backendVals = (values as string[]).map(d => util.encodeString(d));\n    }\n    const dataId = backend.write(backendVals, shape, dtype);\n    const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n    this.trackTensor(t, backend);\n\n    // Count bytes for string tensors.\n    if (dtype === 'string') {\n      const info = this.state.tensorInfo.get(dataId);\n      const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n      this.state.numBytes += newBytes - info.bytes;\n      info.bytes = newBytes;\n    }\n    return t;\n  }\n\n  /**\n   * Internal method used by backends. Makes a new tensor\n   * that is a wrapper around an existing data id. It doesn't create\n   * a new data id, only increments the ref count used in memory tracking.\n   * @deprecated\n   */\n  makeTensorFromDataId(\n    dataId: DataId, shape: number[], dtype: DataType,\n    backend?: KernelBackend): Tensor {\n    dtype = dtype || 'float32';\n    const tensorInfo: TensorInfo = {dataId, shape, dtype};\n    return this.makeTensorFromTensorInfo(tensorInfo, backend);\n  }\n\n  /**\n   * Internal method used by backends. Makes a new tensor that is a wrapper\n   * around an existing data id in TensorInfo. It doesn't create a new data id,\n   * only increments the ref count used in memory tracking.\n   */\n  makeTensorFromTensorInfo(tensorInfo: TensorInfo, backend?: KernelBackend):\n      Tensor {\n    const {dataId, shape, dtype} = tensorInfo;\n    const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n    this.trackTensor(t, backend);\n    return t;\n  }\n\n  makeVariable(\n      initialValue: Tensor, trainable = true, name?: string,\n      dtype?: DataType): Variable {\n    name = name || this.nextVariableId().toString();\n    if (dtype != null && dtype !== initialValue.dtype) {\n      initialValue = initialValue.cast(dtype);\n    }\n    const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n    if (this.state.registeredVariables[v.name] != null) {\n      throw new Error(`Variable with name ${v.name} was already registered`);\n    }\n    this.state.registeredVariables[v.name] = v;\n    this.incRef(v, this.backend);\n    return v;\n  }\n\n  trackTensor(a: Tensor, backend: KernelBackend): void {\n    this.state.numTensors++;\n    if (a.dtype === 'string') {\n      this.state.numStringTensors++;\n    }\n    // Bytes for complex numbers are counted by their components. Bytes for\n    // string tensors are counted when writing values.\n    let bytes = 0;\n    if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n      bytes = a.size * util.bytesPerElement(a.dtype);\n    }\n    this.state.numBytes += bytes;\n\n    if (!this.state.tensorInfo.has(a.dataId)) {\n      this.state.numDataBuffers++;\n      this.state.tensorInfo.set(a.dataId, {\n        backend: backend || this.backend,\n        dtype: a.dtype,\n        shape: a.shape,\n        bytes\n      });\n    }\n\n    if (!(a instanceof Variable)) {\n      this.track(a);\n    }\n  }\n\n  // Track the tensor by dataId and increase the refCount for the dataId in the\n  // backend.\n  // TODO(pyu10055): This is currently used by makeVariable method, to increase\n  // refCount on the backend for the dataId. It can potentially be replaced with\n  // Identity op indead of calling backend directly.\n  incRef(a: Tensor, backend: KernelBackend): void {\n    this.trackTensor(a, backend);\n    this.backend.incRef(a.dataId);\n  }\n\n  removeDataId(dataId: DataId, backend: KernelBackend) {\n    if (this.state.tensorInfo.has(dataId) &&\n        this.state.tensorInfo.get(dataId).backend === backend) {\n      this.state.tensorInfo.delete(dataId);\n      this.state.numDataBuffers--;\n    }\n  }\n  disposeTensor(a: Tensor): void {\n    if (!this.state.tensorInfo.has(a.dataId)) {\n      return;\n    }\n    const info = this.state.tensorInfo.get(a.dataId);\n\n    this.state.numTensors--;\n    if (a.dtype === 'string') {\n      this.state.numStringTensors--;\n      this.state.numBytes -= info.bytes;\n    }\n    // Don't count bytes for complex numbers as they are counted by their\n    // components.\n    if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n      const bytes = a.size * util.bytesPerElement(a.dtype);\n      this.state.numBytes -= bytes;\n    }\n\n    // Remove the reference to dataId if backend dispose the data successfully\n    if (info.backend.disposeData(a.dataId)) {\n      this.removeDataId(a.dataId, info.backend);\n    }\n\n    // TODO(nsthorat): Construct an error and save the stack trace for\n    // debugging when in debug mode. Creating a stack trace is too expensive\n    // to do unconditionally.\n  }\n\n  disposeVariables(): void {\n    for (const varName in this.state.registeredVariables) {\n      const v = this.state.registeredVariables[varName];\n      this.disposeVariable(v);\n    }\n  }\n\n  disposeVariable(v: Variable): void {\n    this.disposeTensor(v);\n    if (this.state.registeredVariables[v.name] != null) {\n      delete this.state.registeredVariables[v.name];\n    }\n  }\n\n  memory(): MemoryInfo {\n    const info = this.backend.memory() as MemoryInfo;\n    info.numTensors = this.state.numTensors;\n    info.numDataBuffers = this.state.numDataBuffers;\n    info.numBytes = this.state.numBytes;\n    if (this.state.numStringTensors > 0) {\n      info.unreliable = true;\n      if (info.reasons == null) {\n        info.reasons = [];\n      }\n      info.reasons.push(\n          'Memory usage by string tensors is approximate ' +\n          '(2 bytes per character)');\n    }\n    return info;\n  }\n\n  async profile(query: () => (TensorContainer | Promise<TensorContainer>)):\n      Promise<ProfileInfo> {\n    this.state.profiling = true;\n\n    const startBytes = this.state.numBytes;\n    const startNumTensors = this.state.numTensors;\n\n    this.state.activeProfile.kernels = [];\n    this.state.activeProfile.result = await query();\n\n    this.state.profiling = false;\n\n    this.state.activeProfile.peakBytes = Math.max(\n        ...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));\n    this.state.activeProfile.newBytes = this.state.numBytes - startBytes;\n    this.state.activeProfile.newTensors =\n        this.state.numTensors - startNumTensors;\n    for (const kernel of this.state.activeProfile.kernels) {\n      kernel.kernelTimeMs = await kernel.kernelTimeMs;\n      kernel.extraInfo = await kernel.extraInfo;\n    }\n    return this.state.activeProfile;\n  }\n\n  isTapeOn(): boolean {\n    return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;\n  }\n\n  private addTapeNode(\n      kernelName: string, inputs: NamedTensorMap, outputs: Tensor[],\n      gradientsFunc: GradFunc, saved: Tensor[], attrs: NamedAttrMap): void {\n    const tapeNode: TapeNode =\n        {id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved};\n\n    const gradConfig = getGradient(kernelName);\n    if (gradConfig != null) {\n      gradientsFunc = gradConfig.gradFunc;\n    }\n    if (gradientsFunc != null) {\n      tapeNode.gradient = (dys: Tensor[]) => {\n        // TODO(smilkov): To optimize back-prop, pass dys that are not used in\n        // the backprop graph to the user as null instead of zeros\n        dys = dys.map((dy, i) => {\n          if (dy == null) {\n            const output = outputs[i];\n            const vals = util.makeZerosTypedArray(output.size, output.dtype);\n            return this.makeTensor(vals, output.shape, output.dtype);\n          }\n          return dy;\n        });\n        // Grad functions of ops with single outputs expect a dy, while ops\n        // with multiple outputs expect dys (array of dy).\n        return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);\n      };\n    }\n    this.state.activeTape.push(tapeNode);\n  }\n\n  keep<T extends Tensor>(result: T): T {\n    result.kept = true;\n    return result;\n  }\n\n  private startTape() {\n    if (this.state.gradientDepth === 0) {\n      this.state.activeTape = [];\n    }\n    this.state.gradientDepth++;\n  }\n\n  private endTape() {\n    this.state.gradientDepth--;\n  }\n\n  /**\n   * Start a scope. Use this with endScope() to achieve the same functionality\n   * as scope() without the need for a function closure.\n   */\n  startScope(name?: string) {\n    const scopeInfo: ScopeState = {\n      track: [],\n      name: 'unnamed scope',\n      id: this.state.nextScopeId++\n    };\n    if (name) {\n      scopeInfo.name = name;\n    }\n    this.state.scopeStack.push(scopeInfo);\n    this.state.activeScope = scopeInfo;\n  }\n\n  /**\n   * End a scope. Use this with startScope() to achieve the same functionality\n   * as scope() without the need for a function closure.\n   */\n  endScope(result?: TensorContainer) {\n    const tensorsToTrackInParent = getTensorsInContainer(result);\n    const tensorsToTrackInParentSet =\n        new Set(tensorsToTrackInParent.map(t => t.id));\n\n    // Dispose the arrays tracked in this scope.\n    for (let i = 0; i < this.state.activeScope.track.length; i++) {\n      const tensor = this.state.activeScope.track[i];\n      if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {\n        tensor.dispose();\n      }\n    }\n\n    const oldScope = this.state.scopeStack.pop();\n    this.state.activeScope = this.state.scopeStack.length === 0 ?\n        null :\n        this.state.scopeStack[this.state.scopeStack.length - 1];\n\n    // Track the current result in the parent scope.\n    tensorsToTrackInParent.forEach(tensor => {\n      // Only track the tensor if was allocated in the inner scope and is not\n      // globally kept.\n      if (!tensor.kept && tensor.scopeId === oldScope.id) {\n        this.track(tensor);\n      }\n    });\n  }\n\n  /**\n   * Returns gradients of `f` with respect to each of the `xs`. The gradients\n   * returned are of the same length as `xs`, but some might be null if `f`\n   * was not a function of that `x`. It also takes optional dy to multiply the\n   * gradient, which defaults to `1`.\n   */\n  gradients<T extends Tensor>(\n      f: () => T, xs: Tensor[], dy?: T,\n      allowNoGradients = false): {value: T, grads: Tensor[]} {\n    util.assert(\n        xs.length > 0, () => 'gradients() received an empty list of xs.');\n    if (dy != null && dy.dtype !== 'float32') {\n      throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);\n    }\n\n    const y = this.scopedRun(\n        () => this.startTape(), () => this.endTape(),\n        () => this.tidy('forward', f));\n\n    util.assert(\n        y instanceof Tensor,\n        () => 'The result y returned by f() must be a tensor.');\n    // Filter out the nodes that don't connect x => y.\n    const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);\n    if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {\n      throw new Error(\n          'Cannot compute gradient of y=f(x) with respect to x. Make sure ' +\n          'that the f you passed encloses all operations that lead from x ' +\n          'to y.');\n    }\n\n    return this.tidy('backward', () => {\n      const accumulatedGradientMap: {[tensorId: number]: Tensor} = {};\n      accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;\n\n      // Backprop gradients through the filtered nodes.\n      backpropagateGradients(\n          accumulatedGradientMap, filteredTape,\n          // Pass the tidy function to avoid circular dep with `tape.ts`.\n          f => this.tidy(f as ScopeFn<Tensor>),\n          // Pass an add function to avoide a circular dep with `tape.ts`.\n          add);\n      const grads = xs.map(x => accumulatedGradientMap[x.id]);\n\n      if (this.state.gradientDepth === 0) {\n        // This means that we are not computing higher-order gradients\n        // and can clean up the tape.\n        this.state.activeTape.forEach(node => {\n          for (const tensor of node.saved) {\n            tensor.dispose();\n          }\n        });\n        this.state.activeTape = null;\n      }\n      return {value: y, grads};\n    });\n  }\n\n  customGrad<T extends Tensor>(f: CustomGradientFunc<T>):\n      (...args: Array<Tensor|GradSaveFunc>) => T {\n    util.assert(\n        util.isFunction(f),\n        () => 'The f passed in customGrad(f) must be a function.');\n    return (...inputs: Tensor[]): T => {\n      util.assert(\n          inputs.every(t => t instanceof Tensor),\n          () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +\n              'tensors');\n\n      let res: {\n        value: T,\n        gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[],\n      };\n      const inputMap: NamedTensorMap = {};\n      inputs.forEach((input, i) => {\n        inputMap[i] = input;\n      });\n\n      const forwardFunc: ForwardFunc<T> = (_, save) => {\n        res = f(...[...inputs, save]);\n        util.assert(\n            res.value instanceof Tensor,\n            () => 'The function f passed in customGrad(f) must return an ' +\n                'object where `obj.value` is a tensor');\n        util.assert(\n            util.isFunction(res.gradFunc),\n            () => 'The function f passed in customGrad(f) must return an ' +\n                'object where `obj.gradFunc` is a function.');\n        return res.value;\n      };\n\n      const backwardsFunc = (dy: T, saved: Tensor[]) => {\n        const gradRes = res.gradFunc(dy, saved);\n        const grads: Tensor[] = Array.isArray(gradRes) ? gradRes : [gradRes];\n        util.assert(\n            grads.length === inputs.length,\n            () => 'The function f passed in customGrad(f) must return an ' +\n                'object where `obj.gradFunc` is a function that returns ' +\n                'the same number of tensors as inputs passed to f(...).');\n        util.assert(\n            grads.every(t => t instanceof Tensor),\n            () => 'The function f passed in customGrad(f) must return an ' +\n                'object where `obj.gradFunc` is a function that returns ' +\n                'a list of only tensors.');\n        const gradMap: {[key: string]: () => Tensor} = {};\n        grads.forEach((grad, i) => {\n          gradMap[i] = () => grad;\n        });\n        return gradMap;\n      };\n\n      return this.runKernelFunc({\n        forwardFunc,\n        backwardsFunc,\n        inputs: inputMap,\n      });\n    };\n  }\n\n  readSync(dataId: DataId): BackendValues {\n    // Route the read to the correct backend.\n    const info = this.state.tensorInfo.get(dataId);\n    return info.backend.readSync(dataId);\n  }\n  read(dataId: DataId): Promise<BackendValues> {\n    // Route the read to the correct backend.\n    const info = this.state.tensorInfo.get(dataId);\n    return info.backend.read(dataId);\n  }\n\n  readToGPU(dataId: DataId, options?: DataToGPUOptions): GPUData {\n    // Route the read to the correct backend.\n    const info = this.state.tensorInfo.get(dataId);\n    return info.backend.readToGPU(dataId, options);\n  }\n\n  async time(query: () => void): Promise<TimingInfo> {\n    const start = now();\n    const timingInfo = await this.backend.time(query) as TimingInfo;\n    timingInfo.wallMs = now() - start;\n    return timingInfo;\n  }\n\n  /**\n   * Tracks a Tensor in the current scope to be automatically cleaned up\n   * when the current scope ends, and returns the value.\n   *\n   * @param result The Tensor to track in the current scope.\n   */\n  private track<T extends Tensor>(result: T): T {\n    if (this.state.activeScope != null) {\n      result.scopeId = this.state.activeScope.id;\n      this.state.activeScope.track.push(result);\n    }\n\n    return result;\n  }\n\n  get registeredVariables(): NamedVariableMap {\n    return this.state.registeredVariables;\n  }\n\n  /**\n   * Resets the engine state. Removes all backends but does not remove\n   * registered backend factories.\n   */\n  reset(): void {\n    // Make any pending promise obsolete.\n    this.pendingBackendInitId++;\n\n    this.state.dispose();\n    this.ENV.reset();\n    this.state = new EngineState();\n\n    for (const backendName in this.registry) {\n      this.disposeRegisteredKernels(backendName);\n      this.registry[backendName].dispose();\n      delete this.registry[backendName];\n    }\n    this.backendName = null;\n    this.backendInstance = null;\n    this.pendingBackendInit = null;\n  }\n}\n\nfunction ones(shape: number[]): Tensor {\n  const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n  return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n  const ns = getGlobalNamespace() as unknown as {_tfengine: Engine};\n  if (ns._tfengine == null) {\n    const environment = new Environment(ns);\n    ns._tfengine = new Engine(environment);\n  }\n  setEnvironmentGlobal(ns._tfengine.ENV);\n\n  // Tell the current tensor interface that the global engine is responsible\n  // for tracking.\n  setTensorTracker(() => ns._tfengine);\n  return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n  // We duplicate Add here to avoid a circular dependency with add.ts.\n  const inputs = {a, b};\n  return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {getGlobalTensorClass, Tensor} from './tensor';\nimport {DataType, isWebGLData, isWebGPUData, TensorLike, WebGLData, WebGPUData} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\nimport {bytesPerElement} from './util_base';\n\nexport function inferShape(\n    val: TensorLike|WebGLData|WebGPUData, dtype?: DataType): number[] {\n  let firstElem: typeof val = val;\n\n  if (isTypedArray(val)) {\n    return dtype === 'string' ? [] : [val.length];\n  }\n\n  if (isWebGLData(val)) {\n    const usedChannels = val.channels || 'RGBA';\n    return [val.height, val.width * usedChannels.length];\n  } else if (isWebGPUData(val)) {\n    return [val.buffer.size / (dtype == null ? 4 : bytesPerElement(dtype))];\n  }\n  if (!Array.isArray(val)) {\n    return [];  // Scalar.\n  }\n  const shape: number[] = [];\n\n  while (Array.isArray(firstElem) ||\n         isTypedArray(firstElem) && dtype !== 'string') {\n    shape.push(firstElem.length);\n    firstElem = firstElem[0];\n  }\n  if (Array.isArray(val) &&\n      env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {\n    deepAssertShapeConsistency(val, shape, []);\n  }\n\n  return shape;\n}\n\nfunction deepAssertShapeConsistency(\n    val: TensorLike, shape: number[], indices: number[]) {\n  indices = indices || [];\n  if (!(Array.isArray(val)) && !isTypedArray(val)) {\n    assert(\n        shape.length === 0,\n        () => `Element arr[${indices.join('][')}] is a primitive, ` +\n            `but should be an array/TypedArray of ${shape[0]} elements`);\n    return;\n  }\n  assert(\n      shape.length > 0,\n      () => `Element arr[${indices.join('][')}] should be a primitive, ` +\n          `but is an array of ${val.length} elements`);\n  assert(\n      val.length === shape[0],\n      () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +\n          `elements, but has ${val.length} elements`);\n  const subShape = shape.slice(1);\n  for (let i = 0; i < val.length; ++i) {\n    deepAssertShapeConsistency(val[i], subShape, indices.concat(i));\n  }\n}\n\nfunction assertDtype(\n    expectedDtype: DataType|'numeric'|'string_or_numeric',\n    actualDType: DataType, argName: string, functionName: string) {\n  if (expectedDtype === 'string_or_numeric') {\n    return;\n  }\n  if (expectedDtype == null) {\n    throw new Error(`Expected dtype cannot be null.`);\n  }\n  if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||\n      expectedDtype === 'numeric' && actualDType === 'string') {\n    throw new Error(\n        `Argument '${argName}' passed to '${functionName}' must ` +\n        `be ${expectedDtype} tensor, but got ${actualDType} tensor`);\n  }\n}\n\nexport function convertToTensor<T extends Tensor>(\n    x: T|TensorLike, argName: string, functionName: string,\n    parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T {\n  if (x instanceof getGlobalTensorClass()) {\n    assertDtype(parseAsDtype, x.dtype, argName, functionName);\n    return x;\n  }\n  let inferredDtype = inferDtype(x);\n  // If the user expects a bool/int/float, use that info to update the\n  // inferredDtype when it is not a string.\n  if (inferredDtype !== 'string' &&\n      ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {\n    inferredDtype = parseAsDtype as DataType;\n  }\n  assertDtype(parseAsDtype, inferredDtype, argName, functionName);\n\n  if ((x == null) ||\n      (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&\n       typeof x !== 'boolean' && typeof x !== 'string')) {\n    const type = x == null ? 'null' : (x as {}).constructor.name;\n    throw new Error(\n        `Argument '${argName}' passed to '${functionName}' must be a ` +\n        `Tensor or TensorLike, but got '${type}'`);\n  }\n  const inferredShape = inferShape(x, inferredDtype);\n  if (!isTypedArray(x) && !Array.isArray(x)) {\n    x = [x] as number[];\n  }\n  const skipTypedArray = true;\n  const values = inferredDtype !== 'string' ?\n      toTypedArray(x, inferredDtype as DataType) :\n      flatten(x as string[], [], skipTypedArray) as string[];\n  return ENGINE.makeTensor(values, inferredShape, inferredDtype) as T;\n}\n\nexport function convertToTensorArray<T extends Tensor>(\n    arg: Array<T|TensorLike>, argName: string, functionName: string,\n    parseAsDtype: DataType|'numeric'|'string_or_numeric' = 'numeric'): T[] {\n  if (!Array.isArray(arg)) {\n    throw new Error(\n        `Argument ${argName} passed to ${functionName} must be a ` +\n        '`Tensor[]` or `TensorLike[]`');\n  }\n  const tensors = arg as T[];\n  return tensors.map(\n      (t, i) =>\n          convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype));\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {isPromise} from '../util';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op<T extends Function>(f: {[name: string]: T}): T {\n  const keys = Object.keys(f);\n  if (keys.length !== 1) {\n    throw new Error(\n        `Please provide an object with a single key ` +\n        `(operation name) mapping to a function. Got an object with ` +\n        `${keys.length} keys.`);\n  }\n\n  let opName = keys[0];\n  const fn = f[opName];\n\n  // Strip the underscore from the end of the function name.\n  if (opName.endsWith('_')) {\n    opName = opName.substring(0, opName.length - 1);\n  }\n\n  // add an __op suffix to distinguish ops from kernels in tf.profile\n  opName = opName + OP_SCOPE_SUFFIX;\n\n  // tslint:disable-next-line:no-any\n  const f2 = (...args: any[]) => {\n    ENGINE.startScope(opName);\n    try {\n      const result = fn(...args);\n      if (isPromise(result)) {\n        console.error('Cannot return a Promise inside of tidy.');\n      }\n      ENGINE.endScope(result);\n      return result;\n    } catch (ex) {\n      ENGINE.endScope(null);\n      throw ex;\n    }\n  };\n  Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n  // tslint:disable-next-line:no-any\n  return f2 as any as T;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Abs, AbsInputs, ComplexAbs, ComplexAbsInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes absolute value element-wise: `abs(x)`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.abs().print();  // or tf.abs(x)\n * ```\n * @param x The input `tf.Tensor`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction abs_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'abs');\n\n  if ($x.dtype === 'complex64') {\n    const inputs: ComplexAbsInputs = {x: $x};\n    return ENGINE.runKernel(ComplexAbs, inputs as unknown as NamedTensorMap);\n  } else {\n    const inputs: AbsInputs = {x: $x};\n    return ENGINE.runKernel(Abs, inputs as unknown as NamedTensorMap);\n  }\n}\n\nexport const abs = /* @__PURE__ */ op({abs_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Acos, AcosInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes acos of the input `tf.Tensor` element-wise: `acos(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.acos().print();  // or tf.acos(x)\n * ```\n * @param x The input tensor.\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction acos_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'acos');\n  const inputs: AcosInputs = {x: $x};\n\n  return ENGINE.runKernel(Acos, inputs as unknown as NamedTensorMap);\n}\nexport const acos = /* @__PURE__ */ op({acos_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Acosh, AcoshInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the inverse hyperbolic cos of the input `tf.Tensor` element-wise:\n * `acosh(x)`\n *\n * ```js\n * const x = tf.tensor1d([10, 1, 3, 5.7]);\n *\n * x.acosh().print();  // or tf.acosh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction acosh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'acosh');\n  const inputs: AcoshInputs = {x: $x};\n\n  return ENGINE.runKernel(Acosh, inputs as unknown as NamedTensorMap);\n}\nexport const acosh = /* @__PURE__ */ op({acosh_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Add, AddInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Adds two `tf.Tensor`s element-wise, A + B. Supports broadcasting.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print();  // or tf.add(a, b)\n * ```\n *\n * ```js\n * // Broadcast add a with b.\n * const a = tf.scalar(5);\n * const b = tf.tensor1d([10, 20, 30, 40]);\n *\n * a.add(b).print();  // or tf.add(a, b)\n * ```\n * @param a The first `tf.Tensor` to add.\n * @param b The second `tf.Tensor` to add. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction add_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'add');\n  let $b = convertToTensor(b, 'b', 'add');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: AddInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Add, inputs as unknown as NamedTensorMap);\n}\n\nexport const add = /* @__PURE__ */ op({add_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {AddN, AddNInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Adds a list of `tf.Tensor`s element-wise, each with the same shape and dtype.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n *\n * tf.addN([a, b, c]).print();\n * ```\n * @param tensors A list of tensors with the same shape and dtype.\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction addN_<T extends Tensor>(tensors: Array<T|TensorLike>): T {\n  util.assert(\n      Array.isArray(tensors),\n      () => 'The argument passed to tf.addN() must be a list of tensors');\n  util.assert(\n      tensors.length >= 1,\n      () => `Must pass at least one tensor to tf.addN(), but got ` +\n          `${tensors.length}`);\n\n  const $tensors =\n      tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'addN'));\n\n  const firstTensor = $tensors[0];\n  $tensors.forEach(t => {\n    if (t.dtype !== firstTensor.dtype) {\n      throw new Error(\n          'All tensors passed to tf.addN() must have the same dtype');\n    }\n  });\n\n  $tensors.forEach(t => {\n    if (!util.arraysEqual(t.shape, firstTensor.shape)) {\n      throw new Error(\n          'All tensors passed to tf.addN() must have the same shape');\n    }\n  });\n\n  const inputs: AddNInputs = $tensors;\n\n  return ENGINE.runKernel(AddN, inputs as unknown as NamedTensorMap);\n}\n\nexport const addN = /* @__PURE__ */ op({addN_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {All, AllAttrs, AllInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the logical and of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 1, 1], 'bool');\n *\n * x.all().print();  // or tf.all(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');\n *\n * const axis = 1;\n * x.all(axis).print();  // or tf.all(x, axis)\n * ```\n *\n * @param x The input tensor. Must be of dtype bool.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction all_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'all', 'bool');\n\n  const inputs: AllInputs = {x: $x};\n  const attrs: AllAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      All, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const all = /* @__PURE__ */ op({all_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Any, AnyAttrs, AnyInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the logical or of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 1, 1], 'bool');\n *\n * x.any().print();  // or tf.any(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 1, 0, 0], [2, 2], 'bool');\n *\n * const axis = 1;\n * x.any(axis).print();  // or tf.any(x, axis)\n * ```\n *\n * @param x The input tensor. Must be of dtype bool.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction any_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'any', 'bool');\n\n  const inputs: AnyInputs = {x: $x};\n  const attrs: AnyAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      Any, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\n// tslint:disable-next-line:variable-name\nexport const any = /* @__PURE__ */ op({any_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ArgMax, ArgMaxAttrs, ArgMaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the indices of the maximum values along an `axis`.\n *\n * The result has the same shape as `input` with the dimension along `axis`\n * removed.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.argMax().print();  // or tf.argMax(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);\n *\n * const axis = 1;\n * x.argMax(axis).print();  // or tf.argMax(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction argMax_<T extends Tensor>(x: Tensor|TensorLike, axis = 0): T {\n  const $x = convertToTensor(x, 'x', 'argMax');\n\n  const inputs: ArgMaxInputs = {x: $x};\n  const attrs: ArgMaxAttrs = {axis};\n\n  return ENGINE.runKernel(\n      ArgMax, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const argMax = /* @__PURE__ */ op({argMax_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ArgMin, ArgMinAttrs, ArgMinInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the indices of the minimum values along an `axis`.\n *\n * The result has the same shape as `input` with the dimension along `axis`\n * removed.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.argMin().print();  // or tf.argMin(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 4, 3], [2, 2]);\n *\n * const axis = 1;\n * x.argMin(axis).print();  // or tf.argMin(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension to reduce. Defaults to 0 (outer-most dimension).\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction argMin_<T extends Tensor>(x: Tensor|TensorLike, axis = 0): T {\n  const $x = convertToTensor(x, 'x', 'argMin');\n\n  const inputs: ArgMinInputs = {x: $x};\n  const attrs: ArgMinAttrs = {axis};\n\n  return ENGINE.runKernel(\n      ArgMin, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const argMin = /* @__PURE__ */ op({argMin_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Asin, AsinInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes asin of the input `tf.Tensor` element-wise: `asin(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.asin().print();  // or tf.asin(x)\n * ```\n * @param x The input tensor.\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction asin_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'asin');\n  const inputs: AsinInputs = {x: $x};\n\n  return ENGINE.runKernel(Asin, inputs as unknown as NamedTensorMap);\n}\nexport const asin = /* @__PURE__ */ op({asin_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Asinh, AsinhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes inverse hyperbolic sin of the input `tf.Tensor` element-wise:\n * `asinh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.asinh().print();  // or tf.asinh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction asinh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'asinh');\n\n  const inputs: AsinhInputs = {x: $x};\n\n  return ENGINE.runKernel(Asinh, inputs as unknown as NamedTensorMap);\n}\nexport const asinh = /* @__PURE__ */ op({asinh_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atan, AtanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes atan of the input `tf.Tensor` element-wise: `atan(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.atan().print();  // or tf.atan(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atan_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'atan');\n\n  const inputs: AtanInputs = {x: $x};\n\n  return ENGINE.runKernel(Atan, inputs as unknown as NamedTensorMap);\n}\nexport const atan = /* @__PURE__ */ op({atan_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atan2, Atan2Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes arctangent of `tf.Tensor`s a / b element-wise: `atan2(a, b)`.\n * Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1.0, 1.0, -1.0, .7]);\n * const b = tf.tensor1d([2.0, 13.0, 3.5, .21]);\n *\n * tf.atan2(a, b).print()\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atan2_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'atan2');\n  let $b = convertToTensor(b, 'b', 'atan2');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: Atan2Inputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Atan2, inputs as unknown as NamedTensorMap);\n}\n\nexport const atan2 = /* @__PURE__ */ op({atan2_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Atanh, AtanhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes inverse hyperbolic tan of the input `tf.Tensor` element-wise:\n * `atanh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, .1, -.1, .7]);\n *\n * x.atanh().print();  // or tf.atanh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction atanh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'atanh');\n\n  const inputs: AtanhInputs = {x: $x};\n\n  return ENGINE.runKernel(Atanh, inputs as unknown as NamedTensorMap);\n}\nexport const atanh = /* @__PURE__ */ op({atanh_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_<T extends Tensor>(x: T|TensorLike, dtype: DataType): T {\n  const $x = convertToTensor(x, 'x', 'cast');\n\n  // Sanity checks.\n  if (!util.isValidDtype(dtype)) {\n    throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n  }\n  if (dtype === 'string' && $x.dtype !== 'string' ||\n      dtype !== 'string' && $x.dtype === 'string') {\n    throw new Error('Only strings can be casted to strings');\n  }\n\n  const inputs: CastInputs = {x: $x};\n  const attrs: CastAttrs = {dtype};\n\n  return ENGINE.runKernel(\n      Cast, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const cast = /* @__PURE__ */ op({cast_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\ntype PadType = 'SAME'|'VALID'|'NUMBER'|'EXPLICIT';\n\n// For NHWC should be in the following form:\n//  [[0, 0], [pad_top,pad_bottom], [pad_left, pad_right], [0, 0]]\n// For NCHW should be in the following form:\n//  [[0, 0], [0, 0], [pad_top,pad_bottom], [pad_left, pad_right]]\n// Reference: https://www.tensorflow.org/api_docs/python/tf/nn/conv2d\nexport type ExplicitPadding =\n    [[number, number], [number, number], [number, number], [number, number]];\n\nexport type PadInfo = {\n  top: number,\n  left: number,\n  right: number,\n  bottom: number,\n  type: PadType\n};\n\nexport type PadInfo3D = {\n  top: number,\n  left: number,\n  right: number,\n  bottom: number,\n  front: number,\n  back: number,\n  type: PadType\n};\n\n/**\n * Information about the forward pass of a convolution/pooling operation.\n * It includes input and output shape, strides, filter size and padding\n * information.\n */\nexport type Conv2DInfo = {\n  batchSize: number,\n  inHeight: number,\n  inWidth: number,\n  inChannels: number,\n  outHeight: number,\n  outWidth: number,\n  outChannels: number,\n  dataFormat: 'channelsFirst'|'channelsLast',\n  strideHeight: number,\n  strideWidth: number,\n  dilationHeight: number,\n  dilationWidth: number,\n  filterHeight: number,\n  filterWidth: number,\n  effectiveFilterHeight: number,\n  effectiveFilterWidth: number,\n  padInfo: PadInfo,\n  inShape: [number, number, number, number],\n  outShape: [number, number, number, number],\n  filterShape: [number, number, number, number]\n};\n\n/**\n *\n * @param inputShape Input tensor shape is of the following dimensions:\n *     `[batch, height, width, inChannels]`.\n * @param filterShape The filter shape is of the following dimensions:\n *     `[filterHeight, filterWidth, depth]`.\n * @param strides The strides of the sliding window for each dimension of the\n *     input tensor: `[strideHeight, strideWidth]`.\n *     If `strides` is a single number,\n *     then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1*1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat The data format of the input and output data.\n *     Defaults to 'NHWC'.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`.\n *     Defaults to `[1, 1]`. If `dilations` is a single number, then\n *     `dilationHeight == dilationWidth`.\n */\nexport function computeDilation2DInfo(\n    inputShape: [number, number, number, number],\n    filterShape: [number, number, number], strides: number|[number, number],\n    pad: 'same'|'valid'|number, dataFormat: 'NHWC' = 'NHWC',\n    dilations: number|[number, number]) {\n  // `computerConv2DInfo` require filterShape to be in the dimension of:\n  // `[filterHeight, filterWidth, depth, outDepth]`, dilation2d doesn't have\n  // outDepth, it should have the same depth as the input.\n  // Input shape: [batch, height, width, inChannels]\n  const inputChannels = inputShape[3];\n  const $filterShape =\n      [...filterShape, inputChannels] as [number, number, number, number];\n  const $dataFormat = convertConv2DDataFormat(dataFormat);\n\n  return computeConv2DInfo(\n      inputShape, $filterShape, strides, dilations, pad,\n      null /* roundingMode */, null /* depthWise */, $dataFormat);\n}\n\nexport function computePool2DInfo(\n    inShape: [number, number, number, number],\n    filterSize: [number, number]|number, strides: number|[number, number],\n    dilations: number|[number, number],\n    pad: 'same'|'valid'|number|ExplicitPadding,\n    roundingMode?: 'floor'|'round'|'ceil',\n    dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast'): Conv2DInfo {\n  const [filterHeight, filterWidth] = parseTupleParam(filterSize);\n\n  let filterShape: [number, number, number, number];\n  if (dataFormat === 'channelsLast') {\n    filterShape = [filterHeight, filterWidth, inShape[3], inShape[3]];\n  } else if (dataFormat === 'channelsFirst') {\n    filterShape = [filterHeight, filterWidth, inShape[1], inShape[1]];\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n\n  return computeConv2DInfo(\n      inShape, filterShape, strides, dilations, pad, roundingMode, false,\n      dataFormat);\n}\n\n/**\n * Computes the information for a forward pass of a pooling3D operation.\n */\nexport function computePool3DInfo(\n    inShape: [number, number, number, number, number],\n    filterSize: number|[number, number, number],\n    strides: number|[number, number, number],\n    dilations: number|[number, number, number], pad: 'same'|'valid'|number,\n    roundingMode?: 'floor'|'round'|'ceil',\n    dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): Conv3DInfo {\n  const [filterDepth, filterHeight, filterWidth] = parse3TupleParam(filterSize);\n\n  let filterShape: [number, number, number, number, number];\n  let $dataFormat: 'channelsFirst'|'channelsLast';\n  if (dataFormat === 'NDHWC') {\n    $dataFormat = 'channelsLast';\n    filterShape =\n        [filterDepth, filterHeight, filterWidth, inShape[4], inShape[4]];\n  } else if (dataFormat === 'NCDHW') {\n    $dataFormat = 'channelsFirst';\n    filterShape =\n        [filterDepth, filterHeight, filterWidth, inShape[1], inShape[1]];\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n\n  return computeConv3DInfo(\n      inShape, filterShape, strides, dilations, pad, false, $dataFormat,\n      roundingMode);\n}\n\n/**\n * Computes the information for a forward pass of a convolution/pooling\n * operation.\n */\nexport function computeConv2DInfo(\n    inShape: [number, number, number, number],\n    filterShape: [number, number, number, number],\n    strides: number|[number, number], dilations: number|[number, number],\n    pad: 'same'|'valid'|number|ExplicitPadding,\n    roundingMode?: 'floor'|'round'|'ceil', depthwise = false,\n    dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast'): Conv2DInfo {\n  let [batchSize, inHeight, inWidth, inChannels] = [-1, -1, -1, -1];\n  if (dataFormat === 'channelsLast') {\n    [batchSize, inHeight, inWidth, inChannels] = inShape;\n  } else if (dataFormat === 'channelsFirst') {\n    [batchSize, inChannels, inHeight, inWidth] = inShape;\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n\n  const [filterHeight, filterWidth, , filterChannels] = filterShape;\n  const [strideHeight, strideWidth] = parseTupleParam(strides);\n  const [dilationHeight, dilationWidth] = parseTupleParam(dilations);\n\n  const effectiveFilterHeight =\n      getEffectiveFilterSize(filterHeight, dilationHeight);\n  const effectiveFilterWidth =\n      getEffectiveFilterSize(filterWidth, dilationWidth);\n  const {padInfo, outHeight, outWidth} = getPadAndOutInfo(\n      pad, inHeight, inWidth, strideHeight, strideWidth, effectiveFilterHeight,\n      effectiveFilterWidth, roundingMode, dataFormat);\n\n  const outChannels = depthwise ? filterChannels * inChannels : filterChannels;\n\n  let outShape: [number, number, number, number];\n  if (dataFormat === 'channelsFirst') {\n    outShape = [batchSize, outChannels, outHeight, outWidth];\n  } else if (dataFormat === 'channelsLast') {\n    outShape = [batchSize, outHeight, outWidth, outChannels];\n  }\n\n  return {\n    batchSize,\n    dataFormat,\n    inHeight,\n    inWidth,\n    inChannels,\n    outHeight,\n    outWidth,\n    outChannels,\n    padInfo,\n    strideHeight,\n    strideWidth,\n    filterHeight,\n    filterWidth,\n    effectiveFilterHeight,\n    effectiveFilterWidth,\n    dilationHeight,\n    dilationWidth,\n    inShape,\n    outShape,\n    filterShape\n  };\n}\n\n/**\n * Information about the forward pass of a 3D convolution/pooling operation.\n * It includes input and output shape, strides, filter size and padding\n * information.\n */\nexport type Conv3DInfo = {\n  batchSize: number,\n  inDepth: number,\n  inHeight: number,\n  inWidth: number,\n  inChannels: number,\n  outDepth: number,\n  outHeight: number,\n  outWidth: number,\n  outChannels: number,\n  dataFormat: 'channelsFirst'|'channelsLast',\n  strideDepth: number,\n  strideHeight: number,\n  strideWidth: number,\n  dilationDepth: number,\n  dilationHeight: number,\n  dilationWidth: number,\n  filterDepth: number,\n  filterHeight: number,\n  filterWidth: number,\n  effectiveFilterDepth: number,\n  effectiveFilterHeight: number,\n  effectiveFilterWidth: number,\n  padInfo: PadInfo3D,\n  inShape: [number, number, number, number, number],\n  outShape: [number, number, number, number, number],\n  filterShape: [number, number, number, number, number]\n};\n\n/**\n * Computes the information for a forward pass of a 3D convolution/pooling\n * operation.\n */\nexport function computeConv3DInfo(\n    inShape: [number, number, number, number, number],\n    filterShape: [number, number, number, number, number],\n    strides: number|[number, number, number],\n    dilations: number|[number, number, number], pad: 'same'|'valid'|number,\n    depthwise = false,\n    dataFormat: 'channelsFirst'|'channelsLast' = 'channelsLast',\n    roundingMode?: 'floor'|'round'|'ceil'): Conv3DInfo {\n  let [batchSize, inDepth, inHeight, inWidth, inChannels] =\n      [-1, -1, -1, -1, -1];\n  if (dataFormat === 'channelsLast') {\n    [batchSize, inDepth, inHeight, inWidth, inChannels] = inShape;\n  } else if (dataFormat === 'channelsFirst') {\n    [batchSize, inChannels, inDepth, inHeight, inWidth] = inShape;\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n\n  const [filterDepth, filterHeight, filterWidth, , filterChannels] =\n      filterShape;\n  const [strideDepth, strideHeight, strideWidth] = parse3TupleParam(strides);\n  const [dilationDepth, dilationHeight, dilationWidth] =\n      parse3TupleParam(dilations);\n\n  const effectiveFilterDepth =\n      getEffectiveFilterSize(filterDepth, dilationDepth);\n  const effectiveFilterHeight =\n      getEffectiveFilterSize(filterHeight, dilationHeight);\n  const effectiveFilterWidth =\n      getEffectiveFilterSize(filterWidth, dilationWidth);\n  const {padInfo, outDepth, outHeight, outWidth} = get3DPadAndOutInfo(\n      pad, inDepth, inHeight, inWidth, strideDepth, strideHeight, strideWidth,\n      effectiveFilterDepth, effectiveFilterHeight, effectiveFilterWidth,\n      roundingMode);\n\n  const outChannels = depthwise ? filterChannels * inChannels : filterChannels;\n\n  let outShape: [number, number, number, number, number];\n  if (dataFormat === 'channelsFirst') {\n    outShape = [batchSize, outChannels, outDepth, outHeight, outWidth];\n  } else if (dataFormat === 'channelsLast') {\n    outShape = [batchSize, outDepth, outHeight, outWidth, outChannels];\n  }\n\n  return {\n    batchSize,\n    dataFormat,\n    inDepth,\n    inHeight,\n    inWidth,\n    inChannels,\n    outDepth,\n    outHeight,\n    outWidth,\n    outChannels,\n    padInfo,\n    strideDepth,\n    strideHeight,\n    strideWidth,\n    filterDepth,\n    filterHeight,\n    filterWidth,\n    effectiveFilterDepth,\n    effectiveFilterHeight,\n    effectiveFilterWidth,\n    dilationDepth,\n    dilationHeight,\n    dilationWidth,\n    inShape,\n    outShape,\n    filterShape\n  };\n}\n\nfunction computeOutputShape2D(\n    inShape: [number, number], fieldSize: number, stride: number,\n    zeroPad?: number, roundingMode?: 'floor'|'round'|'ceil'): [number, number] {\n  if (zeroPad == null) {\n    zeroPad = computeDefaultPad(inShape, fieldSize, stride);\n  }\n  const inputRows = inShape[0];\n  const inputCols = inShape[1];\n\n  const outputRows =\n      round((inputRows - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\n  const outputCols =\n      round((inputCols - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\n\n  return [outputRows, outputCols];\n}\n\nfunction computeOutputShape4D(\n    inShape: [number, number, number, number],\n    filterShape: [number, number, number], outChannels: number,\n    strides: [number, number, number], zeroPad?: number,\n    roundingMode?: 'floor'|'round'|'ceil'): [number, number, number, number] {\n  if (zeroPad == null) {\n    zeroPad = computeDefaultPad(inShape, filterShape[0], strides[0]);\n  }\n  const outShape: [number, number, number, number] = [0, 0, 0, outChannels];\n  for (let index = 0; index < 3; index++) {\n    if (inShape[index] + 2 * zeroPad >= filterShape[index]) {\n      outShape[index] = round(\n          (inShape[index] - filterShape[index] + 2 * zeroPad) / strides[index] +\n              1,\n          roundingMode);\n    }\n  }\n  return outShape;\n}\n\nexport function computeDefaultPad(\n    inputShape: [number, number]|[number, number, number, number],\n    fieldSize: number, stride: number, dilation = 1): number {\n  const effectiveFieldSize = getEffectiveFilterSize(fieldSize, dilation);\n  return Math.floor(\n      (inputShape[0] * (stride - 1) - stride + effectiveFieldSize) / 2);\n}\n\nfunction parseTupleParam(param: number|number[]): [number, number, number] {\n  if (typeof param === 'number') {\n    return [param, param, param];\n  }\n  if (param.length === 2) {\n    return [param[0], param[1], 1];\n  }\n  return param as [number, number, number];\n}\n\nfunction parse3TupleParam(param: number|[number, number, number]):\n    [number, number, number] {\n  return typeof param === 'number' ? [param, param, param] : param;\n}\n\n/* See https://www.tensorflow.org/api_docs/python/tf/nn/atrous_conv2d\n * Atrous convolution is equivalent to standard convolution with upsampled\n * filters with effective_filter_height =\n * filter_height + (filter_height - 1) * (dilation - 1)\n * and effective_filter_width =\n * filter_width + (filter_width - 1) * (dilation - 1),\n * produced by inserting dilation - 1 zeros along consecutive elements across\n * the filters' spatial dimensions.\n * When there is a dilation, this converts a filter dimension to the\n * effective filter dimension, so it can be used in a standard convolution.\n */\nfunction getEffectiveFilterSize(filterSize: number, dilation: number) {\n  if (dilation <= 1) {\n    return filterSize;\n  }\n\n  return filterSize + (filterSize - 1) * (dilation - 1);\n}\n\nfunction getPadAndOutInfo(\n    pad: 'same'|'valid'|number|ExplicitPadding, inHeight: number,\n    inWidth: number, strideHeight: number, strideWidth: number,\n    filterHeight: number, filterWidth: number,\n    roundingMode: 'floor'|'round'|'ceil',\n    dataFormat: 'channelsFirst'|\n    'channelsLast'): {padInfo: PadInfo, outHeight: number, outWidth: number} {\n  let padInfo: PadInfo;\n  let outHeight: number;\n  let outWidth: number;\n\n  if (typeof pad === 'number') {\n    const padType = (pad === 0) ? 'VALID' : 'NUMBER';\n    padInfo = {top: pad, bottom: pad, left: pad, right: pad, type: padType};\n    const outShape = computeOutputShape2D(\n        [inHeight, inWidth], filterHeight, strideHeight, pad, roundingMode);\n    outHeight = outShape[0];\n    outWidth = outShape[1];\n  } else if (pad === 'same') {\n    outHeight = Math.ceil(inHeight / strideHeight);\n    outWidth = Math.ceil(inWidth / strideWidth);\n    const padAlongHeight =\n        Math.max(0, (outHeight - 1) * strideHeight + filterHeight - inHeight);\n    const padAlongWidth =\n        Math.max(0, (outWidth - 1) * strideWidth + filterWidth - inWidth);\n    const top = Math.floor(padAlongHeight / 2);\n    const bottom = padAlongHeight - top;\n    const left = Math.floor(padAlongWidth / 2);\n    const right = padAlongWidth - left;\n    padInfo = {top, bottom, left, right, type: 'SAME'};\n  } else if (pad === 'valid') {\n    padInfo = {top: 0, bottom: 0, left: 0, right: 0, type: 'VALID'};\n    outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);\n    outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);\n  } else if (typeof pad === 'object') {\n    const top = dataFormat === 'channelsLast' ? pad[1][0] : pad[2][0];\n    const bottom = dataFormat === 'channelsLast' ? pad[1][1] : pad[2][1];\n    const left = dataFormat === 'channelsLast' ? pad[2][0] : pad[3][0];\n    const right = dataFormat === 'channelsLast' ? pad[2][1] : pad[3][1];\n    const padType = (top === 0 && bottom === 0 && left === 0 && right === 0) ?\n        'VALID' :\n        'EXPLICIT';\n    padInfo = {top, bottom, left, right, type: padType};\n    outHeight = round(\n        (inHeight - filterHeight + top + bottom) / strideHeight + 1,\n        roundingMode);\n    outWidth = round(\n        (inWidth - filterWidth + left + right) / strideWidth + 1, roundingMode);\n  } else {\n    throw Error(`Unknown padding parameter: ${pad}`);\n  }\n  return {padInfo, outHeight, outWidth};\n}\n\nfunction get3DPadAndOutInfo(\n    pad: 'same'|'valid'|number, inDepth: number, inHeight: number,\n    inWidth: number, strideDepth: number, strideHeight: number,\n    strideWidth: number, filterDepth: number, filterHeight: number,\n    filterWidth: number, roundingMode?: 'floor'|'round'|'ceil'): {\n  padInfo: PadInfo3D,\n  outDepth: number,\n  outHeight: number,\n  outWidth: number\n} {\n  let padInfo: PadInfo3D;\n  let outDepth: number;\n  let outHeight: number;\n  let outWidth: number;\n\n  if (pad === 'valid') {\n    pad = 0;\n  }\n\n  if (typeof pad === 'number') {\n    const padType = (pad === 0) ? 'VALID' : 'NUMBER';\n    padInfo = {\n      top: pad,\n      bottom: pad,\n      left: pad,\n      right: pad,\n      front: pad,\n      back: pad,\n      type: padType\n    };\n    const outShape = computeOutputShape4D(\n        [inDepth, inHeight, inWidth, 1],\n        [filterDepth, filterHeight, filterWidth], 1,\n        [strideDepth, strideHeight, strideWidth], pad, roundingMode);\n    outDepth = outShape[0];\n    outHeight = outShape[1];\n    outWidth = outShape[2];\n  } else if (pad === 'same') {\n    outDepth = Math.ceil(inDepth / strideDepth);\n    outHeight = Math.ceil(inHeight / strideHeight);\n    outWidth = Math.ceil(inWidth / strideWidth);\n    const padAlongDepth = (outDepth - 1) * strideDepth + filterDepth - inDepth;\n    const padAlongHeight =\n        (outHeight - 1) * strideHeight + filterHeight - inHeight;\n    const padAlongWidth = (outWidth - 1) * strideWidth + filterWidth - inWidth;\n    const front = Math.floor(padAlongDepth / 2);\n    const back = padAlongDepth - front;\n    const top = Math.floor(padAlongHeight / 2);\n    const bottom = padAlongHeight - top;\n    const left = Math.floor(padAlongWidth / 2);\n    const right = padAlongWidth - left;\n\n    padInfo = {top, bottom, left, right, front, back, type: 'SAME'};\n  } else {\n    throw Error(`Unknown padding parameter: ${pad}`);\n  }\n  return {padInfo, outDepth, outHeight, outWidth};\n}\n\n/**\n * Rounds a value depending on the rounding mode\n * @param value\n * @param roundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n */\nfunction round(value: number, roundingMode?: 'floor'|'round'|'ceil') {\n  if (!roundingMode) {\n    return Math.trunc(value);\n  }\n  switch (roundingMode) {\n    case 'round':\n      // used for Caffe Conv\n      return Math.round(value);\n    case 'ceil':\n      // used for Caffe Pool\n      return Math.ceil(value);\n    case 'floor':\n      return Math.floor(value);\n    default:\n      throw new Error(`Unknown roundingMode ${roundingMode}`);\n  }\n}\n\nexport function tupleValuesAreOne(param: number|number[]): boolean {\n  const [dimA, dimB, dimC] = parseTupleParam(param);\n  return dimA === 1 && dimB === 1 && dimC === 1;\n}\n\nexport function eitherStridesOrDilationsAreOne(\n    strides: number|number[], dilations: number|number[]): boolean {\n  return tupleValuesAreOne(strides) || tupleValuesAreOne(dilations);\n}\n\nexport function stridesOrDilationsArePositive(values: number|\n                                              number[]): boolean {\n  return parseTupleParam(values).every(value => value > 0);\n}\n\n/**\n * Convert Conv2D dataFormat from 'NHWC'|'NCHW' to\n *    'channelsLast'|'channelsFirst'\n * @param dataFormat in 'NHWC'|'NCHW' mode\n * @return dataFormat in 'channelsLast'|'channelsFirst' mode\n * @throws unknown dataFormat\n */\nexport function convertConv2DDataFormat(dataFormat: 'NHWC'|'NCHW'):\n    'channelsLast'|'channelsFirst' {\n  if (dataFormat === 'NHWC') {\n    return 'channelsLast';\n  } else if (dataFormat === 'NCHW') {\n    return 'channelsFirst';\n  } else {\n    throw new Error(`Unknown dataFormat ${dataFormat}`);\n  }\n}\n\n/**\n * Check validity of pad when using dimRoundingMode.\n * @param opDesc A string of op description\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid` output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @throws unknown padding parameter\n */\nexport function checkPadOnDimRoundingMode(\n    opDesc: string, pad: 'valid'|'same'|number|ExplicitPadding,\n    dimRoundingMode?: 'floor'|'round'|'ceil') {\n  if (dimRoundingMode != null) {\n    if (typeof pad === 'string') {\n      throw Error(\n          `Error in ${opDesc}: pad must be an integer when using ` +\n          `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n    } else if (typeof pad === 'number') {\n      util.assert(\n          util.isInt(pad),\n          () => `Error in ${opDesc}: pad must be an integer when using ` +\n              `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n    } else if (typeof pad === 'object') {\n      (pad as ExplicitPadding).forEach(p => {\n        p.forEach(v => {\n          util.assert(\n              util.isInt(v),\n              () => `Error in ${opDesc}: pad must be an integer when using ` +\n                  `dimRoundingMode ${dimRoundingMode} but got pad ${v}.`);\n        });\n      });\n    } else {\n      throw Error(`Error in ${opDesc}: Unknown padding parameter: ${pad}`);\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reshape, ReshapeAttrs, ReshapeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Reshapes a `tf.Tensor` to a given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * If one component of shape is the special value -1, the size of that\n * dimension is computed so that the total size remains constant. In\n * particular, a shape of [-1] flattens into 1-D. At most one component of\n * shape can be -1.\n *\n * If shape is 1-D or higher, then the operation returns a tensor with shape\n * shape filled with the values of tensor. In this case, the number of\n * elements implied by shape must be the same as the number of elements in\n * tensor.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.reshape([2, 2]).print();\n * ```\n *\n * @param x The input tensor to be reshaped.\n * @param shape An array of integers defining the output tensor shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction reshape_<R extends Rank>(\n    x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor<R> {\n  const $x = convertToTensor(x, 'x', 'reshape', 'string_or_numeric');\n\n  const inputs: ReshapeInputs = {x: $x};\n  const attrs: ReshapeAttrs = {shape};\n  return ENGINE.runKernel(\n      Reshape, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\nexport const reshape = /* @__PURE__ */ op({reshape_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {AvgPool, AvgPoolAttrs, AvgPoolInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 2D average pooling of an image.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n *     `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n *     `strides` is a single number, then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm:\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *         https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction avgPool_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filterSize: [number, number]|number,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'avgPool', 'float32');\n  const dilations = 1;\n\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in avgPool: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in avgPool: x must be rank 4 but got rank ${x4D.rank}.`);\n  conv_util.checkPadOnDimRoundingMode('avgPool', pad, dimRoundingMode);\n  const inputs: AvgPoolInputs = {x: x4D};\n  const attrs: AvgPoolAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  let res = ENGINE.runKernel(\n                AvgPool, inputs as unknown as NamedTensorMap,\n                attrs as unknown as NamedAttrMap) as T;\n\n  res = cast(res, $x.dtype);\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n\n  return res;\n}\n\nexport const avgPool = /* @__PURE__ */ op({avgPool_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {AvgPool3D, AvgPool3DAttrs, AvgPool3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {checkPadOnDimRoundingMode} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 3D average pooling.\n *\n * ```js\n * const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);\n * const result = tf.avgPool3d(x, 2, 1, 'valid');\n * result.print();\n * ```\n *\n * @param x The input tensor, of rank 5 or rank 4 of shape\n *     `[batch, depth, height, width, inChannels]`.\n * @param filterSize The filter size:\n *     `[filterDepth, filterHeight, filterWidth]`.\n *     If `filterSize` is a single number,\n *     then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n *     `[strideDepth, strideHeight, strideWidth]`.\n *     If `strides` is a single number,\n *     then `strideDepth == strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1*1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n *     \"NDHWC\". Specify the data format of the input and output data. With the\n *     default format \"NDHWC\", the data is stored in the order of: [batch,\n *     depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction avgPool3d_<T extends Tensor4D|Tensor5D>(\n    x: T|TensorLike, filterSize: [number, number, number]|number,\n    strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n    dimRoundingMode?: 'floor'|'round'|'ceil',\n    dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): T {\n  const $x = convertToTensor(x, 'x', 'avgPool3d', 'float32');\n\n  let x5D = $x as Tensor5D;\n  let reshapedTo5D = false;\n  if ($x.rank === 4) {\n    reshapedTo5D = true;\n    x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n  }\n\n  util.assert(\n      x5D.rank === 5,\n      () => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`);\n  util.assert(\n      dataFormat === 'NDHWC',\n      () => `Error in avgPool3d: Only NDHWC is currently supported, ` +\n          `but got dataFormat of ${dataFormat}`);\n  util.assert(\n      (typeof strides === 'number' && strides > 0) ||\n          (Array.isArray(strides) && strides[0] > 0 && strides[1] > 0 &&\n           strides[2] > 0),\n      () => `Error in avgPool3d: Stride must be > 0, but got '${strides}'`);\n  checkPadOnDimRoundingMode('avgPool3d', pad, dimRoundingMode);\n  const inputs: AvgPool3DInputs = {x: x5D};\n  const attrs:\n      AvgPool3DAttrs = {filterSize, strides, pad, dimRoundingMode, dataFormat};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  let res = ENGINE.runKernel(\n                AvgPool3D, inputs as unknown as NamedTensorMap,\n                attrs as unknown as NamedAttrMap) as T;\n\n  res = cast(res, x5D.dtype);\n\n  if (reshapedTo5D) {\n    return reshape(\n               res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n        T;\n  }\n\n  return res;\n}\n\nexport const avgPool3d = /* @__PURE__ */ op({avgPool3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'clone', 'string_or_numeric');\n  const inputs: IdentityInputs = {x: $x};\n\n  // Note this op is called tf.identity in python. Hence the kernel name used\n  // here.\n  return ENGINE.runKernel(Identity, inputs as unknown as NamedTensorMap);\n}\n\nexport const clone = /* @__PURE__ */ op({clone_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Concat, ConcatAttrs, ConcatInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\n\nimport {clone} from './clone';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor`s along a given axis.\n *\n * The tensors ranks and types must match, and their sizes must match in all\n * dimensions except `axis`.\n *\n * Also available are stricter rank-specific methods that assert that\n * `tensors` are of the given rank:\n *   - `tf.concat1d`\n *   - `tf.concat2d`\n *   - `tf.concat3d`\n *   - `tf.concat4d`\n *\n * Except `tf.concat1d` (which does not have axis param), all methods have\n * same signature as this method.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * a.concat(b).print();  // or a.concat(b)\n * ```\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n * tf.concat([a, b, c]).print();\n * ```\n *\n * ```js\n * const a = tf.tensor2d([[1, 2], [10, 20]]);\n * const b = tf.tensor2d([[3, 4], [30, 40]]);\n * const axis = 1;\n * tf.concat([a, b], axis).print();\n * ```\n * @param tensors A list of tensors to concatenate.\n * @param axis The axis to concatenate along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction concat_<T extends Tensor>(tensors: Array<T|TensorLike>, axis = 0): T {\n  assert(tensors.length >= 1, () => 'Pass at least one tensor to concat');\n\n  const $tensors =\n      convertToTensorArray(tensors, 'tensors', 'concat', 'string_or_numeric');\n\n  if ($tensors[0].dtype === 'complex64') {\n    $tensors.forEach(tensor => {\n      if (tensor.dtype !== 'complex64') {\n        throw new Error(`Cannot concatenate complex64 tensors with a tensor\n          with dtype ${tensor.dtype}. `);\n      }\n    });\n  }\n\n  if ($tensors.length === 1) {\n    return clone($tensors[0]);\n  }\n\n  const inputs: ConcatInputs = $tensors;\n  const attr: ConcatAttrs = {axis};\n\n  return ENGINE.runKernel(\n      Concat, inputs as unknown as NamedTensorMap,\n      attr as unknown as NamedAttrMap);\n}\n\nexport const concat = /* @__PURE__ */ op({concat_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the dot product of two matrices, A * B. These must be matrices.\n *\n * ```js\n * const a = tf.tensor2d([1, 2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.matMul(b).print();  // or tf.matMul(a, b)\n * ```\n * @param a First matrix in dot product operation.\n * @param b Second matrix in dot product operation.\n * @param transposeA If true, `a` is transposed before multiplication.\n * @param transposeB If true, `b` is transposed before multiplication.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction matMul_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike, transposeA = false,\n    transposeB = false): T {\n  let $a = convertToTensor(a, 'a', 'matMul');\n  let $b = convertToTensor(b, 'b', 'matMul');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: BatchMatMulInputs = {a: $a, b: $b};\n  const attrs: BatchMatMulAttrs = {transposeA, transposeB};\n\n  return ENGINE.runKernel(\n      BatchMatMul, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const matMul = /* @__PURE__ */ op({matMul_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multiply, MultiplyInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Multiplies two `tf.Tensor`s element-wise, A * B. Supports broadcasting.\n *\n * We also expose `tf.mulStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.tensor1d([2, 3, 4, 5]);\n *\n * a.mul(b).print();  // or tf.mul(a, b)\n * ```\n *\n * ```js\n * // Broadcast mul a with b.\n * const a = tf.tensor1d([1, 2, 3, 4]);\n * const b = tf.scalar(5);\n *\n * a.mul(b).print();  // or tf.mul(a, b)\n * ```\n * @param a The first tensor to multiply.\n * @param b The second tensor to multiply. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction mul_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'mul');\n  let $b = convertToTensor(b, 'b', 'mul');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: MultiplyInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Multiply, inputs as unknown as NamedTensorMap);\n}\nexport const mul = /* @__PURE__ */ op({mul_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sigmoid, SigmoidInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes sigmoid element-wise, `1 / (1 + exp(-x))`\n *\n * ```js\n * const x = tf.tensor1d([0, -1, 2, -3]);\n *\n * x.sigmoid().print();  // or tf.sigmoid(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sigmoid_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sigmoid', 'float32');\n\n  const inputs: SigmoidInputs = {x: $x};\n\n  return ENGINE.runKernel(Sigmoid, inputs as unknown as NamedTensorMap);\n}\nexport const sigmoid = /* @__PURE__ */ op({sigmoid_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Slice, SliceAttrs, SliceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Extracts a slice from a `tf.Tensor` starting at coordinates `begin`\n * and is of size `size`.\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that `x` is of the given rank:\n *   - `tf.slice1d`\n *   - `tf.slice2d`\n *   - `tf.slice3d`\n *   - `tf.slice4d`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.slice([1], [2]).print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * x.slice([1, 0], [1, 2]).print();\n * ```\n * @param x The input `tf.Tensor` to slice from.\n * @param begin The coordinates to start the slice from. The length can be\n *     less than the rank of x - the rest of the axes will have implicit 0 as\n *     start. Can also be a single number, in which case it specifies the\n *     first axis.\n * @param size The size of the slice. The length can be less than the rank of\n *     x - the rest of the axes will have implicit -1. A value of -1 requests\n *     the rest of the dimensions in the axis. Can also be a single number,\n *     in which case it specifies the size of the first axis.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction slice_<R extends Rank, T extends Tensor<R>>(\n    x: T|TensorLike, begin: number|number[], size?: number|number[]): T {\n  const $x = convertToTensor(x, 'x', 'slice', 'string_or_numeric');\n\n  if ($x.rank === 0) {\n    throw new Error('Slicing scalar is not possible');\n  }\n\n  const inputs: SliceInputs = {x: $x};\n  const attrs: SliceAttrs = {begin, size};\n\n  return ENGINE.runKernel(\n      Slice, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const slice = /* @__PURE__ */ op({slice_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tanh, TanhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic tangent of the input `tf.Tensor` element-wise: `tanh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, 70]);\n *\n * x.tanh().print();  // or tf.tanh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction tanh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'tanh', 'float32');\n\n  const inputs: TanhInputs = {x: $x};\n\n  return ENGINE.runKernel(Tanh, inputs as unknown as NamedTensorMap);\n}\nexport const tanh = /* @__PURE__ */ op({tanh_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {add} from './add';\nimport {concat} from './concat';\nimport {matMul} from './mat_mul';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {sigmoid} from './sigmoid';\nimport {slice} from './slice';\nimport {tanh} from './tanh';\n\n/**\n * Computes the next state and output of a BasicLSTMCell.\n *\n * Returns `[newC, newH]`.\n *\n * Derived from tf.contrib.rnn.BasicLSTMCell.\n *\n * @param forgetBias Forget bias for the cell.\n * @param lstmKernel The weights for the cell.\n * @param lstmBias The bias for the cell.\n * @param data The input to the cell.\n * @param c Previous cell state.\n * @param h Previous cell output.\n *\n * @doc {heading: 'Operations', subheading: 'RNN'}\n */\nfunction basicLSTMCell_(\n    forgetBias: Scalar|TensorLike, lstmKernel: Tensor2D|TensorLike,\n    lstmBias: Tensor1D|TensorLike, data: Tensor2D|TensorLike,\n    c: Tensor2D|TensorLike, h: Tensor2D|TensorLike): [Tensor2D, Tensor2D] {\n  const $forgetBias =\n      convertToTensor(forgetBias, 'forgetBias', 'basicLSTMCell');\n  const $lstmKernel =\n      convertToTensor(lstmKernel, 'lstmKernel', 'basicLSTMCell');\n  const $lstmBias = convertToTensor(lstmBias, 'lstmBias', 'basicLSTMCell');\n  const $data = convertToTensor(data, 'data', 'basicLSTMCell');\n  const $c = convertToTensor(c, 'c', 'basicLSTMCell');\n  const $h = convertToTensor(h, 'h', 'basicLSTMCell');\n\n  const combined = concat([$data, $h], 1);\n  const weighted = matMul(combined, $lstmKernel);\n  const res: Tensor2D = add(weighted, $lstmBias);\n\n  // i = input_gate, j = new_input, f = forget_gate, o = output_gate\n  const batchSize = res.shape[0];\n  const sliceCols = res.shape[1] / 4;\n  const sliceSize: [number, number] = [batchSize, sliceCols];\n  const i = slice(res, [0, 0], sliceSize);\n  const j = slice(res, [0, sliceCols], sliceSize);\n  const f = slice(res, [0, sliceCols * 2], sliceSize);\n  const o = slice(res, [0, sliceCols * 3], sliceSize);\n\n  const newC: Tensor2D =\n      add(mul(sigmoid(i), tanh(j)),\n          mul($c, sigmoid(add($forgetBias, f)) as Tensor2D));\n  const newH: Tensor2D = mul(tanh(newC), sigmoid(o));\n  return [newC, newH];\n}\n\nexport const basicLSTMCell = /* @__PURE__ */ op({basicLSTMCell_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * This operation reshapes the \"batch\" dimension 0 into `M + 1` dimensions of\n * shape `blockShape + [batch]`, interleaves these blocks back into the grid\n * defined by the spatial dimensions `[1, ..., M]`, to obtain a result with\n * the same rank as the input. The spatial dimensions of this intermediate\n * result are then optionally cropped according to `crops` to produce the\n * output. This is the reverse of `tf.spaceToBatchND`. See below for a precise\n * description.\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [4, 1, 1, 1]);\n * const blockShape = [2, 2];\n * const crops = [[0, 0], [0, 0]];\n *\n * x.batchToSpaceND(blockShape, crops).print();\n * ```\n *\n * @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +\n * remainingShape`, where spatialShape has `M` dimensions.\n * @param blockShape A 1-D array. Must have shape `[M]`, all values must\n * be >= 1.\n * @param crops A 2-D array.  Must have shape `[M, 2]`, all values must be >= 0.\n * `crops[i] = [cropStart, cropEnd]` specifies the amount to crop from input\n * dimension `i + 1`, which corresponds to spatial dimension `i`. It is required\n * that `cropStart[i] + cropEnd[i] <= blockShape[i] * inputShape[i + 1]`\n *\n * This operation is equivalent to the following steps:\n *\n * 1. Reshape `x` to `reshaped` of shape: `[blockShape[0], ...,\n * blockShape[M-1], batch / prod(blockShape), x.shape[1], ...,\n * x.shape[N-1]]`\n *\n * 2. Permute dimensions of `reshaped` to produce `permuted` of shape `[batch /\n * prod(blockShape),x.shape[1], blockShape[0], ..., x.shape[M],\n * blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * 3. Reshape `permuted` to produce `reshapedPermuted` of shape `[batch /\n * prod(blockShape),x.shape[1] * blockShape[0], ..., x.shape[M] *\n * blockShape[M-1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * 4. Crop the start and end of dimensions `[1, ..., M]` of `reshapedPermuted`\n * according to `crops` to produce the output of shape: `[batch /\n * prod(blockShape),x.shape[1] * blockShape[0] - crops[0,0] - crops[0,1],\n * ..., x.shape[M] * blockShape[M-1] - crops[M-1,0] -\n * crops[M-1,1],x.shape[M+1], ..., x.shape[N-1]]`\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction batchToSpaceND_<T extends Tensor>(\n    x: T|TensorLike, blockShape: number[], crops: number[][]): T {\n  const $x = convertToTensor(x, 'x', 'batchToSpaceND');\n  const prod = blockShape.reduce((a, b) => a * b);\n\n  util.assert(\n      $x.rank >= 1 + blockShape.length,\n      () => `input rank is ${$x.rank} but should be > than blockShape.length ${\n          blockShape.length}`);\n\n  util.assert(\n      crops.length === blockShape.length,\n      () => `crops.length is ${\n          crops.length} but should be equal to blockShape.length  ${\n          blockShape.length}`);\n\n  util.assert(\n      $x.shape[0] % prod === 0,\n      () => `input tensor batch is ${\n                $x.shape[0]} but is not divisible by the product of ` +\n          `the elements of blockShape ${blockShape.join(' * ')} === ${prod}`);\n\n  const inputs: BatchToSpaceNDInputs = {x: $x};\n  const attrs: BatchToSpaceNDAttrs = {blockShape, crops};\n\n  return ENGINE.runKernel(\n      BatchToSpaceND, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const batchToSpaceND = /* @__PURE__ */ op({batchToSpaceND_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor, Tensor4D} from '../tensor';\nimport {Rank} from '../types';\nimport {reshape} from './reshape';\n\nexport function xAs4D<R extends Rank>(x: Tensor<R>) {\n  let x4D: Tensor4D;\n  if (x.rank === 0 || x.rank === 1) {\n    x4D = reshape(x, [1, 1, 1, x.size]);\n  } else if (x.rank === 2) {\n    x4D = reshape(x, [1, 1, x.shape[0], x.shape[1]]);\n  } else if (x.rank === 3) {\n    x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n  } else {\n    x4D = x as Tensor4D;\n  }\n\n  return x4D;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {xAs4D} from './batchnorm_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Batch normalization.\n *\n * As described in\n * [http://arxiv.org/abs/1502.03167](http://arxiv.org/abs/1502.03167).\n *\n * Mean, variance, scale, and offset can be of two shapes:\n *   - The same shape as the input.\n *   - In the common case, the depth dimension is the last dimension of x, so\n *     the values would be a `tf.Tensor1D` of shape [depth].\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that parameters passed are of given rank\n *   - `tf.batchNorm2d`\n *   - `tf.batchNorm3d`\n *   - `tf.batchNorm4d`\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction batchNorm_<R extends Rank>(\n    x: Tensor<R>|TensorLike, mean: Tensor<R>|Tensor1D|TensorLike,\n    variance: Tensor<R>|Tensor1D|TensorLike,\n    offset?: Tensor<R>|Tensor1D|TensorLike,\n    scale?: Tensor<R>|Tensor1D|TensorLike,\n    varianceEpsilon?: number): Tensor<R> {\n  if (varianceEpsilon == null) {\n    varianceEpsilon = 0.001;\n  }\n  const $x = convertToTensor(x, 'x', 'batchNorm');\n  const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n  const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n  let $scale: Tensor<R>|Tensor1D;\n  if (scale != null) {\n    $scale = convertToTensor(scale, 'scale', 'batchNorm');\n  }\n  let $offset: Tensor<R>|Tensor1D;\n  if (offset != null) {\n    $offset = convertToTensor(offset, 'offset', 'batchNorm');\n  }\n\n  util.assert(\n      $mean.rank === $variance.rank,\n      () => 'Batch normalization gradient requires mean and variance to have ' +\n          'equal ranks.');\n  util.assert(\n      $offset == null || $mean.rank === $offset.rank,\n      () => 'Batch normalization gradient requires mean and offset to have ' +\n          'equal ranks.');\n  util.assert(\n      $scale == null || $mean.rank === $scale.rank,\n      () => 'Batch normalization gradient requires mean and scale to have ' +\n          'equal ranks.');\n\n  const x4D: Tensor4D = xAs4D($x);\n\n  const inputs: FusedBatchNormInputs = {\n    x: x4D,\n    scale: $scale,\n    offset: $offset,\n    mean: $mean,\n    variance: $variance\n  };\n\n  const attrs: FusedBatchNormAttrs = {varianceEpsilon};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  FusedBatchNorm, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as Tensor<R>;\n\n  return reshape(res, $x.shape);\n}\n\nexport const batchNorm = /* @__PURE__ */ op({batchNorm_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 2D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm2d_(\n    x: Tensor2D|TensorLike, mean: Tensor2D|Tensor1D|TensorLike,\n    variance: Tensor2D|Tensor1D|TensorLike,\n    offset?: Tensor2D|Tensor1D|TensorLike, scale?: Tensor2D|Tensor1D|TensorLike,\n    varianceEpsilon?: number): Tensor2D {\n  const $x = convertToTensor(x, 'x', 'batchNorm');\n  const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n  const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n  let $scale: Tensor2D|Tensor1D;\n  if (scale != null) {\n    $scale = convertToTensor(scale, 'scale', 'batchNorm');\n  }\n  let $offset: Tensor2D|Tensor1D;\n  if (offset != null) {\n    $offset = convertToTensor(offset, 'offset', 'batchNorm');\n  }\n  util.assert(\n      $x.rank === 2,\n      () => `Error in batchNorm2D: x must be rank 2 but got rank ` +\n          `${$x.rank}.`);\n  util.assert(\n      $mean.rank === 2 || $mean.rank === 1,\n      () => `Error in batchNorm2D: mean must be rank 2 or rank 1 but ` +\n          `got rank ${$mean.rank}.`);\n  util.assert(\n      $variance.rank === 2 || $variance.rank === 1,\n      () => `Error in batchNorm2D: variance must be rank 2 or rank 1 ` +\n          `but got rank ${$variance.rank}.`);\n  if ($scale != null) {\n    util.assert(\n        $scale.rank === 2 || $scale.rank === 1,\n        () => `Error in batchNorm2D: scale must be rank 2 or rank 1 ` +\n            `but got rank ${$scale.rank}.`);\n  }\n  if ($offset != null) {\n    util.assert(\n        $offset.rank === 2 || $offset.rank === 1,\n        () => `Error in batchNorm2D: offset must be rank 2 or rank 1 ` +\n            `but got rank ${$offset.rank}.`);\n  }\n\n  return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm2d = /* @__PURE__ */ op({batchNorm2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 3D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm3d_(\n    x: Tensor3D|TensorLike, mean: Tensor3D|Tensor1D|TensorLike,\n    variance: Tensor3D|Tensor1D|TensorLike,\n    offset?: Tensor3D|Tensor1D|TensorLike, scale?: Tensor3D|Tensor1D|TensorLike,\n    varianceEpsilon?: number): Tensor3D {\n  const $x = convertToTensor(x, 'x', 'batchNorm');\n  const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n  const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n  let $scale: Tensor3D|Tensor1D;\n  if (scale != null) {\n    $scale = convertToTensor(scale, 'scale', 'batchNorm');\n  }\n  let $offset: Tensor3D|Tensor1D;\n  if (offset != null) {\n    $offset = convertToTensor(offset, 'offset', 'batchNorm');\n  }\n  util.assert(\n      $x.rank === 3,\n      () => `Error in batchNorm3D: x must be rank 3 but got rank ` +\n          `${$x.rank}.`);\n  util.assert(\n      $mean.rank === 3 || $mean.rank === 1,\n      () => `Error in batchNorm3D: mean must be rank 3 or rank 1 but ` +\n          `got rank ${$mean.rank}.`);\n  util.assert(\n      $variance.rank === 3 || $variance.rank === 1,\n      () => `Error in batchNorm3D: variance must be rank 3 or rank 1 ` +\n          `but got rank ${$variance.rank}.`);\n  if ($scale != null) {\n    util.assert(\n        $scale.rank === 3 || $scale.rank === 1,\n        () => `Error in batchNorm3D: scale must be rank 3 or rank 1 ` +\n            `but got rank ${$scale.rank}.`);\n  }\n  if ($offset != null) {\n    util.assert(\n        $offset.rank === 3 || $offset.rank === 1,\n        () => `Error in batchNorm3D: offset must be rank 3 or rank 1 ` +\n            `but got rank ${$offset.rank}.`);\n  }\n\n  return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm3d = /* @__PURE__ */ op({batchNorm3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {batchNorm} from './batchnorm';\nimport {op} from './operation';\n\n/**\n * Batch normalization, strictly for 4D. For the more relaxed version, see\n * `tf.batchNorm`.\n *\n * @param x The input Tensor.\n * @param mean A mean Tensor.\n * @param variance A variance Tensor.\n * @param offset An offset Tensor.\n * @param scale A scale Tensor.\n * @param varianceEpsilon A small float number to avoid dividing by 0.\n */\nfunction batchNorm4d_(\n    x: Tensor4D|TensorLike, mean: Tensor4D|Tensor1D|TensorLike,\n    variance: Tensor4D|Tensor1D|TensorLike,\n    offset?: Tensor4D|Tensor1D|TensorLike, scale?: Tensor4D|Tensor1D|TensorLike,\n    varianceEpsilon?: number): Tensor4D {\n  const $x = convertToTensor(x, 'x', 'batchNorm');\n  const $mean = convertToTensor(mean, 'mean', 'batchNorm');\n  const $variance = convertToTensor(variance, 'variance', 'batchNorm');\n  let $scale: Tensor4D|Tensor1D;\n  if (scale != null) {\n    $scale = convertToTensor(scale, 'scale', 'batchNorm');\n  }\n  let $offset: Tensor4D|Tensor1D;\n  if (offset != null) {\n    $offset = convertToTensor(offset, 'offset', 'batchNorm');\n  }\n  util.assert(\n      $x.rank === 4,\n      () => `Error in batchNorm4D: x must be rank 4 but got rank ` +\n          `${$x.rank}.`);\n  util.assert(\n      $mean.rank === 4 || $mean.rank === 1,\n      () => `Error in batchNorm4D: mean must be rank 4 or rank 1 but ` +\n          `got rank ${$mean.rank}.`);\n  util.assert(\n      $variance.rank === 4 || $variance.rank === 1,\n      () => `Error in batchNorm4D: variance must be rank 4 or rank 1 ` +\n          `but got rank ${$variance.rank}.`);\n  if ($scale != null) {\n    util.assert(\n        $scale.rank === 4 || $scale.rank === 1,\n        () => `Error in batchNorm4D: scale must be rank 4 or rank 1 ` +\n            `but got rank ${$scale.rank}.`);\n  }\n  if ($offset != null) {\n    util.assert(\n        $offset.rank === 4 || $offset.rank === 1,\n        () => `Error in batchNorm4D: offset must be rank 4 or rank 1 ` +\n            `but got rank ${$offset.rank}.`);\n  }\n  return batchNorm($x, $mean, $variance, $offset, $scale, varianceEpsilon);\n}\n\nexport const batchNorm4d = /* @__PURE__ */ op({batchNorm4d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Bincount, BincountAttrs, BincountInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Outputs a vector with length `size` and the same dtype as `weights`.\n *\n * If `weights` are empty, then index `i` stores the number of times the value\n * `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the\n * sum of the value in `weights` at each index where the corresponding value in\n * `x` is `i`.\n *\n * Values in `x` outside of the range [0, size) are ignored.\n *\n * @param x The input int tensor, rank 1.\n * @param weights The weights tensor, must have the same shape as x, or a\n *     length-0 Tensor, in which case it acts as all weights equal to 1.\n * @param size Non-negative integer.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction bincount_<T extends Tensor1D>(\n    x: T|TensorLike, weights: T|TensorLike, size: number): T {\n  const $x = convertToTensor(x, 'x', 'bincount');\n  const $weights = convertToTensor(weights, 'weights', 'bincount');\n\n  util.assert(\n      $x.dtype === 'int32',\n      () => `Error in bincount: input ` +\n          `dtype must be int32, but got ${$x.dtype}`);\n  util.assert(size >= 0, () => `size must be non-negative, but got ${size}.`);\n  util.assert(\n      $weights.size === $x.size || $weights.size === 0,\n      () => `Error in bincount: weights must have the same size as input or` +\n          `0-length, but got input shape: ${$x.shape}, weights shape: ` +\n          `${$weights.shape}.`);\n\n  const inputs: BincountInputs = {x: $x, weights: $weights};\n  const attrs: BincountAttrs = {size};\n\n  return ENGINE.runKernel(\n      Bincount, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const bincount = /* @__PURE__ */ op({bincount_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {BitwiseAnd, BitwiseAndInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank} from '../types';\nimport {arraysEqual} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Bitwise `AND` operation for input tensors.\n *\n * Given two input tensors, returns a new tensor\n * with the `AND` calculated values.\n *\n * The method supports int32 values\n *\n *\n * ```js\n * const x = tf.tensor1d([0, 5, 3, 14], 'int32');\n * const y = tf.tensor1d([5, 0, 7, 11], 'int32');\n * tf.bitwiseAnd(x, y).print();\n * ```\n *\n * @param x The input tensor to be calculated.\n * @param y The input tensor to be calculated.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction bitwiseAnd_<R extends Rank>(x: Tensor, y: Tensor): Tensor<R> {\n  const $x = convertToTensor(x, 'x', 'bitwiseAnd');\n  const $y = convertToTensor(y, 'y', 'bitwiseAnd');\n\n  if (!arraysEqual($x.shape, $y.shape)) {\n    throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${\n        $x.shape}, y: ${$y.shape}`);\n  }\n  if ($x.dtype !== 'int32' || $y.dtype !== 'int32') {\n    throw new Error(\n        `BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${\n            $x.dtype} and type of y: ${$y.dtype}`);\n  }\n\n  const inputs: BitwiseAndInputs = {a: $x, b: $y};\n  return ENGINE.runKernel(BitwiseAnd, inputs as unknown as NamedTensorMap);\n}\nexport const bitwiseAnd = /* @__PURE__ */ op({bitwiseAnd_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { NamedTensorMap } from '../tensor_types';\nimport { ENGINE } from '../engine';\nimport { BroadcastArgs, BroadcastArgsInputs } from '../kernel_names';\nimport { Tensor } from '../tensor';\nimport { convertToTensor } from '../tensor_util_env';\nimport { Rank, TensorLike } from '../types';\n\nimport { op } from './operation';\n\n/**\n * Return the shape of s0 op s1 with broadcast.\n *\n * compute r0, the broadcasted shape as a tensor.\n * s0, s1 and r0 are all integer vectors.\n *\n * This function returns the shape of the result of an operation between\n * two tensors of size s0 and s1 performed with broadcast.\n *\n * @param s0 A tensor representing a shape\n * @param s1 A tensor representing a shape\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction broadcastArgs_<R extends Rank>(\n  s0: Tensor | TensorLike, s1: Tensor | TensorLike): Tensor<R> {\n  const shape1Input = convertToTensor(s0, 's0', 'broadcastArgs', 'int32');\n  const shape2Input = convertToTensor(s1, 's1', 'broadcastArgs', 'int32');\n\n  if (shape1Input.rank !== 1) {\n    throw new Error(\n      'broadcastArgs(): first input must be a vector (rank=1). ' +\n      `Has rank ${shape1Input.rank}`);\n  }\n\n  if (shape2Input.rank !== 1) {\n    throw new Error(\n      'broadcastArgs(): second input must be a vector (rank=1). ' +\n      `Has rank ${shape2Input.rank}`);\n  }\n\n  const inputs: BroadcastArgsInputs = { s0: shape1Input, s1: shape2Input };\n  return ENGINE.runKernel(BroadcastArgs, inputs as unknown as NamedTensorMap);\n}\n\nexport const broadcastArgs = /* @__PURE__ */ op({ broadcastArgs_ });\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tile, TileAttrs, TileInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {clone} from './clone';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Broadcast an array to a compatible shape NumPy-style.\n *\n * The tensor's shape is compared to the broadcast shape from end to beginning.\n * Ones are prepended to the tensor's shape until it has the same length as\n * the broadcast shape. If input.shape[i]==shape[i], the (i+1)-th axis is\n * already broadcast-compatible. If input.shape[i]==1 and shape[i]==N, then\n * the input tensor is tiled N times along that axis (using tf.tile).\n *\n * @param input The tensor that is to be broadcasted.\n * @param shape The input is to be broadcast to this shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction broadcastTo_<R extends Rank>(\n    x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor<R> {\n  let input = convertToTensor(x, 'broadcastTo', 'x');\n  const xShape = input.shape;\n\n  assertNonNegativeIntegerDimensions(shape);\n\n  if (shape.length < input.rank) {\n    throw new Error(`broadcastTo(): shape.length=${shape.length} < input.rank=${\n        input.rank}.`);\n  }\n\n  if (shape.length > input.rank) {\n    const newShape = input.shape.slice();\n    while (newShape.length < shape.length) {\n      newShape.unshift(1);\n    }\n    input = reshape(input, newShape);\n  }\n\n  const inputShape = input.shape;\n  const reps: number[] = Array.from(shape);\n  for (let i = shape.length - 1; i >= 0; i--) {\n    if (inputShape[i] === shape[i]) {\n      reps[i] = 1;\n    } else if (input.shape[i] !== 1) {\n      throw new Error(\n          `broadcastTo(): [${xShape}] cannot be broadcast to [${shape}].`);\n    }\n  }\n  const axes = reps.map((n, i) => n > 1 ? i : -1).filter(i => i >= 0);\n\n  if (axes.length === 0) {\n    return clone(input) as Tensor<R>;\n  }\n\n  // TODO call broadcastTo kernel directly once backends implement broadcstTo\n  const inputs: TileInputs = {x: input};\n  const attrs: TileAttrs = {reps};\n  return ENGINE.runKernel(\n      Tile, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const broadcastTo = /* @__PURE__ */ op({broadcastTo_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer<R extends Rank, D extends DataType = 'float32'>(\n    shape: ShapeMap[R], dtype: D = 'float32' as D,\n    values?: DataTypeMap[D]): TensorBuffer<R, D> {\n  dtype = dtype || 'float32' as D;\n  util.assertNonNegativeIntegerDimensions(shape);\n  return new TensorBuffer<R, D>(shape, dtype, values);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Ceil, CeilInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes ceiling of input `tf.Tensor` element-wise: `ceil(x)`\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.ceil().print();  // or tf.ceil(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction ceil_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'ceil', 'float32');\n\n  const inputs: CeilInputs = {x: $x};\n  return ENGINE.runKernel(Ceil, inputs as unknown as NamedTensorMap);\n}\nexport const ceil = /* @__PURE__ */ op({ceil_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Fill, FillAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {inferDtype} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\n/**\n * Creates a `tf.Tensor` filled with a scalar value.\n *\n * ```js\n * tf.fill([2, 2], 4).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param value The scalar value to fill the tensor with.\n * @param dtype The type of an element in the resulting tensor. Defaults to\n *     'float32' if the given param value is a number, otherwise 'string'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction fill<R extends Rank>(\n    shape: ShapeMap[R], value: number|string, dtype?: DataType): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n\n  dtype = dtype || inferDtype(value);\n  const attrs: FillAttrs = {shape, value, dtype};\n\n  return ENGINE.runKernel(Fill, {}, attrs as unknown as NamedAttrMap);\n}\n\nexport {fill};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {ClipByValue, ClipByValueAttrs, ClipByValueInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {fill} from './fill';\n\nimport {op} from './operation';\n\n/**\n * Clips values element-wise. `max(min(x, clipValueMax), clipValueMin)`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.clipByValue(-2, 3).print();  // or tf.clipByValue(x, -2, 3)\n * ```\n * @param x The input tensor.\n * @param clipValueMin Lower bound of range to be clipped to.\n * @param clipValueMax Upper bound of range to be clipped to.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction clipByValue_<T extends Tensor>(\n    x: T|TensorLike, clipValueMin: number, clipValueMax: number): T {\n  const $x = convertToTensor(x, 'x', 'clipByValue');\n  util.assert(\n      (clipValueMin <= clipValueMax),\n      () => `Error in clip: min (${clipValueMin}) must be ` +\n          `less than or equal to max (${clipValueMax}).`);\n\n  if (clipValueMin === clipValueMax) {\n    return fill($x.shape, clipValueMin, $x.dtype) as T;\n  }\n\n  const inputs: ClipByValueInputs = {x: $x};\n  const attrs: ClipByValueAttrs = {clipValueMin, clipValueMax};\n\n  return ENGINE.runKernel(\n      ClipByValue, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const clipByValue = /* @__PURE__ */ op({clipByValue_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Complex, ComplexInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Converts two real numbers to a complex number.\n *\n * Given a tensor `real` representing the real part of a complex number, and a\n * tensor `imag` representing the imaginary part of a complex number, this\n * operation returns complex numbers elementwise of the form [r0, i0, r1, i1],\n * where r represents the real part and i represents the imag part.\n *\n * The input tensors real and imag must have the same shape.\n *\n * ```js\n * const real = tf.tensor1d([2.25, 3.25]);\n * const imag = tf.tensor1d([4.75, 5.75]);\n * const complex = tf.complex(real, imag);\n *\n * complex.print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction complex_<T extends Tensor>(real: T|TensorLike, imag: T|TensorLike): T {\n  const $real = convertToTensor(real, 'real', 'complex');\n  const $imag = convertToTensor(imag, 'imag', 'complex');\n  util.assertShapesMatch(\n      $real.shape, $imag.shape,\n      `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +\n          `must match in call to tf.complex().`);\n\n  const inputs: ComplexInputs = {real: $real, imag: $imag};\n  return ENGINE.runKernel(Complex, inputs as unknown as NamedTensorMap);\n}\n\nexport const complex = /* @__PURE__ */ op({complex_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of`tf.Tensor1D`s along an axis. See `concat` for details.\n *\n * For example, if:\n * A: shape(3) = |r1, g1, b1|\n * B: shape(2) = |r2, g2|\n * C = tf.concat1d([A, B]) == |r1, g1, b1, r2, g2|\n *\n * @param tensors A list of`tf.Tensor`s to concatenate.\n * @return The concatenated array.\n */\nfunction concat1d_(tensors: Array<Tensor1D|TensorLike>): Tensor1D {\n  return concat(tensors, 0 /* axis */);\n}\n\nexport const concat1d = /* @__PURE__ */ op({concat1d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of`tf.Tensor2D`s along an axis. See `concat` for details.\n *\n * For example, if:\n * A: shape(2, 3) = | r1, g1, b1 |\n *                  | r2, g2, b2 |\n *\n * B: shape(2, 3) = | r3, g3, b3 |\n *                  | r4, g4, b4 |\n *\n * C = tf.concat2d([A, B], axis)\n *\n * if axis = 0:\n * C: shape(4, 3) = | r1, g1, b1 |\n *                  | r2, g2, b2 |\n *                  | r3, g3, b3 |\n *                  | r4, g4, b4 |\n *\n * if axis = 1:\n * C = shape(2, 6) = | r1, g1, b1, r3, g3, b3 |\n *                   | r2, g2, b2, r4, g4, b4 |\n *\n *\n * @param tensors A list of `tf.Tensor`s to concatenate.\n * @param axis The axis to concatenate along.\n * @return The concatenated array.\n */\nfunction concat2d_(\n    tensors: Array<Tensor2D|TensorLike>, axis: number): Tensor2D {\n  return concat(tensors, axis);\n}\n\nexport const concat2d = /* @__PURE__ */ op({concat2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor3D`s along an axis.\n * See `concat` for details.\n *\n * For example, if:\n * A: shape(2, 1, 3) = | r1, g1, b1 |\n *                     | r2, g2, b2 |\n *\n * B: shape(2, 1, 3) = | r3, g3, b3 |\n *                     | r4, g4, b4 |\n *\n * C = tf.concat3d([A, B], axis)\n *\n * if axis = 0:\n * C: shape(4, 1, 3) = | r1, g1, b1 |\n *                     | r2, g2, b2 |\n *                     | r3, g3, b3 |\n *                     | r4, g4, b4 |\n *\n * if axis = 1:\n * C: shape(2, 2, 3) = | r1, g1, b1, r3, g3, b3 |\n *                     | r2, g2, b2, r4, g4, b4 |\n *\n * if axis = 2:\n * C = shape(2, 1, 6) = | r1, g1, b1, r3, g3, b3 |\n *                      | r2, g2, b2, r4, g4, b4 |\n *\n * @param tensors A list of`tf.Tensor`s to concatenate.\n * @param axis The axis to concate along.\n * @return The concatenated array.\n */\nfunction concat3d_(\n    tensors: Array<Tensor3D|TensorLike>, axis: number): Tensor3D {\n  return concat(tensors, axis);\n}\n\nexport const concat3d = /* @__PURE__ */ op({concat3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {concat} from './concat';\nimport {op} from './operation';\n\n/**\n * Concatenates a list of `tf.Tensor4D`s along an axis.\n * See `concat` for details.\n *\n * @param tensors A list of `tf.Tensor`s to concatenate.\n * @param axis The axis to concate along.\n * @return The concatenated array.\n */\nfunction concat4d_(\n    tensors: Array<Tensor4D|TensorLike>, axis: number): Tensor4D {\n  return concat(tensors, axis);\n}\n\nexport const concat4d = /* @__PURE__ */ op({concat4d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2D, Conv2DAttrs, Conv2DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 2D convolution over the input x.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n *     `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels].\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv2d_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filter: Tensor4D|TensorLike,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n    dilations: [number, number]|number = [1, 1],\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'conv2d', 'float32');\n  const $filter = convertToTensor(filter, 'filter', 'conv2d', 'float32');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in conv2d: input must be rank 4, but got rank ${x4D.rank}.`);\n  util.assert(\n      $filter.rank === 4,\n      () => `Error in conv2d: filter must be rank 4, but got rank ` +\n          `${$filter.rank}.`);\n  conv_util.checkPadOnDimRoundingMode('conv2d', pad, dimRoundingMode);\n  const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n  util.assert(\n      inDepth === $filter.shape[2],\n      () => `Error in conv2d: depth of input (${inDepth}) must match ` +\n          `input depth for filter ${$filter.shape[2]}.`);\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in conv2D: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n  util.assert(\n      conv_util.stridesOrDilationsArePositive(dilations),\n      () => 'Error in conv2D: Dilated rates should be larger than 0.');\n  util.assert(\n      conv_util.stridesOrDilationsArePositive(strides),\n      () => 'Error in conv2D: Strides should be larger than 0.');\n\n  const inputs: Conv2DInputs = {x: x4D, filter: $filter};\n  const attrs:\n      Conv2DAttrs = {strides, pad, dataFormat, dilations, dimRoundingMode};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Conv2D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const conv2d = /* @__PURE__ */ op({conv2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D, Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {conv2d} from './conv2d';\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 1D convolution over the input x.\n *\n * @param x The input tensor, of rank 3 or rank 2, of shape\n *     `[batch, width, inChannels]`. If rank 2, batch of 1 is assumed.\n * @param filter The filter, rank 3, of shape\n *     `[filterWidth, inDepth, outDepth]`.\n * @param stride The number of entries by which the filter is moved right at\n *     each step.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat An optional string from \"NWC\", \"NCW\". Defaults to \"NWC\",\n *     the data is stored in the order of [batch, in_width, in_channels]. Only\n *     \"NWC\" is currently supported.\n * @param dilation The dilation rate in which we sample input values in\n *     atrous convolution. Defaults to `1`. If it is greater than 1, then\n *     stride must be `1`.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv1d_<T extends Tensor2D|Tensor3D>(\n    x: T|TensorLike, filter: Tensor3D|TensorLike, stride: number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NWC'|'NCW' = 'NWC', dilation = 1,\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'conv1d');\n  const $filter = convertToTensor(filter, 'filter', 'conv1d');\n\n  let x3D = $x as Tensor3D;\n  let reshapedTo3D = false;\n  if ($x.rank === 2) {\n    reshapedTo3D = true;\n    x3D = reshape($x, [1, $x.shape[0], $x.shape[1]]);\n  }\n\n  util.assert(\n      x3D.rank === 3,\n      () => `Error in conv1d: input must be rank 3, but got rank ${x3D.rank}.`);\n  util.assert(\n      $filter.rank === 3,\n      () => `Error in conv1d: filter must be rank 3, but got rank ` +\n          `${$filter.rank}.`);\n  conv_util.checkPadOnDimRoundingMode('conv1d', pad, dimRoundingMode);\n  util.assert(\n      x3D.shape[2] === $filter.shape[1],\n      () => `Error in conv1d: depth of input (${x3D.shape[2]}) must match ` +\n          `input depth for filter ${$filter.shape[1]}.`);\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(stride, dilation),\n      () => 'Error in conv1D: Either stride or dilation must be 1. ' +\n          `Got stride ${stride} and dilation '${dilation}'`);\n  util.assert(\n      conv_util.stridesOrDilationsArePositive(dilation),\n      () => 'Error in conv1D: Dilated rates should be larger than 0.');\n  util.assert(\n      conv_util.stridesOrDilationsArePositive(stride),\n      () => 'Error in conv1D: Stride should be larger than 0.');\n  util.assert(\n      dataFormat === 'NWC',\n      () => `Error in conv1d: got dataFormat of ${\n          dataFormat} but only NWC is currently supported.`);\n\n  const filter4D = reshape(\n      $filter, [1, $filter.shape[0], $filter.shape[1], $filter.shape[2]]);\n  const input4D = reshape(x3D, [x3D.shape[0], 1, x3D.shape[1], x3D.shape[2]]);\n  const strides: [number, number] = [1, stride];\n  const dilations: [number, number] = [1, dilation];\n\n  const conv2dDataFormat = 'NHWC';\n\n  const res = conv2d(\n      (input4D as Tensor4D), (filter4D as Tensor4D), strides, pad,\n      conv2dDataFormat, dilations, dimRoundingMode);\n\n  if (reshapedTo3D) {\n    return reshape(res, [res.shape[2], res.shape[3]]) as T;\n  }\n\n  return reshape(res, [res.shape[0], res.shape[2], res.shape[3]]) as T;\n}\n\nexport const conv1d = /* @__PURE__ */ op({conv1d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the input of a 2D convolution.\n *\n * @param xShape The shape of the input: [batch, height, width, inDepth].\n * If length of 3, batch of 1 is assumed.\n * @param dy The derivative of the output, of rank 4 or rank 3 of shape\n *   `[batch, outHeight, outWidth, outDepth]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n *     `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm used:\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels].\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n */\nfunction conv2DBackpropInput_<T extends Tensor3D|Tensor4D>(\n    xShape: [number, number, number, number]|[number, number, number], dy: T,\n    filter: Tensor4D, strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  util.assert(\n      xShape.length === dy.rank,\n      () => `Length of inShape ` +\n          `(${xShape.length}) and rank of dy (${dy.rank}) must match`);\n\n  let xShape4D = xShape as [number, number, number, number];\n  let dy4D = dy as Tensor4D;\n  let reshapedTo4D = false;\n  if (dy.rank === 3) {\n    reshapedTo4D = true;\n    dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n    xShape4D = [1, xShape[0], xShape[1], xShape[2]];\n  }\n\n  util.assert(\n      xShape4D.length === 4,\n      () =>\n          `Error in conv2dDerInput: inShape must be length 4, but got length ` +\n          `${xShape4D.length}.`);\n  util.assert(\n      dy4D.rank === 4,\n      () => `Error in conv2dDerInput: dy must be rank 4, but got ` +\n          `rank ${dy4D.rank}`);\n  util.assert(\n      filter.rank === 4,\n      () => `Error in conv2dDerInput: filter must be rank 4, but got ` +\n          `rank ${filter.rank}`);\n  const inDepth = dataFormat === 'NHWC' ? xShape4D[3] : xShape4D[1];\n  const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];\n  util.assert(\n      inDepth === filter.shape[2],\n      () => `Error in conv2dDerInput: depth of input (${inDepth}) must ` +\n          `match input depth for filter ${filter.shape[2]}.`);\n  util.assert(\n      outDepth === filter.shape[3],\n      () => `Error in conv2dDerInput: depth of output (${outDepth}) must ` +\n          `match output depth for filter ${filter.shape[3]}.`);\n  conv_util.checkPadOnDimRoundingMode('conv2dDerInput', pad, dimRoundingMode);\n  const inputs: Conv2DBackpropInputInputs = {dy: dy4D, filter};\n  const attrs: Conv2DBackpropInputAttrs =\n      {strides, pad, dataFormat, dimRoundingMode, inputShape: xShape4D};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Conv2DBackpropInput, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const conv2DBackpropInput = /* @__PURE__ */ op({conv2DBackpropInput_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {conv2DBackpropInput} from './conv2d_backprop_input';\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\n\n/**\n * Computes the transposed 2D convolution of an image, also known as a\n * deconvolution.\n *\n * @param x The input image, of rank 4 or rank 3, of shape\n *   `[batch, height, width, inDepth]`. If rank 3, batch of 1 is assumed.\n * @param filter The filter, rank 4, of shape\n *     `[filterHeight, filterWidth, outDepth, inDepth]`.\n *     `inDepth` must match `inDepth` in `x`.\n * @param outputShape Output shape, of rank 4 or rank 3:\n *     `[batch, height, width, outDepth]`. If rank 3, batch of 1 is assumed.\n * @param strides The strides of the original convolution:\n *     `[strideHeight, strideWidth]`.\n * @param pad  The type of padding algorithm used in the non-transpose version\n *    of the op.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv2dTranspose_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filter: Tensor4D|TensorLike,\n    outputShape: [number, number, number, number]|[number, number, number],\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|ExplicitPadding,\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'conv2dTranspose');\n  const $filter = convertToTensor(filter, 'filter', 'conv2dTranspose');\n\n  return conv2DBackpropInput(\n      outputShape, $x, $filter, strides, pad, 'NHWC', dimRoundingMode);\n}\n\nexport const conv2dTranspose = /* @__PURE__ */ op({conv2dTranspose_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv3D, Conv3DAttrs, Conv3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {eitherStridesOrDilationsAreOne, stridesOrDilationsArePositive} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes a 3D convolution over the input x.\n *\n * @param x The input tensor, of rank 5 or rank 4, of shape\n *     `[batch, depth, height, width, channels]`. If rank 4,\n * batch of 1 is assumed.\n * @param filter The filter, rank 5, of shape\n *     `[filterDepth, filterHeight, filterWidth, inChannels, outChannels]`.\n *      inChannels must match between input and filter.\n * @param strides The strides of the convolution: `[strideDepth, strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat: An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n *     \"NDHWC\". Specify the data format of the input and output data. With the\n *     default format \"NDHWC\", the data is stored in the order of: [batch,\n *     depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @param dilations The dilation rates: `[dilationDepth, dilationHeight,\n *     dilationWidth]` in which we sample input values across the height\n *     and width dimensions in atrous convolution. Defaults to `[1, 1, 1]`.\n *     If `dilations` is a single number, then\n *     `dilationDepth == dilationHeight == dilationWidth`. If it is greater\n *     than 1, then all values of `strides` must be 1.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv3d_<T extends Tensor4D|Tensor5D>(\n    x: T|TensorLike, filter: Tensor5D|TensorLike,\n    strides: [number, number, number]|number, pad: 'valid'|'same',\n    dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC',\n    dilations: [number, number, number]|number = [1, 1, 1]): T {\n  const $x = convertToTensor(x, 'x', 'conv3d');\n  const $filter = convertToTensor(filter, 'filter', 'conv3d');\n\n  let x5D = $x as Tensor5D;\n  let reshapedTo5D = false;\n\n  if ($x.rank === 4) {\n    reshapedTo5D = true;\n    x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n  }\n  util.assert(\n      x5D.rank === 5,\n      () => `Error in conv3d: input must be rank 5, but got rank ${x5D.rank}.`);\n  util.assert(\n      $filter.rank === 5,\n      () => `Error in conv3d: filter must be rank 5, but got rank ` +\n          `${$filter.rank}.`);\n  util.assert(\n      x5D.shape[4] === $filter.shape[3],\n      () => `Error in conv3d: depth of input (${x5D.shape[4]}) must match ` +\n          `input depth for filter ${$filter.shape[3]}.`);\n  util.assert(\n      eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in conv3D: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n  util.assert(\n      dataFormat === 'NDHWC',\n      () => `Error in conv3d: got dataFormat of ${\n          dataFormat} but only NDHWC is currently supported.`);\n  util.assert(\n      stridesOrDilationsArePositive(dilations),\n      () => 'Error in conv3D: Dilated rates should be larger than 0.');\n  util.assert(\n      stridesOrDilationsArePositive(strides),\n      () => 'Error in conv3D: Strides should be larger than 0.');\n\n  const inputs: Conv3DInputs = {x: x5D, filter: $filter};\n\n  const attrs: Conv3DAttrs = {strides, pad, dataFormat, dilations};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Conv3D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo5D) {\n    return reshape(\n               res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n        T;\n  }\n  return res;\n}\n\nexport const conv3d = /* @__PURE__ */ op({conv3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv3DBackpropInputV2, Conv3DBackpropInputV2Attrs, Conv3DBackpropInputV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the input of a 3D convolution.\n *\n * @param xShape The shape of the input: [batch, depth, height, width,\n * in_channels]. If length of 4, batch of 1 is assumed.\n * @param dy The derivative of the output, of rank 5 or rank 4 of shape\n *   `[batch, outDepth, outHeight, outWidth, in_channels]`.\n * If rank 4, batch of 1 is assumed.\n * @param filter The filter, rank 5, of shape\n *     `[filterDepth, filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideDepth, strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm used:\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n */\nfunction conv3DBackpropInput_<T extends Tensor4D|Tensor5D>(\n    xShape:\n        [number, number, number, number,\n         number]|[number, number, number, number],\n    dy: T, filter: Tensor5D, strides: [number, number, number]|number,\n    pad: 'valid'|'same'): T {\n  util.assert(\n      xShape.length === dy.rank,\n      () => `Length of inShape ` +\n          `(${xShape.length}) and rank of dy (${dy.rank}) must match`);\n\n  let xShape5D = xShape as [number, number, number, number, number];\n  let dy5D = dy as Tensor5D;\n  let reshapedTo5D = false;\n  if (dy.rank === 4) {\n    reshapedTo5D = true;\n    dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);\n    xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];\n  }\n\n  const inDepth = xShape5D[4];\n  const outDepth = dy5D.shape[4];\n  util.assert(\n      xShape5D.length === 5,\n      () =>\n          `Error in conv3dDerInput: inShape must be length 5, but got length ` +\n          `${xShape5D.length}.`);\n  util.assert(\n      dy5D.rank === 5,\n      () => `Error in conv3dDerInput: dy must be rank 5, but got ` +\n          `rank ${dy5D.rank}`);\n  util.assert(\n      filter.rank === 5,\n      () => `Error in conv3dDerInput: filter must be rank 5, but got ` +\n          `rank ${filter.rank}`);\n  util.assert(\n      inDepth === filter.shape[3],\n      () => `Error in conv3dDerInput: depth of input (${inDepth}) must ` +\n          `match input depth for filter ${filter.shape[3]}.`);\n  util.assert(\n      outDepth === filter.shape[4],\n      () => `Error in conv3dDerInput: depth of output (${outDepth}) must ` +\n          `match output depth for filter ${filter.shape[4]}.`);\n\n  const inputs: Conv3DBackpropInputV2Inputs = {dy: dy5D, filter};\n\n  const attrs:\n      Conv3DBackpropInputV2Attrs = {pad, strides, inputShape: xShape5D};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Conv3DBackpropInputV2, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo5D) {\n    return reshape(\n               res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n        T;\n  }\n  return res;\n}\n\nexport const conv3DBackpropInput = /* @__PURE__ */ op({conv3DBackpropInput_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {conv3DBackpropInput} from './conv3d_backprop_input';\nimport {op} from './operation';\n\n/**\n * Computes the transposed 3D convolution of a volume, also known as a\n * deconvolution.\n *\n * @param x The input image, of rank 5 or rank 4, of shape\n *   `[batch, depth, height, width, inDepth]`. If rank 4, batch of 1 is assumed.\n * @param filter The filter, rank 4, of shape\n *     `[depth, filterHeight, filterWidth, outDepth, inDepth]`.\n *     `inDepth` must match `inDepth` in `x`.\n * @param outputShape Output shape, of rank 5 or rank 4:\n *     `[batch, depth, height, width, outDepth]`. If rank 3, batch of 1 is\n *    assumed.\n * @param strides The strides of the original convolution:\n *     `[strideDepth, strideHeight, strideWidth]`.\n * @param pad  The type of padding algorithm used in the non-transpose version\n *    of the op.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction conv3dTranspose_<T extends Tensor4D|Tensor5D>(\n    x: T|TensorLike, filter: Tensor5D|TensorLike,\n    outputShape:\n        [number, number, number, number,\n         number]|[number, number, number, number],\n    strides: [number, number, number]|number, pad: 'valid'|'same'): T {\n  const $x = convertToTensor(x, 'x', 'conv3dTranspose');\n  const $filter = convertToTensor(filter, 'filter', 'conv3dTranspose');\n\n  return conv3DBackpropInput(outputShape, $x, $filter, strides, pad);\n}\n\nexport const conv3dTranspose = /* @__PURE__ */ op({conv3dTranspose_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cos, CosInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes cos of the input `tf.Tensor` element-wise: `cos(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.cos().print();  // or tf.cos(x)\n * ```\n * @param x The input tensor. Must be float32 type.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction cos_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'cos', 'float32');\n\n  const inputs: CosInputs = {x: $x};\n\n  return ENGINE.runKernel(Cos, inputs as unknown as NamedTensorMap);\n}\nexport const cos = /* @__PURE__ */ op({cos_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cosh, CoshInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic cos of the input `tf.Tensor` element-wise: `cosh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.cosh().print();  // or tf.cosh(x)\n * ```\n * @param x The input tensor. Must be float32 type.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction cosh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'cosh', 'float32');\n  const inputs: CoshInputs = {x: $x};\n\n  return ENGINE.runKernel(Cosh, inputs as unknown as NamedTensorMap);\n}\nexport const cosh = /* @__PURE__ */ op({cosh_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { ENGINE } from '../engine';\nimport { Cumprod, CumprodAttrs, CumprodInputs } from '../kernel_names';\nimport { NamedAttrMap } from '../kernel_registry';\nimport { Tensor } from '../tensor';\nimport { NamedTensorMap } from '../tensor_types';\nimport { convertToTensor } from '../tensor_util_env';\nimport { TensorLike } from '../types';\n\nimport { op } from './operation';\n\n/**\n * Computes the cumulative product of a `tf.Tensor` along `axis`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4]);\n * x.cumprod().print();\n * ```\n * ```js\n * const x = tf.tensor([[1, 2], [3, 4]]);\n * x.cumprod().print();\n * ```\n *\n * @param x The input tensor to cumulatively multiply.\n * @param axis The axis along which to multiply. Optional. Defaults to 0.\n * @param exclusive Whether to perform exclusive cumulative product. Optional.\n *     Defaults to false. If set to true then the product of each tensor entry\n *     does not include its own value, but only the values previous to it\n *     along the specified axis.\n * @param reverse Whether to multiply in the opposite direction. Optional.\n *     Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Scan'}\n */\nfunction cumprod_<T extends Tensor>(\n  x: Tensor | TensorLike,\n  axis = 0,\n  exclusive = false,\n  reverse = false\n): T {\n  const $x = convertToTensor(x, 'x', 'cumprod');\n\n  const inputs: CumprodInputs = { x: $x };\n  const attrs: CumprodAttrs = { axis, exclusive, reverse };\n\n  return ENGINE.runKernel(\n    Cumprod,\n    inputs as unknown as NamedTensorMap,\n    attrs as unknown as NamedAttrMap\n  );\n}\n\nexport const cumprod = /* @__PURE__ */ op({ cumprod_ });\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Cumsum, CumsumAttrs, CumsumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the cumulative sum of a `tf.Tensor` along `axis`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4]);\n * x.cumsum().print();\n * ```\n * ```js\n * const x = tf.tensor([[1, 2], [3, 4]]);\n * x.cumsum().print();\n * ```\n *\n * @param x The input tensor to be summed.\n * @param axis The axis along which to sum. Optional. Defaults to 0.\n * @param exclusive Whether to perform exclusive cumulative sum. Optional.\n *     Defaults to false. If set to true then the sum of each tensor entry\n *     does not include its own value, but only the values previous to it\n *     along the specified axis.\n * @param reverse Whether to sum in the opposite direction. Optional.\n *     Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Scan'}\n */\nfunction cumsum_<T extends Tensor>(\n    x: Tensor|TensorLike, axis = 0, exclusive = false, reverse = false): T {\n  const $x = convertToTensor(x, 'x', 'cumsum');\n\n  const inputs: CumsumInputs = {x: $x};\n  const attrs: CumsumAttrs = {axis, exclusive, reverse};\n\n  return ENGINE.runKernel(\n      Cumsum, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const cumsum = /* @__PURE__ */ op({cumsum_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {DenseBincount, DenseBincountAttrs, DenseBincountInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Outputs a vector with length `size` and the same dtype as `weights`.\n *\n * If `weights` are empty, then index `i` stores the number of times the value\n * `i` is counted in `x`. If `weights` are non-empty, then index `i` stores the\n * sum of the value in `weights` at each index where the corresponding value in\n * `x` is `i`.\n *\n * Values in `x` outside of the range [0, size) are ignored.\n *\n * @param x The input int tensor, rank 1 or rank 2.\n * @param weights The weights tensor, must have the same shape as x, or a\n *     length-0 Tensor, in which case it acts as all weights equal to 1.\n * @param size Non-negative integer.\n * @param binaryOutput Optional. Whether the kernel should count the appearance\n *     or number of occurrences. Defaults to False.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction denseBincount_<T extends Tensor1D|Tensor2D>(\n    x: T|TensorLike, weights: T|TensorLike, size: number,\n    binaryOutput = false): T {\n  const $x = convertToTensor(x, 'x', 'denseBincount');\n  const $weights = convertToTensor(weights, 'weights', 'denseBincount');\n\n  util.assert(\n      $x.dtype === 'int32',\n      () => `Error in denseBincount: input ` +\n          `dtype must be int32, but got ${$x.dtype}`);\n  util.assert(\n      $x.rank <= 2,\n      () => `Error in denseBincount: input must be at most rank 2, but got ` +\n          `rank ${$x.rank}.`);\n  util.assert(size >= 0, () => `size must be non-negative, but got ${size}.`);\n  util.assert(\n      $weights.size === $x.size || $weights.size === 0,\n      () =>\n          `Error in denseBincount: weights must have the same shape as x or ` +\n          `0-length, but got x shape: ${$x.shape}, weights shape: ` +\n          `${$weights.shape}.`);\n\n  const inputs: DenseBincountInputs = {x: $x, weights: $weights};\n  const attrs: DenseBincountAttrs = {size, binaryOutput};\n\n  return ENGINE.runKernel(\n      DenseBincount, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const denseBincount = /* @__PURE__ */ op({denseBincount_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike4D} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Rearranges data from depth into blocks of spatial data. More specifically,\n * this op outputs a copy of the input tensor where values from the `depth`\n * dimension are moved in spatial blocks to the `height` and `width` dimensions.\n * The attr `blockSize` indicates the input block size and how the data is\n * moved.\n *\n *  - Chunks of data of size `blockSize * blockSize` from depth are rearranged\n * into non-overlapping blocks of size `blockSize x blockSize`\n *\n *  - The width the output tensor is `inputWidth * blockSize`, whereas the\n * height is `inputHeight * blockSize`\n *\n *  - The Y, X coordinates within each block of the output image are determined\n * by the high order component of the input channel index\n *\n *  - The depth of the input tensor must be divisible by `blockSize *\n * blockSize`\n *\n * The `dataFormat` attr specifies the layout of the input and output tensors\n * with the following options: \"NHWC\": [ `batch, height, width, channels` ]\n * \"NCHW\": [ `batch, channels, height, width` ]\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [1, 1, 1, 4]);\n * const blockSize = 2;\n * const dataFormat = \"NHWC\";\n *\n * tf.depthToSpace(x, blockSize, dataFormat).print();\n * ```\n *\n * @param x The input tensor of rank 4\n * @param blockSIze  An `int` that is `>= 2`. The size of the spatial block\n * @param dataFormat An optional string from: \"NHWC\", \"NCHW\". Defaults to \"NHWC\"\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction depthToSpace_(\n    x: Tensor4D|TensorLike4D, blockSize: number,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC'): Tensor4D {\n  const $x = convertToTensor(x, 'x', 'depthToSpace', 'float32') as Tensor4D;\n\n  const inputHeight = (dataFormat === 'NHWC') ? $x.shape[1] : $x.shape[2];\n  const inputWidth = (dataFormat === 'NHWC') ? $x.shape[2] : $x.shape[3];\n  const inputDepth = (dataFormat === 'NHWC') ? $x.shape[3] : $x.shape[1];\n\n  util.assert(\n      blockSize > 1,\n      () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);\n\n  util.assert(\n      inputHeight * blockSize >= 0,\n      () => `Negative dimension size caused by overflow when multiplying\n    ${inputHeight} and ${blockSize}  for depthToSpace with input shape\n    ${$x.shape}`);\n\n  util.assert(\n      inputWidth * blockSize >= 0,\n      () => `Negative dimension size caused by overflow when multiplying\n    ${inputWidth} and ${blockSize} for depthToSpace with input shape\n        ${$x.shape}`);\n\n  util.assert(\n      (inputDepth % (blockSize * blockSize) === 0),\n      () => `Dimension size must be evenly divisible by ${\n          blockSize * blockSize} but is ${\n          inputDepth} for depthToSpace with input shape ${$x.shape}`);\n\n  const inputs: DepthToSpaceInputs = {x: $x};\n  const attrs: DepthToSpaceAttrs = {blockSize, dataFormat};\n\n  return ENGINE.runKernel(\n      DepthToSpace, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const depthToSpace = /* @__PURE__ */ op({depthToSpace_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Depthwise 2D convolution.\n *\n * Given a 4D `input` array and a `filter` array of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing\n * `inChannels` convolutional filters of depth 1, this op applies a\n * different filter to each input channel (expanding from 1 channel to\n * `channelMultiplier` channels for each), then concatenates the results\n * together. The output has `inChannels * channelMultiplier` channels.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](\n *     https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)\n * for more details.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter tensor, rank 4, of shape\n *     `[filterHeight, filterWidth, inChannels, channelMultiplier]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction depthwiseConv2d_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filter: Tensor4D|TensorLike,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n    dilations: [number, number]|number = [1, 1],\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'depthwiseConv2d', 'float32');\n  const $filter =\n      convertToTensor(filter, 'filter', 'depthwiseConv2d', 'float32');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in depthwiseConv2d: input must be rank 4, but got ` +\n          `rank ${x4D.rank}.`);\n  util.assert(\n      $filter.rank === 4,\n      () => `Error in depthwiseConv2d: filter must be rank 4, but got rank ` +\n          `${$filter.rank}.`);\n  const inChannels = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n  util.assert(\n      inChannels === $filter.shape[2],\n      () => `Error in depthwiseConv2d: number of input channels ` +\n          `(${inChannels}) must match the inChannels dimension in ` +\n          `filter ${$filter.shape[2]}.`);\n  conv_util.checkPadOnDimRoundingMode('depthwiseConv2d', pad, dimRoundingMode);\n  const inputs: DepthwiseConv2dNativeInputs = {x: x4D, filter: $filter};\n  const attrs: DepthwiseConv2dNativeAttrs =\n      {strides, pad, dataFormat, dilations, dimRoundingMode};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  DepthwiseConv2dNative, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const depthwiseConv2d = /* @__PURE__ */ op({depthwiseConv2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Diag, DiagInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\n\nimport {op} from './operation';\n\n/**\n * Returns a diagonal tensor with given diagonal values.\n *\n * Given a diagonal, this operation returns a tensor with the diagonal and\n * everything else padded with zeros.\n *\n * Assume the input has dimensions `[D1,..., Dk]`, then the output is a tensor\n * of rank 2k with dimensions `[D1,..., Dk, D1,..., Dk]`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * tf.diag(x).print()\n * ```\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [4, 2])\n *\n * tf.diag(x).print()\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction diag_(x: Tensor): Tensor {\n  const $x = convertToTensor(x, 'x', 'diag');\n\n  const inputs: DiagInputs = {x: $x};\n\n  return ENGINE.runKernel(Diag, inputs as unknown as NamedTensorMap);\n}\n\nexport const diag = /* @__PURE__ */ op({diag_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Dilation2D, Dilation2DAttrs, Dilation2DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the grayscale dilation over the input `x`.\n *\n * @param x The input tensor, rank 3 or rank 4 of shape\n *     `[batch, height, width, depth]`. If rank 3, batch of 1 is assumed.\n * @param filter The filter tensor, rank 3, of shape\n *     `[filterHeight, filterWidth, depth]`.\n * @param strides The strides of the sliding window for each dimension of the\n *     input tensor: `[strideHeight, strideWidth]`.\n *     If `strides` is a single number,\n *     then `strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1*1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat Specify the data format of the input and output data.\n *      Defaults to 'NHWC'. Only 'NHWC' is currently supported. With the\n *      default format \"NHWC\", the data is stored in the order of: [batch,\n *      height, width, channels].\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     for atrous morphological dilation. Defaults to `[1, 1]`. If `dilations`\n *     is a single number, then `dilationHeight == dilationWidth`. If it is\n *     greater than 1, then all values of `strides` must be 1.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction dilation2d_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filter: Tensor3D|TensorLike,\n    strides: [number, number]|number, pad: 'valid'|'same',\n    dilations: [number, number]|number = [1, 1],\n    dataFormat: 'NHWC' = 'NHWC'): T {\n  const $x = convertToTensor(x, 'x', 'dilation2d');\n  const $filter = convertToTensor(filter, 'filter', 'dilation2d');\n\n  util.assert(\n      $x.rank === 3 || $x.rank === 4,\n      () => `Error in dilation2d: input must be rank 3 or 4, but got rank ` +\n          `${$x.rank}.`);\n  util.assert(\n      $filter.rank === 3,\n      () => `Error in dilation2d: filter must be rank 3, but got rank ` +\n          `${$filter.rank}.`);\n  util.assert(\n      dataFormat === 'NHWC',\n      () => `Error in dilation2d: Only NHWC is currently supported, ` +\n          `but got dataFormat of ${dataFormat}`);\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n\n  if ($x.rank === 3) {\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n    reshapedTo4D = true;\n  }\n\n  util.assert(\n      x4D.shape[3] === $filter.shape[2],\n      () => `Error in dilation2d:  input and filter must have the same depth: ${\n          x4D.shape[3]} vs ${$filter.shape[2]}`);\n\n  const inputs: Dilation2DInputs = {x: x4D, filter: $filter};\n  const attrs: Dilation2DAttrs = {strides, pad, dilations};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Dilation2D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n\n  return res;\n}\n\nexport const dilation2d = /* @__PURE__ */ op({dilation2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FloorDiv, FloorDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n * The result is rounded with floor function.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.floorDiv(b).print();  // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.floorDiv(b).print();  // or tf.floorDiv(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction floorDiv_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'floorDiv');\n  let $b = convertToTensor(b, 'b', 'floorDiv');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: FloorDivInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(FloorDiv, inputs as unknown as NamedTensorMap);\n}\n\nexport const floorDiv = /* @__PURE__ */ op({floorDiv_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RealDiv, RealDivInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {floorDiv} from './floorDiv';\nimport {op} from './operation';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.div(b).print();  // or tf.div(a, b)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n *\n * a.div(b).print();  // or tf.div(a, b)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction div_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'div');\n  let $b = convertToTensor(b, 'b', 'div');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  if ($a.dtype === 'int32' && $b.dtype === 'int32') {\n    return floorDiv($a, $b);\n  }\n\n  const inputs: RealDivInputs = {a: $a, b: $b};\n  const attrs = {};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(RealDiv,\n                          inputs as unknown as NamedTensorMap, attrs) as T;\n}\n\nexport const div = /* @__PURE__ */ op({div_});\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Returns the dimensions in the input shape that are broadcasted to\n * produce the provided output shape.\n *\n * The returned dimensions are 0-indexed and sorted. An example:\n * inShape = [4, 1, 3]\n * outShape = [5, 4, 3, 3]\n * result = [1]. Dimension 1 (2nd dimension of input) gets broadcasted 1 => 3.\n */\nexport function getBroadcastDims(\n    inShape: number[], outShape: number[]): number[] {\n  const inRank = inShape.length;\n  const dims: number[] = [];\n  for (let i = 0; i < inRank; i++) {\n    const dim = inRank - 1 - i;\n    const a = inShape[dim] || 1;\n    const b = outShape[outShape.length - 1 - i] || 1;\n    if (b > 1 && a === 1) {\n      dims.unshift(dim);\n    }\n  }\n  return dims;\n}\n\n/**\n * Returns the axes in the output space that should be reduced to produce\n * the input space.\n */\nexport function getReductionAxes(\n    inShape: number[], outShape: number[]): number[] {\n  const result: number[] = [];\n  for (let i = 0; i < outShape.length; i++) {\n    const inDim = inShape[inShape.length - i - 1];\n    const outAxis = outShape.length - i - 1;\n    const outDim = outShape[outAxis];\n    if (inDim == null || (inDim === 1 && outDim > 1)) {\n      result.unshift(outAxis);\n    }\n  }\n  return result;\n}\n\nexport function assertAndGetBroadcastShape(\n    shapeA: number[], shapeB: number[]): number[] {\n  const l = Math.max(shapeA.length, shapeB.length);\n  const result = new Array(l);\n\n  for (let i = 0; i < l; i++) {\n    let a = shapeA[shapeA.length - i - 1];\n    if (a == null) {\n      a = 1;\n    }\n    let b = shapeB[shapeB.length - i - 1];\n    if (b == null) {\n      b = 1;\n    }\n    if (a === 1) {\n      result[l - i - 1] = b;\n    } else if (b === 1) {\n      result[l - i - 1] = a;\n    } else if (a !== b) {\n      const errMsg = `Operands could not be broadcast together with shapes ` +\n          `${shapeA} and ${shapeB}.`;\n      throw Error(errMsg);\n    } else {\n      result[l - i - 1] = a;\n    }\n  }\n  return result;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Equal, EqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a == b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.equal(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction equal_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'equal', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'equal', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: EqualInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Equal, inputs as unknown as NamedTensorMap);\n}\n\nexport const equal = /* @__PURE__ */ op({equal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Select, SelectInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {broadcastTo} from './broadcast_to';\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the elements, either `a` or `b` depending on the `condition`.\n *\n * If the condition is true, select from `a`, otherwise select from `b`.\n *\n * ```js\n * const cond = tf.tensor1d([false, false, true], 'bool');\n * const a = tf.tensor1d([1 , 2, 3]);\n * const b = tf.tensor1d([-1, -2, -3]);\n *\n * a.where(cond, b).print();\n * ```\n *\n * @param condition The input condition. Must be of dtype bool.\n * @param a If `condition` is rank 1, `a` may have a higher rank but\n *     its first dimension must match the size of `condition`.\n * @param b A tensor with the same dtype as `a` and with shape that is\n *     compatible with `a`.\n * @return A tensor with same dtype as `a` and `b`, and shape that is\n *     broadcastable from `a` and `b`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction where_<T extends Tensor>(\n    condition: Tensor|TensorLike, a: T|TensorLike, b: T|TensorLike): T {\n  const $a = convertToTensor(a, 'a', 'where');\n  const $b = convertToTensor(b, 'b', 'where');\n  const $condition = convertToTensor(condition, 'condition', 'where', 'bool');\n  // TODO: move this logic to forward function when the broadcastTo op is\n  // implemented in WASM.\n  // Find the broadcastable shape for $condition, $a, and $b.\n  const broadcastShape = assertAndGetBroadcastShape(\n      assertAndGetBroadcastShape($condition.shape, $a.shape), $b.shape);\n  const $broadcastedCondition = broadcastTo($condition, broadcastShape);\n  const $broadcastedA = broadcastTo($a, broadcastShape);\n  const $broadcastedB = broadcastTo($b, broadcastShape);\n\n  const inputs: SelectInputs = {\n    condition: $broadcastedCondition,\n    t: $broadcastedA,\n    e: $broadcastedB\n  };\n  return ENGINE.runKernel(Select, inputs as unknown as NamedTensorMap);\n}\n\nexport const where = /* @__PURE__ */ op({where_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ZerosLike, ZerosLikeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0 with the same shape as the\n * given tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n * tf.zerosLike(x).print();\n * ```\n *\n * @param x The tensor of required shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction zerosLike_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'zerosLike');\n  const inputs: ZerosLikeInputs = {x: $x};\n  return ENGINE.runKernel(ZerosLike, inputs as unknown as NamedTensorMap);\n}\nexport const zerosLike = /* @__PURE__ */ op({zerosLike_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {div} from './div';\nimport {equal} from './equal';\nimport {op} from './operation';\nimport {where} from './where';\nimport {zerosLike} from './zeros_like';\n\n/**\n * Divides two `tf.Tensor`s element-wise, A / B. Supports broadcasting. Return 0\n * if denominator is 0.\n *\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 9, 16]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n * const c = tf.tensor1d([0, 0, 0, 0]);\n *\n * a.divNoNan(b).print();  // or tf.divNoNan(a, b)\n * a.divNoNan(c).print();  // or tf.divNoNan(a, c)\n * ```\n *\n * ```js\n * // Broadcast div a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(2);\n * const c = tf.scalar(0);\n *\n * a.divNoNan(b).print();  // or tf.divNoNan(a, b)\n * a.divNoNan(c).print();  // or tf.divNoNan(a, c)\n * ```\n *\n * @param a The first tensor as the numerator.\n * @param b The second tensor as the denominator. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction divNoNan_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  // TODO: Make this into its own kernel.\n  let $a = convertToTensor(a, 'a', 'div');\n  let $b = convertToTensor(b, 'b', 'div');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const divResult = div($a, $b);\n  const zeros = zerosLike(divResult);\n  const bEqualsZero = equal($b, zeros);\n  return where(bEqualsZero, zeros, divResult) as T;\n}\n\nexport const divNoNan = /* @__PURE__ */ op({divNoNan_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor,} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {matMul} from './mat_mul';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the dot product of two matrices and/or vectors, `t1` and `t2`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor2d([[1, 2], [3, 4]]);\n * const c = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n *\n * a.dot(b).print();  // or tf.dot(a, b)\n * b.dot(a).print();\n * b.dot(c).print();\n * ```\n * @param t1 The first tensor in the dot operation.\n * @param t2 The second tensor in the dot operation.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction dot_(t1: Tensor|TensorLike, t2: Tensor|TensorLike): Tensor {\n  const $t1 = convertToTensor(t1, 't1', 'dot');\n  const $t2 = convertToTensor(t2, 't2', 'dot');\n\n  util.assert(\n      ($t1.rank === 1 || $t1.rank === 2) && ($t2.rank === 1 || $t2.rank === 2),\n      () => `Error in dot: inputs must all be rank 1 or 2, but got ranks ` +\n          `${$t1.rank} and ${$t2.rank}.`);\n\n  const t1Inner = ($t1.rank === 1 ? $t1.size : $t1.shape[1]);\n  const t2Inner = ($t2.rank === 1 ? $t2.size : $t2.shape[0]);\n\n  util.assert(\n      t1Inner === t2Inner,\n      () => `Error in dot: inner dimensions of inputs must match, but got ` +\n          `${t1Inner} and ${t2Inner}.`);\n\n  if ($t1.rank === 1 && $t2.rank === 1) {\n    const t12D = reshape($t1, [1, -1]);\n    const t22D = reshape($t2, [-1, 1]);\n    const t1t2 = matMul(t12D, t22D);\n    return reshape(t1t2, []);\n  } else if ($t1.rank === 1 && $t2.rank === 2) {\n    const t12D = reshape($t1, [1, -1]);\n    const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);\n    const t1t2 = matMul(t12D, t22D);\n    return reshape(t1t2, [t1t2.size]);\n  } else if ($t1.rank === 2 && $t2.rank === 1) {\n    const t22D = reshape($t2, [-1, 1]);\n    const t1t2 = matMul($t1, t22D);\n    return reshape(t1t2, [t1t2.size]);\n  } else {\n    const t22D = reshape($t2, [$t2.shape[0], $t2.shape[1]]);\n    const t1t2 = matMul($t1, t22D);\n    return t1t2;\n  }\n}\n\nexport const dot = /* @__PURE__ */ op({dot_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Einsum, EinsumAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\n\nimport {op} from './operation';\n\n/**\n * Tensor contraction over specified indices and outer product.\n *\n * `einsum` allows defining Tensors by defining their element-wise computation.\n * This computation is based on\n * [Einstein summation](https://en.wikipedia.org/wiki/Einstein_notation).\n *\n * Some special cases include:\n *\n * Matrix multiplication:\n * ```js\n * const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n * const y = tf.tensor2d([[0, 1], [2, 3], [4, 5]]);\n * x.print();\n * y.print();\n * tf.einsum('ij,jk->ik', x, y).print();\n * ```\n *\n * Dot product:\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n * const y = tf.tensor1d([0, 1, 2]);\n * x.print();\n * y.print();\n * tf.einsum('i,i->', x, y).print();\n * ```\n *\n * Batch dot product:\n * ```js\n * const x = tf.tensor2d([[1, 2, 3], [4, 5, 6]]);\n * const y = tf.tensor2d([[0, 1, 2], [3, 4, 5]]);\n * x.print();\n * y.print();\n * tf.einsum('bi,bi->b', x, y).print();\n * ```\n *\n * Outer prouduct:\n * ```js\n * const x = tf.tensor1d([1, 3, 5]);\n * const y = tf.tensor1d([2, 4, 6]);\n * x.print();\n * y.print();\n * tf.einsum('i,j->ij', x, y).print();\n * ```\n *\n * Matrix transpose:\n * ```js\n * const x = tf.tensor2d([[1, 2], [3, 4]]);\n * x.print();\n * tf.einsum('ij->ji', x).print();\n * ```\n *\n * Batch matrix transpose:\n * ```js\n * const x = tf.tensor3d([[[1, 2], [3, 4]], [[-1, -2], [-3, -4]]]);\n * x.print();\n * tf.einsum('bij->bji', x).print();\n * ```\n *\n * Limitations:\n *\n * This implementation of einsum has the following limitations:\n *\n * - Does not support >2 input tensors.\n * - Does not support duplicate axes for any given input tensor. E.g., equation\n *   'ii->' is not supported.\n * - The `...` notation is not supported.\n *\n * @param equation a string describing the contraction, in the same format as\n * [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html).\n * @param tensors the input(s) to contract (each one a Tensor), whose shapes\n *     should be consistent with equation.\n * @returns The output tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Matrices'}\n */\nexport function einsum_(equation: string, ...tensors: Tensor[]): Tensor {\n  const $tensors =\n      tensors.map((t, i) => convertToTensor(t, `tensors${i}`, 'einsum'));\n  const attrs: EinsumAttrs = {equation};\n  return ENGINE.runKernel(\n      Einsum, $tensors as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const einsum = /* @__PURE__ */ op({einsum_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Elu, EluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential linear element-wise: `x > 0 ? x : (e ^ x) - 1`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 1, -3, 2]);\n *\n * x.elu().print();  // or tf.elu(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction elu_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'elu', 'float32');\n\n  const inputs: EluInputs = {x: $x};\n\n  return ENGINE.runKernel(Elu, inputs as unknown as NamedTensorMap);\n}\n\nexport const elu = /* @__PURE__ */ op({elu_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap} from '../types';\nimport {arraysEqualWithNull} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Checks the input tensor mathes the given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * The method supports the null value in tensor. It will still check the shapes,\n * and null is a placeholder.\n *\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const y = tf.tensor1d([1, null, 3, 4]);\n * const z = tf.tensor2d([1, 2, 3, 4], [2,2]);\n * tf.ensureShape(x, [4]).print();\n * tf.ensureShape(y, [4]).print();\n * tf.ensureShape(z, [null, 2]).print();\n * ```\n *\n * @param x The input tensor to be ensured.\n * @param shape A TensorShape representing the shape of this tensor, an array\n *     or null.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction ensureShape_<R extends Rank>(x: Tensor, shape: ShapeMap[R]): Tensor {\n  const $x = convertToTensor(x, 'x', 'ensureShape', 'string_or_numeric');\n  if (!arraysEqualWithNull($x.shape, shape)) {\n    throw new Error(`EnsureShape: Shape of tensor ${\n        $x.shape} is not compatible with expected shape ${shape}`);\n  }\n\n  return x;\n}\nexport const ensureShape = /* @__PURE__ */ op({ensureShape_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Erf, ErfInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes Gauss error function of the input `tf.Tensor` element-wise:\n * `erf(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, .1, -.1, .7]);\n *\n * x.erf().print(); // or tf.erf(x);\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction erf_<T extends Tensor>(x: T|TensorLike): T {\n  let $x = convertToTensor(x, 'x', 'erf');\n  util.assert(\n      $x.dtype === 'int32' || $x.dtype === 'float32',\n      () => 'Input dtype must be `int32` or `float32`.');\n\n  if ($x.dtype === 'int32') {\n    $x = cast($x, 'float32');\n  }\n\n  const inputs: ErfInputs = {x: $x};\n  return ENGINE.runKernel(Erf, inputs as unknown as NamedTensorMap);\n}\nexport const erf = /* @__PURE__ */ op({erf_});\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as util from '../util';\n\n/**\n * Returns true if the axis specifies the inner most dimensions of the\n * array.\n */\nexport function axesAreInnerMostDims(axes: number[], rank: number): boolean {\n  for (let i = 0; i < axes.length; ++i) {\n    if (axes[axes.length - i - 1] !== rank - 1 - i) {\n      return false;\n    }\n  }\n  return true;\n}\n\nexport function combineLocations(\n    outputLoc: number[], reduceLoc: number[], axes: number[]): number[] {\n  const rank = outputLoc.length + reduceLoc.length;\n  const loc = [];\n  let outIdx = 0;\n  let reduceIdx = 0;\n    for (let dim = 0; dim < rank; dim++) {\n    if (axes.indexOf(dim) === -1) {\n      loc.push(outputLoc[outIdx++]);\n    } else {\n      loc.push(reduceLoc[reduceIdx++]);\n    }\n  }\n  return loc;\n}\n\nexport function computeOutAndReduceShapes(\n    aShape: number[], axes: number[]): [number[], number[]] {\n  const outShape = [];\n  const rank = aShape.length;\n  for (let dim = 0; dim < rank; dim++) {\n    if (axes.indexOf(dim) === -1) {\n      outShape.push(aShape[dim]);\n    }\n  }\n  const reduceShape = axes.map(dim => aShape[dim]);\n  return [outShape, reduceShape];\n}\n\nexport function expandShapeToKeepDim(\n    shape: number[], axes: number[]): number[] {\n  const reduceSubShape = axes.map(x => 1);\n  return combineLocations(shape, reduceSubShape, axes);\n}\n\nexport function assertAxesAreInnerMostDims(\n    msg: string, axes: number[], rank: number): void {\n  util.assert(\n      axesAreInnerMostDims(axes, rank),\n      () => `${msg} supports only inner-most axes for now. ` +\n          `Got axes ${axes} and rank-${rank} input.`);\n}\n\n/**\n * Returns the axes permutation to be used with `tf.transpose`, if such\n * permutation is necessary. Otherwise it returns null. This method is used by\n * operations that operate only on inner-most axes.\n */\nexport function getAxesPermutation(axes: number[], rank: number): number[]|\n    null {\n  if (axesAreInnerMostDims(axes, rank)) {\n    return null;\n  }\n  const result: number[] = [];\n  for (let i = 0; i < rank; ++i) {\n    if (axes.indexOf(i) === -1) {\n      result.push(i);\n    }\n  }\n  axes.forEach(axis => result.push(axis));\n  return result;\n}\n\n/** Returns the axes permutation that undoes the original permutation. */\nexport function getUndoAxesPermutation(axes: number[]): number[] {\n  return axes.map((axis, i) => [i, axis])\n      .sort((a, b) => a[1] - b[1])\n      .map(x => x[0]);\n}\n\nexport function getInnerMostAxes(numAxes: number, rank: number): number[] {\n  const res: number[] = [];\n  for (let i = rank - numAxes; i < rank; ++i) {\n    res.push(i);\n  }\n  return res;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Max, MaxAttrs, MaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the maximum of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.max().print();  // or tf.max(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.max(axis).print();  // or tf.max(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction max_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'max');\n\n  const inputs: MaxInputs = {x: $x};\n  const attrs: MaxAttrs = {reductionIndices: axis, keepDims};\n\n  return ENGINE.runKernel(\n      Max, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const max = /* @__PURE__ */ op({max_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Min, MinAttrs, MinInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the minimum value from the input.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the array is reduced by 1 for each entry in `axes`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axes` has no entries, all dimensions are reduced, and an array with a\n * single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.min().print();  // or tf.min(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.min(axis).print();  // or tf.min(x, axis)\n * ```\n *\n * @param x The input Tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction min_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'min');\n\n  const inputs: MinInputs = {x: $x};\n  const attrs: MinAttrs = {axis, keepDims};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             Min, inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as T;\n}\n\nexport const min = /* @__PURE__ */ op({min_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Pow, PowInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the power of one `tf.Tensor` to another. Supports broadcasting.\n *\n * Given a `tf.Tensor` x and a `tf.Tensor` y, this operation computes x^y for\n * corresponding elements in x and y. The result's dtype will be the upcasted\n * type of the `base` and `exp` dtypes.\n *\n * ```js\n * const a = tf.tensor([[2, 3], [4, 5]])\n * const b = tf.tensor([[1, 2], [3, 0]]).toInt();\n *\n * a.pow(b).print();  // or tf.pow(a, b)\n * ```\n *\n * ```js\n * const a = tf.tensor([[1, 2], [3, 4]])\n * const b = tf.tensor(2).toInt();\n *\n * a.pow(b).print();  // or tf.pow(a, b)\n * ```\n * We also expose `powStrict` which has the same signature as this op and\n * asserts that `base` and `exp` are the same shape (does not broadcast).\n *\n * @param base The base `tf.Tensor` to pow element-wise.\n * @param exp The exponent `tf.Tensor` to pow element-wise.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction pow_<T extends Tensor>(\n    base: Tensor|TensorLike, exp: Tensor|TensorLike): T {\n  let $base = convertToTensor(base, 'base', 'pow');\n  let $exp = convertToTensor(exp, 'exp', 'pow');\n  [$base, $exp] = makeTypesMatch($base, $exp);\n\n  const inputs: PowInputs = {a: $base, b: $exp};\n\n  return ENGINE.runKernel(Pow, inputs as unknown as NamedTensorMap);\n}\n\nexport const pow = /* @__PURE__ */ op({pow_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {isWebGLData, isWebGPUData, TensorLike, TypedArray, WebGLData, WebGPUData} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n    values: TensorLike|WebGLData|WebGPUData, shape: number[],\n    inferredShape: number[], dtype?: DataType): Tensor {\n  if (dtype == null) {\n    dtype = inferDtype(values);\n  } else if (dtype === 'complex64') {\n    throw new Error(\n        `Cannot construct a complex64 tensor directly. ` +\n        `Please use tf.complex(real, imag).`);\n  }\n\n  if (isWebGPUData(values) || isWebGLData(values)) {\n    if (dtype !== 'float32' && dtype !== 'int32') {\n      throw new Error(\n          `Creating tensor from GPU data only supports ` +\n          `'float32'|'int32' dtype, while the dtype is ${dtype}.`);\n    }\n    return ENGINE.backend.createTensorFromGPUData(\n        values, shape || inferredShape, dtype);\n  }\n\n  if (!isTypedArray(values) && !Array.isArray(values) &&\n      typeof values !== 'number' && typeof values !== 'boolean' &&\n      typeof values !== 'string') {\n    throw new Error(\n        'values passed to tensor(values) must be a number/boolean/string or ' +\n        'an array of numbers/booleans/strings, or a TypedArray');\n  }\n  // Verify that the shape matches the inferred shape.\n  if (shape != null) {\n    assertNonNegativeIntegerDimensions(shape);\n\n    const providedSize = sizeFromShape(shape);\n    const inferredSize = sizeFromShape(inferredShape);\n    assert(\n        providedSize === inferredSize,\n        () =>\n            `Based on the provided shape, [${shape}], the tensor should have ` +\n            `${providedSize} values but has ${inferredSize}`);\n\n    for (let i = 0; i < inferredShape.length; ++i) {\n      const inferred = inferredShape[i];\n      const flatDimsDontMatch = i === inferredShape.length - 1 ?\n          inferred !== sizeFromShape(shape.slice(i)) :\n          true;\n      assert(\n          inferredShape[i] === shape[i] || !flatDimsDontMatch,\n          () => `Error creating a new Tensor. Inferred shape ` +\n              `(${inferredShape}) does not match the provided ` +\n              `shape (${shape}). `);\n    }\n  }\n\n  if (!isTypedArray(values) && !Array.isArray(values)) {\n    values = [values] as number[];\n  }\n\n  shape = shape || inferredShape;\n  values = dtype !== 'string' ?\n      toTypedArray(values, dtype) :\n      flatten(values as string[], [], true) as string[];\n  return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar} from '../tensor';\nimport {DataType} from '../types';\nimport {isTypedArray} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-0 `tf.Tensor` (scalar) with the provided value and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.scalar` as it makes the code more readable.\n *\n * ```js\n * tf.scalar(3.14).print();\n * ```\n *\n * @param value The value of the scalar.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function scalar(\n    value: number|boolean|string|Uint8Array, dtype?: DataType): Scalar {\n  if (((isTypedArray(value) && dtype !== 'string') || Array.isArray(value)) &&\n      dtype !== 'complex64') {\n    throw new Error(\n        'Error creating a new Scalar: value must be a primitive ' +\n        '(number|boolean|string)');\n  }\n  if (dtype === 'string' && isTypedArray(value) &&\n      !(value instanceof Uint8Array)) {\n    throw new Error(\n        'When making a scalar from encoded string, ' +\n        'the value must be `Uint8Array`.');\n  }\n  const shape: number[] = [];\n  const inferredShape: number[] = [];\n  return makeTensor(value, shape, inferredShape, dtype) as Scalar;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sqrt, SqrtInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes square root of the input `tf.Tensor` element-wise: `y = sqrt(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 4, -1]);\n *\n * x.sqrt().print();  // or tf.sqrt(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sqrt_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sqrt', 'float32');\n\n  const inputs: SqrtInputs = {x: $x};\n\n  return ENGINE.runKernel(Sqrt, inputs as unknown as NamedTensorMap);\n}\nexport const sqrt = /* @__PURE__ */ op({sqrt_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Computes square of `x` element-wise: `x ^ 2`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.sqrt(2), -1]);\n *\n * x.square().print();  // or tf.square(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction square_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'square');\n  const attrs = {};\n  return ENGINE.runKernel('Square', {x: $x}, attrs);\n}\n\nexport const square = /* @__PURE__ */ op({square_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Sum, SumAttrs, SumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes the sum of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If axes has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.sum().print();  // or tf.sum(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.sum(axis).print();  // or tf.sum(x, axis)\n * ```\n *\n * @param x The input tensor to compute the sum over. If the dtype is `bool`\n *   it will be converted to `int32` and the output dtype will be `int32`.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction sum_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  let $x = convertToTensor(x, 'x', 'sum');\n  if ($x.dtype === 'bool') {\n    $x = cast($x, 'int32');\n  }\n\n  const inputs: SumInputs = {x: $x};\n  const attrs: SumAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      Sum, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const sum = /* @__PURE__ */ op({sum_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {abs} from './abs';\nimport * as axis_util from './axis_util';\nimport {max} from './max';\nimport {min} from './min';\nimport {op} from './operation';\nimport {pow} from './pow';\nimport {reshape} from './reshape';\nimport {scalar} from './scalar';\nimport {sqrt} from './sqrt';\nimport {square} from './square';\nimport {sum} from './sum';\n\n/**\n * Computes the norm of scalar, vectors, and matrices.\n * This function can compute several different vector norms (the 1-norm, the\n * Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0)\n * and matrix norms (Frobenius, 1-norm, and inf-norm).\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.norm().print();  // or tf.norm(x)\n * ```\n *\n * @param x The input array.\n * @param ord Optional. Order of the norm. Supported norm types are\n * following:\n *\n *  | ord        | norm for matrices         | norm for vectors\n *  |------------|---------------------------|---------------------\n *  |'euclidean' |Frobenius norm             |2-norm\n *  |'fro'       |Frobenius norm\t           |\n *  |Infinity    |max(sum(abs(x), axis=1))   |max(abs(x))\n *  |-Infinity   |min(sum(abs(x), axis=1))   |min(abs(x))\n *  |1           |max(sum(abs(x), axis=0))   |sum(abs(x))\n *  |2           |                           |sum(abs(x)^2)^(1/2)\n *\n * @param axis Optional. If axis is null (the default), the input is\n * considered a vector and a single vector norm is computed over the entire\n * set of values in the Tensor, i.e. norm(x, ord) is equivalent\n * to norm(x.reshape([-1]), ord). If axis is an integer, the input\n * is considered a batch of vectors, and axis determines the axis in x\n * over which to compute vector norms. If axis is a 2-tuple of integer it is\n * considered a batch of matrices and axis determines the axes in NDArray\n * over which to compute a matrix norm.\n * @param keepDims Optional. If true, the norm has the same dimensionality\n * as the input.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction norm_(\n    x: Tensor|TensorLike, ord: number|'euclidean'|'fro' = 'euclidean',\n    axis: number|number[] = null, keepDims = false): Tensor {\n  x = convertToTensor(x, 'x', 'norm');\n\n  const norm = normImpl(x, ord, axis);\n  let keepDimsShape = norm.shape;\n  if (keepDims) {\n    const axes = parseAxisParam(axis, x.shape);\n    keepDimsShape = axis_util.expandShapeToKeepDim(norm.shape, axes);\n  }\n  return reshape(norm, keepDimsShape);\n}\n\nfunction normImpl(\n    x: Tensor, p: number|string, axis: number|number[] = null): Tensor {\n  if (x.rank === 0) {\n    return abs(x);\n  }\n\n  // consider vector when no axis is specified\n  if (x.rank !== 1 && axis === null) {\n    return normImpl(reshape(x, [-1]), p, axis);\n  }\n\n  // vector\n  if (x.rank === 1 || typeof axis === 'number' ||\n      Array.isArray(axis) && axis.length === 1) {\n    if (p === 1) {\n      return sum(abs(x), axis);\n    }\n    if (p === Infinity) {\n      return max(abs(x), axis);\n    }\n    if (p === -Infinity) {\n      return min(abs(x), axis);\n    }\n    if (p === 'euclidean' || p === 2) {\n      // norm(x, 2) = sum(abs(xi) ^ 2) ^ 1/2\n      return sqrt(sum(pow(abs(x), scalar(2, 'int32')), axis));\n    }\n\n    throw new Error(`Error in norm: invalid ord value: ${p}`);\n  }\n\n  // matrix (assumption axis[0] < axis[1])\n  if (Array.isArray(axis) && axis.length === 2) {\n    if (p === 1) {\n      return max(sum(abs(x), axis[0]), axis[1] - 1);\n    }\n    if (p === Infinity) {\n      return max(sum(abs(x), axis[1]), axis[0]);\n    }\n    if (p === -Infinity) {\n      return min(sum(abs(x), axis[1]), axis[0]);\n    }\n    if (p === 'fro' || p === 'euclidean') {\n      // norm(x) = sqrt(sum(pow(x, 2)))\n      return sqrt(sum(square(x), axis));\n    }\n\n    throw new Error(`Error in norm: invalid ord value: ${p}`);\n  }\n\n  throw new Error(`Error in norm: invalid axis: ${axis}`);\n}\n\nexport const norm = /* @__PURE__ */ op({norm_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\n\nimport {norm} from './norm';\nimport {op} from './operation';\n\n/**\n * Computes the Euclidean norm of scalar, vectors, and matrices.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.euclideanNorm().print();  // or tf.euclideanNorm(x)\n * ```\n *\n * @param x The input array.\n * @param axis Optional. If axis is null (the default), the input is\n * considered a vector and a single vector norm is computed over the entire\n * set of values in the Tensor, i.e. euclideanNorm(x) is equivalent\n * to euclideanNorm(x.reshape([-1])). If axis is an integer, the input\n * is considered a batch of vectors, and axis determines the axis in x\n * over which to compute vector norms. If axis is a 2-tuple of integer it is\n * considered a batch of matrices and axis determines the axes in NDArray\n * over which to compute a matrix norm.\n * @param keepDims Optional. If true, the norm has the same dimensionality\n * as the input.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction euclideanNorm_(\n    x: Tensor|TensorLike, axis: number|number[] = null,\n    keepDims = false): Tensor {\n  return norm(x, 'euclidean', axis, keepDims);\n}\n\nexport const euclideanNorm = /* @__PURE__ */ op({euclideanNorm_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Exp, ExpInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential of the input `tf.Tensor` element-wise. `e ^ x`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, -3]);\n *\n * x.exp().print();  // or tf.exp(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction exp_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'exp');\n\n  const inputs: ExpInputs = {x: $x};\n  return ENGINE.runKernel(Exp, inputs as unknown as NamedTensorMap);\n}\nexport const exp = /* @__PURE__ */ op({exp_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Returns a `tf.Tensor` that has expanded rank, by inserting a dimension\n * into the tensor's shape.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const axis = 1;\n * x.expandDims(axis).print();\n * ```\n *\n * @param x The input tensor whose dimensions are to be expanded.\n * @param axis The dimension index at which to insert shape of `1`. Defaults\n *     to 0 (the first dimension).\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction expandDims_<T extends Tensor>(x: Tensor|TensorLike, axis = 0): T {\n  const $x = convertToTensor(x, 'x', 'expandDims', 'string_or_numeric');\n\n  util.assert(axis <= $x.rank, () => 'Axis must be <= rank of the tensor');\n\n  const inputs: ExpandDimsInputs = {input: $x};\n  const attrs: ExpandDimsAttrs = {dim: axis};\n\n  return ENGINE.runKernel(\n      ExpandDims, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const expandDims = /* @__PURE__ */ op({expandDims_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Expm1, Expm1Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes exponential of the input `tf.Tensor` minus one element-wise.\n * `e ^ x - 1`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, -3]);\n *\n * x.expm1().print();  // or tf.expm1(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction expm1_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'expm1');\n\n  const inputs: Expm1Inputs = {x: $x};\n  return ENGINE.runKernel(Expm1, inputs as unknown as NamedTensorMap);\n}\nexport const expm1 = /* @__PURE__ */ op({expm1_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tile, TileAttrs, TileInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Construct a tensor by repeating it the number of times given by reps.\n *\n * This operation creates a new tensor by replicating `input` `reps`\n * times. The output tensor's `i`th dimension has `input.shape[i] *\n * reps[i]` elements, and the values of `input` are replicated\n * `reps[i]` times along the `i`th dimension. For example, tiling\n * `[a, b, c, d]` by `[2]` produces `[a, b, c, d, a, b, c, d]`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n *\n * a.tile([2]).print();    // or tf.tile(a, [2])\n * ```\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.tile([1, 2]).print();  // or tf.tile(a, [1,2])\n * ```\n * @param x The tensor to tile.\n * @param reps Determines the number of replications per dimension.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction tile_<T extends Tensor>(x: T|TensorLike, reps: number[]): T {\n  const $x = convertToTensor(x, 'x', 'tile', 'string_or_numeric');\n  util.assert(\n      $x.rank === reps.length,\n      () => `Error in transpose: rank of input ${$x.rank} ` +\n          `must match length of reps ${reps}.`);\n\n  const inputs: TileInputs = {x: $x};\n  const attrs: TileAttrs = {reps};\n\n  return ENGINE.runKernel(\n      Tile, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const tile = /* @__PURE__ */ op({tile_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {DataType} from '../types';\n\nimport {buffer} from './buffer';\nimport {expandDims} from './expand_dims';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {tile} from './tile';\n\n/**\n * Create an identity matrix.\n *\n * @param numRows Number of rows.\n * @param numColumns Number of columns. Defaults to `numRows`.\n * @param batchShape If provided, will add the batch shape to the beginning\n *   of the shape of the returned `tf.Tensor` by repeating the identity\n *   matrix.\n * @param dtype Data type.\n * @returns Identity matrix of the specified size and data type, possibly\n *   with batch repetition if `batchShape` is specified.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction eye_(\n    numRows: number, numColumns?: number,\n    batchShape?:\n        [\n          number\n        ]|[number,\n           number]|[number, number, number]|[number, number, number, number],\n    dtype: DataType = 'float32'): Tensor2D {\n  if (numColumns == null) {\n    numColumns = numRows;\n  }\n  const buff = buffer([numRows, numColumns], dtype);\n  const n = numRows <= numColumns ? numRows : numColumns;\n  for (let i = 0; i < n; ++i) {\n    buff.set(1, i, i);\n  }\n  const out: Tensor2D = reshape(buff.toTensor(), [numRows, numColumns]);\n  if (batchShape == null) {\n    return out;\n  } else {\n    if (batchShape.length === 1) {\n      return tile(expandDims(out, 0), [batchShape[0], 1, 1]) as Tensor2D;\n    } else if (batchShape.length === 2) {\n      // tslint:disable-next-line:no-unnecessary-type-assertion\n      return tile(\n                 expandDims(expandDims(out, 0), 0),\n                 [batchShape[0], batchShape[1], 1, 1]) as Tensor2D;\n    } else if (batchShape.length === 3) {\n      // tslint:disable-next-line:no-unnecessary-type-assertion\n      return tile(expandDims(expandDims(expandDims(out, 0), 0), 0), [\n               batchShape[0], batchShape[1], batchShape[2], 1, 1\n             ]) as Tensor2D;\n    } else {\n      throw new Error(\n          `eye() currently supports only 1D and 2D ` +\n          // tslint:disable-next-line:no-any\n          `batchShapes, but received ${(batchShape as any).length}D.`);\n    }\n  }\n}\n\nexport const eye = /* @__PURE__ */ op({eye_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Floor, FloorInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes floor of input `tf.Tensor` element-wise: `floor(x)`.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.floor().print();  // or tf.floor(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction floor_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'floor', 'float32');\n\n  const inputs: FloorInputs = {x: $x};\n  return ENGINE.runKernel(Floor, inputs as unknown as NamedTensorMap);\n}\nexport const floor = /* @__PURE__ */ op({floor_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {GatherV2, GatherV2Attrs, GatherV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Gather slices from tensor `x`'s axis `axis` according to `indices`.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const indices = tf.tensor1d([1, 3, 3], 'int32');\n *\n * x.gather(indices).print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const indices = tf.tensor1d([1, 1, 0], 'int32');\n *\n * x.gather(indices).print();\n * ```\n * @param x The input tensor whose slices are to be gathered.\n * @param indices The indices of the values to extract.\n * @param axis The axis over which to select values. Defaults to 0.\n * @param batchDims Optional. The number of batch dimensions. It must be less\n *     than or equal to rank(indices). Defaults to 0.\n *     The output tensor will have shape of\n *     `x.shape[:axis] + indices.shape[batchDims:] + x.shape[axis + 1:]`\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction gather_<T extends Tensor>(\n    x: T|TensorLike, indices: Tensor|TensorLike, axis = 0, batchDims = 0): T {\n  const $x = convertToTensor(x, 'x', 'gather');\n  const $indices = convertToTensor(indices, 'indices', 'gather', 'int32');\n\n  const inputs: GatherV2Inputs = {x: $x, indices: $indices};\n  const attrs: GatherV2Attrs = {axis, batchDims};\n\n  return ENGINE.runKernel(\n      GatherV2, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const gather = /* @__PURE__ */ op({gather_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Greater, GreaterInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a > b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.greater(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction greater_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'greater', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'greater', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: GreaterInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Greater, inputs as unknown as NamedTensorMap);\n}\n\nexport const greater = /* @__PURE__ */ op({greater_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {GreaterEqual, GreaterEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a >= b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.greaterEqual(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction greaterEqual_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'greaterEqual', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'greaterEqual', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: GreaterEqualInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(GreaterEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const greaterEqual = /* @__PURE__ */ op({greaterEqual_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Imag, ImagInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n/**\n * Returns the imaginary part of a complex (or real) tensor.\n *\n * Given a tensor input, this operation returns a tensor of type float that is\n * the imaginary part of each element in input considered as a complex number.\n * If input is real, a tensor of all zeros is returned.\n *\n * ```js\n * const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);\n * tf.imag(x).print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction imag_<T extends Tensor>(input: T|TensorLike): T {\n  const $input = convertToTensor(input, 'input', 'imag');\n\n  const inputs: ImagInputs = {input: $input};\n  return ENGINE.runKernel(Imag, inputs as unknown as NamedTensorMap);\n}\n\nexport const imag = /* @__PURE__ */ op({imag_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsFinite, IsFiniteInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are finite.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isFinite().print();  // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isFinite_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'isFinite');\n\n  const inputs: IsFiniteInputs = {x: $x};\n\n  return ENGINE.runKernel(IsFinite, inputs as unknown as NamedTensorMap);\n}\nexport const isFinite = /* @__PURE__ */ op({isFinite_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsInf, IsInfInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are Infinity or -Infinity.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isInf().print();  // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isInf_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'isInf');\n\n  const inputs: IsInfInputs = {x: $x};\n\n  return ENGINE.runKernel(IsInf, inputs as unknown as NamedTensorMap);\n}\nexport const isInf = /* @__PURE__ */ op({isInf_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {IsNan, IsNanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns which elements of x are NaN.\n *\n * ```js\n * const x = tf.tensor1d([NaN, Infinity, -Infinity, 0, 1]);\n *\n * x.isNaN().print();  // or tf.isNaN(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction isNaN_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'isNaN');\n  const inputs: IsNanInputs = {x: $x};\n\n  return ENGINE.runKernel(IsNan, inputs as unknown as NamedTensorMap);\n}\nexport const isNaN = /* @__PURE__ */ op({isNaN_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LeakyRelu, LeakyReluAttrs, LeakyReluInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes leaky rectified linear element-wise.\n *\n * See\n * [http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf](\n *     http://web.stanford.edu/~awni/papers/relu_hybrid_icml2013_final.pdf)\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.leakyRelu(0.1).print();  // or tf.leakyRelu(x, 0.1)\n * ```\n * @param x The input tensor.\n * @param alpha The scaling factor for negative values, defaults to 0.2.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction leakyRelu_<T extends Tensor>(x: T|TensorLike, alpha = 0.2): T {\n  const $x = convertToTensor(x, 'x', 'leakyRelu');\n\n  const inputs: LeakyReluInputs = {x: $x};\n  const attrs: LeakyReluAttrs = {alpha};\n\n  return ENGINE.runKernel(\n      LeakyRelu, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const leakyRelu = /* @__PURE__ */ op({leakyRelu_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Less, LessInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a < b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.less(b).print();\n * ```\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction less_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'less', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'less', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: LessInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Less, inputs as unknown as NamedTensorMap);\n}\n\nexport const less = /* @__PURE__ */ op({less_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {LessEqual, LessEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a <= b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([2, 2, 2]);\n *\n * a.lessEqual(b).print();\n * ```\n *\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction lessEqual_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'lessEqual', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'lessEqual', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: LessEqualInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(LessEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const lessEqual = /* @__PURE__ */ op({lessEqual_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LinSpace, LinSpaceAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\n\n/**\n * Return an evenly spaced sequence of numbers over the given interval.\n *\n * ```js\n * tf.linspace(0, 9, 10).print();\n * ```\n * @param start The start value of the sequence.\n * @param stop The end value of the sequence.\n * @param num The number of values to generate.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function linspace(start: number, stop: number, num: number): Tensor1D {\n  if (num <= 0) {\n    throw new Error('The number of values should be positive.');\n  }\n\n  const attrs: LinSpaceAttrs = {start, stop, num};\n  return ENGINE.runKernel(LinSpace, {}, attrs as unknown as NamedAttrMap);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LRN, LRNAttrs, LRNInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Normalizes the activation of a local neighborhood across or within\n * channels.\n *\n * @param x The input tensor. The 4-D input tensor is treated as a 3-D array\n *     of 1D vectors (along the last dimension), and each vector is\n *     normalized independently.\n * @param depthRadius The number of adjacent channels in the 1D normalization\n *     window.\n * @param bias A constant bias term for the basis.\n * @param alpha A scale factor, usually positive.\n * @param beta An exponent.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction localResponseNormalization_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5): T {\n  const $x = convertToTensor(x, 'x', 'localResponseNormalization');\n  util.assert(\n      $x.rank === 4 || $x.rank === 3,\n      () => `Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank ${$x.rank}.`);\n  util.assert(\n      util.isInt(depthRadius),\n      () => `Error in localResponseNormalization: depthRadius must be an ` +\n          `integer but got depthRadius ${depthRadius}.`);\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  const inputs: LRNInputs = {x: x4D};\n\n  const attrs: LRNAttrs = {depthRadius, bias, alpha, beta};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  LRN, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  } else {\n    return res;\n  }\n}\n\nexport const localResponseNormalization = /* @__PURE__ */ op({localResponseNormalization_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Log, LogInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes natural logarithm of the input `tf.Tensor` element-wise: `ln(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.E]);\n *\n * x.log().print();  // or tf.log(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction log_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'log', 'float32');\n\n  const inputs: LogInputs = {x: $x};\n  return ENGINE.runKernel(Log, inputs as unknown as NamedTensorMap);\n}\nexport const log = /* @__PURE__ */ op({log_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Log1p, Log1pInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes natural logarithm of the input `tf.Tensor` plus one\n * element-wise: `ln(1 + x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, Math.E - 1]);\n *\n * x.log1p().print();  // or tf.log1p(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction log1p_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'log1p');\n\n  const inputs: Log1pInputs = {x: $x};\n  return ENGINE.runKernel(Log1p, inputs as unknown as NamedTensorMap);\n}\nexport const log1p = /* @__PURE__ */ op({log1p_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {CustomGradientFunc, ENGINE} from './engine';\nimport {Scalar, Tensor, Variable} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {convertToTensor, convertToTensorArray} from './tensor_util_env';\nimport {TensorLike} from './types';\nimport * as util from './util';\n\n/**\n * Provided `f(x)`, returns another function `g(x, dy?)`, which gives the\n * gradient of `f(x)` with respect to `x`.\n *\n * If `dy` is provided, the gradient of `f(x).mul(dy).sum()` with respect to\n * `x` is computed instead. `f(x)` must take a single tensor `x` and return a\n * single tensor `y`. If `f()` takes multiple inputs, use `tf.grads` instead.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.grad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * g(x).print();\n * ```\n *\n * ```js\n * // f(x) = x ^ 3\n * const f = x => x.pow(tf.scalar(3, 'int32'));\n * // f'(x) = 3x ^ 2\n * const g = tf.grad(f);\n * // f''(x) = 6x\n * const gg = tf.grad(g);\n *\n * const x = tf.tensor1d([2, 3]);\n * gg(x).print();\n * ```\n *\n * @param f The function f(x), to compute gradient for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grad(f: (x: Tensor) => Tensor): (\n    x: TensorLike|Tensor, dy?: TensorLike|Tensor) => Tensor {\n  util.assert(\n      util.isFunction(f), () => 'The f passed in grad(f) must be a function');\n  return (x: TensorLike|Tensor, dy?: TensorLike|Tensor): Tensor => {\n    // x can be of any dtype, thus null as the last argument.\n    const $x = convertToTensor(x, 'x', 'tf.grad', 'string_or_numeric');\n    const $dy: Tensor =\n        (dy != null) ? convertToTensor(dy, 'dy', 'tf.grad') : null;\n    return ENGINE.tidy(() => {\n      const {value, grads} = ENGINE.gradients(() => f($x), [$x], $dy);\n      if ($dy != null) {\n        util.assertShapesMatch(\n            value.shape, $dy.shape,\n            'The shape of dy passed in grad(f)(x, dy) must match the shape ' +\n                'returned by f(x)');\n      }\n      checkGrads(grads);\n      return grads[0];\n    });\n  };\n}\n\n/**\n * Provided `f(x1, x2,...)`, returns another function `g([x1, x2,...], dy?)`,\n * which gives an array of gradients of `f()` with respect to each input\n * [`x1`,`x2`,...].\n *\n * If `dy` is passed when calling `g()`, the gradient of\n * `f(x1,...).mul(dy).sum()` with respect to each input is computed instead.\n * The provided `f` must take one or more tensors and return a single tensor\n * `y`. If `f()` takes a single input, we recommend using `tf.grad` instead.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df / da = b, df / db = a\n * const g = tf.grads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const [da, db] = g([a, b]);\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @param f The function `f(x1, x2,...)` to compute gradients for.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction grads(f: (...args: Tensor[]) => Tensor): (\n    args: Array<Tensor|TensorLike>, dy?: Tensor|TensorLike) => Tensor[] {\n  util.assert(\n      util.isFunction(f), () => 'The f passed in grads(f) must be a function');\n  return (args: Array<Tensor|TensorLike>, dy?: Tensor|TensorLike): Tensor[] => {\n    util.assert(\n        Array.isArray(args),\n        () => 'The args passed in grads(f)(args) must be an array ' +\n            'of `Tensor`s or `TensorLike`s');\n    // args can be of any dtype, thus null as the last argument.\n    const $args =\n        convertToTensorArray(args, 'args', 'tf.grads', 'string_or_numeric');\n    const $dy: Tensor =\n        (dy != null) ? convertToTensor(dy, 'dy', 'tf.grads') : null;\n    return ENGINE.tidy(() => {\n      const {value, grads} = ENGINE.gradients(() => f(...$args), $args, $dy);\n      if ($dy != null) {\n        util.assertShapesMatch(\n            value.shape, $dy.shape,\n            'The shape of dy passed in grads(f)([x1,...], dy) must ' +\n                'match the shape returned by f([x1,...])');\n      }\n      checkGrads(grads);\n      return grads;\n    });\n  };\n}\n\n/**\n * Like `tf.grad`, but also returns the value of `f()`. Useful when `f()`\n * returns a metric you want to show.\n *\n * The result is a rich object with the following properties:\n * - grad: The gradient of `f(x)` w.r.t. `x` (result of `tf.grad`).\n * - value: The value returned by `f(x)`.\n *\n * ```js\n * // f(x) = x ^ 2\n * const f = x => x.square();\n * // f'(x) = 2x\n * const g = tf.valueAndGrad(f);\n *\n * const x = tf.tensor1d([2, 3]);\n * const {value, grad} = g(x);\n *\n * console.log('value');\n * value.print();\n * console.log('grad');\n * grad.print();\n * ```\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction valueAndGrad<I extends Tensor, O extends Tensor>(f: (x: I) => O): (\n    x: I, dy?: O) => {\n  value: O;\n  grad: I;\n} {\n  util.assert(\n      util.isFunction(f),\n      () => 'The f passed in valueAndGrad(f) must be a function');\n  return (x: I, dy?: O) => {\n    util.assert(\n        x instanceof Tensor,\n        () => 'The x passed in valueAndGrad(f)(x) must be a tensor');\n    util.assert(\n        dy == null || dy instanceof Tensor,\n        () => 'The dy passed in valueAndGrad(f)(x, dy) must be a tensor');\n    const {grads, value} = ENGINE.gradients(() => f(x), [x], dy);\n    checkGrads(grads);\n    return {grad: grads[0] as I, value};\n  };\n}\n\n/**\n * Like `tf.grads`, but returns also the value of `f()`. Useful when `f()`\n * returns a metric you want to show.\n *\n * The result is a rich object with the following properties:\n * - grads: The gradients of `f()` w.r.t. each input (result of `tf.grads`).\n * - value: The value returned by `f(x)`.\n *\n * ```js\n * // f(a, b) = a * b\n * const f = (a, b) => a.mul(b);\n * // df/da = b, df/db = a\n * const g = tf.valueAndGrads(f);\n *\n * const a = tf.tensor1d([2, 3]);\n * const b = tf.tensor1d([-2, -3]);\n * const {value, grads} = g([a, b]);\n *\n * const [da, db] = grads;\n *\n * console.log('value');\n * value.print();\n *\n * console.log('da');\n * da.print();\n * console.log('db');\n * db.print();\n * ```\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction valueAndGrads<O extends Tensor>(f: (...args: Tensor[]) => O): (\n    args: Tensor[], dy?: O) => {\n  grads: Tensor[];\n  value: O;\n} {\n  util.assert(\n      util.isFunction(f),\n      () => 'The f passed in valueAndGrads(f) must be a function');\n  return (args: Tensor[], dy?: O) => {\n    util.assert(\n        Array.isArray(args) && args.every(arg => arg instanceof Tensor),\n        () => 'The args passed in valueAndGrads(f)(args) must be array of ' +\n            'tensors');\n    util.assert(\n        dy == null || dy instanceof Tensor,\n        () => 'The dy passed in valueAndGrads(f)(args, dy) must be a tensor');\n    const res = ENGINE.gradients(() => f(...args), args, dy);\n    if (dy != null) {\n      util.assertShapesMatch(\n          res.value.shape, dy.shape,\n          'The shape of dy passed in valueAndGrads(f)([x1,...], dy) must ' +\n              'match the shape returned by f([x1,...])');\n    }\n    checkGrads(res.grads);\n    return res;\n  };\n}\n\n/**\n * Computes and returns the gradient of f(x) with respect to the list of\n * trainable variables provided by `varList`. If no list is provided, it\n * defaults to all trainable variables.\n *\n * ```js\n * const a = tf.variable(tf.tensor1d([3, 4]));\n * const b = tf.variable(tf.tensor1d([5, 6]));\n * const x = tf.tensor1d([1, 2]);\n *\n * // f(a, b) = a * x ^ 2 + b * x\n * const f = () => a.mul(x.square()).add(b.mul(x)).sum();\n * // df/da = x ^ 2, df/db = x\n * const {value, grads} = tf.variableGrads(f);\n *\n * Object.keys(grads).forEach(varName => grads[varName].print());\n * ```\n *\n * @param f The function to execute. f() should return a scalar.\n * @param varList The list of variables to compute the gradients with respect\n *     to. Defaults to all trainable variables.\n * @returns An object with the following keys and values:\n *   - `value`: The value of the function `f`.\n *   - `grads`: A map from the names of the variables to the gradients.\n *     If the `varList` argument is provided explicitly and contains a subset of\n *     non-trainable variables, this map in the return value will contain keys\n *     that map the names of the non-trainable variables to `null`.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction variableGrads(f: () => Scalar, varList?: Variable[]):\n    {value: Scalar, grads: NamedTensorMap} {\n  util.assert(\n      util.isFunction(f),\n      () => 'The f passed in variableGrads(f) must be a function');\n  util.assert(\n      varList == null ||\n          Array.isArray(varList) && varList.every(v => v instanceof Variable),\n      () =>\n          'The varList passed in variableGrads(f, varList) must be an array ' +\n          'of variables');\n\n  const specifiedVarList = varList != null;\n  if (!specifiedVarList) {\n    // Get all of the trainable variables.\n    varList = [];\n    for (const varName in ENGINE.registeredVariables) {\n      varList.push(ENGINE.registeredVariables[varName]);\n    }\n  }\n\n  const specifiedNonTrainable: Variable[] =\n      specifiedVarList ? varList.filter(variable => !variable.trainable) : null;\n\n  // Prune non-trainable variables.\n  const originalVarCount = varList.length;\n  varList = varList.filter(variable => variable.trainable);\n  util.assert(\n      varList.length > 0,\n      () => `variableGrads() expects at least one of the input variables to ` +\n          `be trainable, but none of the ${originalVarCount} variables is ` +\n          `trainable.`);\n\n  const allowNoGradients = true;\n  const {value, grads} = ENGINE.gradients(f, varList, null, allowNoGradients);\n\n  util.assert(\n      grads.some(g => g != null),\n      () => 'Cannot find a connection between any variable and the result of ' +\n          'the loss function y=f(x). Please make sure the operations that ' +\n          'use variables are inside the function f passed to minimize().');\n  util.assert(\n      value.rank === 0,\n      () => `The f passed in variableGrads(f) must return a scalar, but it ` +\n          `returned a rank-${value.rank} tensor`);\n\n  const namedGrads: NamedTensorMap = {};\n  varList.forEach((v, i) => {\n    if (grads[i] != null) {\n      namedGrads[v.name] = grads[i];\n    }\n  });\n  if (specifiedNonTrainable != null) {\n    // If varList is explicitly provided and contains non-trainable values,\n    // add them to the returned gradients with `null` values.\n    specifiedNonTrainable.forEach(v => namedGrads[v.name] = null);\n  }\n  return {value, grads: namedGrads};\n}\n\n/**\n * Overrides the gradient computation of a function `f`.\n *\n * Takes a function\n * `f(...inputs, save) => {value: Tensor, gradFunc: (dy, saved) => Tensor[]}`\n * and returns another function `g(...inputs)` which takes the same inputs as\n * `f`. When called, `g` returns `f().value`. In backward mode, custom gradients\n * with respect to each input of `f` are computed using `f().gradFunc`.\n *\n * The `save` function passed to `f` should be used for saving tensors needed\n * in the gradient. And the `saved` passed to the `gradFunc` is a\n * `NamedTensorMap`, which contains those saved tensors.\n *\n * ```js\n * const customOp = tf.customGrad((x, save) => {\n *   // Save x to make sure it's available later for the gradient.\n *   save([x]);\n *   // Override gradient of our custom x ^ 2 op to be dy * abs(x);\n *   return {\n *     value: x.square(),\n *     // Note `saved.x` which points to the `x` we saved earlier.\n *     gradFunc: (dy, saved) => [dy.mul(saved[0].abs())]\n *   };\n * });\n *\n * const x = tf.tensor1d([-1, -2, 3]);\n * const dx = tf.grad(x => customOp(x));\n *\n * console.log(`f(x):`);\n * customOp(x).print();\n * console.log(`f'(x):`);\n * dx(x).print();\n * ```\n *\n * @param f The function to evaluate in forward mode, which should return\n *     `{value: Tensor, gradFunc: (dy, saved) => Tensor[]}`, where `gradFunc`\n *     returns the custom gradients of `f` with respect to its inputs.\n *\n * @doc {heading: 'Training', subheading: 'Gradients'}\n */\nfunction customGrad<T extends Tensor>(f: CustomGradientFunc<T>):\n    (...args: Tensor[]) => T {\n  return ENGINE.customGrad(f);\n}\n\nfunction checkGrads(grads: Tensor[]) {\n  const numNullGradients = grads.filter(g => g == null).length;\n  if (numNullGradients > 0) {\n    throw new Error(\n        `Cannot compute gradient of y=f(x) with respect to x. Make sure that\n    the f you passed encloses all operations that lead from x to y.`);\n  }\n}\n\nexport {\n  customGrad,\n  variableGrads,\n  valueAndGrad,\n  valueAndGrads,\n  grad,\n  grads,\n};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Neg, NegInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes `-1 * x` element-wise.\n *\n * ```js\n * const x = tf.tensor2d([1, 2, -2, 0], [2, 2]);\n *\n * x.neg().print();  // or tf.neg(x)\n * ```\n *\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction neg_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'neg');\n\n  const inputs: NegInputs = {x: $x};\n  return ENGINE.runKernel(Neg, inputs as unknown as NamedTensorMap);\n}\nexport const neg = /* @__PURE__ */ op({neg_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Softplus, SoftplusInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes softplus of the input `tf.Tensor` element-wise: `log(exp(x) + 1)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.softplus().print();  // or tf.softplus(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction softplus_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'softplus');\n\n  const inputs: SoftplusInputs = {x: $x};\n  return ENGINE.runKernel(Softplus, inputs as unknown as NamedTensorMap);\n}\nexport const softplus = /* @__PURE__ */ op({softplus_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {customGrad} from '../gradients';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {mul} from './mul';\nimport {neg} from './neg';\nimport {op} from './operation';\nimport {sigmoid} from './sigmoid';\nimport {softplus} from './softplus';\n\n/**\n * Computes log sigmoid of the input `tf.Tensor` element-wise:\n * `logSigmoid(x)`. For numerical stability, we use `-tf.softplus(-x)`.\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.logSigmoid().print();  // or tf.logSigmoid(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction logSigmoid_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'logSigmoid');\n\n  // Use a custom gradient to maintain previous implementation.\n  // There is no LogSigmoid kernel in TF so we can't use engine.runKernel\n  // directly\n  const customOp = customGrad((x: Tensor) => {\n    // TODO(yassogba) we can remove the chained softplus call here only\n    // after backends have modualrized softplus at which point we can call\n    // engine runKernel(..., Sotfplus, ...) directly.\n    const value = neg(softplus(neg(x)));\n\n    const gradFunc = (dy: T) => {\n      const derX = mul(dy, sigmoid(neg(x)));\n      return derX;\n    };\n    return {value, gradFunc};\n  });\n\n  return customOp($x) as T;\n}\nexport const logSigmoid = /* @__PURE__ */ op({logSigmoid_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Sub, SubInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Subtracts two `tf.Tensor`s element-wise, A - B. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([10, 20, 30, 40]);\n * const b = tf.tensor1d([1, 2, 3, 4]);\n *\n * a.sub(b).print();  // or tf.sub(a, b)\n * ```\n *\n * ```js\n * // Broadcast subtract a with b.\n * const a = tf.tensor1d([10, 20, 30, 40]);\n * const b = tf.scalar(5);\n *\n * a.sub(b).print();  // or tf.sub(a, b)\n * ```\n * @param a The first `tf.Tensor` to subtract from.\n * @param b The second `tf.Tensor` to be subtracted. Must have the same dtype as\n * `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction sub_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'sub');\n  let $b = convertToTensor(b, 'b', 'sub');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: SubInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Sub, inputs as unknown as NamedTensorMap);\n}\n\nexport const sub = /* @__PURE__ */ op({sub_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {customGrad} from '../gradients';\n\nimport {Tensor} from '../tensor';\nimport {GradSaveFunc} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {exp} from './exp';\nimport {log} from './log';\nimport {max} from './max';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {sub} from './sub';\nimport {sum} from './sum';\n\n/**\n * Computes the log softmax.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n *\n * a.logSoftmax().print();  // or tf.logSoftmax(a)\n * ```\n *\n * ```js\n * const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);\n *\n * a.logSoftmax().print();  // or tf.logSoftmax(a)\n * ```\n *\n * @param logits The logits array.\n * @param axis The dimension softmax would be performed on. Defaults to `-1`\n *     which indicates the last dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction logSoftmax_<T extends Tensor>(logits: T|TensorLike, axis = -1): T {\n  const $logits = convertToTensor(logits, 'logits', 'logSoftmax');\n\n  if (axis === -1) {\n    axis = $logits.rank - 1;\n  }\n  if (axis !== $logits.rank - 1) {\n    throw Error(\n        'Log Softmax along a non-last dimension is not yet supported. ' +\n        `Logits was rank ${$logits.rank} and axis was ${axis}`);\n  }\n\n  // const forward: ForwardFunc<Tensor> = (backend, save) => {\n  //   const keepDims = true;\n  //   const xMax = max(logits, axis, true);\n  //   const shifted = sub(logits, xMax);\n  //   const value =\n  //       sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis,\n  //       keepDims)));\n  //   save([value]);\n  //   return value;\n  // };\n\n  // Use a custom gradient for numerical stability.\n  const customOp = customGrad((logits: Tensor, save: GradSaveFunc) => {\n    const keepDims = true;\n    const xMax = max(logits, axis, true);\n    const shifted = sub(logits, xMax);\n    const value =\n        sub(cast(shifted, 'float32'), log(sum(exp(shifted), axis, keepDims)));\n    save([value]);\n\n    const gradFunc = (dy: Tensor, saved: Tensor[]) => {\n      const [value] = saved;\n      const keepDims = true;\n      const softmax = exp(value);\n      return sub(dy, mul(sum(dy, axis, keepDims), softmax));\n    };\n    return {value, gradFunc};\n  });\n\n  return customOp($logits) as T;\n\n  // TODO Use Engine.runKernel when CPU/WebGL/WASM backends implement this.\n  // const inputs: LogSoftmaxInputs = {logits: $logits};\n  // const attrs: LogSoftmaxAttrs = {axis};\n  // return ENGINE.runKernel(\n  //            LogSoftmax, inputs as unknown as NamedTensorMap,\n  //            attrs as unknown as NamedAttrMap);\n}\n\nexport const logSoftmax = /* @__PURE__ */ op({logSoftmax_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {add} from './add';\nimport {expandShapeToKeepDim} from './axis_util';\nimport {exp} from './exp';\nimport {log} from './log';\nimport {max} from './max';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {sub} from './sub';\nimport {sum} from './sum';\n\n/**\n * Computes the log(sum(exp(elements across the reduction dimensions))).\n *\n * Reduces the input along the dimensions given in `axis`. Unless `keepDims`\n * is true, the rank of the array is reduced by 1 for each entry in `axis`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axis` has no entries, all dimensions are reduced, and an array with a\n * single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.logSumExp().print();  // or tf.logSumExp(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.logSumExp(axis).print();  // or tf.logSumExp(a, axis)\n * ```\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. If null (the default),\n *     reduces all dimensions.\n * @param keepDims If true, retains reduced dimensions with length\n *     of 1. Defaults to false.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction logSumExp_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'logSumExp');\n\n  const axes = parseAxisParam(axis, $x.shape);\n  const xMax = max($x, axes, true /* keepDims */);\n  const a = sub($x, xMax);\n  const b = exp(a);\n  const c = sum(b, axes);\n  const d = log(c);\n  const res = add(reshape(xMax, d.shape), d);\n\n  if (keepDims) {\n    const newShape = expandShapeToKeepDim(res.shape, axes);\n    return reshape(res, newShape) as T;\n  }\n  return res as T;\n}\n\nexport const logSumExp = /* @__PURE__ */ op({logSumExp_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {LogicalAnd, LogicalAndInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a AND b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalAnd(b).print();\n * ```\n *\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalAnd_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  const $a = convertToTensor(a, 'a', 'logicalAnd', 'bool');\n  const $b = convertToTensor(b, 'b', 'logicalAnd', 'bool');\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: LogicalAndInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(LogicalAnd, inputs as unknown as NamedTensorMap);\n}\n\nexport const logicalAnd = /* @__PURE__ */ op({logicalAnd_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LogicalNot, LogicalNotInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `NOT x` element-wise.\n *\n * ```js\n * const a = tf.tensor1d([false, true], 'bool');\n *\n * a.logicalNot().print();\n * ```\n *\n * @param x The input tensor. Must be of dtype 'bool'.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalNot_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'logicalNot', 'bool');\n  const inputs: LogicalNotInputs = {x: $x};\n  return ENGINE.runKernel(LogicalNot, inputs as unknown as NamedTensorMap);\n}\n\nexport const logicalNot = /* @__PURE__ */ op({logicalNot_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {LogicalOr, LogicalOrInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a OR b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalOr(b).print();\n * ```\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalOr_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  const $a = convertToTensor(a, 'a', 'logicalOr', 'bool');\n  const $b = convertToTensor(b, 'b', 'logicalOr', 'bool');\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: LogicalOrInputs = {a: $a, b: $b};\n  return ENGINE.runKernel(LogicalOr, inputs as unknown as NamedTensorMap);\n}\nexport const logicalOr = /* @__PURE__ */ op({logicalOr_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {logicalAnd} from './logical_and';\nimport {logicalNot} from './logical_not';\nimport {logicalOr} from './logical_or';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of `a XOR b` element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([false, false, true, true], 'bool');\n * const b = tf.tensor1d([false, true, false, true], 'bool');\n *\n * a.logicalXor(b).print();\n * ```\n *\n * @param a The first input tensor. Must be of dtype bool.\n * @param b The second input tensor. Must be of dtype bool.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction logicalXor_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  const $a = convertToTensor(a, 'a', 'logicalXor', 'bool');\n  const $b = convertToTensor(b, 'b', 'logicalXor', 'bool');\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  // x ^ y = (x | y) & ~(x & y)\n  return logicalAnd(logicalOr(a, b), logicalNot(logicalAnd(a, b)));\n}\n\nexport const logicalXor = /* @__PURE__ */ op({logicalXor_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SearchSorted, SearchSortedAttrs, SearchSortedInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nconst INT32_MAX = 2147483648;\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The side argument controls which index is returned if a value lands exactly\n * on an edge.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'sortedSequence' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);\n * let values = tf.tensor1d([0.0, 4.1, 12.0]);\n * const result1 = tf.searchSorted(edges, values, 'left');\n * result1.print(); // [1, 2, 4]\n *\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * values = tf.tensor1d([0, 4, 10]);\n * const result2 = tf.searchSorted(seq, values, 'left');\n * result2.print(); // [0, 2, 3]\n * const result3 = tf.searchSorted(seq, values, 'right');\n * result3.print(); // [1, 2, 5]\n *\n * const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],\n *                                     [1., 2., 3., 4., 5.]]);\n * values = tf.tensor2d([[9.8, 2.1, 4.3],\n *                       [0.1, 6.6, 4.5, ]]);\n * const result4 = tf.searchSorted(sortedSequence, values, 'left');\n * result4.print(); // [[4, 1, 2], [0, 5, 4]]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @param side: 'left'|'right'. Defaults to 'left'. 'left' corresponds to lower\n *     bound and 'right' to upper bound.\n * @return An N-D int32 tensor the size of values containing the result of\n *     applying either lower bound or upper bound (depending on side) to each\n *     value. The result is not a global index to the entire Tensor, but the\n *     index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction searchSorted_(\n    sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike,\n    side: 'left'|'right' = 'left'): Tensor {\n  const $sortedSequence =\n      convertToTensor(sortedSequence, 'sortedSequence', 'searchSorted');\n  const $values = convertToTensor(values, 'values', 'searchSorted');\n\n  const sequenceSize = $sortedSequence.shape[$sortedSequence.shape.length - 1];\n  const valuesSize = $values.shape[$values.shape.length - 1];\n  const $sortedSequence2D = reshape($sortedSequence, [-1, sequenceSize]);\n  const $values2D = reshape($values, [-1, valuesSize]);\n\n  if ($sortedSequence2D.rank < 2) {\n    throw new Error(`Sorted input argument must be at least 2-dimensional`);\n  }\n  if ($sortedSequence2D.shape[0] !== $values2D.shape[0]) {\n    throw new Error(\n        `Leading dimension of 'sortedSequence' and 'values' must match.`);\n  }\n  if (sizeFromShape($values2D.shape) >= INT32_MAX) {\n    throw new Error(`values tensor size must less than ${INT32_MAX}`);\n  }\n  if ($sortedSequence2D.shape[1] >= INT32_MAX) {\n    throw new Error(`trailing dim_size must less than ${\n        INT32_MAX} for int32 output type, was ${$sortedSequence2D.shape[1]}`);\n  }\n\n  const inputs: SearchSortedInputs = {\n    sortedSequence: $sortedSequence2D,\n    values: $values2D,\n  };\n  const attrs: SearchSortedAttrs = {side};\n\n  return ENGINE.runKernel(SearchSorted, inputs as {}, attrs as {});\n}\n\nexport const searchSorted = /* @__PURE__ */ op({searchSorted_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\nimport {searchSorted} from './search_sorted';\n\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The index returned corresponds to the first edge greater than or equal to the\n * value.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'lowerBound' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const edges = tf.tensor1d([-1, 3.3, 9.1, 10.0]);\n * let values = tf.tensor1d([0.0, 4.1, 12.0]);\n * const result1 = tf.lowerBound(edges, values);\n * result1.print(); // [1, 2, 4]\n *\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * values = tf.tensor1d([0, 4, 10]);\n * const result2 = tf.lowerBound(seq, values);\n * result2.print(); // [0, 2, 3]\n *\n * const sortedSequence = tf.tensor2d([[0., 3., 8., 9., 10.],\n *                                     [1., 2., 3., 4., 5.]]);\n * values = tf.tensor2d([[9.8, 2.1, 4.3],\n *                       [0.1, 6.6, 4.5, ]]);\n * const result3 = tf.lowerBound(sortedSequence, values);\n * result3.print(); // [[4, 1, 2], [0, 5, 4]]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @return An N-D int32 tensor the size of values containing the result of\n *     applying lower bound to each value. The result is not a global index to\n *     the entire Tensor, but the index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function lowerBound(\n    sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike): Tensor {\n  return searchSorted(sortedSequence, values, 'left');\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPool, MaxPoolAttrs, MaxPoolInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 2D max pooling of an image.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n *     `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n *     `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in dilated pooling. Defaults to `[1, 1]`. If `dilations` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n */\nfunction maxPool_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, filterSize: [number, number]|number,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  const $x = convertToTensor(x, 'x', 'maxPool');\n  const dilations = 1;\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in maxPool: input must be rank 4 but got rank ${x4D.rank}.`);\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n  conv_util.checkPadOnDimRoundingMode('maxPool', pad, dimRoundingMode);\n  const inputs: MaxPoolInputs = {x: x4D};\n  const attrs: MaxPoolAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  MaxPool, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const maxPool = /* @__PURE__ */ op({maxPool_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPool3D, MaxPool3DAttrs, MaxPool3DInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D, Tensor5D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {checkPadOnDimRoundingMode} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the 3D max pooling.\n *\n * ```js\n * const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]);\n * const result = tf.maxPool3d(x, 2, 1, 'valid');\n * result.print();\n * ```\n *\n * @param x The input tensor, of rank 5 or rank 4 of shape\n *     `[batch, depth, height, width, inChannels]`.\n * @param filterSize The filter size:\n *     `[filterDepth, filterHeight, filterWidth]`.\n *     If `filterSize` is a single number,\n *     then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n *     `[strideDepth, strideHeight, strideWidth]`.\n *     If `strides` is a single number,\n *     then `strideDepth == strideHeight == strideWidth`.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1*1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n *     \"NDHWC\". Specify the data format of the input and output data. With the\n *     default format \"NDHWC\", the data is stored in the order of: [batch,\n *     depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction maxPool3d_<T extends Tensor4D|Tensor5D>(\n    x: T|TensorLike, filterSize: [number, number, number]|number = [1, 1, 1],\n    strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n    dimRoundingMode?: 'floor'|'round'|'ceil',\n    dataFormat: 'NDHWC'|'NCDHW' = 'NDHWC'): T {\n  const $x = convertToTensor(x, 'x', 'maxPool3d');\n\n  let x5D = $x as Tensor5D;\n  let reshapedTo5D = false;\n  if ($x.rank === 4) {\n    reshapedTo5D = true;\n    x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);\n  }\n\n  util.assert(\n      x5D.rank === 5,\n      () => `Error in maxPool3d: x must be rank 5 but got rank ${x5D.rank}.`);\n  util.assert(\n      dataFormat === 'NDHWC',\n      () => `Error in maxPool3d: Only NDHWC is currently supported, ` +\n          `but got dataFormat of ${dataFormat}`);\n  checkPadOnDimRoundingMode('maxPool3d', pad, dimRoundingMode);\n  const inputs: MaxPool3DInputs = {x: x5D};\n  const attrs:\n      MaxPool3DAttrs = {filterSize, strides, pad, dimRoundingMode, dataFormat};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  MaxPool3D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo5D) {\n    return reshape(\n               res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]) as\n        T;\n  }\n\n  return res;\n}\n\nexport const maxPool3d = /* @__PURE__ */ op({maxPool3d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MaxPoolWithArgmax, MaxPoolWithArgmaxAttrs, MaxPoolWithArgmaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the 2D max pooling of an image with Argmax index.\n * The indices in argmax are flattened, so that a maximum value at position `[b,\n * y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if\n * include_batch_in_index is False; `((b * height + y) * width + x) * channels\n * +c` if include_batch_in_index is True.\n *\n * The indices returned are always in `[0, height) x [0, width)` before\n * flattening.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param filterSize The filter size: `[filterHeight, filterWidth]`. If\n *     `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n *     `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dataFormat An optional string from: \"NDHWC\", \"NCDHW\". Defaults to\n *     \"NDHWC\". Specify the data format of the input and output data. With the\n *     default format \"NDHWC\", the data is stored in the order of: [batch,\n *     depth, height, width, channels]. Only \"NDHWC\" is currently supported.\n * @param pad The type of padding algorithm.\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param includeBatchIndex Defaults to False. Whether to include batch\n *    dimension in flattened index of argmax.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction maxPoolWithArgmax_<T extends Tensor4D>(\n    x: T|TensorLike, filterSize: [number, number]|number,\n    strides: [number, number]|number, pad: 'valid'|'same'|number,\n    includeBatchInIndex = false): NamedTensorMap {\n  const $x = convertToTensor(x, 'x', 'maxPoolWithArgmax');\n\n  const inputs: MaxPoolWithArgmaxInputs = {x: $x};\n  const attrs:\n      MaxPoolWithArgmaxAttrs = {filterSize, strides, pad, includeBatchInIndex};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const result = ENGINE.runKernel(\n                     MaxPoolWithArgmax, inputs as unknown as NamedTensorMap,\n                     attrs as unknown as NamedAttrMap) as Tensor[];\n\n  return {result: result[0], indexes: result[1]};\n}\n\nexport const maxPoolWithArgmax = /* @__PURE__ */ op({maxPoolWithArgmax_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Maximum, MaximumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the max of a and b (`a > b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `tf.maximumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.maximum(b).print();  // or tf.maximum(a, b)\n * ```\n *\n * ```js\n * // Broadcast maximum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.maximum(b).print();  // or tf.maximum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction maximum_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'maximum');\n  let $b = convertToTensor(b, 'b', 'maximum');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  if ($a.dtype === 'bool') {\n    $a = cast($a, 'int32');\n    $b = cast($b, 'int32');\n  }\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: MaximumInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Maximum, inputs as unknown as NamedTensorMap);\n}\n\nexport const maximum = /* @__PURE__ */ op({maximum_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Mean, MeanAttrs, MeanInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the mean of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces `x` along the dimensions given in `axis`. Unless `keepDims` is\n * true, the rank of the `tf.Tensor` is reduced by 1 for each entry in `axis`.\n * If `keepDims` is true, the reduced dimensions are retained with length 1.\n * If `axis` has no entries, all dimensions are reduced, and a `tf.Tensor` with\n * a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.mean().print();  // or tf.mean(a)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.mean(axis).print();  // or tf.mean(x, axis)\n * ```\n *\n * @param x The input tensor.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction mean_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  const $x = convertToTensor(x, 'x', 'mean');\n\n  const inputs: MeanInputs = {x: $x};\n  const attrs: MeanAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      Mean, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const mean = /* @__PURE__ */ op({mean_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions, makeZerosTypedArray, sizeFromShape} from '../util';\n\nimport {complex} from './complex';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 0.\n *\n * ```js\n * tf.zeros([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The type of an element in the resulting tensor. Can\n *     be 'float32', 'int32' or 'bool'. Defaults to 'float'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function zeros<R extends Rank>(\n    shape: ShapeMap[R], dtype: DataType = 'float32'): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (dtype === 'complex64') {\n    const real = zeros(shape, 'float32');\n    const imag = zeros(shape, 'float32');\n    return complex(real, imag);\n  }\n  const values = makeZerosTypedArray(sizeFromShape(shape), dtype);\n  return ENGINE.makeTensor(values, shape, dtype) as Tensor<R>;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {makeOnesTypedArray, sizeFromShape} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\nimport {complex} from './complex';\nimport {zeros} from './zeros';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 1.\n *\n * ```js\n * tf.ones([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The type of an element in the resulting tensor. Defaults to\n *     'float'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function ones<R extends Rank>(\n    shape: ShapeMap[R], dtype: DataType = 'float32'): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (dtype === 'complex64') {\n    const real = ones(shape, 'float32');\n    const imag = zeros(shape, 'float32');\n    return complex(real, imag);\n  }\n  const values = makeOnesTypedArray(sizeFromShape(shape), dtype);\n  return ENGINE.makeTensor(values, shape, dtype) as Tensor<R>;\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {matMul} from './mat_mul';\nimport {ones} from './ones';\nimport {reshape} from './reshape';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\n\n/**\n * Broadcasts parameters for evaluation on an N-D grid.\n *\n * Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`\n * of N-D coordinate arrays for evaluating expressions on an N-D grid.\n *\n * Notes:\n * `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.\n * When the `indexing` argument is set to 'xy' (the default), the broadcasting\n * instructions for the first two dimensions are swapped.\n * Examples:\n * Calling `const [X, Y] = meshgrid(x, y)` with the tensors\n *\n * ```javascript\n * const x = [1, 2, 3];\n * const y = [4, 5, 6];\n * const [X, Y] = tf.meshgrid(x, y);\n * // X = [[1, 2, 3],\n * //      [1, 2, 3],\n * //      [1, 2, 3]]\n * // Y = [[4, 4, 4],\n * //      [5, 5, 5],\n * //      [6, 6, 6]]\n * ```\n *\n * @param x Tensor with rank geq 1.\n * @param y Tensor with rank geq 1.\n * @param indexing\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nexport function meshgrid<T extends Tensor>(\n    x?: T|TensorLike, y?: T|TensorLike, {indexing = 'xy'} = {}): T[] {\n  if (indexing !== 'xy' && indexing !== 'ij') {\n    throw new TypeError(\n        `${indexing} is not a valid third argument to meshgrid`);\n  }\n  if (x === undefined) {\n    return [];\n  }\n  let $x = convertToTensor(\n      x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');\n\n  if (y === undefined) {\n    return [$x];\n  }\n  let $y = convertToTensor(\n      y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');\n\n  const w = sizeFromShape($x.shape);\n  const h = sizeFromShape($y.shape);\n\n  if (indexing === 'xy') {\n    $x = reshape($x, [1, -1]) as T;\n    $y = reshape($y, [-1, 1]) as T;\n    return [\n      matMul(ones([h, 1], $x.dtype), $x),\n      matMul($y, ones([1, w], $y.dtype)),\n    ];\n  }\n\n  $x = reshape($x, [-1, 1]) as T;\n  $y = reshape($y, [1, -1]) as T;\n  return [\n    matMul($x, ones([1, h], $x.dtype)),\n    matMul(ones([w, 1], $y.dtype), $y),\n  ];\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Minimum, MinimumInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Returns the min of a and b (`a < b ? a : b`) element-wise.\n * Supports broadcasting.\n *\n * We also expose `minimumStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.minimum(b).print();  // or tf.minimum(a, b)\n * ```\n *\n * ```js\n * // Broadcast minimum a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.minimum(b).print();  // or tf.minimum(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction minimum_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'minimum');\n  let $b = convertToTensor(b, 'b', 'minimum');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  if ($a.dtype === 'bool') {\n    $a = cast($a, 'int32');\n    $b = cast($b, 'int32');\n  }\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: MinimumInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Minimum, inputs as unknown as NamedTensorMap);\n}\n\nexport const minimum = /* @__PURE__ */ op({minimum_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {MirrorPad, MirrorPadAttrs, MirrorPadInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Pads a `tf.Tensor` using mirror padding.\n *\n * This operation implements the `REFLECT` and `SYMMETRIC` modes of pad.\n *\n * ```js\n * const x = tf.range(0, 9).reshape([1, 1, 3, 3]);\n * x.mirrorPad([[0, 0], [0, 0], [2, 2], [2, 2]], 'reflect').print();\n * ```\n * @param x The tensor to pad.\n * @param paddings An array of length `R` (the rank of the tensor), where\n * each element is a length-2 tuple of ints `[padBefore, padAfter]`,\n * specifying how much to pad along each dimension of the tensor.\n * In \"reflect\" mode, the padded regions do not include the borders,\n * while in \"symmetric\" mode the padded regions do include the borders.\n * For example, if the input is `[1, 2, 3]` and paddings is `[0, 2]`,\n * then the output is `[1, 2, 3, 2, 1]` in \"reflect\" mode, and\n * `[1, 2, 3, 3, 2]` in \"symmetric\" mode.\n * If `mode` is \"reflect\" then both `paddings[D, 0]` and `paddings[D, 1]`\n * must be no greater than `x.shape[D] - 1`. If mode is \"symmetric\"\n * then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than\n * `x.shape[D]`\n * @param mode String to specify padding mode. Can be `'reflect' | 'symmetric'`\n */\n/** @doc {heading: 'Tensors', subheading: 'Transformations'} */\nfunction mirrorPad_<T extends Tensor>(\n    x: T|TensorLike, paddings: Array<[number, number]>,\n    mode: 'reflect'|'symmetric'): T {\n  util.assert(\n      mode === 'reflect' || mode === 'symmetric',\n      () => `Invalid mode. Mode must be either reflect or symmetric. ` +\n          `Got ${mode}.`);\n\n  const $x = convertToTensor(x, 'x', 'mirrorPad');\n  if ($x.rank === 0) {\n    throw new Error(\n        'mirrorPad(scalar) is not defined. ' +\n        'Pass non-scalar to mirrorPad');\n  }\n  util.assert(\n      paddings.length === $x.rank,\n      () => `Padding doesn't match input. Must be ${$x.rank}. ` +\n          `Got ${paddings.length}.`);\n  const shapeOffset = mode === 'reflect' ? 1 : 0;\n  for (let i = 0; i < $x.rank; i++) {\n    util.assert(\n        paddings[i].length === 2,\n        () => `Invalid number of paddings. Must be length of 2 each.`);\n    util.assert(\n        paddings[i][0] >= 0 && paddings[i][0] <= $x.shape[i] - shapeOffset &&\n            paddings[i][1] >= 0 && paddings[i][1] <= $x.shape[i] - shapeOffset,\n        () => `Padding in dimension ${i} cannot be greater than or equal ` +\n            `to ${$x.shape[i] - shapeOffset} or less than 0 for input of ` +\n            `shape ${$x.shape}`);\n  }\n\n  const attrs: MirrorPadAttrs = {paddings, mode};\n  const inputs: MirrorPadInputs = {x: $x};\n  return ENGINE.runKernel(\n      MirrorPad, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const mirrorPad = /* @__PURE__ */ op({mirrorPad_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Mod, ModInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns the mod of a and b element-wise.\n * `floor(x / y) * y + mod(x, y) = x`\n * Supports broadcasting.\n *\n * We also expose `tf.modStrict` which has the same signature as this op and\n * asserts that `a` and `b` are the same shape (does not broadcast).\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.mod(b).print();  // or tf.mod(a, b)\n * ```\n *\n * ```js\n * // Broadcast a mod b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.mod(b).print();  // or tf.mod(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction mod_<T extends Tensor>(a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'mod');\n  let $b = convertToTensor(b, 'b', 'mod');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  const inputs: ModInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(Mod, inputs as unknown as NamedTensorMap);\n}\n\nexport const mod = /* @__PURE__ */ op({mod_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {parseAxisParam} from '../util';\n\nimport {expandShapeToKeepDim} from './axis_util';\nimport {cast} from './cast';\nimport {mean} from './mean';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {square} from './square';\nimport {sub} from './sub';\n\n/**\n * Calculates the mean and variance of `x`. The mean and variance are\n * calculated by aggregating the contents of `x` across `axes`. If `x` is\n * 1-D and `axes = [0]` this is just the mean and variance of a vector.\n *\n * @param x The input tensor.\n * @param axis The dimension(s) along with to compute mean and\n *     variance. By default it reduces all dimensions.\n * @param keepDims If true, the moments have the same dimensionality as the\n *     input.\n * @return An object with two keys: `mean` and `variance`.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction moments_(\n    x: Tensor|TensorLike, axis: number|number[] = null,\n    keepDims = false): {mean: Tensor, variance: Tensor} {\n  x = convertToTensor(x, 'x', 'moments');\n  const axes = parseAxisParam(axis, x.shape);\n  const xMean = mean(x, axes, keepDims);\n  let keepDimsShape = xMean.shape;\n  if (!keepDims) {\n    keepDimsShape = expandShapeToKeepDim(xMean.shape, axes);\n  }\n  const devSquared =\n      square(sub(cast(x, 'float32'), reshape(xMean, keepDimsShape)));\n  const variance = mean(devSquared, axes, keepDims);\n  return {mean: xMean, variance};\n}\n\nexport const moments = /* @__PURE__ */ op({moments_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor, convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * @docalias (data: Tensor2D, c: Tensor2D, h: Tensor2D): [Tensor2D, Tensor2D]\n */\nexport type LSTMCellFunc = {\n  (data: Tensor2D, c: Tensor2D, h: Tensor2D): [Tensor2D, Tensor2D];\n};\n\n/**\n * Computes the next states and outputs of a stack of LSTMCells.\n *\n * Each cell output is used as input to the next cell.\n *\n * Returns `[cellState, cellOutput]`.\n *\n * Derived from tf.contrib.rn.MultiRNNCell.\n *\n * @param lstmCells Array of LSTMCell functions.\n * @param data The input to the cell.\n * @param c Array of previous cell states.\n * @param h Array of previous cell outputs.\n *\n * @doc {heading: 'Operations', subheading: 'RNN'}\n */\nfunction multiRNNCell_(\n    lstmCells: LSTMCellFunc[], data: Tensor2D|TensorLike,\n    c: Array<Tensor2D|TensorLike>,\n    h: Array<Tensor2D|TensorLike>): [Tensor2D[], Tensor2D[]] {\n  const $data = convertToTensor(data, 'data', 'multiRNNCell');\n  const $c = convertToTensorArray(c, 'c', 'multiRNNCell');\n  const $h = convertToTensorArray(h, 'h', 'multiRNNCell');\n\n  let input = $data;\n  const newStates = [];\n  for (let i = 0; i < lstmCells.length; i++) {\n    const output = lstmCells[i](input, $c[i], $h[i]);\n    newStates.push(output[0]);\n    newStates.push(output[1]);\n    input = output[1];\n  }\n  const newC: Tensor2D[] = [];\n  const newH: Tensor2D[] = [];\n  for (let i = 0; i < newStates.length; i += 2) {\n    newC.push(newStates[i]);\n    newH.push(newStates[i + 1]);\n  }\n  return [newC, newH];\n}\nexport const multiRNNCell = /* @__PURE__ */ op({multiRNNCell_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Multinomial, MultinomialAttrs, MultinomialInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Creates a `tf.Tensor` with values drawn from a multinomial distribution.\n *\n * ```js\n * const probs = tf.tensor([.75, .25]);\n * tf.multinomial(probs, 3).print();\n * ```\n *\n * @param logits 1D array with unnormalized log-probabilities, or\n *     2D array of shape `[batchSize, numOutcomes]`. See the `normalized`\n *     parameter.\n * @param numSamples Number of samples to draw for each row slice.\n * @param seed The seed number.\n * @param normalized Whether the provided `logits` are normalized true\n *     probabilities (sum to 1). Defaults to false.\n * @return 1D array of shape `[numSamples]`, or 2D array of shape\n *     `[batchSize, numSamples]`, depending on the rank of the input.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction multinomial_(\n    logits: Tensor1D|Tensor2D|TensorLike, numSamples: number, seed?: number,\n    normalized = false): Tensor1D|Tensor2D {\n  const $logits = convertToTensor(logits, 'logits', 'multinomial');\n  const numOutcomes = $logits.size;\n  const origRank = $logits.rank;\n  if (numOutcomes < 2) {\n    throw new Error(\n        `Error in multinomial: you need at least 2 outcomes, but got ` +\n        `${numOutcomes}.`);\n  }\n  if (origRank > 2) {\n    throw new Error(`Rank of probabilities must be 1 or 2, but is ${origRank}`);\n  }\n  // TODO(lina128): Investigate correct seed behavior. The code seems not allow\n  // setting see to 0.\n  seed = seed || Math.random();\n\n  // The kernel only accepts (and returns) rank 2 tensors.\n  const logits2D: Tensor2D =\n      origRank === 1 ? reshape($logits, [1, -1]) : $logits as Tensor2D;\n\n  const inputs: MultinomialInputs = {logits: logits2D};\n  const attrs: MultinomialAttrs = {numSamples, seed, normalized};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  Multinomial, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as Tensor2D;\n\n  // tslint:disable-next-line:no-unnecessary-type-assertion\n  return origRank === 1 ? reshape(res, [res.size]) as Tensor1D : res;\n}\n\nexport const multinomial = /* @__PURE__ */ op({multinomial_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {NotEqual, NotEqualInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns the truth value of (a != b) element-wise. Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([0, 2, 3]);\n *\n * a.notEqual(b).print();\n * ```\n * @param a The first input tensor.\n * @param b The second input tensor. Must have the same dtype as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nfunction notEqual_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'notEqual', 'string_or_numeric');\n  let $b = convertToTensor(b, 'b', 'notEqual', 'string_or_numeric');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: NotEqualInputs = {a: $a, b: $b};\n\n  return ENGINE.runKernel(NotEqual, inputs as unknown as NamedTensorMap);\n}\n\nexport const notEqual = /* @__PURE__ */ op({notEqual_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {OneHot, OneHotAttrs, OneHotInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take\n * value `onValue` (defaults to 1), while all other locations take value\n * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank\n * `R+1` with the last axis of size `depth`.\n * `indices` used to encode prediction class must start from 0. For example,\n *  if you have 3 classes of data, class 1 should be encoded as 0, class 2\n *  should be 1, and class 3 should be 2.\n *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`. Indices must\n * start from 0.\n * @param depth The depth of the one hot dimension.\n * @param onValue A number used to fill in the output when the index matches\n * the location.\n * @param offValue A number used to fill in the output when the index does\n *     not match the location.\n * @param dtype The dtype of the output tensor, default to 'int32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(\n    indices: Tensor|TensorLike, depth: number, onValue = 1, offValue = 0,\n    dtype: DataType = 'int32'): Tensor {\n  if (depth < 2) {\n    throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);\n  }\n  const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');\n\n  const inputs: OneHotInputs = {indices: $indices};\n  const attrs: OneHotAttrs = {dtype, depth, onValue, offValue};\n\n  return ENGINE.runKernel(\n      OneHot, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const oneHot = /* @__PURE__ */ op({oneHot_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {OnesLike, OnesLikeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with all elements set to 1 with the same shape as the\n * given tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n * tf.onesLike(x).print();\n * ```\n * @param x A tensor.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction onesLike_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'onesLike');\n\n  const inputs: OnesLikeInputs = {x: $x};\n  return ENGINE.runKernel(OnesLike, inputs as unknown as NamedTensorMap);\n}\n\nexport const onesLike = /* @__PURE__ */ op({onesLike_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {matMul} from './mat_mul';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the outer product of two vectors, `v1` and `v2`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n * const b = tf.tensor1d([3, 4, 5]);\n *\n * tf.outerProduct(a, b).print();\n * ```\n * @param v1 The first vector in the outer product operation.\n * @param v2 The second vector in the outer product operation.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction outerProduct_(\n    v1: Tensor1D|TensorLike, v2: Tensor1D|TensorLike): Tensor2D {\n  const $v1 = convertToTensor(v1, 'v1', 'outerProduct');\n  const $v2 = convertToTensor(v2, 'v2', 'outerProduct');\n\n  util.assert(\n      $v1.rank === 1 && $v2.rank === 1,\n      () => `Error in outerProduct: inputs must be rank 1, but got ranks ` +\n          `${$v1.rank} and ${$v2.rank}.`);\n\n  const v12D = reshape($v1, [-1, 1]);\n  const v22D = reshape($v2, [1, -1]);\n  return matMul(v12D, v22D);\n}\n\nexport const outerProduct = /* @__PURE__ */ op({outerProduct_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {PadV2, PadV2Attrs, PadV2Inputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Pads a `tf.Tensor` with a given value and paddings.\n *\n * This operation implements `CONSTANT` mode. For `REFLECT` and `SYMMETRIC`,\n * refer to `tf.mirrorPad`.\n *\n * Also available are stricter rank-specific methods with the same signature\n * as this method that assert that `paddings` is of given length.\n *   - `tf.pad1d`\n *   - `tf.pad2d`\n *   - `tf.pad3d`\n *   - `tf.pad4d`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.pad([[1, 2]]).print();\n * ```\n * @param x The tensor to pad.\n * @param paddings An array of length `R` (the rank of the tensor), where\n * each element is a length-2 tuple of ints `[padBefore, padAfter]`,\n * specifying how much to pad along each dimension of the tensor.\n * @param constantValue The pad value to use. Defaults to 0.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction pad_<T extends Tensor>(\n    x: T|TensorLike, paddings: Array<[number, number]>, constantValue = 0): T {\n  const $x = convertToTensor(x, 'x', 'pad');\n  if ($x.rank === 0) {\n    throw new Error('pad(scalar) is not defined. Pass non-scalar to pad');\n  }\n\n  const attrs: PadV2Attrs = {paddings, constantValue};\n  const inputs: PadV2Inputs = {x: $x};\n  return ENGINE.runKernel(\n      PadV2, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const pad = /* @__PURE__ */ op({pad_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor1D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor1D` with a given value and paddings. See `pad` for details.\n */\nfunction pad1d_(\n    x: Tensor1D|TensorLike, paddings: [number, number],\n    constantValue = 0): Tensor1D {\n  assert(\n      paddings.length === 2,\n      () => 'Invalid number of paddings. Must be length of 2.');\n  return pad(x, [paddings], constantValue);\n}\n\nexport const pad1d = /* @__PURE__ */ op({pad1d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor2D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor2D` with a given value and paddings. See `pad` for details.\n */\nfunction pad2d_(\n    x: Tensor2D|TensorLike, paddings: [[number, number], [number, number]],\n    constantValue = 0): Tensor2D {\n  assert(\n      paddings.length === 2 && paddings[0].length === 2 &&\n          paddings[1].length === 2,\n      () => 'Invalid number of paddings. Must be length of 2 each.');\n  return pad(x, paddings, constantValue);\n}\n\nexport const pad2d = /* @__PURE__ */ op({pad2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor3D` with a given value and paddings. See `pad` for details.\n */\nfunction pad3d_(\n    x: Tensor3D|TensorLike,\n    paddings: [[number, number], [number, number], [number, number]],\n    constantValue = 0): Tensor3D {\n  assert(\n      paddings.length === 3 && paddings[0].length === 2 &&\n          paddings[1].length === 2 && paddings[2].length === 2,\n      () => 'Invalid number of paddings. Must be length of 2 each.');\n  return pad(x, paddings, constantValue);\n}\n\nexport const pad3d = /* @__PURE__ */ op({pad3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor4D} from '../tensor';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\nimport {op} from './operation';\nimport {pad} from './pad';\n\n/**\n * Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details.\n */\nfunction pad4d_(\n    x: Tensor4D|TensorLike,\n    paddings:\n        [\n          [number, number], [number, number], [number, number], [number, number]\n        ],\n    constantValue = 0): Tensor4D {\n  assert(\n      paddings.length === 4 && paddings[0].length === 2 &&\n          paddings[1].length === 2 && paddings[2].length === 2 &&\n          paddings[3].length === 2,\n      () => 'Invalid number of paddings. Must be length of 2 each.');\n  return pad(x, paddings, constantValue);\n}\n\nexport const pad4d = /* @__PURE__ */ op({pad4d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * This operation divides \"spatial\" dimensions `[1, ..., M]` of the input into\n * a grid of blocks of shape `blockShape`, and interleaves these blocks with\n * the \"batch\" dimension (0) such that in the output, the spatial\n * dimensions `[1, ..., M]` correspond to the position within the grid,\n * and the batch dimension combines both the position within a spatial block\n * and the original batch position. Prior to division into blocks,\n * the spatial dimensions of the input are optionally zero padded\n * according to `paddings`. See below for a precise description.\n *\n * ```js\n * const x = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);\n * const blockShape = [2, 2];\n * const paddings = [[0, 0], [0, 0]];\n *\n * x.spaceToBatchND(blockShape, paddings).print();\n * ```\n *\n * @param x A `tf.Tensor`. N-D with `x.shape` = `[batch] + spatialShape +\n * remainingShape`, where spatialShape has `M` dimensions.\n * @param blockShape A 1-D array. Must have shape `[M]`, all values must\n * be >= 1.\n * @param paddings A 2-D array. Must have shape `[M, 2]`, all values must be >=\n *     0. `paddings[i] = [padStart, padEnd]` specifies the amount to zero-pad\n * from input dimension `i + 1`, which corresponds to spatial dimension `i`. It\n * is required that\n * `(inputShape[i + 1] + padStart + padEnd) % blockShape[i] === 0`\n *\n * This operation is equivalent to the following steps:\n *\n * 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input\n * according to `paddings` to produce `padded` of shape paddedShape.\n *\n * 2. Reshape `padded` to `reshapedPadded` of shape:\n * `[batch] + [paddedShape[1] / blockShape[0], blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1], blockShape[M-1]] + remainingShape`\n *\n * 3. Permute dimensions of `reshapedPadded` to produce `permutedReshapedPadded`\n * of shape: `blockShape + [batch] + [paddedShape[1] / blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1]] + remainingShape`\n *\n * 4. Reshape `permutedReshapedPadded` to flatten `blockShape` into the\n * batch dimension, producing an output tensor of shape:\n * `[batch * prod(blockShape)] + [paddedShape[1] / blockShape[0], ...,\n * paddedShape[M] / blockShape[M-1]] + remainingShape`\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction spaceToBatchND_<T extends Tensor>(\n    x: T|TensorLike, blockShape: number[], paddings: number[][]): T {\n  const $x = convertToTensor(x, 'x', 'spaceToBatchND');\n\n  util.assert(\n      $x.rank >= 1 + blockShape.length,\n      () => `input rank ${$x.rank} should be > than [blockShape] ${\n          blockShape.length}`);\n\n  util.assert(\n      paddings.length === blockShape.length,\n      () => `paddings.shape[0] ${\n          paddings.length} must be equal to [blockShape] ${blockShape.length}`);\n\n  util.assert(\n      $x.shape.reduce(\n          (a, b, i) => {\n            if (i > 0 && i <= blockShape.length) {\n              return a &&\n                  ((b + paddings[i - 1][0] + paddings[i - 1][1]) %\n                       blockShape[i - 1] ===\n                   0);\n            }\n            return a;\n          },\n          true),\n      () => `input spatial dimensions ${$x.shape.slice(1)} with paddings ${\n          paddings.toString()} must be divisible by blockShapes ${\n          blockShape.toString()}`);\n\n  const inputs: SpaceToBatchNDInputs = {x: $x};\n  const attrs: SpaceToBatchNDAttrs = {blockShape, paddings};\n\n  return ENGINE.runKernel(\n      SpaceToBatchND, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const spaceToBatchND = /* @__PURE__ */ op({spaceToBatchND_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {avgPool} from './avg_pool';\nimport {batchToSpaceND} from './batch_to_space_nd';\nimport * as conv_util from './conv_util';\nimport {maxPool} from './max_pool';\nimport {op} from './operation';\nimport {reshape} from './reshape';\nimport {spaceToBatchND} from './space_to_batch_nd';\n\n/**\n * Performs an N-D pooling operation\n *\n * @param input The input tensor, of rank 4 or rank 3 of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param windowShape The filter size: `[filterHeight, filterWidth]`. If\n *     `filterSize` is a single number, then `filterHeight == filterWidth`.\n * @param poolingType The type of pooling, either 'max' or 'avg'.\n * @param pad The type of padding algorithm:\n *    - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *    - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *    - For more info, see this guide:\n *     [https://www.tensorflow.org/api_guides/python/nn#Convolution](\n *         https://www.tensorflow.org/api_guides/python/nn#Convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in dilated pooling. Defaults to `[1, 1]`. If `dilationRate` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param strides The strides of the pooling: `[strideHeight, strideWidth]`. If\n *     `strides` is a single number, then `strideHeight == strideWidth`.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction pool_<T extends Tensor3D|Tensor4D>(\n    input: T|TensorLike, windowShape: [number, number]|number,\n    poolingType: 'avg'|'max',\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dilations?: [number, number]|number, strides?: [number, number]|number,\n    dimRoundingMode?: 'floor'|'round'|'ceil') {\n  if (dilations == null) {\n    dilations = [1, 1];\n  }\n  if (strides == null) {\n    strides = 1;\n  }\n  if (pad === 0) {\n    pad = 'valid';\n  }\n\n  const $x = convertToTensor(input, 'x', 'maxPool');\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in pool: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n\n  const convInfo = conv_util.computePool2DInfo(\n      x4D.shape, windowShape, strides, dilations, pad);\n  const dilation: [number, number] =\n      [convInfo.dilationHeight, convInfo.dilationWidth];\n\n  // The following implementation does batchToSpace(pool(spaceToBatch(x)))\n  // whenever dilation > 1 since the TF kernels do not support dilation > 1.\n  // tslint:disable-next-line:max-line-length\n  // https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L1037\n\n  let basePadding: number[][];\n  if (pad === 'same') {\n    basePadding = withSpaceToBatchBasePaddings(\n        [convInfo.filterHeight, convInfo.filterWidth], dilation);\n  } else {\n    basePadding = [[0, 0], [0, 0]];\n  }\n\n  const isDilationOne = dilation[0] === 1 && dilation[1] === 1;\n  const [adjustedPadding, adjustedCrops] = requiredSpaceToBatchPaddings(\n      [convInfo.inHeight, convInfo.inWidth], dilation, basePadding);\n  const convertedPad = isDilationOne ? pad : 'valid';\n  const convertedX =\n      isDilationOne ? x4D : spaceToBatchND(x4D, dilation, adjustedPadding);\n\n  const forwardOp = poolingType === 'avg' ?\n      () => avgPool(convertedX, windowShape, strides, convertedPad,\n                    dimRoundingMode) :\n      () => maxPool(convertedX, windowShape, strides, convertedPad,\n                    dimRoundingMode);\n  const y = forwardOp();\n\n  const res = isDilationOne ? y : batchToSpaceND(y, dilation, adjustedCrops);\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n\n  return res as T;\n}\n\n// Helper function to compute crops and paddings for pool with dilation > 1.\n// tslint:disable-next-line:max-line-length\n// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/array_ops.py#L2184\nfunction requiredSpaceToBatchPaddings(\n    inputShape: [number, number], blockShape: [number, number],\n    basePadding: number[][]) {\n  const padStart = basePadding.map(b => b[0]);\n  const origPadEnd = basePadding.map(b => b[1]);\n  const fullInputShape = inputShape.concat(padStart, origPadEnd);\n  const padEndExtra = blockShape.map((b, i) => (b - fullInputShape[i] % b) % b);\n  const padEnd = origPadEnd.map((s, i) => s + padEndExtra[i]);\n  const paddings = blockShape.map((_, i) => [padStart[i], padEnd[i]]);\n  const crops = blockShape.map((_, i) => [0, padEndExtra[i]]);\n  return [paddings, crops];\n}\n\n// Helper function to compute base paddings for pool with dilation > 1.\n// tslint:disable-next-line:max-line-length\n// https://github.com/tensorflow/tensorflow/blob/50f6bb67dc98c9b74630b6047aae7a4f8a40fd02/tensorflow/python/ops/nn_ops.py#L524\nfunction withSpaceToBatchBasePaddings(\n    filterShape: [number, number], dilation: [number, number]) {\n  // Spatial dimensions of the filters and the upsampled filters in which we\n  // introduce (rate - 1) zeros between consecutive filter values.\n  const dilatedFilterShape = filterShape.map((s, i) => {\n    return s + (s - 1) * (dilation[i] - 1);\n  });\n  const padExtraShape = dilatedFilterShape.map(s => s - 1);\n\n  // When padding is odd, we pad more at end, following the same\n  // convention as conv2d.\n  const padExtraStart = padExtraShape.map(s => Math.floor(s / 2));\n  const padExtraEnd = padExtraShape.map((s, i) => s - padExtraStart[i]);\n  return padExtraShape.map((_, i) => {\n    return [padExtraStart[i], padExtraEnd[i]];\n  });\n}\n\nexport const pool = /* @__PURE__ */ op({pool_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Prelu, PreluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes leaky rectified linear element-wise with parametric alphas.\n *\n * `x < 0 ? alpha * x : f(x) = x`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n * const alpha = tf.scalar(0.1);\n *\n * x.prelu(alpha).print();  // or tf.prelu(x, alpha)\n * ```\n * @param x The input tensor.\n * @param alpha Scaling factor for negative values.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction prelu_<T extends Tensor>(x: T|TensorLike, alpha: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'prelu');\n  const $alpha = convertToTensor(alpha, 'alpha', 'prelu');\n\n  const inputs: PreluInputs = {x: $x, alpha: $alpha};\n  return ENGINE.runKernel(Prelu, inputs as unknown as NamedTensorMap);\n}\n\nexport const prelu = /* @__PURE__ */ op({prelu_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print<T extends Tensor>(x: T, verbose = false): void {\n  console.log(x.toString(verbose));\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Prod, ProdAttrs, ProdInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\n\n/**\n * Computes the product of elements across dimensions of a `tf.Tensor`.\n *\n * Reduces the input along the dimensions given in `axes`. Unless `keepDims`\n * is true, the rank of the `tf.Tensor` is reduced by 1 for each entry in\n * `axes`. If `keepDims` is true, the reduced dimensions are retained with\n * length 1. If `axes` has no entries, all dimensions are reduced, and a\n * `tf.Tensor` with a single element is returned.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3]);\n *\n * x.prod().print();  // or tf.prod(x)\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.prod(axis).print();  // or tf.prod(x, axis)\n * ```\n *\n * @param x The input tensor to compute the product over. If the dtype is `bool`\n *   it will be converted to `int32` and the output dtype will be `int32`.\n * @param axis The dimension(s) to reduce. By default it reduces\n *     all dimensions.\n * @param keepDims If true, retains reduced dimensions with size 1.\n *\n * @doc {heading: 'Operations', subheading: 'Reduction'}\n */\nfunction prod_<T extends Tensor>(\n    x: Tensor|TensorLike, axis: number|number[] = null, keepDims = false): T {\n  let $x = convertToTensor(x, 'x', 'prod');\n\n  if ($x.dtype === 'bool') {\n    // bool is not an allowed type for the underlying kernel.\n    $x = cast($x, 'int32');\n  }\n\n  const inputs: ProdInputs = {x: $x};\n  const attrs: ProdAttrs = {axis, keepDims};\n\n  return ENGINE.runKernel(\n      Prod, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const prod = /* @__PURE__ */ op({prod_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedGather, RaggedGatherAttrs, RaggedGatherInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Gather ragged slices from params axis 0 according to indices.\n *\n * @param paramsNestedSplits: A list of at least 1 Tensor with type 'int32' The\n *     nestedRowSplits tensors that define the row-partitioning for the params\n *     RaggedTensor input.\n * @param paramsDenseValues: A Tensor. The flatValues for the params\n *     RaggedTensor.\n * @param indices: A Tensor. Must be one of type: int32. Indices in the\n *     outermost dimension of params of the values that should be gathered.\n * @param outputRaggedRank: An int that is >= 0. The ragged rank of the output\n *     RaggedTensor. outputNestedSplits will contain this number of rowSplits\n *     tensors. This value should equal indices.shape.ndims + params.raggedRank\n *     - 1.\n * @return A map with the following properties:\n *     - outputNestedSplits: A list of outputRaggedRank Tensor objects with the\n * same type as paramsNestedSplits.\n *     - outputDenseValues: A Tensor. Has the same type as paramsDenseValues.\n * @doc {heading: 'Operations', subheading: 'Ragged'}\n */\n\ninterface RaggedGatherMap {\n  outputNestedSplits: Tensor[];\n  outputDenseValues: Tensor;\n}\n\nfunction raggedGather_(\n    paramsNestedSplits: Tensor[], paramsDenseValues: Tensor|TensorLike,\n    indices: Tensor|TensorLike, outputRaggedRank: number): RaggedGatherMap {\n  const $paramsNestedSplits = paramsNestedSplits.map(\n      (t, i) => convertToTensor(t, `tensors${i}`, 'raggedGather', 'int32'));\n  const $paramsDenseValues =\n      convertToTensor(paramsDenseValues, 'paramsDenseValues', 'raggedGather');\n  const $indices = convertToTensor(indices, 'indices', 'raggedGather', 'int32');\n\n  const inputs: RaggedGatherInputs = {\n    paramsNestedSplits: $paramsNestedSplits,\n    paramsDenseValues: $paramsDenseValues,\n    indices: $indices,\n  };\n  const attrs: RaggedGatherAttrs = {outputRaggedRank};\n\n  const result: Tensor[] =\n      ENGINE.runKernel(RaggedGather, inputs as {}, attrs as {});\n  return {\n    outputNestedSplits: result.slice(0, result.length - 1),\n    outputDenseValues: result[result.length - 1],\n  };\n}\n\nexport const raggedGather = /* @__PURE__ */ op({raggedGather_});\n", "/**\n * @license\n * Copyright 2022 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedRange, RaggedRangeInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns a RaggedTensor result composed from rtDenseValues and rtNestedSplits,\n * such that result[i] = [starts[i], starts[i] + deltas[i], ..., limits[i]]).\n *\n * @param starts: A Tensor. Must be one of the following types:\n *     'float32', 'int32'. The starts of each range.\n * @param limits: A Tensor. Must have the same type as starts. The limits of\n *     each range.\n * @param deltas: A Tensor. Must have the same type as starts. The deltas of\n *     each range.\n * @return A map with the following properties:\n *     - rtNestedSplits: A Tensor of type 'int32'.\n *     - rtDenseValues: A Tensor. Has the same type as starts.\n */\n\nfunction raggedRange_(\n    starts: Tensor|TensorLike, limits: Tensor|TensorLike,\n    deltas: Tensor|TensorLike): NamedTensorMap {\n  const $starts = convertToTensor(starts, 'starts', 'raggedRange');\n  const $limits =\n      convertToTensor(limits, 'limits', 'raggedRange', $starts.dtype);\n  const $deltas =\n      convertToTensor(deltas, 'deltas', 'raggedRange', $starts.dtype);\n\n  const inputs: RaggedRangeInputs = {\n    starts: $starts,\n    limits: $limits,\n    deltas: $deltas,\n  };\n\n  const result: Tensor[] = ENGINE.runKernel(RaggedRange, inputs as {});\n  return {\n    rtNestedSplits: result[0],\n    rtDenseValues: result[1],\n  };\n}\n\nexport const raggedRange = /* @__PURE__ */ op({raggedRange_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {RaggedTensorToTensor, RaggedTensorToTensorAttrs, RaggedTensorToTensorInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Create a dense tensor from a ragged tensor, possibly altering its shape.\n *\n * The raggedTensorToTensor op creates a dense tensor from am array of row\n * partition tensors, a value vector, and default values. If the shape is\n * unspecified, the minimal shape required to contain all the elements in the\n * ragged tensor (the natural shape) will be used. If some dimensions are left\n * unspecified, then the size of the natural shape is used in that dimension.\n *\n * The defaultValue will be broadcast to the output shape. After that, the\n * values from the ragged tensor overwrite the default values. Note that the\n * defaultValue must have less dimensions than the value.\n *\n * The row partition tensors are in the order of the dimensions. At present, the\n * types can be: \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n *   \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n *   \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then it\n * is preceded by \"FIRST_DIM_SIZE\".\n * ```\n * @param shape: A Tensor. Must be one of the following types: 'int32'. The\n *     desired shape of the output tensor. If left unspecified (empty), the\n *     minimal shape required to contain all the elements in the ragged tensor\n *     (the natural shape) will be used. If some dimensions are left\n *     unspecified, then the size of the natural shape is used in that\n *     dimension.\n *\n *     Note that dense dimensions cannot be modified by the shape argument.\n *     Trying to change the size of a dense dimension will cause the op to fail.\n *     Examples: natural shape: [4, 5, 6] shape: -1 output shape: [4, 5, 6]\n *\n *     natural shape: [4, 5, 6] shape: [3, -1, 2] output shape: [3, 5, 2]\n *\n *     natural shape: [4, 5, 6] shape: [3, 7, 2] output shape: [3, 7, 2]\n * @param values: A Tensor. A 1D tensor representing the values of the ragged\n *     tensor.\n * @param defaultValue: A Tensor. Must have the same type as values. The\n *     defaultValue when the shape is larger than the ragged tensor. The\n *     defaultValue is broadcast until it is the shape of the output tensor,\n *     and then overwritten by values in the ragged tensor. The default value\n *     must be compatible with this broadcast operation, and must have fewer\n *     dimensions than the value tensor.\n * @param rowPartitionTensors: A list of at least 1 Tensor objects with the same\n *     type in: 'int32'.\n * @param rowPartitionTypes: A list of strings. The types of the row partition\n *     tensors. At present, these can be:\n *     \"ROW_SPLITS\": the row_splits tensor from the ragged tensor.\n *     \"VALUE_ROWIDS\": the value_rowids tensor from the ragged tensor.\n *     \"FIRST_DIM_SIZE\": if value_rowids is used for the first dimension, then\n *         it is preceded by \"FIRST_DIM_SIZE\". The tensors are in the order of\n *         the dimensions.\n * @return A Tensor. Has the same type as values.\n * @doc {heading: 'Operations', subheading: 'Ragged'}\n */\nfunction raggedTensorToTensor_(\n    shape: Tensor|TensorLike, values: Tensor|TensorLike,\n    defaultValue: Tensor|TensorLike, rowPartitionTensors: Tensor[],\n    rowPartitionTypes: string[]): Tensor {\n  const $shape =\n      convertToTensor(shape, 'shape', 'raggedTensorToTensor', 'int32');\n  const $values = convertToTensor(values, 'values', 'raggedTensorToTensor');\n  const $defaultValue = convertToTensor(\n      defaultValue, 'defaultValue', 'raggedTensorToTensor', $values.dtype);\n  const $rowPartitionTensors = rowPartitionTensors.map(\n      (t, i) =>\n          convertToTensor(t, `tensors${i}`, 'raggedTensorToTensor', 'int32'));\n\n  const inputs: RaggedTensorToTensorInputs = {\n    shape: $shape,\n    values: $values,\n    defaultValue: $defaultValue,\n    rowPartitionTensors: $rowPartitionTensors\n  };\n  const attrs: RaggedTensorToTensorAttrs = {rowPartitionTypes};\n\n  return ENGINE.runKernel(RaggedTensorToTensor, inputs as {}, attrs as {});\n}\n\nexport const raggedTensorToTensor = /* @__PURE__ */ op({raggedTensorToTensor_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {sizeFromShape} from '../util';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a random number generator\n * function defined by the user.\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param randFunction A random number generator function which is called\n * for each element in the output tensor.\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction rand_<R extends Rank>(\n    shape: ShapeMap[R], randFunction: () => number,\n    dtype?: DataType): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  const size = sizeFromShape(shape);\n  let values = null;\n  if (dtype == null || dtype === 'float32') {\n    values = new Float32Array(size);\n  } else if (dtype === 'int32') {\n    values = new Int32Array(size);\n  } else if (dtype === 'bool') {\n    values = new Uint8Array(size);\n  } else {\n    throw new Error(`Unknown data type ${dtype}`);\n  }\n  for (let i = 0; i < size; i++) {\n    values[i] = randFunction();\n  }\n  return ENGINE.makeTensor(values, shape, dtype) as Tensor<R>;\n}\n\nexport const rand = /* @__PURE__ */ op({rand_});\n", "// A port of an algorithm by Johannes Baagøe <baagoe@baagoe.com>, 2010\n// http://baagoe.com/en/RandomMusings/javascript/\n// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror\n// Original work is under MIT license -\n\n// Copyright (C) 2010 by Johannes Baagøe <baagoe@baagoe.org>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n\n(function(global, module, define) {\n\nfunction Alea(seed) {\n  var me = this, mash = Mash();\n\n  me.next = function() {\n    var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32\n    me.s0 = me.s1;\n    me.s1 = me.s2;\n    return me.s2 = t - (me.c = t | 0);\n  };\n\n  // Apply the seeding algorithm from Baagoe.\n  me.c = 1;\n  me.s0 = mash(' ');\n  me.s1 = mash(' ');\n  me.s2 = mash(' ');\n  me.s0 -= mash(seed);\n  if (me.s0 < 0) { me.s0 += 1; }\n  me.s1 -= mash(seed);\n  if (me.s1 < 0) { me.s1 += 1; }\n  me.s2 -= mash(seed);\n  if (me.s2 < 0) { me.s2 += 1; }\n  mash = null;\n}\n\nfunction copy(f, t) {\n  t.c = f.c;\n  t.s0 = f.s0;\n  t.s1 = f.s1;\n  t.s2 = f.s2;\n  return t;\n}\n\nfunction impl(seed, opts) {\n  var xg = new Alea(seed),\n      state = opts && opts.state,\n      prng = xg.next;\n  prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }\n  prng.double = function() {\n    return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n  };\n  prng.quick = prng;\n  if (state) {\n    if (typeof(state) == 'object') copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nfunction Mash() {\n  var n = 0xefc8249d;\n\n  var mash = function(data) {\n    data = String(data);\n    for (var i = 0; i < data.length; i++) {\n      n += data.charCodeAt(i);\n      var h = 0.02519603282416938 * n;\n      n = h >>> 0;\n      h -= n;\n      h *= n;\n      n = h >>> 0;\n      h -= n;\n      n += h * 0x100000000; // 2^32\n    }\n    return (n >>> 0) * 2.3283064365386963e-10; // 2^-32\n  };\n\n  return mash;\n}\n\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.alea = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xor128\" prng algorithm by\n// George Marsaglia.  See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this, strseed = '';\n\n  me.x = 0;\n  me.y = 0;\n  me.z = 0;\n  me.w = 0;\n\n  // Set up generator function.\n  me.next = function() {\n    var t = me.x ^ (me.x << 11);\n    me.x = me.y;\n    me.y = me.z;\n    me.z = me.w;\n    return me.w ^= (me.w >>> 19) ^ t ^ (t >>> 8);\n  };\n\n  if (seed === (seed | 0)) {\n    // Integer seed.\n    me.x = seed;\n  } else {\n    // String seed.\n    strseed += seed;\n  }\n\n  // Mix in string seed, then discard an initial batch of 64 values.\n  for (var k = 0; k < strseed.length + 64; k++) {\n    me.x ^= strseed.charCodeAt(k) | 0;\n    me.next();\n  }\n}\n\nfunction copy(f, t) {\n  t.x = f.x;\n  t.y = f.y;\n  t.z = f.z;\n  t.w = f.w;\n  return t;\n}\n\nfunction impl(seed, opts) {\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (typeof(state) == 'object') copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.xor128 = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xorwow\" prng algorithm by\n// George Marsaglia.  See http://www.jstatsoft.org/v08/i14/paper\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this, strseed = '';\n\n  // Set up generator function.\n  me.next = function() {\n    var t = (me.x ^ (me.x >>> 2));\n    me.x = me.y; me.y = me.z; me.z = me.w; me.w = me.v;\n    return (me.d = (me.d + 362437 | 0)) +\n       (me.v = (me.v ^ (me.v << 4)) ^ (t ^ (t << 1))) | 0;\n  };\n\n  me.x = 0;\n  me.y = 0;\n  me.z = 0;\n  me.w = 0;\n  me.v = 0;\n\n  if (seed === (seed | 0)) {\n    // Integer seed.\n    me.x = seed;\n  } else {\n    // String seed.\n    strseed += seed;\n  }\n\n  // Mix in string seed, then discard an initial batch of 64 values.\n  for (var k = 0; k < strseed.length + 64; k++) {\n    me.x ^= strseed.charCodeAt(k) | 0;\n    if (k == strseed.length) {\n      me.d = me.x << 10 ^ me.x >>> 4;\n    }\n    me.next();\n  }\n}\n\nfunction copy(f, t) {\n  t.x = f.x;\n  t.y = f.y;\n  t.z = f.z;\n  t.w = f.w;\n  t.v = f.v;\n  t.d = f.d;\n  return t;\n}\n\nfunction impl(seed, opts) {\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (typeof(state) == 'object') copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.xorwow = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n\n", "// A Javascript implementaion of the \"xorshift7\" algorithm by\n// François Panneton and Pierre L'ecuyer:\n// \"On the Xorgshift Random Number Generators\"\n// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this;\n\n  // Set up generator function.\n  me.next = function() {\n    // Update xor generator.\n    var X = me.x, i = me.i, t, v, w;\n    t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n    t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n    t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n    t = X[(i + 4) & 7]; v ^= t ^ (t << 7);\n    t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n    X[i] = v;\n    me.i = (i + 1) & 7;\n    return v;\n  };\n\n  function init(me, seed) {\n    var j, w, X = [];\n\n    if (seed === (seed | 0)) {\n      // Seed state array using a 32-bit integer.\n      w = X[0] = seed;\n    } else {\n      // Seed state using a string.\n      seed = '' + seed;\n      for (j = 0; j < seed.length; ++j) {\n        X[j & 7] = (X[j & 7] << 15) ^\n            (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);\n      }\n    }\n    // Enforce an array length of 8, not all zeroes.\n    while (X.length < 8) X.push(0);\n    for (j = 0; j < 8 && X[j] === 0; ++j);\n    if (j == 8) w = X[7] = -1; else w = X[j];\n\n    me.x = X;\n    me.i = 0;\n\n    // Discard an initial 256 values.\n    for (j = 256; j > 0; --j) {\n      me.next();\n    }\n  }\n\n  init(me, seed);\n}\n\nfunction copy(f, t) {\n  t.x = f.x.slice();\n  t.i = f.i;\n  return t;\n}\n\nfunction impl(seed, opts) {\n  if (seed == null) seed = +(new Date);\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (state.x) copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.xorshift7 = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n", "// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\n//\n// This fast non-cryptographic random number generator is designed for\n// use in Monte-Carlo algorithms. It combines a long-period xorshift\n// generator with a Weyl generator, and it passes all common batteries\n// of stasticial tests for randomness while consuming only a few nanoseconds\n// for each prng generated.  For background on the generator, see Brent's\n// paper: \"Some long-period random number generators using shifts and xors.\"\n// http://arxiv.org/pdf/1004.3115v1.pdf\n//\n// Usage:\n//\n// var xor4096 = require('xor4096');\n// random = xor4096(1);                        // Seed with int32 or string.\n// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.\n// assert.equal(random.int32(), 1806534897);   // signed int32, 32 bits.\n//\n// For nonzero numeric keys, this impelementation provides a sequence\n// identical to that by Brent's xorgens 3 implementaion in C.  This\n// implementation also provides for initalizing the generator with\n// string seeds, or for saving and restoring the state of the generator.\n//\n// On Chrome, this prng benchmarks about 2.1 times slower than\n// Javascript's built-in Math.random().\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this;\n\n  // Set up generator function.\n  me.next = function() {\n    var w = me.w,\n        X = me.X, i = me.i, t, v;\n    // Update Weyl generator.\n    me.w = w = (w + 0x61c88647) | 0;\n    // Update xor generator.\n    v = X[(i + 34) & 127];\n    t = X[i = ((i + 1) & 127)];\n    v ^= v << 13;\n    t ^= t << 17;\n    v ^= v >>> 15;\n    t ^= t >>> 12;\n    // Update Xor generator array state.\n    v = X[i] = v ^ t;\n    me.i = i;\n    // Result is the combination.\n    return (v + (w ^ (w >>> 16))) | 0;\n  };\n\n  function init(me, seed) {\n    var t, v, i, j, w, X = [], limit = 128;\n    if (seed === (seed | 0)) {\n      // Numeric seeds initialize v, which is used to generates X.\n      v = seed;\n      seed = null;\n    } else {\n      // String seeds are mixed into v and X one character at a time.\n      seed = seed + '\\0';\n      v = 0;\n      limit = Math.max(limit, seed.length);\n    }\n    // Initialize circular array and weyl value.\n    for (i = 0, j = -32; j < limit; ++j) {\n      // Put the unicode characters into the array, and shuffle them.\n      if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n      // After 32 shuffles, take v as the starting w value.\n      if (j === 0) w = v;\n      v ^= v << 10;\n      v ^= v >>> 15;\n      v ^= v << 4;\n      v ^= v >>> 13;\n      if (j >= 0) {\n        w = (w + 0x61c88647) | 0;     // Weyl.\n        t = (X[j & 127] ^= (v + w));  // Combine xor and weyl to init array.\n        i = (0 == t) ? i + 1 : 0;     // Count zeroes.\n      }\n    }\n    // We have detected all zeroes; make the key nonzero.\n    if (i >= 128) {\n      X[(seed && seed.length || 0) & 127] = -1;\n    }\n    // Run the generator 512 times to further mix the state before using it.\n    // Factoring this as a function slows the main generator, so it is just\n    // unrolled here.  The weyl generator is not advanced while warming up.\n    i = 127;\n    for (j = 4 * 128; j > 0; --j) {\n      v = X[(i + 34) & 127];\n      t = X[i = ((i + 1) & 127)];\n      v ^= v << 13;\n      t ^= t << 17;\n      v ^= v >>> 15;\n      t ^= t >>> 12;\n      X[i] = v ^ t;\n    }\n    // Storing state as object members is faster than using closure variables.\n    me.w = w;\n    me.X = X;\n    me.i = i;\n  }\n\n  init(me, seed);\n}\n\nfunction copy(f, t) {\n  t.i = f.i;\n  t.w = f.w;\n  t.X = f.X.slice();\n  return t;\n};\n\nfunction impl(seed, opts) {\n  if (seed == null) seed = +(new Date);\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (state.X) copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.xor4096 = impl;\n}\n\n})(\n  this,                                     // window object or global\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n", "// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\n// Samuel Neves and Filipe Araujo.\n// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n  var me = this, strseed = '';\n\n  // Set up generator function.\n  me.next = function() {\n    var b = me.b, c = me.c, d = me.d, a = me.a;\n    b = (b << 25) ^ (b >>> 7) ^ c;\n    c = (c - d) | 0;\n    d = (d << 24) ^ (d >>> 8) ^ a;\n    a = (a - b) | 0;\n    me.b = b = (b << 20) ^ (b >>> 12) ^ c;\n    me.c = c = (c - d) | 0;\n    me.d = (d << 16) ^ (c >>> 16) ^ a;\n    return me.a = (a - b) | 0;\n  };\n\n  /* The following is non-inverted tyche, which has better internal\n   * bit diffusion, but which is about 25% slower than tyche-i in JS.\n  me.next = function() {\n    var a = me.a, b = me.b, c = me.c, d = me.d;\n    a = (me.a + me.b | 0) >>> 0;\n    d = me.d ^ a; d = d << 16 ^ d >>> 16;\n    c = me.c + d | 0;\n    b = me.b ^ c; b = b << 12 ^ d >>> 20;\n    me.a = a = a + b | 0;\n    d = d ^ a; me.d = d = d << 8 ^ d >>> 24;\n    me.c = c = c + d | 0;\n    b = b ^ c;\n    return me.b = (b << 7 ^ b >>> 25);\n  }\n  */\n\n  me.a = 0;\n  me.b = 0;\n  me.c = 2654435769 | 0;\n  me.d = 1367130551;\n\n  if (seed === Math.floor(seed)) {\n    // Integer seed.\n    me.a = (seed / 0x100000000) | 0;\n    me.b = seed | 0;\n  } else {\n    // String seed.\n    strseed += seed;\n  }\n\n  // Mix in string seed, then discard an initial batch of 64 values.\n  for (var k = 0; k < strseed.length + 20; k++) {\n    me.b ^= strseed.charCodeAt(k) | 0;\n    me.next();\n  }\n}\n\nfunction copy(f, t) {\n  t.a = f.a;\n  t.b = f.b;\n  t.c = f.c;\n  t.d = f.d;\n  return t;\n};\n\nfunction impl(seed, opts) {\n  var xg = new XorGen(seed),\n      state = opts && opts.state,\n      prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n  prng.double = function() {\n    do {\n      var top = xg.next() >>> 11,\n          bot = (xg.next() >>> 0) / 0x100000000,\n          result = (top + bot) / (1 << 21);\n    } while (result === 0);\n    return result;\n  };\n  prng.int32 = xg.next;\n  prng.quick = prng;\n  if (state) {\n    if (typeof(state) == 'object') copy(state, xg);\n    prng.state = function() { return copy(xg, {}); }\n  }\n  return prng;\n}\n\nif (module && module.exports) {\n  module.exports = impl;\n} else if (define && define.amd) {\n  define(function() { return impl; });\n} else {\n  this.tychei = impl;\n}\n\n})(\n  this,\n  (typeof module) == 'object' && module,    // present in node.js\n  (typeof define) == 'function' && define   // present with an AMD loader\n);\n\n\n", "/*\nCopyright 2019 David Bau.\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\n\n(function (global, pool, math) {\n//\n// The following constants are related to IEEE 754 limits.\n//\n\nvar width = 256,        // each RC4 output is 0 <= x < 256\n    chunks = 6,         // at least six RC4 outputs for each double\n    digits = 52,        // there are 52 significant digits in a double\n    rngname = 'random', // rngname: name for Math.random and Math.seedrandom\n    startdenom = math.pow(width, chunks),\n    significance = math.pow(2, digits),\n    overflow = significance * 2,\n    mask = width - 1,\n    nodecrypto;         // node.js crypto module, initialized at the bottom.\n\n//\n// seedrandom()\n// This is the seedrandom function described above.\n//\nfunction seedrandom(seed, options, callback) {\n  var key = [];\n  options = (options == true) ? { entropy: true } : (options || {});\n\n  // Flatten the seed string or build one from local entropy if needed.\n  var shortseed = mixkey(flatten(\n    options.entropy ? [seed, tostring(pool)] :\n    (seed == null) ? autoseed() : seed, 3), key);\n\n  // Use the seed to initialize an ARC4 generator.\n  var arc4 = new ARC4(key);\n\n  // This function returns a random double in [0, 1) that contains\n  // randomness in every bit of the mantissa of the IEEE 754 value.\n  var prng = function() {\n    var n = arc4.g(chunks),             // Start with a numerator n < 2 ^ 48\n        d = startdenom,                 //   and denominator d = 2 ^ 48.\n        x = 0;                          //   and no 'extra last byte'.\n    while (n < significance) {          // Fill up all significant digits by\n      n = (n + x) * width;              //   shifting numerator and\n      d *= width;                       //   denominator and generating a\n      x = arc4.g(1);                    //   new least-significant-byte.\n    }\n    while (n >= overflow) {             // To avoid rounding up, before adding\n      n /= 2;                           //   last byte, shift everything\n      d /= 2;                           //   right using integer math until\n      x >>>= 1;                         //   we have exactly the desired bits.\n    }\n    return (n + x) / d;                 // Form the number within [0, 1).\n  };\n\n  prng.int32 = function() { return arc4.g(4) | 0; }\n  prng.quick = function() { return arc4.g(4) / 0x100000000; }\n  prng.double = prng;\n\n  // Mix the randomness into accumulated entropy.\n  mixkey(tostring(arc4.S), pool);\n\n  // Calling convention: what to return as a function of prng, seed, is_math.\n  return (options.pass || callback ||\n      function(prng, seed, is_math_call, state) {\n        if (state) {\n          // Load the arc4 state from the given state if it has an S array.\n          if (state.S) { copy(state, arc4); }\n          // Only provide the .state method if requested via options.state.\n          prng.state = function() { return copy(arc4, {}); }\n        }\n\n        // If called as a method of Math (Math.seedrandom()), mutate\n        // Math.random because that is how seedrandom.js has worked since v1.0.\n        if (is_math_call) { math[rngname] = prng; return seed; }\n\n        // Otherwise, it is a newer calling convention, so return the\n        // prng directly.\n        else return prng;\n      })(\n  prng,\n  shortseed,\n  'global' in options ? options.global : (this == math),\n  options.state);\n}\n\n//\n// ARC4\n//\n// An ARC4 implementation.  The constructor takes a key in the form of\n// an array of at most (width) integers that should be 0 <= x < (width).\n//\n// The g(count) method returns a pseudorandom integer that concatenates\n// the next (count) outputs from ARC4.  Its return value is a number x\n// that is in the range 0 <= x < (width ^ count).\n//\nfunction ARC4(key) {\n  var t, keylen = key.length,\n      me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];\n\n  // The empty key [] is treated as [0].\n  if (!keylen) { key = [keylen++]; }\n\n  // Set up S using the standard key scheduling algorithm.\n  while (i < width) {\n    s[i] = i++;\n  }\n  for (i = 0; i < width; i++) {\n    s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];\n    s[j] = t;\n  }\n\n  // The \"g\" method returns the next (count) outputs as one number.\n  (me.g = function(count) {\n    // Using instance members instead of closure state nearly doubles speed.\n    var t, r = 0,\n        i = me.i, j = me.j, s = me.S;\n    while (count--) {\n      t = s[i = mask & (i + 1)];\n      r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];\n    }\n    me.i = i; me.j = j;\n    return r;\n    // For robust unpredictability, the function call below automatically\n    // discards an initial batch of values.  This is called RC4-drop[256].\n    // See http://google.com/search?q=rsa+fluhrer+response&btnI\n  })(width);\n}\n\n//\n// copy()\n// Copies internal state of ARC4 to or from a plain object.\n//\nfunction copy(f, t) {\n  t.i = f.i;\n  t.j = f.j;\n  t.S = f.S.slice();\n  return t;\n};\n\n//\n// flatten()\n// Converts an object tree to nested arrays of strings.\n//\nfunction flatten(obj, depth) {\n  var result = [], typ = (typeof obj), prop;\n  if (depth && typ == 'object') {\n    for (prop in obj) {\n      try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}\n    }\n  }\n  return (result.length ? result : typ == 'string' ? obj : obj + '\\0');\n}\n\n//\n// mixkey()\n// Mixes a string seed into a key that is an array of integers, and\n// returns a shortened string seed that is equivalent to the result key.\n//\nfunction mixkey(seed, key) {\n  var stringseed = seed + '', smear, j = 0;\n  while (j < stringseed.length) {\n    key[mask & j] =\n      mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));\n  }\n  return tostring(key);\n}\n\n//\n// autoseed()\n// Returns an object for autoseeding, using window.crypto and Node crypto\n// module if available.\n//\nfunction autoseed() {\n  try {\n    var out;\n    if (nodecrypto && (out = nodecrypto.randomBytes)) {\n      // The use of 'out' to remember randomBytes makes tight minified code.\n      out = out(width);\n    } else {\n      out = new Uint8Array(width);\n      (global.crypto || global.msCrypto).getRandomValues(out);\n    }\n    return tostring(out);\n  } catch (e) {\n    var browser = global.navigator,\n        plugins = browser && browser.plugins;\n    return [+new Date, global, plugins, global.screen, tostring(pool)];\n  }\n}\n\n//\n// tostring()\n// Converts an array of charcodes to a string\n//\nfunction tostring(a) {\n  return String.fromCharCode.apply(0, a);\n}\n\n//\n// When seedrandom.js is loaded, we immediately mix a few bits\n// from the built-in RNG into the entropy pool.  Because we do\n// not want to interfere with deterministic PRNG state later,\n// seedrandom will not call math.random on its own again after\n// initialization.\n//\nmixkey(math.random(), pool);\n\n//\n// Nodejs and AMD support: export the implementation as a module using\n// either convention.\n//\nif ((typeof module) == 'object' && module.exports) {\n  module.exports = seedrandom;\n  // When in node.js, try using crypto package for autoseeding.\n  try {\n    nodecrypto = require('crypto');\n  } catch (ex) {}\n} else if ((typeof define) == 'function' && define.amd) {\n  define(function() { return seedrandom; });\n} else {\n  // When included as a plain script, set up Math.seedrandom global.\n  math['seed' + rngname] = seedrandom;\n}\n\n\n// End anonymous scope, and pass initial values.\n})(\n  // global: `self` in browsers (including strict mode and web workers),\n  // otherwise `this` in Node and other environments\n  (typeof self !== 'undefined') ? self : this,\n  [],     // pool: entropy pool starts empty\n  Math    // math: package containing random, pow, and seedrandom\n);\n", "// A library of seedable RNGs implemented in Javascript.\n//\n// Usage:\n//\n// var seedrandom = require('seedrandom');\n// var random = seedrandom(1); // or any seed.\n// var x = random();       // 0 <= x < 1.  Every bit is random.\n// var x = random.quick(); // 0 <= x < 1.  32 bits of randomness.\n\n// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.\n// Period: ~2^116\n// Reported to pass all BigCrush tests.\nvar alea = require('./lib/alea');\n\n// xor128, a pure xor-shift generator by George Marsaglia.\n// Period: 2^128-1.\n// Reported to fail: MatrixRank and LinearComp.\nvar xor128 = require('./lib/xor128');\n\n// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.\n// Period: 2^192-2^32\n// Reported to fail: CollisionOver, SimpPoker, and LinearComp.\nvar xorwow = require('./lib/xorwow');\n\n// xorshift7, by François Panneton and Pierre L'ecuyer, takes\n// a different approach: it adds robustness by allowing more shifts\n// than Marsaglia's original three.  It is a 7-shift generator\n// with 256 bits, that passes BigCrush with no systmatic failures.\n// Period 2^256-1.\n// No systematic BigCrush failures reported.\nvar xorshift7 = require('./lib/xorshift7');\n\n// xor4096, by Richard Brent, is a 4096-bit xor-shift with a\n// very long period that also adds a Weyl generator. It also passes\n// BigCrush with no systematic failures.  Its long period may\n// be useful if you have many generators and need to avoid\n// collisions.\n// Period: 2^4128-2^32.\n// No systematic BigCrush failures reported.\nvar xor4096 = require('./lib/xor4096');\n\n// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random\n// number generator derived from ChaCha, a modern stream cipher.\n// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n// Period: ~2^127\n// No systematic BigCrush failures reported.\nvar tychei = require('./lib/tychei');\n\n// The original ARC4-based prng included in this library.\n// Period: ~2^1600\nvar sr = require('./seedrandom');\n\nsr.alea = alea;\nsr.xor128 = xor128;\nsr.xorwow = xorwow;\nsr.xorshift7 = xorshift7;\nsr.xor4096 = xor4096;\nsr.tychei = tychei;\n\nmodule.exports = sr;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as seedrandom from 'seedrandom';\n\nimport {expectNumbersClose, testEpsilon} from '../test_util';\nimport {TypedArray} from '../types';\n\nexport interface RandomBase {\n  nextValue(): number;\n}\n\nexport interface RandomGamma {\n  nextValue(): number;\n}\n\nexport interface RandNormalDataTypes {\n  float32: Float32Array;\n  int32: Int32Array;\n}\n\nexport interface RandGammaDataTypes {\n  float32: Float32Array;\n  int32: Int32Array;\n}\n\n// https://en.wikipedia.org/wiki/Marsaglia_polar_method\nexport class MPRandGauss implements RandomBase {\n  private mean: number;\n  private stdDev: number;\n  private nextVal: number;\n  private dtype?: keyof RandNormalDataTypes;\n  private truncated?: boolean;\n  private upper?: number;\n  private lower?: number;\n  private random: seedrandom.prng;\n\n  constructor(\n      mean: number, stdDeviation: number, dtype?: keyof RandNormalDataTypes,\n      truncated?: boolean, seed?: number) {\n    this.mean = mean;\n    this.stdDev = stdDeviation;\n    this.dtype = dtype;\n    this.nextVal = NaN;\n    this.truncated = truncated;\n    if (this.truncated) {\n      this.upper = this.mean + this.stdDev * 2;\n      this.lower = this.mean - this.stdDev * 2;\n    }\n    const seedValue = seed ? seed : Math.random();\n    this.random = seedrandom.alea(seedValue.toString());\n  }\n\n  /** Returns next sample from a Gaussian distribution. */\n  public nextValue(): number {\n    if (!isNaN(this.nextVal)) {\n      const value = this.nextVal;\n      this.nextVal = NaN;\n      return value;\n    }\n\n    let resultX: number, resultY: number;\n    let isValid = false;\n    while (!isValid) {\n      let v1: number, v2: number, s: number;\n      do {\n        v1 = 2 * this.random() - 1;\n        v2 = 2 * this.random() - 1;\n        s = v1 * v1 + v2 * v2;\n      } while (s >= 1 || s === 0);\n\n      const mul = Math.sqrt(-2.0 * Math.log(s) / s);\n      resultX = this.mean + this.stdDev * v1 * mul;\n      resultY = this.mean + this.stdDev * v2 * mul;\n\n      if (!this.truncated || this.isValidTruncated(resultX)) {\n        isValid = true;\n      }\n    }\n\n    if (!this.truncated || this.isValidTruncated(resultY)) {\n      this.nextVal = this.convertValue(resultY);\n    }\n    return this.convertValue(resultX);\n  }\n\n  /** Handles proper rounding for non-floating-point numbers. */\n  private convertValue(value: number): number {\n    if (this.dtype == null || this.dtype === 'float32') {\n      return value;\n    }\n    return Math.round(value);\n  }\n\n  /** Returns true if less than 2-standard-deviations from the mean. */\n  private isValidTruncated(value: number): boolean {\n    return value <= this.upper && value >= this.lower;\n  }\n}\n\n// Marsaglia, George, and Wai Wan Tsang. 2000. \"A Simple Method for Generating\n// Gamma Variables.\"\nexport class RandGamma implements RandomGamma {\n  private alpha: number;\n  private beta: number;\n  private d: number;\n  private c: number;\n  private dtype?: keyof RandGammaDataTypes;\n  private randu: seedrandom.prng;\n  private randn: MPRandGauss;\n\n  constructor(\n      alpha: number, beta: number, dtype: keyof RandGammaDataTypes,\n      seed?: number) {\n    this.alpha = alpha;\n    this.beta = 1 / beta;  // convert rate to scale parameter\n    this.dtype = dtype;\n\n    const seedValue = seed ? seed : Math.random();\n    this.randu = seedrandom.alea(seedValue.toString());\n    this.randn = new MPRandGauss(0, 1, dtype, false, this.randu());\n\n    if (alpha < 1) {\n      this.d = alpha + (2 / 3);\n    } else {\n      this.d = alpha - (1 / 3);\n    }\n    this.c = 1 / Math.sqrt(9 * this.d);\n  }\n\n  /** Returns next sample from a gamma distribution. */\n  public nextValue(): number {\n    let x2: number, v0: number, v1: number, x: number, u: number, v: number;\n    while (true) {\n      do {\n        x = this.randn.nextValue();\n        v = 1 + (this.c * x);\n      } while (v <= 0);\n      v *= v * v;\n      x2 = x * x;\n      v0 = 1 - (0.331 * x2 * x2);\n      v1 = (0.5 * x2) + (this.d * (1 - v + Math.log(v)));\n      u = this.randu();\n      if (u < v0 || Math.log(u) < v1) {\n        break;\n      }\n    }\n    v = (1 / this.beta) * this.d * v;\n    if (this.alpha < 1) {\n      v *= Math.pow(this.randu(), 1 / this.alpha);\n    }\n    return this.convertValue(v);\n  }\n  /** Handles proper rounding for non-floating-point numbers. */\n  private convertValue(value: number): number {\n    if (this.dtype === 'float32') {\n      return value;\n    }\n    return Math.round(value);\n  }\n}\n\nexport class UniformRandom implements RandomBase {\n  private min: number;\n  private range: number;\n  private random: seedrandom.prng;\n  private dtype?: keyof RandNormalDataTypes;\n\n  constructor(\n      min = 0, max = 1, dtype?: keyof RandNormalDataTypes,\n      seed?: string|number) {\n    this.min = min;\n    this.range = max - min;\n    this.dtype = dtype;\n    if (seed == null) {\n      seed = Math.random();\n    }\n    if (typeof seed === 'number') {\n      seed = seed.toString();\n    }\n\n    if (!this.canReturnFloat() && this.range <= 1) {\n      throw new Error(\n          `The difference between ${min} - ${max} <= 1 and dtype is not float`);\n    }\n    this.random = seedrandom.alea(seed);\n  }\n\n  /** Handles proper rounding for non floating point numbers. */\n  private canReturnFloat = () =>\n      (this.dtype == null || this.dtype === 'float32');\n\n  private convertValue(value: number): number {\n    if (this.canReturnFloat()) {\n      return value;\n    }\n    return Math.round(value);\n  }\n\n  nextValue() {\n    return this.convertValue(this.min + this.range * this.random());\n  }\n}\n\nexport function jarqueBeraNormalityTest(values: TypedArray|number[]) {\n  // https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test\n  const n = values.length;\n  const s = skewness(values);\n  const k = kurtosis(values);\n  const jb = n / 6 * (Math.pow(s, 2) + 0.25 * Math.pow(k - 3, 2));\n  // JB test requires 2-degress of freedom from Chi-Square @ 0.95:\n  // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm\n  const CHI_SQUARE_2DEG = 5.991;\n  if (jb > CHI_SQUARE_2DEG) {\n    throw new Error(`Invalid p-value for JB: ${jb}`);\n  }\n}\n\nexport function expectArrayInMeanStdRange(\n    actual: TypedArray|number[], expectedMean: number, expectedStdDev: number,\n    epsilon?: number) {\n  if (epsilon == null) {\n    epsilon = testEpsilon();\n  }\n  const actualMean = mean(actual);\n  expectNumbersClose(actualMean, expectedMean, epsilon);\n  expectNumbersClose(\n      standardDeviation(actual, actualMean), expectedStdDev, epsilon);\n}\n\nfunction mean(values: TypedArray|number[]) {\n  let sum = 0;\n  for (let i = 0; i < values.length; i++) {\n    sum += values[i];\n  }\n  return sum / values.length;\n}\n\nfunction standardDeviation(values: TypedArray|number[], mean: number) {\n  let squareDiffSum = 0;\n  for (let i = 0; i < values.length; i++) {\n    const diff = values[i] - mean;\n    squareDiffSum += diff * diff;\n  }\n  return Math.sqrt(squareDiffSum / values.length);\n}\n\nfunction kurtosis(values: TypedArray|number[]) {\n  // https://en.wikipedia.org/wiki/Kurtosis\n  const valuesMean = mean(values);\n  const n = values.length;\n  let sum2 = 0;\n  let sum4 = 0;\n  for (let i = 0; i < n; i++) {\n    const v = values[i] - valuesMean;\n    sum2 += Math.pow(v, 2);\n    sum4 += Math.pow(v, 4);\n  }\n  return (1 / n) * sum4 / Math.pow((1 / n) * sum2, 2);\n}\n\nfunction skewness(values: TypedArray|number[]) {\n  // https://en.wikipedia.org/wiki/Skewness\n  const valuesMean = mean(values);\n  const n = values.length;\n  let sum2 = 0;\n  let sum3 = 0;\n  for (let i = 0; i < n; i++) {\n    const v = values[i] - valuesMean;\n    sum2 += Math.pow(v, 2);\n    sum3 += Math.pow(v, 3);\n  }\n  return (1 / n) * sum3 / Math.pow((1 / (n - 1)) * sum2, 3 / 2);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {RandGamma} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a gamma distribution.\n *\n * ```js\n * tf.randomGamma([2, 2], 1).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param alpha The shape parameter of the gamma distribution.\n * @param beta The inverse scale parameter of the gamma distribution. Defaults\n *     to 1.\n * @param dtype The data type of the output. Defaults to float32.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomGamma_<R extends Rank>(\n    shape: ShapeMap[R], alpha: number, beta = 1,\n    dtype: 'float32'|'int32' = 'float32', seed?: number): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (beta == null) {\n    beta = 1;\n  }\n  if (dtype == null) {\n    dtype = 'float32';\n  }\n  if (dtype !== 'float32' && dtype !== 'int32') {\n    throw new Error(`Unsupported data type ${dtype}`);\n  }\n  const rgamma = new RandGamma(alpha, beta, dtype, seed);\n  const res = buffer(shape, dtype);\n  for (let i = 0; i < res.values.length; i++) {\n    res.values[i] = rgamma.nextValue();\n  }\n  return res.toTensor();\n}\n\nexport const randomGamma = /* @__PURE__ */ op({randomGamma_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {MPRandGauss} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a normal distribution.\n *\n * ```js\n * tf.randomNormal([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param mean The mean of the normal distribution.\n * @param stdDev The standard deviation of the normal distribution.\n * @param dtype The data type of the output.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomNormal_<R extends Rank>(\n    shape: ShapeMap[R], mean = 0, stdDev = 1, dtype?: 'float32'|'int32',\n    seed?: number): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (dtype != null && (dtype as DataType) === 'bool') {\n    throw new Error(`Unsupported data type ${dtype}`);\n  }\n  const randGauss =\n      new MPRandGauss(mean, stdDev, dtype, false /* truncated */, seed);\n  const res = buffer(shape, dtype);\n  for (let i = 0; i < res.values.length; i++) {\n    res.values[i] = randGauss.nextValue();\n  }\n  return res.toTensor();\n}\n\nexport const randomNormal = /* @__PURE__ */ op({randomNormal_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {op} from './operation';\nimport {randomNormal} from './random_normal';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a normal distribution.\n *\n * The generated values will have mean 0 and standard deviation 1.\n *\n * ```js\n * tf.randomStandardNormal([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The data type of the output.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomStandardNormal_<R extends Rank>(\n    shape: ShapeMap[R], dtype?: 'float32'|'int32', seed?: number): Tensor<R> {\n  if (dtype != null && (dtype as DataType) === 'bool') {\n    throw new Error(`Unsupported data type ${dtype}`);\n  }\n  return randomNormal(shape, 0, 1, dtype, seed);\n}\n\nexport const randomStandardNormal = /* @__PURE__ */ op({randomStandardNormal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {UniformRandom} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a uniform distribution.\n *\n * The generated values follow a uniform distribution in the range [minval,\n * maxval). The lower bound minval is included in the range, while the upper\n * bound maxval is excluded.\n *\n * ```js\n * tf.randomUniform([2, 2]).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param minval The lower bound on the range of random values to generate.\n *   Defaults to 0.\n * @param maxval The upper bound on the range of random values to generate.\n *   Defaults to 1.\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n * @param seed An optional int. Defaults to 0. If seed is set to be non-zero,\n *   the random number generator is seeded by the given seed. Otherwise, it is\n *   seeded by a random seed.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomUniform_<R extends Rank>(\n    shape: ShapeMap[R], minval = 0, maxval = 1, dtype: DataType = 'float32',\n    seed?: number|string): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  const res = buffer(shape, dtype);\n  const random = new UniformRandom(minval, maxval, null, seed);\n  for (let i = 0; i < res.values.length; i++) {\n    res.values[i] = random.nextValue();\n  }\n  return res.toTensor();\n}\n\nexport const randomUniform = /* @__PURE__ */ op({randomUniform_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {Rank, ShapeMap} from '../types';\nimport {op} from './operation';\nimport {randomUniform} from './random_uniform';\n\n/**\n * Creates a `tf.Tensor` with integers sampled from a uniform distribution.\n *\n * The generated values are uniform integers in the range [minval, maxval). The\n * lower bound minval is included in the range, while the upper bound maxval is\n * excluded.\n *\n * ```js\n * tf.randomUniformInt([2, 2], 0, 10).print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param minval Inclusive lower bound on the generated integers.\n * @param maxval Exclusive upper bound on the generated integers.\n * @param seed An optional int. Defaults to 0. If seed is set to be non-zero,\n *   the random number generator is seeded by the given seed. Otherwise, it is\n *   seeded by a random seed.\n *\n * @doc {heading: 'Tensors', subheading: 'Random'}\n */\nfunction randomUniformInt_<R extends Rank>(\n  shape: ShapeMap[R], minval: number, maxval: number,\n    seed?: number|string): Tensor<R> {\n  // TODO(mattsoulanille): Handle optional seed2 input.\n  return randomUniform(shape, minval, maxval, 'int32', seed);\n}\n\nexport const randomUniformInt = /* @__PURE__ */ op({randomUniformInt_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Range, RangeAttrs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor1D} from '../tensor';\n\n/**\n * Creates a new `tf.Tensor1D` filled with the numbers in the range provided.\n *\n * The tensor is a half-open interval meaning it includes start, but\n * excludes stop. Decrementing ranges and negative step values are also\n * supported.\n *\n *\n * ```js\n * tf.range(0, 9, 2).print();\n * ```\n *\n * @param start An integer start value\n * @param stop An integer stop value\n * @param step An integer increment (will default to 1 or -1)\n * @param dtype The data type of the output tensor. Defaults to 'float32'.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function range(\n    start: number, stop: number, step = 1,\n    dtype: 'float32'|'int32' = 'float32'): Tensor1D {\n  if (step === 0) {\n    throw new Error('Cannot have a step of zero');\n  }\n\n  const attrs: RangeAttrs = {start, stop, step, dtype};\n\n  return ENGINE.runKernel(Range, {} /* inputs */,\n      attrs as unknown as NamedAttrMap);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Real, RealInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Returns the real part of a complex (or real) tensor.\n *\n * Given a tensor input, this operation returns a tensor of type float that is\n * the real part of each element in input considered as a complex number.\n *\n * If the input is real, it simply makes a clone.\n *\n * ```js\n * const x = tf.complex([-2.25, 3.25], [4.75, 5.75]);\n * tf.real(x).print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction real_<T extends Tensor>(input: T|TensorLike): T {\n  const $input = convertToTensor(input, 'input', 'real');\n\n  const inputs: RealInputs = {input: $input};\n  return ENGINE.runKernel(Real, inputs as unknown as NamedTensorMap);\n}\n\nexport const real = /* @__PURE__ */ op({real_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reciprocal, ReciprocalInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes reciprocal of x element-wise: `1 / x`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, 2]);\n *\n * x.reciprocal().print();  // or tf.reciprocal(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction reciprocal_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'reciprocal');\n\n  const inputs: ReciprocalInputs = {x: $x};\n  return ENGINE.runKernel(Reciprocal, inputs as unknown as NamedTensorMap);\n}\nexport const reciprocal = /* @__PURE__ */ op({reciprocal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Relu, ReluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes rectified linear element-wise: `max(x, 0)`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.relu().print();  // or tf.relu(x)\n * ```\n * @param x The input tensor. If the dtype is `bool`, the output dtype will be\n *     `int32`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction relu_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'relu');\n\n  const inputs: ReluInputs = {x: $x};\n\n  return ENGINE.runKernel(Relu, inputs as unknown as NamedTensorMap);\n}\n\nexport const relu = /* @__PURE__ */ op({relu_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Relu6, Relu6Inputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes rectified linear 6 element-wise: `min(max(x, 0), 6)`.\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 8]);\n *\n * x.relu6().print();  // or tf.relu6(x)\n * ```\n * @param x The input tensor. If the dtype is `bool`, the output dtype will be\n *     `int32`.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction relu6_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'relu6');\n\n  const inputs: Relu6Inputs = {x: $x};\n\n  return ENGINE.runKernel(Relu6, inputs as unknown as NamedTensorMap);\n}\n\nexport const relu6 = /* @__PURE__ */ op({relu6_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Reverse, ReverseAttrs, ReverseInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Reverses a `tf.Tensor` along a specified axis.\n *\n * Also available are stricter rank-specific methods that assert that `x` is\n * of the given rank:\n *   - `tf.reverse1d`\n *   - `tf.reverse2d`\n *   - `tf.reverse3d`\n *   - `tf.reverse4d`\n *\n * Except `tf.reverse1d` (which does not have axis param), all methods have\n * same signature as this method.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n *\n * x.reverse().print();\n * ```\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * const axis = 1;\n * x.reverse(axis).print();\n * ```\n * @param x The input tensor to be reversed.\n * @param axis The set of dimensions to reverse. Must be in the\n *     range [-rank(x), rank(x)). Defaults to all axes.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction reverse_<T extends Tensor>(\n    x: T|TensorLike, axis?: number|number[]): T {\n  const $x = convertToTensor(x, 'x', 'reverse');\n\n  const inputs: ReverseInputs = {x: $x};\n  const attrs: ReverseAttrs = {dims: axis};\n\n  return ENGINE.runKernel(\n      Reverse, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const reverse = /* @__PURE__ */ op({reverse_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor1D`.\n *\n * @param x The input tensor.\n */\nfunction reverse1d_(x: Tensor1D|TensorLike): Tensor1D {\n  const $x = convertToTensor(x, 'x', 'reverse');\n  util.assert(\n      $x.rank === 1,\n      () => `Error in reverse1D: x must be rank 1 but got rank ${$x.rank}.`);\n  return reverse($x, 0);\n}\n\nexport const reverse1d = /* @__PURE__ */ op({reverse1d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor2D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n *     range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse2d_(x: Tensor2D|TensorLike, axis?: number|number[]): Tensor2D {\n  const $x = convertToTensor(x, 'x', 'reverse');\n  util.assert(\n      $x.rank === 2,\n      () => `Error in reverse2D: x must be rank 2 but got rank ${$x.rank}.`);\n  return reverse($x, axis);\n}\n\nexport const reverse2d = /* @__PURE__ */ op({reverse2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor3D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n *     range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse3d_(x: Tensor3D|TensorLike, axis?: number|number[]): Tensor3D {\n  const $x = convertToTensor(x, 'x', 'reverse');\n  util.assert(\n      $x.rank === 3,\n      () => `Error in reverse3D: x must be rank 3 but got rank ${$x.rank}.`);\n  return reverse($x, axis);\n}\n\nexport const reverse3d = /* @__PURE__ */ op({reverse3d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {op} from './operation';\nimport {reverse} from './reverse';\n\n/**\n * Reverses a `tf.Tensor4D` along a specified axis.\n *\n * @param x The input tensor.\n * @param axis The set of dimensions to reverse. Must be in the\n *     range [-rank(x), rank(x)). Defaults to all axes.\n */\nfunction reverse4d_(x: Tensor4D|TensorLike, axis?: number|number[]): Tensor4D {\n  const $x = convertToTensor(x, 'x', 'reverse');\n  util.assert(\n      $x.rank === 4,\n      () => `Error in reverse4D: x must be rank 4 but got rank ${$x.rank}.`);\n  return reverse($x, axis);\n}\n\nexport const reverse4d = /* @__PURE__ */ op({reverse4d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Round, RoundInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes round of input `tf.Tensor` element-wise: `round(x)`.\n * It implements banker's rounding.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3]);\n *\n * x.round().print();  // or tf.round(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction round_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'round');\n  const inputs: RoundInputs = {x: $x};\n\n  return ENGINE.runKernel(Round, inputs as unknown as NamedTensorMap);\n}\n\nexport const round = /* @__PURE__ */ op({round_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Rsqrt, RsqrtInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes reciprocal of square root of the input `tf.Tensor` element-wise:\n * `y = 1 / sqrt(x)`\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 4, -1]);\n *\n * x.rsqrt().print();  // or tf.rsqrt(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction rsqrt_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'rsqrt', 'float32');\n\n  const inputs: RsqrtInputs = {x: $x};\n\n  return ENGINE.runKernel(Rsqrt, inputs as unknown as NamedTensorMap);\n}\nexport const rsqrt = /* @__PURE__ */ op({rsqrt_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Selu, SeluInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes scaled exponential linear element-wise.\n *\n * `x < 0 ? scale * alpha * (exp(x) - 1) : scale * x`\n *\n * ```js\n * const x = tf.tensor1d([-1, 2, -3, 4]);\n *\n * x.selu().print();  // or tf.selu(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction selu_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'selu');\n\n  const inputs: SeluInputs = {x: $x};\n\n  return ENGINE.runKernel(Selu, inputs as unknown as NamedTensorMap);\n}\n\nexport const selu = /* @__PURE__ */ op({selu_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {conv2d} from './conv2d';\nimport {depthwiseConv2d} from './depthwise_conv2d';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * 2-D convolution with separable filters.\n *\n * Performs a depthwise convolution that acts separately on channels followed\n * by a pointwise convolution that mixes channels. Note that this is\n * separability between dimensions [1, 2] and 3, not spatial separability\n * between dimensions 1 and 2.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d](\n *     https://www.tensorflow.org/api_docs/python/tf/nn/separable_conv2d)\n * for more details.\n *\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param depthwiseFilter The depthwise filter tensor, rank 4, of shape\n *     `[filterHeight, filterWidth, inChannels, channelMultiplier]`. This is\n *     the filter used in the first step.\n * @param pointwiseFilter The pointwise filter tensor, rank 4, of shape\n *     `[1, 1, inChannels * channelMultiplier, outChannels]`. This is\n *     the filter used in the second step.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels]. Only \"NHWC\" is currently supported.\n *\n * @doc {heading: 'Operations', subheading: 'Convolution'}\n */\nfunction separableConv2d_<T extends Tensor3D|Tensor4D>(\n    x: T|TensorLike, depthwiseFilter: Tensor4D|TensorLike,\n    pointwiseFilter: Tensor4D|TensorLike, strides: [number, number]|number,\n    pad: 'valid'|'same', dilation: [number, number]|number = [1, 1],\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC'): T {\n  const $x = convertToTensor(x, 'x', 'separableConv2d');\n  const $depthwiseFilter =\n      convertToTensor(depthwiseFilter, 'depthwiseFilter', 'separableConv2d');\n  const $pointwiseFilter =\n      convertToTensor(pointwiseFilter, 'pointwiseFilter', 'separableConv2d');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n\n  if (dataFormat === 'NCHW') {\n    throw new Error(\n        'separableConv2d currently does not support dataFormat NCHW; only ' +\n        'NHWC is supported');\n  }\n\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in separableConv2d: input must be rank 4, but got ` +\n          `rank ${x4D.rank}.`);\n  util.assert(\n      $depthwiseFilter.rank === 4,\n      () => `Error in separableConv2d: depthwise filter must be rank 4, but ` +\n          `got rank ${$depthwiseFilter.rank}.`);\n  util.assert(\n      $pointwiseFilter.rank === 4,\n      () => `Error in separableConv2d: pointwise filter must be rank 4, but ` +\n          `got rank ${$depthwiseFilter.rank}.`);\n  util.assert(\n      $pointwiseFilter.shape[0] === 1,\n      () =>\n          `Error in separableConv2d: the first dimension of pointwise filter ` +\n          ` must be 1, but got ${$pointwiseFilter.shape[0]}.`);\n  util.assert(\n      $pointwiseFilter.shape[1] === 1,\n      () => `Error in separableConv2d: the second dimension of pointwise ` +\n          `filter must be 1, but got ${$pointwiseFilter.shape[1]}.`);\n\n  const inChannels = $depthwiseFilter.shape[2];\n  const channelMultiplier = $depthwiseFilter.shape[3];\n  util.assert(\n      $pointwiseFilter.shape[2] === inChannels * channelMultiplier,\n      () =>\n          `Error in separableConv2d: the third dimension of pointwise filter ` +\n          `must be ${inChannels * channelMultiplier}, ` +\n          `but got ${$pointwiseFilter.shape[2]}.`);\n\n  const depthwise = depthwiseConv2d(\n      x4D, $depthwiseFilter, strides, pad, dataFormat, dilation);\n  const pointwiseStride = 1;\n  const res =\n      conv2d(depthwise, $pointwiseFilter, pointwiseStride, 'valid', dataFormat);\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res as T;\n}\n\nexport const separableConv2d = /* @__PURE__ */ op({separableConv2d_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor, TensorBuffer} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\n/**\n * Computes the difference between two lists of numbers.\n *\n * Given a Tensor `x` and a Tensor `y`, this operation returns a Tensor `out`\n * that represents all values that are in `x` but not in `y`. The returned\n * Tensor `out` is sorted in the same order that the numbers appear in `x`\n * (duplicates are preserved). This operation also returns a Tensor indices that\n * represents the position of each out element in `x`. In other words:\n *\n * `out[i] = x[idx[i]] for i in [0, 1, ..., out.length - 1]`\n *\n * ```js\n * const x = [1, 2, 3, 4, 5, 6];\n * const y = [1, 3, 5];\n *\n * const [out, indices] = await tf.setdiff1dAsync(x, y);\n * out.print(); // [2, 4, 6]\n * indices.print(); // [1, 3, 5]\n * ```\n *\n * @param x 1-D Tensor. Values to keep.\n * @param y 1-D Tensor. Must have the same type as x. Values to exclude in the\n *     output.\n * @returns Promise of Tensor tuple [out, indices].\n *  out: Tensor with the same type as x.\n *  indices: A Tensor of type int32.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nasync function setdiff1dAsync_(\n    x: Tensor|TensorLike, y: Tensor|TensorLike): Promise<[Tensor, Tensor]> {\n  const $x = convertToTensor(x, 'x', 'setdiff1d');\n  const $y = convertToTensor(y, 'y', 'setdiff1d');\n\n  util.assert(\n      $x.dtype === $y.dtype,\n      () => `x and y should have the same dtype, but got x (${\n          $x.dtype}) and y (${$y.dtype}).`);\n\n  util.assert(\n      $x.rank === 1, () => `x should be 1D tensor, but got x (${$x.shape}).`);\n\n  util.assert(\n      $y.rank === 1, () => `y should be 1D tensor, but got y (${$y.shape}).`);\n\n  const xVals = await $x.data();\n  const yVals = await $y.data();\n  const ySet = new Set(yVals);\n\n  let outputSize = 0;\n  for (let i = 0; i < xVals.length; i++) {\n    if (!ySet.has(xVals[i])) {\n      outputSize++;\n    }\n  }\n\n  const buffer = new TensorBuffer([outputSize], $x.dtype);\n  const indices = new TensorBuffer([outputSize], 'int32');\n  for (let i = 0, p = 0; i < xVals.length; i++) {\n    if (!ySet.has(xVals[i])) {\n      buffer.values[p] = xVals[i];\n      indices.values[p] = i;\n      p++;\n    }\n  }\n  return [buffer.toTensor(), indices.toTensor()];\n}\nexport const setdiff1dAsync = setdiff1dAsync_;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sign, SignInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Returns an element-wise indication of the sign of a number.\n *\n * ```js\n * const x = tf.tensor1d([.6, 1.1, -3.3, NaN, 0]);\n *\n * x.sign().print();  // or tf.sign(x)\n * ```\n * @param x The input Tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sign_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sign');\n  const inputs: SignInputs = {x: $x};\n  return ENGINE.runKernel(Sign, inputs as unknown as NamedTensorMap);\n}\nexport const sign = /* @__PURE__ */ op({sign_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sin, SinInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes sin of the input Tensor element-wise: `sin(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.sin().print();  // or tf.sin(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sin_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sin', 'float32');\n\n  const inputs: SinInputs = {x: $x};\n\n  return ENGINE.runKernel(Sin, inputs as unknown as NamedTensorMap);\n}\nexport const sin = /* @__PURE__ */ op({sin_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Sinh, SinhInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes hyperbolic sin of the input `tf.Tensor` element-wise: `sinh(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, 1, -1, .7]);\n *\n * x.sinh().print();  // or tf.sinh(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction sinh_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'sinh');\n  const inputs: SinhInputs = {x: $x};\n\n  return ENGINE.runKernel(Sinh, inputs as unknown as NamedTensorMap);\n}\nexport const sinh = /* @__PURE__ */ op({sinh_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 1D slice from 1D array starting at coordinates `begin` and is\n * of length `size`. See `slice` for details.\n */\nfunction slice1d_(\n    x: Tensor1D|TensorLike, begin: number, size: number): Tensor1D {\n  const $x = convertToTensor(x, 'x', 'slice1d');\n  util.assert(\n      $x.rank === 1,\n      () =>\n          `slice1d expects a rank-1 tensor, but got a rank-${$x.rank} tensor`);\n  return slice($x, [begin], [size]);\n}\nexport const slice1d = /* @__PURE__ */ op({slice1d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 2D slice from a 2D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice2d_(\n    x: Tensor2D|TensorLike, begin: [number, number],\n    size: [number, number]): Tensor2D {\n  const $x = convertToTensor(x, 'x', 'slice2d');\n  util.assert(\n      $x.rank === 2,\n      () =>\n          `slice2d expects a rank-2 tensor, but got a rank-${$x.rank} tensor`);\n  return slice($x, begin, size);\n}\nexport const slice2d = /* @__PURE__ */ op({slice2d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 3D slice from a 3D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice3d_(\n    x: Tensor3D|TensorLike, begin: [number, number, number],\n    size: [number, number, number]): Tensor3D {\n  const $x = convertToTensor(x, 'x', 'slice3d');\n  util.assert(\n      $x.rank === 3,\n      () =>\n          `slice3d expects a rank-3 tensor, but got a rank-${$x.rank} tensor`);\n  return slice($x, begin, size);\n}\nexport const slice3d = /* @__PURE__ */ op({slice3d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {slice} from './slice';\n\n/**\n * Extracts a 4D slice from a 4D array starting at coordinates `begin` and\n * is of size `size`. See `slice` for details.\n */\nfunction slice4d_(\n    x: Tensor4D|TensorLike, begin: [number, number, number, number],\n    size: [number, number, number, number]): Tensor4D {\n  const $x = convertToTensor(x, 'x', 'slice4d');\n  util.assert(\n      $x.rank === 4,\n      () =>\n          `slice4d expects a rank-4 tensor, but got a rank-${$x.rank} tensor`);\n  return slice($x, begin, size);\n}\nexport const slice4d = /* @__PURE__ */ op({slice4d_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Softmax, SoftmaxAttrs, SoftmaxInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes the softmax normalized vector given the logits.\n *\n * ```js\n * const a = tf.tensor1d([1, 2, 3]);\n *\n * a.softmax().print();  // or tf.softmax(a)\n * ```\n *\n * ```js\n * const a = tf.tensor2d([2, 4, 6, 1, 2, 3], [2, 3]);\n *\n * a.softmax().print();  // or tf.softmax(a)\n * ```\n *\n * @param logits The logits array.\n * @param dim The dimension softmax would be performed on. Defaults to `-1`\n *     which indicates the last dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction softmax_<T extends Tensor>(logits: T|TensorLike, dim = -1): T {\n  const $logits = convertToTensor(logits, 'logits', 'softmax', 'float32');\n\n  if (dim === -1) {\n    dim = $logits.rank - 1;\n  }\n  if (dim !== $logits.rank - 1) {\n    throw Error(\n        'Softmax along a non-last dimension is not yet supported. ' +\n        `Logits was rank ${$logits.rank} and dim was ${dim}`);\n  }\n\n  const inputs: SoftmaxInputs = {logits: $logits};\n  const attrs: SoftmaxAttrs = {dim};\n\n  return ENGINE.runKernel(\n      Softmax, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const softmax = /* @__PURE__ */ op({softmax_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {FFT, FFTInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {assert} from '../../util';\nimport {op} from '../operation';\n\n/**\n * Fast Fourier transform.\n *\n * Computes the 1-dimensional discrete Fourier transform over the inner-most\n * dimension of input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([1, 2, 3]);\n * const x = tf.complex(real, imag);\n *\n * x.fft().print();  // tf.spectral.fft(x).print();\n * ```\n * @param input The complex input to compute an fft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction fft_(input: Tensor): Tensor {\n  assert(\n      input.dtype === 'complex64',\n      () => `The dtype for tf.spectral.fft() must be complex64 ` +\n          `but got ${input.dtype}.`);\n\n  const inputs: FFTInputs = {input};\n\n  return ENGINE.runKernel(FFT, inputs as unknown as NamedTensorMap);\n}\n\nexport const fft = /* @__PURE__ */ op({fft_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {IFFT, IFFTInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {assert} from '../../util';\nimport {op} from '../operation';\n\n/**\n * Inverse fast Fourier transform.\n *\n * Computes the inverse 1-dimensional discrete Fourier transform over the\n * inner-most dimension of input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([1, 2, 3]);\n * const x = tf.complex(real, imag);\n *\n * x.ifft().print();  // tf.spectral.ifft(x).print();\n * ```\n * @param input The complex input to compute an ifft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction ifft_(input: Tensor): Tensor {\n  assert(\n      input.dtype === 'complex64',\n      () => `The dtype for tf.spectral.ifft() must be complex64 ` +\n          `but got ${input.dtype}.`);\n\n  const inputs: IFFTInputs = {input};\n\n  return ENGINE.runKernel(IFFT, inputs as unknown as NamedTensorMap);\n}\n\nexport const ifft = /* @__PURE__ */ op({ifft_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor2D} from '../../tensor';\nimport {complex} from '../complex';\nimport {concat} from '../concat';\nimport {imag} from '../imag';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {real} from '../real';\nimport {reshape} from '../reshape';\nimport {reverse} from '../reverse';\nimport {scalar} from '../scalar';\nimport {slice} from '../slice';\n\nimport {ifft} from './ifft';\n\n/**\n * Inversed real value input fast Fourier transform.\n *\n * Computes the 1-dimensional inversed discrete Fourier transform over the\n * inner-most dimension of the real input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n * const imag = tf.tensor1d([0, 0, 0]);\n * const x = tf.complex(real, imag);\n *\n * x.irfft().print();\n * ```\n * @param input The real value input to compute an irfft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction irfft_(input: Tensor): Tensor {\n  const innerDimensionSize = input.shape[input.shape.length - 1];\n  const batch = input.size / innerDimensionSize;\n  let ret: Tensor;\n  if (innerDimensionSize <= 2) {\n    const complexInput = reshape(input, [batch, innerDimensionSize]);\n    ret = ifft(complexInput);\n  } else {\n    // The length of unique components of the DFT of a real-valued signal\n    // is 2 * (input_len - 1)\n    const outputShape = [batch, 2 * (innerDimensionSize - 1)];\n    const realInput = reshape(real(input), [batch, innerDimensionSize]);\n    const imagInput = reshape(imag(input), [batch, innerDimensionSize]);\n\n    const realConjugate =\n        reverse(slice(realInput, [0, 1], [batch, innerDimensionSize - 2]), 1);\n    const imagConjugate: Tensor2D = mul(\n        reverse(slice(imagInput, [0, 1], [batch, innerDimensionSize - 2]), 1),\n        scalar(-1));\n\n    const r = concat([realInput, realConjugate], 1);\n    const i = concat([imagInput, imagConjugate], 1);\n    const complexInput =\n        reshape(complex(r, i), [outputShape[0], outputShape[1]]);\n    ret = ifft(complexInput);\n  }\n  ret = real(ret);\n  // reshape the result if the input is 3D tensor.\n  if (input.rank === 3 && input.shape[0] !== 0) {\n    const temp = ret;\n    const batch = input.shape[0];\n    ret = reshape(ret, [batch, ret.shape[0] / batch, ret.shape[1]]);\n    temp.dispose();\n  }\n  return ret;\n}\n\nexport const irfft = /* @__PURE__ */ op({irfft_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {SplitV, SplitVAttrs, SplitVInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Splits a `tf.Tensor` into sub tensors.\n *\n * If `numOrSizeSplits` is a number, splits `x` along dimension `axis`\n * into `numOrSizeSplits` smaller tensors.\n * Requires that `numOrSizeSplits` evenly divides `x.shape[axis]`.\n *\n * If `numOrSizeSplits` is a number array, splits `x` into\n * `numOrSizeSplits.length` pieces. The shape of the `i`-th piece has the\n * same size as `x` except along dimension `axis` where the size is\n * `numOrSizeSplits[i]`.\n *\n * ```js\n * const x = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8], [2, 4]);\n * const [a, b] = tf.split(x, 2, 1);\n * a.print();\n * b.print();\n *\n * const [c, d, e] = tf.split(x, [1, 2, 1], 1);\n * c.print();\n * d.print();\n * e.print();\n * ```\n *\n * @param x The input tensor to split.\n * @param numOrSizeSplits Either an integer indicating the number of\n * splits along the axis or an array of integers containing the sizes of\n * each output tensor along the axis. If a number then it must evenly divide\n * `x.shape[axis]`; otherwise the sum of sizes must match `x.shape[axis]`.\n * Can contain one -1 indicating that dimension is to be inferred.\n * @param axis The dimension along which to split. Defaults to 0 (the first\n * dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction split_<T extends Tensor>(\n    x: Tensor|TensorLike, numOrSizeSplits: number[]|number, axis = 0): T[] {\n  const $x = convertToTensor(x, 'x', 'split');\n\n  const inputs: SplitVInputs = {x: $x};\n  const attr: SplitVAttrs = {numOrSizeSplits, axis};\n\n  return ENGINE.runKernel(\n             SplitV, inputs as unknown as NamedTensorMap,\n             attr as unknown as NamedAttrMap) as unknown as T[];\n}\n\nexport const split = /* @__PURE__ */ op({split_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {assert} from '../../util';\nimport {complex} from '../complex';\nimport {concat} from '../concat';\nimport {imag} from '../imag';\nimport {op} from '../operation';\nimport {real} from '../real';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {split} from '../split';\nimport {zeros} from '../zeros';\nimport {zerosLike} from '../zeros_like';\n\nimport {fft} from './fft';\n\n/**\n * Real value input fast Fourier transform.\n *\n * Computes the 1-dimensional discrete Fourier transform over the\n * inner-most dimension of the real input.\n *\n * ```js\n * const real = tf.tensor1d([1, 2, 3]);\n *\n * real.rfft().print();\n * ```\n * @param input The real value input to compute an rfft over.\n *\n * @doc {heading: 'Operations', subheading: 'Spectral', namespace: 'spectral'}\n */\nfunction rfft_(input: Tensor, fftLength?: number): Tensor {\n  assert(\n      input.dtype === 'float32',\n      () => `The dtype for rfft() must be real value but got ${input.dtype}`);\n\n  let innerDimensionSize = input.shape[input.shape.length - 1];\n  const batch = input.size / innerDimensionSize;\n\n  let adjustedInput: Tensor;\n  if (fftLength != null && fftLength < innerDimensionSize) {\n    // Need to crop\n    const begin = input.shape.map(v => 0);\n    const size = input.shape.map(v => v);\n    size[input.shape.length - 1] = fftLength;\n    adjustedInput = slice(input, begin, size);\n    innerDimensionSize = fftLength;\n  } else if (fftLength != null && fftLength > innerDimensionSize) {\n    // Need to pad with zeros\n    const zerosShape = input.shape.map(v => v);\n    zerosShape[input.shape.length - 1] = fftLength - innerDimensionSize;\n    adjustedInput = concat([input, zeros(zerosShape)], input.shape.length - 1);\n    innerDimensionSize = fftLength;\n  } else {\n    adjustedInput = input;\n  }\n\n  // Complement the input with zero imaginary numbers.\n  const zerosInput = zerosLike(adjustedInput);\n  const complexInput =\n      reshape(complex(adjustedInput, zerosInput), [batch, innerDimensionSize]);\n\n  const ret = fft(complexInput);\n\n  // Exclude complex conjugations. These conjugations are put symmetrically.\n  const half = Math.floor(innerDimensionSize / 2) + 1;\n  const realValues = real(ret);\n  const imagValues = imag(ret);\n  const realComplexConjugate = split(\n      realValues, [half, innerDimensionSize - half],\n      realValues.shape.length - 1);\n  const imagComplexConjugate = split(\n      imagValues, [half, innerDimensionSize - half],\n      imagValues.shape.length - 1);\n\n  const outputShape = adjustedInput.shape.slice();\n  outputShape[adjustedInput.shape.length - 1] = half;\n\n  return reshape(\n      complex(realComplexConjugate[0], imagComplexConjugate[0]), outputShape);\n}\n\nexport const rfft = /* @__PURE__ */ op({rfft_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SquaredDifference, SquaredDifferenceInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {assertAndGetBroadcastShape} from './broadcast_util';\nimport {op} from './operation';\n\n/**\n * Returns (a - b) * (a - b) element-wise.\n * Supports broadcasting.\n *\n * ```js\n * const a = tf.tensor1d([1, 4, 3, 16]);\n * const b = tf.tensor1d([1, 2, 9, 4]);\n *\n * a.squaredDifference(b).print();  // or tf.squaredDifference(a, b)\n * ```\n *\n * ```js\n * // Broadcast squared difference  a with b.\n * const a = tf.tensor1d([2, 4, 6, 8]);\n * const b = tf.scalar(5);\n *\n * a.squaredDifference(b).print();  // or tf.squaredDifference(a, b)\n * ```\n *\n * @param a The first tensor.\n * @param b The second tensor. Must have the same type as `a`.\n *\n * @doc {heading: 'Operations', subheading: 'Arithmetic'}\n */\nfunction squaredDifference_<T extends Tensor>(\n    a: Tensor|TensorLike, b: Tensor|TensorLike): T {\n  let $a = convertToTensor(a, 'a', 'squaredDifference');\n  let $b = convertToTensor(b, 'b', 'squaredDifference');\n  [$a, $b] = makeTypesMatch($a, $b);\n\n  assertAndGetBroadcastShape($a.shape, $b.shape);\n\n  const inputs: SquaredDifferenceInputs = {a: $a, b: $b};\n  const attrs = {};\n\n  return ENGINE.runKernel(\n      SquaredDifference, inputs as unknown as NamedTensorMap, attrs);\n}\n\nexport const squaredDifference = /* @__PURE__ */ op({squaredDifference_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {squeezeShape} from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Removes dimensions of size 1 from the shape of a `tf.Tensor`.\n *\n * ```js\n * const x = tf.tensor([1, 2, 3, 4], [1, 1, 4]);\n * x.squeeze().print();\n * ```\n *\n * @param x The input tensor to be squeezed.\n * @param axis An optional list of numbers. If specified, only\n *     squeezes the dimensions listed. The dimension index starts at 0. It\n * is an error to squeeze a dimension that is not 1.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction squeeze_<T extends Tensor>(x: Tensor|TensorLike, axis?: number[]): T {\n  const $x = convertToTensor(x, 'x', 'squeeze', 'string_or_numeric');\n  return reshape($x, squeezeShape($x.shape, axis).newShape) as T;\n}\n\nexport const squeeze = /* @__PURE__ */ op({squeeze_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Pack, PackAttrs, PackInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensorArray} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Stacks a list of rank-`R` `tf.Tensor`s into one rank-`(R+1)` `tf.Tensor`.\n *\n * ```js\n * const a = tf.tensor1d([1, 2]);\n * const b = tf.tensor1d([3, 4]);\n * const c = tf.tensor1d([5, 6]);\n * tf.stack([a, b, c]).print();\n * ```\n *\n * @param tensors A list of tensor objects with the same shape and dtype.\n * @param axis The axis to stack along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction stack_<T extends Tensor>(\n    tensors: Array<T|TensorLike>, axis = 0): Tensor {\n  const $tensors =\n      convertToTensorArray(tensors, 'tensors', 'stack', 'string_or_numeric');\n\n  util.assert(\n      $tensors.length >= 1, () => 'Pass at least one tensor to tf.stack');\n\n  if ($tensors.length > 0) {\n    util.assert(\n        axis <= $tensors[0].rank, () => 'Axis must be <= rank of the tensor');\n  }\n\n  const inputs: PackInputs = $tensors;\n  const attrs: PackAttrs = {axis};\n\n  return ENGINE.runKernel(\n      Pack, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const stack = /* @__PURE__ */ op({stack_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Step, StepAttrs, StepInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes step of the input `tf.Tensor` element-wise: `x > 0 ? 1 : alpha`\n *\n * ```js\n * const x = tf.tensor1d([0, 2, -1, -3]);\n *\n * x.step(.5).print();  // or tf.step(x, .5)\n * ```\n * @param x The input tensor.\n * @param alpha The gradient when input is negative. Defaults to 0.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction step_<T extends Tensor>(x: T|TensorLike, alpha = 0.0): T {\n  const $x = convertToTensor(x, 'x', 'step');\n\n  const inputs: StepInputs = {x: $x};\n  const attrs: StepAttrs = {alpha};\n\n  return ENGINE.runKernel(\n      Step, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\nexport const step = /* @__PURE__ */ op({step_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {StridedSlice, StridedSliceAttrs, StridedSliceInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Extracts a strided slice of a tensor.\n *\n * Roughly speaking, this op extracts a slice of size (end-begin)/stride from\n * the given input tensor (x). Starting at the location specified by begin the\n * slice continues by adding stride to the index until all dimensions are not\n * less than end. Note that a stride can be negative, which causes a reverse\n * slice.\n *\n * ```js\n * const t = tf.tensor3d([1, 1, 1 ,2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],\n *    [3, 2, 3]);\n * t.stridedSlice([1, 0, 0], [2, 1, 3], [1, 1, 1]).print()  // [[[3, 3, 3]]]\n * t.stridedSlice([1, 0, 0], [2, 2, 3], [1, 1, 1]).print()  // [[[3, 3, 3],\n *                                                     // [4, 4, 4]]]\n * t.stridedSlice([1, -1, 0], [2, -3, 3], [1, -1, 1]).print() // [[[4, 4, 4],\n *                                                     // [3, 3, 3]]]\n * ```\n *\n * @param x The tensor to stride slice.\n * @param begin The coordinates to start the slice from.\n * @param end: The coordinates to end the slice at.\n * @param strides: The size of the slice.\n * @param beginMask: If the ith bit of beginMask is set, begin[i] is ignored\n *      and the fullest possible range in that dimension is used instead.\n * @param endMask: If the ith bit of endMask is set, end[i] is ignored\n *      and the fullest possible range in that dimension is used instead.\n * @param shrinkAxisMask: a bitmask where bit i implies that\n * the ith specification should shrink the dimensionality. begin and end must\n * imply a slice of size 1 in the dimension.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction stridedSlice_(\n    x: Tensor|TensorLike, begin: number[], end: number[], strides?: number[],\n    beginMask = 0, endMask = 0, ellipsisMask = 0, newAxisMask = 0,\n    shrinkAxisMask = 0): Tensor {\n  const $x = convertToTensor(x, 'x', 'stridedSlice', 'string_or_numeric');\n\n  const inputs: StridedSliceInputs = {x: $x};\n  const attrs: StridedSliceAttrs = {\n    begin,\n    end,\n    strides,\n    beginMask,\n    endMask,\n    ellipsisMask,\n    newAxisMask,\n    shrinkAxisMask\n  };\n\n  return ENGINE.runKernel(\n      StridedSlice, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const stridedSlice = /* @__PURE__ */ op({stridedSlice_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tan, TanInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Computes tan of the input `tf.Tensor` element-wise, `tan(x)`\n *\n * ```js\n * const x = tf.tensor1d([0, Math.PI / 2, Math.PI * 3 / 4]);\n *\n * x.tan().print();  // or tf.tan(x)\n * ```\n * @param x The input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Basic math'}\n */\nfunction tan_<T extends Tensor>(x: T|TensorLike): T {\n  const $x = convertToTensor(x, 'x', 'tan', 'float32');\n\n  const inputs: TanInputs = {x: $x};\n\n  return ENGINE.runKernel(Tan, inputs as unknown as NamedTensorMap);\n}\nexport const tan = /* @__PURE__ */ op({tan_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {DataType, Rank, ShapeMap, WebGLData, WebGPUData} from '../types';\n\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates a `tf.Tensor` with the provided values, shape and dtype.\n *\n * ```js\n * // Pass an array of values to create a vector.\n * tf.tensor([1, 2, 3, 4]).print();\n * ```\n *\n * ```js\n * // Pass a nested array of values to make a matrix or a higher\n * // dimensional tensor.\n * tf.tensor([[1, 2], [3, 4]]).print();\n * ```\n *\n * ```js\n * // Pass a flat array and specify a shape yourself.\n * tf.tensor([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * ```js\n * // Pass a `WebGLData` object and specify a shape yourself.\n *\n * // This makes it possible for TF.js applications to avoid GPU / CPU sync.\n * // For example, if your application includes a preprocessing step on the GPU,\n * // you could upload the GPU output directly to TF.js, rather than first\n * // downloading the values.\n *\n * // Example for WebGL2:\n * if (tf.findBackend('custom-webgl') == null) {\n *   const customCanvas = document.createElement('canvas');\n *   const customBackend = new tf.MathBackendWebGL(customCanvas);\n *   tf.registerBackend('custom-webgl', () => customBackend);\n * }\n * const savedBackend = tf.getBackend();\n * await tf.setBackend('custom-webgl');\n * const gl = tf.backend().gpgpu.gl;\n * const texture = gl.createTexture();\n * const tex2d = gl.TEXTURE_2D;\n * const width = 2;\n * const height = 2;\n *\n * gl.bindTexture(tex2d, texture);\n * gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n * gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n * gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n * gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n * gl.texImage2D(\n *   tex2d, 0, gl.RGBA32F, // internalFormat\n *   width, height, 0,\n *   gl.RGBA, // textureFormat\n *   gl.FLOAT, // textureType\n *   new Float32Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])\n * );\n *\n * // Currently, the `texture` has 4 pixels:\n * // Pixel0 is {R:0, G:1, B:2, A:3}\n * // Pixel1 is {R:4, G:5, B:6, A:7}\n * // Pixel2 is {R:8, G:9, B:10, A:11}\n * // Pixel3 is {R:12, G:13, B:14, A:15}\n *\n * const logicalShape = [height * width * 2];\n * const a = tf.tensor({texture, height, width, channels: 'BR'}, logicalShape);\n * a.print();\n * // Tensor value will be [2, 0, 6, 4, 10, 8, 14, 12], since [2, 0] is the\n * // values of 'B' and 'R' channels of Pixel0, [6, 4] is the values of 'B' and\n * 'R'\n * // channels of Pixel1...\n *\n * // For postprocessing on the GPU, it's possible to retrieve the texture\n * // backing any tensor by calling the tensor's `dataToGPU` method like\n * // so:\n *\n * const tex = a.dataToGPU();\n * await tf.setBackend(savedBackend);\n * ```\n *\n * ```js\n * // Pass a `WebGPUData` object and specify a shape yourself.\n *\n * // This makes it possible for TF.js applications to avoid GPU / CPU sync.\n * // For example, if your application includes a preprocessing step on the GPU,\n * // you could upload the GPU output directly to TF.js, rather than first\n * // downloading the values. Unlike WebGL, this optionally supports zero copy\n * // by WebGPUData.zeroCopy. When zeroCopy is false or undefined(default), this\n * // passing GPUBuffer can be destroyed after tensor is created. When zeroCopy\n * // is true, this GPUBuffer is bound directly by the tensor, so do not destroy\n * // this GPUBuffer until all access is done.\n *\n * // Example for WebGPU:\n * function createGPUBufferFromData(device, data, dtype) {\n *   const bytesPerElement = 4;\n *   const sizeInBytes = data.length * bytesPerElement;\n *\n *   const gpuWriteBuffer = device.createBuffer({\n *     mappedAtCreation: true,\n *     size: sizeInBytes,\n *     usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC\n *   });\n *   const arrayBuffer = gpuWriteBuffer.getMappedRange();\n *   if (dtype === 'float32') {\n *     new Float32Array(arrayBuffer).set(data);\n *   } else if (dtype === 'int32') {\n *     new Int32Array(arrayBuffer).set(data);\n *   } else {\n *     throw new Error(\n *         `Creating tensor from GPUBuffer only supports` +\n *         `'float32'|'int32' dtype, while the dtype is ${dtype}.`);\n *   }\n *   gpuWriteBuffer.unmap();\n *\n *   const gpuReadBuffer = device.createBuffer({\n *     mappedAtCreation: false,\n *     size: sizeInBytes,\n *     usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.STORAGE |\n *         GPUBufferUsage.COPY_SRC\n *   });\n *\n *   const copyEncoder = device.createCommandEncoder();\n *   copyEncoder.copyBufferToBuffer(\n *       gpuWriteBuffer, 0, gpuReadBuffer, 0, sizeInBytes);\n *   const copyCommands = copyEncoder.finish();\n *   device.queue.submit([copyCommands]);\n *   gpuWriteBuffer.destroy();\n *   return gpuReadBuffer;\n * }\n *\n * const savedBackend = tf.getBackend();\n * await tf.setBackend('webgpu').catch(\n *     () => {throw new Error(\n *         'Failed to use WebGPU backend. Please use Chrome Canary to run.')});\n * const dtype = 'float32';\n * const device = tf.backend().device;\n * const aData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];\n * const bData = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4];\n * const expected = [2, 4, 6, 8, 6, 8, 10, 12, 10, 12, 14, 16, 14, 16, 18, 20];\n * const aBuffer = createGPUBufferFromData(device, aData, dtype);\n * const shape = [aData.length];\n * // To use zeroCopy, use {buffer: aBuffer, zeroCopy: true} instead and destroy\n * // aBuffer untill all access is done.\n * const a = tf.tensor({buffer: aBuffer}, shape, dtype);\n * const b = tf.tensor(bData, shape, dtype);\n * const result = tf.add(a, b);\n * result.print();\n * a.dispose();\n * b.dispose();\n * result.dispose();\n * aBuffer.destroy();\n * await tf.setBackend(savedBackend);\n * ```\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`(At the moment it supports Uint8Array,\n * Uint8ClampedArray, Int32Array, Float32Array) data types, or a `WebGLData`\n * object, or a `WebGPUData` object. If the values are strings, they will be\n * encoded as utf-8 and kept as `Uint8Array[]`. If the values is a `WebGLData`\n * object, the dtype could only be 'float32' or 'int32' and the object has to\n * have: 1. texture, a `WebGLTexture`, the texture must share the same\n * `WebGLRenderingContext` with TFJS's WebGL backend (you could create a custom\n * WebGL backend from your texture's canvas) and the internal texture format\n * for the input texture must be floating point or normalized integer; 2.\n * height, the height of the texture; 3. width, the width of the texture; 4.\n * channels, a non-empty subset of 'RGBA', indicating the values of which\n * channels will be passed to the tensor, such as 'R' or 'BR' (The order of the \n * channels affect the order of tensor values. ). (If the values passed from \n * texture is less than the tensor size, zeros will be padded at the rear.). If \n * the values is a `WebGPUData` object, the dtype could only be 'float32' or\n * 'int32 and the object has to have: buffer, a `GPUBuffer`. The buffer must:\n * 1. share the same `GPUDevice` with TFJS's WebGPU backend; 2. buffer.usage\n * should at least support GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC; 3.\n * buffer.size should not be smaller than the byte size of tensor shape.\n * WebGPUData optionally supports zero copy by flag zeroCopy. When zeroCopy is\n * false or undefined(default),this passing GPUBuffer can be destroyed after\n * tensor is created. When zeroCopy is true, this GPUBuffer is bound directly\n * by the tensor, so do not destroy this GPUBuffer until all access is done.\n * @param shape The shape of the tensor. Optional. If not provided,\n *   it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor<R extends Rank>(\n    values: TensorLike|WebGLData|WebGPUData, shape?: ShapeMap[R],\n    dtype?: DataType): Tensor<R> {\n  const inferredShape = inferShape(values, dtype);\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor<R>;\n}", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike1D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-1 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor1d` as it makes the code more readable.\n *\n * ```js\n * tf.tensor1d([1, 2, 3]).print();\n * ```\n *\n * @param values The values of the tensor. Can be array of numbers,\n *     or a `TypedArray`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor1d(values: TensorLike1D, dtype?: DataType): Tensor1D {\n  assertNonNull(values);\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 1) {\n    throw new Error('tensor1d() requires values to be a flat/TypedArray');\n  }\n  const shape: number[] = null;\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor1D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike2D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-2 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor2d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor2d([[1, 2], [3, 4]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n *     `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor2d(\n    values: TensorLike2D, shape?: [number, number],\n    dtype?: DataType): Tensor2D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 2) {\n    throw new Error('tensor2d() requires shape to have two numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 2 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor2d() requires values to be number[][] or flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor2d() requires shape to be provided when `values` ' +\n        'are a flat/TypedArray');\n  }\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor2D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike3D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor3d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor3d([[[1], [2]], [[3], [4]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided,  it is inferred from\n *     `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor3d(\n    values: TensorLike3D, shape?: [number, number, number],\n    dtype?: DataType): Tensor3D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 3) {\n    throw new Error('tensor3d() requires shape to have three numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 3 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor3d() requires values to be number[][][] or flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor3d() requires shape to be provided when `values` ' +\n        'are a flat array');\n  }\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor3D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor4D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike4D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-4 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor4d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor4d([[[[1], [2]], [[3], [4]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n *   it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor4d(\n    values: TensorLike4D, shape?: [number, number, number, number],\n    dtype?: DataType): Tensor4D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 4) {\n    throw new Error('tensor4d() requires shape to have four numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 4 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor4d() requires values to be number[][][][] or flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor4d() requires shape to be provided when `values` ' +\n        'are a flat array');\n  }\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor4D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor5D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike5D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-5 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor5d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor5d([[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n *   it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor5d(\n    values: TensorLike5D, shape?: [number, number, number, number, number],\n    dtype?: DataType): Tensor5D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 5) {\n    throw new Error('tensor5d() requires shape to have five numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 5 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor5d() requires values to be ' +\n        'number[][][][][] or flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor5d() requires shape to be provided when `values` ' +\n        'are a flat array');\n  }\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor5D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor6D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike6D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-6 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor6d` as it makes the code more readable.\n *\n *  ```js\n * // Pass a nested array.\n * tf.tensor6d([[[[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor6d([1, 2, 3, 4, 5, 6, 7, 8], [1, 1, 2, 2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n *     or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. Optional. If not provided,\n *   it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor6d(\n    values: TensorLike6D,\n    shape?: [number, number, number, number, number, number],\n    dtype?: DataType): Tensor6D {\n  assertNonNull(values);\n  if (shape != null && shape.length !== 6) {\n    throw new Error('tensor6d() requires shape to have six numbers');\n  }\n  const inferredShape = inferShape(values, dtype);\n  if (inferredShape.length !== 6 && inferredShape.length !== 1) {\n    throw new Error(\n        'tensor6d() requires values to be number[][][][][][] or ' +\n        'flat/TypedArray');\n  }\n  if (inferredShape.length === 1 && shape == null) {\n    throw new Error(\n        'tensor6d() requires shape to be provided when `values` ' +\n        'are a flat array');\n  }\n  shape = shape ||\n      inferredShape as [number, number, number, number, number, number];\n  return makeTensor(values, shape, inferredShape, dtype) as Tensor6D;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport { TensorInfo } from '../tensor_info';\nimport {Tensor} from '../tensor';\nimport {computeStrides, sizeFromShape} from '../util';\n\n/**\n * Check whether updates.shape = indices.shape[:batchDim] +\n * shape[sliceDim:]\n *\n * @param x The input tensor.\n */\nexport function validateUpdateShape(\n    shape: number[], indices: Tensor, updates: Tensor) {\n  const sliceDim = (indices.rank > 1) ? indices.shape[indices.rank - 1] : 1;\n  const batchDim = (indices.rank > 1) ? indices.rank - 1 : 1;\n\n  const shapeError = 'Must have updates.shape = indices.shape[:batchDim] + ' +\n      `shape[sliceDim:], got updates.shape: ${updates.shape}` +\n      `, indices.shape: ${indices.shape}, shape: ${shape}` +\n      `, sliceDim: ${sliceDim}, and batchDim: ${batchDim}.`;\n\n  if (updates.rank < batchDim) {\n    throw new Error(shapeError + ` update.rank < ${batchDim}. `);\n  }\n  if (shape.length < sliceDim + (updates.rank - batchDim)) {\n    throw new Error(\n        shapeError +\n        ` Output shape length < ${sliceDim + (updates.rank - batchDim)}`);\n  }\n  if (updates.rank !== batchDim + shape.length - sliceDim) {\n    throw new Error(\n        shapeError + ` update.rank != ${batchDim + shape.length - sliceDim}`);\n  }\n  for (let d = 0; d < batchDim; ++d) {\n    if (updates.shape[d] !== indices.shape[d]) {\n      throw new Error(\n          shapeError +\n          ` updates.shape[${d}] (${updates.shape[d]}) != indices.shape[${d}] (${\n              indices.shape[d]}).`);\n    }\n  }\n  for (let d = 0; d < updates.rank - batchDim; ++d) {\n    if (updates.shape[d + batchDim] !== shape[d + sliceDim]) {\n      throw new Error(\n          shapeError +\n          ` updates.shape[${d + batchDim}] (${\n              updates.shape[d + batchDim]}) != shape[${d + batchDim}] (${\n              shape[d + batchDim]})`);\n    }\n  }\n}\n\nexport interface ScatterShapeInfo {\n  sliceRank: number;\n  numUpdates: number;\n  sliceSize: number;\n  strides: number[];\n  outputSize: number;\n}\n/**\n * Validate scatter nd inputs.\n *\n * @param update The tensor contains the update values.\n * @param indices The tensor contains the indices for the update values.\n * @param shape The shape of the output tensor.\n */\nexport function validateInput(\n    updates: Tensor, indices: Tensor, shape: number[]) {\n  if (indices.rank < 1) {\n    throw new Error(\n        'tf.scatterND() expects the indices to be rank 1 or higher,' +\n        ` but the rank was ${indices.rank}.`);\n  }\n  if (updates.rank < 1) {\n    throw new Error(\n        'tf.scatterND() expects the updates to be rank 1 or higher,' +\n        ` but the rank was ${updates.rank}.`);\n  }\n  if (indices.dtype !== 'int32') {\n    throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${\n        indices.dtype}`);\n  }\n  if (shape.length < 1) {\n    throw new Error(\n        `Output rank must be greater or equal to 1, but got shape: ${shape}`);\n  }\n\n  if (shape.length === 0) {\n    if (indices.size === 0) {\n      throw new Error(`Indices specified for empty output. indices shape: ${\n          indices.shape}`);\n    }\n    if (updates.size === 0) {\n      throw new Error(`Updates specified for empty output. updates shape: ${\n          updates.shape}`);\n    }\n  }\n\n  validateUpdateShape(shape, indices, updates);\n}\n\n/**\n * Calculate the shape information for the output.\n *\n * @param update The tensor contains the update values.\n * @param indices The tensor contains the indices for the update values.\n * @param shape The shape of the output tensor.\n *\n * @returns ScatterShapeInfo\n */\nexport function calculateShapes(\n    updates: TensorInfo, indices: TensorInfo,\n    shape: number[]): ScatterShapeInfo {\n  // Calculate the number of dimensions in indices\n  const indicesRank = indices.shape.length;\n  const sliceRank = (indicesRank > 1) ? indices.shape[indicesRank - 1] : 1;\n\n  // Calculate the number of elements that make up each slice of our updated\n  // tensor. This allows us to work with flattened tensors and copy over whole\n  // slices at a time.\n  const totalNd = shape.length;\n\n  let sliceSize = 1;\n  for (let i = sliceRank; i < totalNd; ++i) {\n    sliceSize *= shape[i];\n  }\n\n  const safeSliceDim = (sliceRank < 1) ? 1 : sliceRank;\n  const numUpdates = sizeFromShape(indices.shape) / safeSliceDim;\n\n  const strides = [...computeStrides(shape.slice(0, sliceRank)), 1];\n  const outputSize = sizeFromShape(shape);\n  return {sliceRank, numUpdates, sliceSize, strides, outputSize};\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {TensorScatterUpdate, TensorScatterUpdateAttrs, TensorScatterUpdateInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, TensorLike} from '../types';\n\nimport {op} from './operation';\nimport * as scatter_nd_util from './scatter_nd_util';\n\n/**\n * Creates a new tensor by applying sparse updates to individual\n * values or slices to the passed in tensor according to\n * indices. This operator is the similar to scatterNd op, except that the\n * udpates are scattered on an existing tensor (as opposed to a zero-tensor).\n *\n * If indices contains duplicates, then we pick the last update for the index.\n *\n * If an out of bound index is found on CPU, an error is returned.\n *\n * Warning: There are some GPU specific semantics for this operation.\n *  - If an out of bound index is found, the index is ignored.\n *  - The order in which updates are applied is nondeterministic, so the output\n * will be nondeterministic if indices contains duplicates.\n * ```js\n * const shape = [8];\n * const tensor = tf.ones(shape);\n * const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');\n * const updates = tf.tensor1d([9, 10, 11, 12]);\n *\n * tf.tensorScatterUpdate(tensor, indices, updates).print();\n *    //[1, 11, 1, 10, 9, 1, 1, 12]\n * ```\n *\n * @param tensor A Tensor. Tensor to copy/update.\n * @param indices The tensor contains the indices into the output tensor, must\n *     have at least 2 axes: (num_updates, index_depth).\n * @param updates The tensor contains the value for the indices.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction tensorScatterUpdate_<R extends Rank>(\n    tensor: Tensor<R>|TensorLike, indices: Tensor|TensorLike,\n    updates: Tensor|TensorLike): Tensor<R> {\n  const $tensor = convertToTensor(tensor, 'tensor', 'tensorScatterupdate');\n  const $indices =\n      convertToTensor(indices, 'indices', 'tensorScatterupdate', 'int32');\n  const $updates = convertToTensor(updates, 'updates', 'tensorScatterupdate');\n  scatter_nd_util.validateInput($updates, $indices, $tensor.shape);\n  if ($tensor.dtype !== $updates.dtype) {\n    throw new Error(\n        `tensor and updates must have the same dtype, instead they are ${\n            $tensor.dtype} and ${$updates.dtype}.`);\n  }\n\n  const inputs: TensorScatterUpdateInputs = {\n    tensor: $tensor,\n    indices: $indices,\n    updates: $updates\n  };\n  const attrs: TensorScatterUpdateAttrs = {};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             TensorScatterUpdate, inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as Tensor<R>;\n}\n\nexport const tensorScatterUpdate = op({tensorScatterUpdate_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {TopK, TopKAttrs, TopKInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Finds the values and indices of the `k` largest entries along the last\n * dimension.\n *\n * If the input is a vector (rank=1), finds the k largest entries in the vector\n * and outputs their values and indices as vectors. Thus values[j] is the j-th\n * largest entry in input, and its index is indices[j].\n * For higher rank inputs, computes the top k entries along the last dimension.\n *\n * If two elements are equal, the lower-index element appears first.\n *\n * ```js\n * const a = tf.tensor2d([[1, 5], [4, 3]]);\n * const {values, indices} = tf.topk(a);\n * values.print();\n * indices.print();\n * ```\n * @param x 1-D or higher `tf.Tensor` with last dimension being at least `k`.\n * @param k Number of top elements to look for along the last dimension.\n * @param sorted If true, the resulting `k` elements will be sorted by the\n *     values in descending order.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction topk_<T extends Tensor>(\n    x: T|TensorLike, k = 1, sorted = true): {values: T, indices: T} {\n  const $x = convertToTensor(x, 'x', 'topk');\n  if ($x.rank === 0) {\n    throw new Error('topk() expects the input to be of rank 1 or higher');\n  }\n  const lastDim = $x.shape[$x.shape.length - 1];\n\n  if (k < 0) {\n    throw new Error(`'k' passed to topk() must be >= 0 but got ${k}`);\n  }\n\n  if (k > lastDim) {\n    throw new Error(\n        `'k' passed to topk() must be <= the last dimension (${lastDim}) ` +\n        `but got ${k}`);\n  }\n\n  const inputs: TopKInputs = {x: $x};\n  const attrs: TopKAttrs = {k, sorted};\n\n  const [values, indices] = ENGINE.runKernel(\n      TopK, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap) as [T, T];\n\n  return {values, indices};\n}\n\nexport const topk = /* @__PURE__ */ op({topk_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {DataType, Rank, ShapeMap} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {buffer} from './buffer';\nimport {op} from './operation';\nimport {MPRandGauss} from './rand_util';\n\n/**\n * Creates a `tf.Tensor` with values sampled from a truncated normal\n * distribution.\n *\n * ```js\n * tf.truncatedNormal([2, 2]).print();\n * ```\n *\n * The generated values follow a normal distribution with specified mean and\n * standard deviation, except that values whose magnitude is more than 2\n * standard deviations from the mean are dropped and re-picked.\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param mean The mean of the normal distribution.\n * @param stdDev The standard deviation of the normal distribution.\n * @param dtype The data type of the output tensor.\n * @param seed The seed for the random number generator.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction truncatedNormal_<R extends Rank>(\n    shape: ShapeMap[R], mean = 0, stdDev = 1, dtype?: 'float32'|'int32',\n    seed?: number): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  if (dtype != null && (dtype as DataType) === 'bool') {\n    throw new Error(`Unsupported data type $ { dtype }`);\n  }\n  const randGauss =\n      new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);\n  const res = buffer(shape, dtype);\n  for (let i = 0; i < res.values.length; i++) {\n    res.values[i] = randGauss.nextValue();\n  }\n  return res.toTensor();\n}\n\nexport const truncatedNormal = /* @__PURE__ */ op({truncatedNormal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Unique, UniqueAttrs, UniqueInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert} from '../util';\n\nimport {op} from './operation';\n\n/**\n * Finds unique elements along an axis of a tensor.\n *\n * It returns a tensor `values` containing all of the unique elements along the\n * `axis` of the given tensor `x` in the same order that they occur along the\n * `axis` in `x`; `x` does not need to be sorted. It also returns a tensor\n * `indices` the same size as the number of the elements in `x` along the `axis`\n * dimension. It contains the index in the unique output `values`.\n *\n * ```js\n * // A 1-D tensor\n * const a = tf.tensor1d([1, 1, 2, 4, 4, 4, 7, 8, 8]);\n * const {values, indices} = tf.unique(a);\n * values.print();   // [1, 2, 4, 7, 8,]\n * indices.print();  // [0, 0, 1, 2, 2, 2, 3, 4, 4]\n * ```\n *\n * ```js\n * // A 2-D tensor with axis=0\n * //\n * // 'a' is: [[1, 0, 0],\n * //          [1, 0, 0],\n * //          [2, 0, 0]]\n * const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);\n * const {values, indices} = tf.unique(a, 0)\n * values.print();   // [[1, 0, 0],\n *                   //  [2, 0, 0]]\n * indices.print();  // [0, 0, 1]\n * ```\n *\n * ```js\n * // A 2-D tensor with axis=1\n * //\n * // 'a' is: [[1, 0, 0],\n * //          [1, 0, 0],\n * //          [2, 0, 0]]\n * const a = tf.tensor2d([[1, 0, 0], [1, 0, 0], [2, 0, 0]]);\n * const {values, indices} = tf.unique(a, 1)\n * values.print();   // [[1, 0],\n *                   //  [1, 0],\n *                   //  [2, 0]]\n * indices.print();  // [0, 1, 1]\n * ```\n * @param x A tensor (int32, string, bool).\n * @param axis The axis of the tensor to find the unique elements.\n * @returns [uniqueElements, indices] (see above for details)\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nfunction unique_<T extends Tensor>(\n    x: T|TensorLike, axis = 0): {values: T, indices: Tensor1D} {\n  const $x = convertToTensor(x, 'x', 'unique', 'string_or_numeric');\n  assert($x.rank > 0, () => 'The input tensor must be at least 1D');\n\n  const inputs: UniqueInputs = {x: $x};\n  const attrs: UniqueAttrs = {axis};\n  const [values, indices] = ENGINE.runKernel(\n      Unique, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap) as [T, Tensor1D];\n  return {values, indices};\n}\n\nexport const unique = /* @__PURE__ */ op({unique_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert, isInt} from '../util';\n\nimport {op} from './operation';\n\n/**\n * Computes the sum along segments of a `tf.Tensor`.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * const segmentIds = tf.tensor1d([1, 2, 0, 1], 'int32');\n * const numSegments = 3;\n *\n * x.unsortedSegmentSum(segmentIds, numSegments).print()\n * //or tf.unsortedSegmentSum(x, segmentIds, numSegments)\n * ```\n * @param x The `tf.Tensor` that will be summed along its segments.\n * @param segmentIds A `tf.Tensor1D` whose rank is equal to the rank of `x`'s\n * dimension along the `axis`.  Maps each element of `x` to a segment.\n * @param numSegments The number of distinct `segmentIds`.\n *\n * @doc {heading: 'Operations', subheading: 'Segment'}\n */\nfunction unsortedSegmentSum_<T extends Tensor>(\n    x: T|TensorLike, segmentIds: Tensor1D|TensorLike, numSegments: number): T {\n  const $x = convertToTensor(x, 'x', 'unsortedSegmentSum');\n  const $segmentIds =\n      convertToTensor(segmentIds, 'segmentIds', 'unsortedSegmentSum', 'int32');\n  assert(isInt(numSegments), () => 'numSegments must be of dtype int');\n\n  const inputs: UnsortedSegmentSumInputs = {x: $x, segmentIds: $segmentIds};\n  const attrs: UnsortedSegmentSumAttrs = {numSegments};\n\n  return ENGINE.runKernel(\n      UnsortedSegmentSum, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const unsortedSegmentSum = /* @__PURE__ */ op({unsortedSegmentSum_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Unpack, UnpackAttrs, UnpackInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Unstacks a `tf.Tensor` of rank-`R` into a list of rank-`(R-1)` `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * tf.unstack(a).forEach(tensor => tensor.print());\n * ```\n *\n * @param x A tensor object.\n * @param axis The axis to unstack along. Defaults to 0 (the first dim).\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nfunction unstack_(x: Tensor|TensorLike, axis = 0): Tensor[] {\n  const $x = convertToTensor(x, 'x', 'unstack', 'string_or_numeric');\n  util.assert(\n      axis >= -$x.shape.length && axis < $x.shape.length,\n      () =>\n          `Axis = ${axis} is not in [-${$x.shape.length}, ${$x.shape.length})`);\n\n  const inputs: UnpackInputs = {value: $x};\n  const attrs: UnpackAttrs = {axis};\n\n  return ENGINE.runKernel(\n      Unpack, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const unstack = /* @__PURE__ */ op({unstack_});\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {TensorLike} from '../types';\nimport {searchSorted} from './search_sorted';\n\n/**\n * Searches for where a value would go in a sorted sequence.\n *\n * This is not a method for checking containment (like javascript in).\n *\n * The typical use case for this operation is \"binning\", \"bucketing\", or\n * \"discretizing\". The values are assigned to bucket-indices based on the edges\n * listed in 'sortedSequence'. This operation returns the bucket-index for each\n * value.\n *\n * The index returned corresponds to the first edge greater than the value.\n *\n * The axis is not settable for this operation. It always operates on the\n * innermost dimension (axis=-1). The operation will accept any number of outer\n * dimensions.\n *\n * Note: This operation assumes that 'upperBound' is sorted along the\n * innermost axis, maybe using 'sort(..., axis=-1)'. If the sequence is not\n * sorted no error is raised and the content of the returned tensor is not well\n * defined.\n *\n * ```js\n * const seq = tf.tensor1d([0, 3, 9, 10, 10]);\n * const values = tf.tensor1d([0, 4, 10]);\n * const result = tf.upperBound(seq, values);\n * result.print(); // [1, 2, 5]\n * ```\n * @param sortedSequence: N-D. Sorted sequence.\n * @param values: N-D. Search values.\n * @return An N-D int32 tensor the size of values containing the result of\n *     applying upper bound to each value. The result is not a global index to\n *     the entire Tensor, but the index in the last dimension.\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function upperBound(\n    sortedSequence: Tensor|TensorLike, values: Tensor|TensorLike): Tensor {\n  return searchSorted(sortedSequence, values, 'right');\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor, Variable} from '../tensor';\nimport {DataType, Rank} from '../types';\n\n/**\n * Creates a new variable with the provided initial value.\n * ```js\n * const x = tf.variable(tf.tensor([1, 2, 3]));\n * x.assign(tf.tensor([4, 5, 6]));\n *\n * x.print();\n * ```\n *\n * @param initialValue Initial value for the tensor.\n * @param trainable If true, optimizers are allowed to update it.\n * @param name Name of the variable. Defaults to a unique id.\n * @param dtype If set, initialValue will be converted to the given type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function variable<R extends Rank>(\n    initialValue: Tensor<R>, trainable = true, name?: string,\n    dtype?: DataType): Variable<R> {\n  return ENGINE.makeVariable(initialValue, trainable, name, dtype) as\n      Variable<R>;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** An implementation of the Where kernel shared between cpu and webgl */\n\nimport {buffer} from '../ops/buffer';\nimport {Tensor2D} from '../tensor';\nimport {TypedArray} from '../types';\n\nexport function whereImpl(condShape: number[], condVals: TypedArray): Tensor2D {\n  const indices = [];\n  for (let i = 0; i < condVals.length; i++) {\n    if (condVals[i]) {\n      indices.push(i);\n    }\n  }\n\n  const inBuffer = buffer(condShape, 'int32');\n\n  const out = buffer([indices.length, condShape.length], 'int32');\n  for (let i = 0; i < indices.length; i++) {\n    const loc = inBuffer.indexToLoc(indices[i]);\n    const offset = i * condShape.length;\n    out.values.set(loc, offset);\n  }\n  return out.toTensor() as Tensor2D;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {whereImpl} from '../backends/where_impl';\nimport {Tensor, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\n/**\n * Returns the coordinates of true elements of condition.\n *\n * The coordinates are returned in a 2-D tensor where the first dimension (rows)\n * represents the number of true elements, and the second dimension (columns)\n * represents the coordinates of the true elements. Keep in mind, the shape of\n * the output tensor can vary depending on how many true values there are in\n * input. Indices are output in row-major order. The resulting tensor has the\n * shape `[numTrueElems, condition.rank]`.\n *\n * This is analogous to calling the python `tf.where(cond)` without an x or y.\n *\n * ```js\n * const cond = tf.tensor1d([false, false, true], 'bool');\n * const result = await tf.whereAsync(cond);\n * result.print();\n * ```\n *\n * @doc {heading: 'Operations', subheading: 'Logical'}\n */\nasync function whereAsync_(condition: Tensor|TensorLike): Promise<Tensor2D> {\n  const $condition =\n      convertToTensor(condition, 'condition', 'whereAsync', 'bool');\n  const vals = await $condition.data();\n  const res = whereImpl($condition.shape, vals);\n  if (condition !== $condition) {\n    $condition.dispose();\n  }\n  return res;\n}\n\nexport const whereAsync = whereAsync_;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {gather} from './gather';\nimport {reshape} from './reshape';\nimport {squeeze} from './squeeze';\nimport {whereAsync} from './where_async';\n\n/**\n * Apply boolean mask to tensor.\n *\n * ```js\n * const tensor = tf.tensor2d([1, 2, 3, 4, 5, 6], [3, 2]);\n * const mask = tf.tensor1d([1, 0, 1], 'bool');\n * const result = await tf.booleanMaskAsync(tensor, mask);\n * result.print();\n * ```\n *\n * @param tensor N-D tensor.\n * @param mask K-D boolean tensor, K <= N and K must be known statically.\n * @param axis A 0-D int Tensor representing the axis in tensor to mask from.\n *     By default, axis is 0 which will mask from the first dimension.\n *     Otherwise K + axis <= N.\n *\n * @doc {heading: 'Tensors', subheading: 'Slicing and Joining'}\n */\nasync function booleanMaskAsync_(\n    tensor: Tensor|TensorLike, mask: Tensor|TensorLike,\n    axis?: number): Promise<Tensor> {\n  const $tensor = convertToTensor(tensor, 'tensor', 'boolMask');\n  const $mask = convertToTensor(mask, 'mask', 'boolMask', 'bool');\n\n  const axisFrom = axis == null ? 0 : axis;\n  const maskDim = $mask.rank;\n  const tensorShape = $tensor.shape;\n\n  util.assert(maskDim > 0, () => 'mask cannot be scalar');\n  util.assertShapesMatch(\n      tensorShape.slice(axisFrom, axisFrom + maskDim), $mask.shape,\n      `mask's shape must match the first K dimensions of tensor's shape,`);\n\n  let leadingSize = 1;\n  for (let i = axisFrom; i < axisFrom + maskDim; i++) {\n    leadingSize *= tensorShape[i];\n  }\n  const targetTensorShape =\n      tensorShape.slice(0, axisFrom)\n          .concat([leadingSize], tensorShape.slice(axisFrom + maskDim));\n  const reshapedTensor = reshape($tensor, targetTensorShape);\n  const reshapedMask = reshape($mask, [-1]);\n  const positivePositions = await whereAsync(reshapedMask);\n  const indices = squeeze(positivePositions, [1]);\n\n  const res = gather(reshapedTensor, indices, axisFrom);\n\n  // Ensure no memory leak.\n  if (tensor !== $tensor) {\n    $tensor.dispose();\n  }\n  if (mask !== $mask) {\n    $mask.dispose();\n  }\n  indices.dispose();\n  reshapedTensor.dispose();\n  reshapedMask.dispose();\n  positivePositions.dispose();\n\n  return res;\n}\n\nexport const booleanMaskAsync = booleanMaskAsync_;\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelBackend} from './backends/backend';\nimport {ENGINE, Engine, MemoryInfo, ProfileInfo, ScopeFn, TimingInfo} from './engine';\nimport {env} from './environment';\n\nimport {Platform} from './platforms/platform';\nimport {setDeprecationWarningFn, Tensor} from './tensor';\nimport {TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\n\n/**\n * Enables production mode which disables correctness checks in favor of\n * performance.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableProdMode(): void {\n  env().set('PROD', true);\n}\n\n/**\n * Enables debug mode which will log information about all executed kernels:\n * the elapsed time of the kernel execution, as well as the rank, shape, and\n * size of the output tensor.\n *\n * Debug mode will significantly slow down your application as it will\n * download the result of every operation to the CPU. This should not be used in\n * production. Debug mode does not affect the timing information of the kernel\n * execution as we do not measure download time in the kernel execution time.\n *\n * See also: `tf.profile`, `tf.memory`.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableDebugMode(): void {\n  env().set('DEBUG', true);\n}\n\n/** Globally disables deprecation warnings */\nexport function disableDeprecationWarnings(): void {\n  env().set('DEPRECATION_WARNINGS_ENABLED', false);\n  console.warn(`TensorFlow.js deprecation warnings have been disabled.`);\n}\n\n/** Warn users about deprecated functionality. */\nexport function deprecationWarn(msg: string) {\n  if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {\n    console.warn(\n        msg + ' You can disable deprecation warnings with ' +\n        'tf.disableDeprecationWarnings().');\n  }\n}\nsetDeprecationWarningFn(deprecationWarn);\n\n/**\n * Dispose all variables kept in backend engine.\n *\n * @doc {heading: 'Environment'}\n */\nexport function disposeVariables(): void {\n  ENGINE.disposeVariables();\n}\n\n/**\n * It returns the global engine that keeps track of all tensors and backends.\n *\n * @doc {heading: 'Environment'}\n */\nexport function engine(): Engine {\n  return ENGINE;\n}\n\n/**\n * Returns memory info at the current time in the program. The result is an\n * object with the following properties:\n *\n * - `numBytes`: Number of bytes allocated (undisposed) at this time.\n * - `numTensors`: Number of unique tensors allocated.\n * - `numDataBuffers`: Number of unique data buffers allocated\n *   (undisposed) at this time, which is ≤ the number of tensors\n *   (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same\n *   data buffer with `a`).\n * - `unreliable`: True if the memory usage is unreliable. See `reasons` when\n *    `unreliable` is true.\n * - `reasons`: `string[]`, reasons why the memory is unreliable, present if\n *    `unreliable` is true.\n *\n * WebGL Properties:\n * - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at\n *     this time.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function memory(): MemoryInfo {\n  return ENGINE.memory();\n}\n\n/**\n * Executes the provided function `f()` and returns a promise that resolves\n * with information about the function's memory use:\n * - `newBytes`: the number of new bytes allocated\n * - `newTensors`: the number of new tensors created\n * - `peakBytes`: the peak number of bytes allocated\n * - `kernels`: an array of objects for each kernel involved that reports\n * their input and output shapes, number of bytes used, and number of new\n * tensors created.\n * - `kernelNames`: an array of unique strings with just the names of the\n * kernels in the `kernels` array.\n *\n * ```js\n * const profile = await tf.profile(() => {\n *   const x = tf.tensor1d([1, 2, 3]);\n *   let x2 = x.square();\n *   x2.dispose();\n *   x2 = x.square();\n *   x2.dispose();\n *   return x;\n * });\n *\n * console.log(`newBytes: ${profile.newBytes}`);\n * console.log(`newTensors: ${profile.newTensors}`);\n * console.log(`byte usage over all kernels: ${profile.kernels.map(k =>\n * k.totalBytesSnapshot)}`);\n * ```\n *\n *\n * @doc {heading: 'Performance', subheading: 'Profile'}\n */\nexport function profile(f: () => (TensorContainer | Promise<TensorContainer>)):\n    Promise<ProfileInfo> {\n  return ENGINE.profile(f);\n}\n\n/**\n * Executes the provided function `fn` and after it is executed, cleans up all\n * intermediate tensors allocated by `fn` except those returned by `fn`.\n * `fn` must not return a Promise (async functions not allowed). The returned\n * result can be a complex object.\n *\n * Using this method helps avoid memory leaks. In general, wrap calls to\n * operations in `tf.tidy` for automatic memory cleanup.\n *\n * NOTE: Variables do *not* get cleaned up when inside a tidy(). If you want to\n * dispose variables, please use `tf.disposeVariables` or call dispose()\n * directly on variables.\n *\n * ```js\n * // y = 2 ^ 2 + 1\n * const y = tf.tidy(() => {\n *   // a, b, and one will be cleaned up when the tidy ends.\n *   const one = tf.scalar(1);\n *   const a = tf.scalar(2);\n *   const b = a.square();\n *\n *   console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n *   // The value returned inside the tidy function will return\n *   // through the tidy, in this case to the variable y.\n *   return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * y.print();\n * ```\n *\n * @param nameOrFn The name of the closure, or the function to execute.\n *     If a name is provided, the 2nd argument should be the function.\n *     If debug mode is on, the timing and the memory usage of the function\n *     will be tracked and displayed on the console using the provided name.\n * @param fn The function to execute.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function tidy<T extends TensorContainer>(\n    nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>): T {\n  return ENGINE.tidy(nameOrFn, fn);\n}\n\n/**\n * Disposes any `tf.Tensor`s found within the provided object.\n *\n * @param container an object that may be a `tf.Tensor` or may directly\n *     contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If\n *     the object is not a `tf.Tensor` or does not contain `Tensors`, nothing\n *     happens. In general it is safe to pass any object here, except that\n *     `Promise`s are not supported.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function dispose(container: TensorContainer) {\n  const tensors = getTensorsInContainer(container);\n  tensors.forEach(tensor => tensor.dispose());\n}\n\n/**\n * Keeps a `tf.Tensor` generated inside a `tf.tidy` from being disposed\n * automatically.\n *\n * ```js\n * let b;\n * const y = tf.tidy(() => {\n *   const one = tf.scalar(1);\n *   const a = tf.scalar(2);\n *\n *   // b will not be cleaned up by the tidy. a and one will be cleaned up\n *   // when the tidy ends.\n *   b = tf.keep(a.square());\n *\n *   console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n *   // The value returned inside the tidy function will return\n *   // through the tidy, in this case to the variable y.\n *   return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * console.log('y:');\n * y.print();\n * console.log('b:');\n * b.print();\n * ```\n *\n * @param result The tensor to keep from being disposed.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function keep<T extends Tensor>(result: T): T {\n  return ENGINE.keep(result);\n}\n\n/**\n * Executes `f()` and returns a promise that resolves with timing\n * information.\n *\n * The result is an object with the following properties:\n *\n * - `wallMs`: Wall execution time.\n * - `kernelMs`: Kernel execution time, ignoring data transfer. If using the\n * WebGL backend and the query timer extension is not available, this will\n * return an error object.\n * - On `WebGL` The following additional properties exist:\n *   - `uploadWaitMs`: CPU blocking time on texture uploads.\n *   - `downloadWaitMs`: CPU blocking time on texture downloads (readPixels).\n *\n * ```js\n * const x = tf.randomNormal([20, 20]);\n * const time = await tf.time(() => x.matMul(x));\n *\n * console.log(`kernelMs: ${time.kernelMs}, wallTimeMs: ${time.wallMs}`);\n * ```\n *\n * @param f The function to execute and time.\n *\n * @doc {heading: 'Performance', subheading: 'Timing'}\n */\nexport function time(f: () => void): Promise<TimingInfo> {\n  return ENGINE.time(f);\n}\n\n/**\n * Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and\n * executing operations on those tensors. Returns a promise that resolves\n * to a boolean if the backend initialization was successful.\n *\n * Note this disposes the current backend, if any, as well as any tensors\n * associated with it. A new backend is initialized, even if it is of the\n * same type as the previous one.\n *\n * @param backendName The name of the backend. Currently supports\n *     `'webgl'|'cpu'` in the browser, `'tensorflow'` under node.js\n *     (requires tfjs-node), and `'wasm'` (requires tfjs-backend-wasm).\n *\n * @doc {heading: 'Backends'}\n */\nexport function setBackend(backendName: string): Promise<boolean> {\n  return ENGINE.setBackend(backendName);\n}\n\n/**\n * Returns a promise that resolves when the currently selected backend (or the\n * highest priority one) has initialized. Await this promise when you are using\n * a backend that has async initialization.\n *\n * @doc {heading: 'Backends'}\n */\nexport function ready(): Promise<void> {\n  return ENGINE.ready();\n}\n\n/**\n * Returns the current backend name (cpu, webgl, etc). The backend is\n * responsible for creating tensors and executing operations on those tensors.\n *\n * @doc {heading: 'Backends'}\n */\nexport function getBackend(): string {\n  return ENGINE.backendName;\n}\n\n/**\n * Removes a backend and the registered factory.\n *\n * @doc {heading: 'Backends'}\n */\nexport function removeBackend(name: string): void {\n  ENGINE.removeBackend(name);\n}\n\n/**\n * Finds the backend registered under the provided name. Returns null if the\n * name is not in the registry, or the registration hasn't finished yet.\n */\nexport function findBackend(name: string): KernelBackend {\n  return ENGINE.findBackend(name);\n}\n\n/**\n * Finds the backend factory registered under the provided name. Returns a\n * function that produces a new backend when called. Returns null if the name\n * is not in the registry.\n */\nexport function findBackendFactory(name: string): () =>\n    KernelBackend | Promise<KernelBackend> {\n  return ENGINE.findBackendFactory(name);\n}\n\n/**\n * Registers a global backend. The registration should happen when importing\n * a module file (e.g. when importing `backend_webgl.ts`), and is used for\n * modular builds (e.g. custom tfjs bundle with only webgl support).\n *\n * @param factory The backend factory function. When called, it should\n * return a backend instance, or a promise of an instance.\n * @param priority The priority of the backend (higher = more important).\n *     In case multiple backends are registered, the priority is used to find\n *     the best backend. Defaults to 1.\n * @return False if there is already a registered backend under this name, true\n *     if not.\n *\n * @doc {heading: 'Backends'}\n */\nexport function registerBackend(\n    name: string, factory: () => KernelBackend | Promise<KernelBackend>,\n    priority = 1): boolean {\n  return ENGINE.registerBackend(name, factory, priority);\n}\n\n/**\n * Gets the current backend. If no backends have been initialized, this will\n * attempt to initialize the best backend. Will throw an error if the highest\n * priority backend has async initialization, in which case you should call\n * 'await tf.ready()' before running other code.\n *\n * @doc {heading: 'Backends'}\n */\nexport function backend(): KernelBackend {\n  return ENGINE.backend;\n}\n\n/**\n * Sets the global platform.\n *\n * @param platformName The name of this platform.\n * @param platform A platform implementation.\n */\nexport function setPlatform(platformName: string, platform: Platform) {\n  env().setPlatform(platformName, platform);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {tidy} from '../globals';\nimport {Transpose, TransposeAttrs, TransposeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\nimport {complex} from './complex';\nimport {imag} from './imag';\nimport {neg} from './neg';\nimport {op} from './operation';\nimport {real} from './real';\n\n/**\n * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.\n *\n * The returned `tf.Tensor`'s dimension `i` will correspond to the input\n * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,\n * where `n` is the rank of the input `tf.Tensor`. Hence by default, this\n * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);\n *\n * a.transpose().print();  // or tf.transpose(a)\n * ```\n *\n * @param x The tensor to transpose.\n * @param perm The permutation of the dimensions of a.\n * @param conjugate Will conjugate complex input if true.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_<T extends Tensor>(\n    x: T|TensorLike, perm?: number[], conjugate?: boolean): T {\n  const $x = convertToTensor(x, 'x', 'transpose');\n\n  if (perm == null) {\n    perm = $x.shape.map((s, i) => i).reverse();\n  }\n  util.assert(\n      $x.rank === perm.length,\n      () => `Error in transpose: rank of input ${$x.rank} ` +\n          `must match length of perm ${perm}.`);\n  perm.forEach(axis => {\n    util.assert(\n        axis >= 0 && axis < $x.rank,\n        () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +\n            ` but got ${perm}`);\n  });\n\n  if ($x.rank <= 1) {\n    return $x.clone();\n  }\n\n  const inputs: TransposeInputs = {x: $x};\n  const attrs: TransposeAttrs = {perm};\n\n  if ($x.dtype === 'complex64') {\n    return tidy(() => {\n      let $real = real($x);\n      let $imag = imag($x);\n      $real = ENGINE.runKernel(\n          Transpose, {x: $real} as unknown as NamedTensorMap,\n          attrs as unknown as NamedAttrMap);\n      $imag = ENGINE.runKernel(\n          Transpose, {x: $imag} as unknown as NamedTensorMap,\n          attrs as unknown as NamedAttrMap);\n      if (conjugate) {\n        $imag = neg($imag);\n      }\n      return complex($real, $imag);\n    });\n  }\n\n  return ENGINE.runKernel(\n      Transpose, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const transpose = /* @__PURE__ */ op({transpose_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor} from '../tensor';\nimport {assertTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {add} from './add';\nimport {div} from './div';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {pow} from './pow';\nimport {scalar} from './scalar';\nimport {sub} from './sub';\n\n/**\n * Compute the moving average of a variable.\n *\n * Without zeroDebias, the moving average operation is defined by:\n *   `v += delta`\n * where\n *   `delta = (1 - decay) * (x - v)`\n *\n * With zeroDebias (default), the `delta` term is scaled to debias the\n * effect of the (assumed) zero-initialization of `v`.\n *   `delta /= (1 - decay ^ step)`\n *\n * For more details on the zero-debiasing algorithm, see:\n *   https://arxiv.org/abs/1412.6980\n *\n * Note that this function is completely stateless and does not keep track of\n * step count. The step count needs to be maintained by the caller and passed\n * in as `step`.\n *\n * @param v The current moving average value.\n * @param x New input value, must have the same shape and dtype as `v`.\n * @param decay The decay factor. Typical values are 0.95 and 0.99.\n * @param step Step count.\n * @param zeroDebias: Whether zeroDebias is to be performed (default: `true`).\n * @returns The new moving average value.\n *\n * @doc {heading: 'Operations', subheading: 'Moving Average'}\n */\nfunction movingAverage_<T extends Tensor>(\n    v: T|TensorLike, x: T|TensorLike, decay: number|Scalar,\n    step?: number|Scalar, zeroDebias = true): T {\n  const $v = convertToTensor(v, 'v', 'movingAverage');\n  const $x = convertToTensor(x, 'x', 'movingAverage');\n  const $decay = convertToTensor(decay, 'decay', 'movingAverage');\n\n  assertTypesMatch($v, $x);\n  util.assert(\n      util.arraysEqual($v.shape, $x.shape), () => 'Shape mismatch in v and x');\n\n  const one = scalar(1);\n  const oneMinusDecay = sub(one, $decay);\n\n  let update = mul(sub($x, $v), oneMinusDecay);\n  if (zeroDebias) {\n    util.assert(\n        step != null, () => 'When using zeroDebias: true, step is required.');\n    const $step = convertToTensor(step, 'step', 'movingAverage');\n    update = div(update, sub(one, pow($decay, $step)));\n  }\n  return add($v, update);\n}\n\nexport const movingAverage = /* @__PURE__ */ op({movingAverage_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {ScatterNd, ScatterNdAttrs, ScatterNdInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\nimport * as scatter_nd_util from './scatter_nd_util';\n\n/**\n * Creates a new tensor by applying sparse updates to individual\n * values or slices within a zero tensor of the given shape tensor according to\n * indices. This operator is the inverse of the `tf.gatherND` operator which\n * extracts values or slices from a given tensor.\n *\n * ```js\n * const indices = tf.tensor2d([4, 3, 1, 7], [4, 1], 'int32');\n * const updates = tf.tensor1d([9, 10, 11, 12]);\n * const shape = [8];\n * tf.scatterND(indices, updates, shape).print() //[0, 11, 0, 10, 9, 0, 0, 12]\n * ```\n *\n * @param indices The tensor contains the indices into the output tensor.\n * @param updates The tensor contains the value for the indices.\n * @param shape: The shape of the output tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction scatterND_<R extends Rank>(\n    indices: Tensor|TensorLike, updates: Tensor|TensorLike,\n    shape: ShapeMap[R]): Tensor<R> {\n  assertNonNegativeIntegerDimensions(shape);\n  const $indices = convertToTensor(indices, 'indices', 'scatterND', 'int32');\n  const $updates = convertToTensor(updates, 'updates', 'scatterND');\n  scatter_nd_util.validateInput($updates, $indices, shape);\n\n  const inputs: ScatterNdInputs = {indices: $indices, updates: $updates};\n  const attrs: ScatterNdAttrs = {shape};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             ScatterNd, inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as Tensor<R>;\n}\n\nexport const scatterND = /* @__PURE__ */ op({scatterND_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../tensor';\n\n/**\n * Validate sparseToDense inputs.\n *\n * @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.\n * sparseIndices[i] contains the complete index where sparseValues[i] will be\n * placed.\n * @param sparseValues A 0-D or 1-D Tensor. Values\n * corresponding to each row of sparseIndices, or a scalar value to be used for\n * all sparse indices.\n * @param outputShape number[]. Shape of the dense output tensor.\n * @param validateIndices boolean. indice validation is not supported, error\n * will be thrown if it is set.\n */\nexport function validateInput(\n    sparseIndices: Tensor, sparseValues: Tensor, outputShape: number[],\n    defaultValues: Tensor) {\n  if (sparseIndices.dtype !== 'int32') {\n    throw new Error(\n        'tf.sparseToDense() expects the indices to be int32 type,' +\n        ` but the dtype was ${sparseIndices.dtype}.`);\n  }\n  if (sparseIndices.rank > 2) {\n    throw new Error(\n        'sparseIndices should be a scalar, vector, or matrix,' +\n        ` but got shape ${sparseIndices.shape}.`);\n  }\n\n  const numElems = sparseIndices.rank > 0 ? sparseIndices.shape[0] : 1;\n  const numDims = sparseIndices.rank > 1 ? sparseIndices.shape[1] : 1;\n\n  if (outputShape.length !== numDims) {\n    throw new Error(\n        'outputShape has incorrect number of elements:,' +\n        ` ${outputShape.length}, should be: ${numDims}.`);\n  }\n\n  const numValues = sparseValues.size;\n  if (!(sparseValues.rank === 0 ||\n        sparseValues.rank === 1 && numValues === numElems)) {\n    throw new Error(\n        'sparseValues has incorrect shape ' +\n        `${sparseValues.shape}, should be [] or [${numElems}]`);\n  }\n\n  if (sparseValues.dtype !== defaultValues.dtype) {\n    throw new Error('sparseValues.dtype must match defaultValues.dtype');\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {SparseToDense, SparseToDenseAttrs, SparseToDenseInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport * as sparse_to_dense from '../ops/sparse_to_dense_util';\nimport {Scalar, Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ScalarLike, ShapeMap, TensorLike} from '../types';\nimport {assertNonNegativeIntegerDimensions} from '../util_base';\n\nimport {op} from './operation';\n\n/**\n * Converts a sparse representation into a dense tensor.\n *\n * Builds an array dense with shape outputShape such that:\n *\n * // If sparseIndices is scalar\n * dense[i] = (i == sparseIndices ? sparseValues : defaultValue)\n *\n * // If sparseIndices is a vector, then for each i\n * dense[sparseIndices[i]] = sparseValues[i]\n *\n * // If sparseIndices is an n by d matrix, then for each i in [0, n)\n * dense[sparseIndices[i][0], ..., sparseIndices[i][d-1]] = sparseValues[i]\n * All other values in dense are set to defaultValue. If sparseValues is a\n * scalar, all sparse indices are set to this single value.\n *\n * If indices are repeated the final value is summed over all values for those\n * indices.\n *\n * ```js\n * const indices = tf.tensor1d([4, 5, 6, 1, 2, 3], 'int32');\n * const values = tf.tensor1d([10, 11, 12, 13, 14, 15], 'float32');\n * const shape = [8];\n * tf.sparseToDense(indices, values, shape).print();\n * ```\n *\n * @param sparseIndices A 0-D, 1-D, or 2-D Tensor of type int32.\n * sparseIndices[i] contains the complete index where sparseValues[i] will be\n * placed.\n * @param sparseValues A 0-D or 1-D Tensor. Values\n * corresponding to each row of sparseIndices, or a scalar value to be used for\n * all sparse indices.\n * @param outputShape Shape of the dense output tensor. The type is inferred.\n * @param defaultValue Scalar. Value to set for indices not specified in\n * sparseIndices. Defaults to zero.\n *\n * @doc {heading: 'Operations', subheading: 'Normalization'}\n */\nfunction sparseToDense_<R extends Rank>(\n    sparseIndices: Tensor|TensorLike, sparseValues: Tensor|TensorLike,\n    outputShape: ShapeMap[R], defaultValue: Scalar|ScalarLike = 0): Tensor<R> {\n  assertNonNegativeIntegerDimensions(outputShape);\n\n  const $sparseIndices =\n      convertToTensor(sparseIndices, 'sparseIndices', 'sparseToDense', 'int32');\n  const $sparseValues = convertToTensor(\n      sparseValues, 'sparseValues', 'sparseToDense', 'string_or_numeric');\n  const $defaultValue = convertToTensor(\n      defaultValue, 'defaultValue', 'sparseToDense', $sparseValues.dtype);\n\n  sparse_to_dense.validateInput(\n      $sparseIndices, $sparseValues, outputShape, $defaultValue);\n\n  const inputs: SparseToDenseInputs = {\n    sparseIndices: $sparseIndices,\n    sparseValues: $sparseValues,\n    defaultValue: $defaultValue\n  };\n\n  const attrs: SparseToDenseAttrs = {outputShape};\n\n  return ENGINE.runKernel(\n      SparseToDense, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const sparseToDense = /* @__PURE__ */ op({sparseToDense_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {GatherNd, GatherNdInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {op} from './operation';\n\n/**\n * Gather slices from input tensor into a Tensor with shape specified by\n * `indices`.\n *\n * `indices` is a K-dimensional integer tensor, best thought of as a\n * (K-1)-dimensional tensor of indices into input, where each element defines a\n * slice of input:\n * output[\\\\(i_0, ..., i_{K-2}\\\\)] = input[indices[\\\\(i_0, ..., i_{K-2}\\\\)]]\n *\n * Whereas in `tf.gather`, `indices` defines slices into the first dimension of\n * input, in `tf.gatherND`, `indices` defines slices into the first N dimensions\n * of input, where N = indices.shape[-1].\n *\n * The last dimension of indices can be at most the rank of input:\n * indices.shape[-1] <= input.rank\n *\n * The last dimension of `indices` corresponds to elements\n * (if indices.shape[-1] == input.rank) or slices\n * (if indices.shape[-1] < input.rank) along dimension indices.shape[-1] of\n * input.\n * The output tensor has shape\n * indices.shape[:-1] + input.shape[indices.shape[-1]:]\n *\n * Note that on CPU, if an out of bound index is found, an error is returned. On\n * GPU, if an out of bound index is found, a 0 is stored in the corresponding\n * output value.\n *\n * ```js\n * const indices = tf.tensor2d([0, 1, 1, 0], [2,2], 'int32');\n * const input = tf.tensor2d([9, 10, 11, 12], [2, 2]);\n * tf.gatherND(input, indices).print() // [10, 11]\n * ```\n *\n * @param x The tensor from which to gather values.\n * @param indices Index tensor, must be of type int32.\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nfunction gatherND_(x: Tensor|TensorLike, indices: Tensor|TensorLike): Tensor {\n  const $indices = convertToTensor(indices, 'indices', 'gatherND', 'int32');\n  const $x = convertToTensor(x, 'x', 'gatherND', 'string_or_numeric');\n\n  const inputs: GatherNdInputs = {params: $x, indices: $indices};\n\n  return ENGINE.runKernel(GatherNd, inputs as unknown as NamedTensorMap);\n}\n\nexport const gatherND = /* @__PURE__ */ op({gatherND_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport * as util from '../util';\n\n/**\n * Normalize noise shape based on provided tensor and noise shape.\n *\n * @param x Tensor.\n * @param noiseShape The shape for the randomly generated keep/drop flags, as\n *   an array of numbers. Optional.\n * @returns Normalized noise shape.\n */\nexport function getNoiseShape(x: Tensor, noiseShape?: number[]): number[] {\n  if (noiseShape == null) {\n    return x.shape.slice();\n  }\n  if (util.arraysEqual(x.shape, noiseShape)) {\n    return noiseShape;\n  }\n  if (x.shape.length === noiseShape.length) {\n    const newDimension: number[] = [];\n    for (let i = 0; i < x.shape.length; i++) {\n      if (noiseShape[i] == null && x.shape[i] != null) {\n        newDimension.push(x.shape[i]);\n      } else {\n        newDimension.push(noiseShape[i]);\n      }\n    }\n    return newDimension;\n  }\n\n  return noiseShape;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {add} from './add';\nimport {div} from './div';\nimport {getNoiseShape} from './dropout_util';\nimport {floor} from './floor';\nimport {mul} from './mul';\nimport {op} from './operation';\nimport {randomUniform} from './random_uniform';\n\n/**\n * Computes dropout.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 2, 1]);\n * const rate = 0.75;\n * const output = tf.dropout(x, rate);\n * output.print();\n * ```\n *\n * @param x A floating point Tensor or TensorLike.\n * @param rate A float in the range [0, 1). The probability that each element\n *   of x is discarded.\n * @param noiseShape An array of numbers of type int32, representing the\n * shape for randomly generated keep/drop flags. If the noiseShape has null\n * value, it will be automatically replaced with the x's relative dimension\n * size. Optional.\n * @param seed Used to create random seeds. Optional.\n * @returns A Tensor of the same shape of x.\n *\n * @doc {heading: 'Operations', subheading: 'Dropout'}\n */\nfunction dropout_(\n    x: Tensor|TensorLike, rate: number, noiseShape?: number[],\n    seed?: number|string): Tensor {\n  const $x = convertToTensor(x, 'x', 'dropout');\n\n  util.assert(\n      $x.dtype === 'float32',\n      () => `x has to be a floating point tensor since it's going to be ` +\n          `scaled, but got a ${$x.dtype} tensor instead.`);\n  util.assert(\n      rate >= 0 && rate < 1,\n      () => `rate must be a float in the range [0, 1), but got ${rate}.`);\n\n  if (rate === 0) {\n    return x instanceof Tensor ? $x.clone() : $x;\n  }\n\n  const $noiseShape = getNoiseShape($x, noiseShape);\n  const keepProb = 1 - rate;\n  const multiplier = div(\n      floor(add(randomUniform($noiseShape, 0, 1, 'float32', seed), keepProb)),\n      keepProb);\n\n  return mul($x, multiplier);\n}\n\nexport const dropout = /* @__PURE__ */ op({dropout_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../tensor';\nimport {tensor1d} from './tensor1d';\n\nexport function enclosingPowerOfTwo(value: number) {\n  // Return 2**N for integer N such that 2**N >= value.\n  return Math.floor(Math.pow(2, Math.ceil(Math.log(value) / Math.log(2.0))));\n}\n\nexport function cosineWindow(\n    windowLength: number, a: number, b: number): Tensor1D {\n  const even = 1 - windowLength % 2;\n  const newValues = new Float32Array(windowLength);\n  for (let i = 0; i < windowLength; ++i) {\n    const cosArg = (2.0 * Math.PI * i) / (windowLength + even - 1);\n    newValues[i] = a - b * Math.cos(cosArg);\n  }\n  return tensor1d(newValues, 'float32');\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {assert, assertShapesMatch, getTypedArrayFromDType} from '../util';\nimport {tensor} from './tensor';\n\n/**\n * Returns whether the targets are in the top K predictions.\n *\n * ```js\n * const predictions = tf.tensor2d([[20, 10, 40, 30], [30, 50, -20, 10]]);\n * const targets = tf.tensor1d([2, 0]);\n * const precision = await tf.inTopKAsync(predictions, targets);\n * precision.print();\n * ```\n * @param predictions 2-D or higher `tf.Tensor` with last dimension being\n *     at least `k`.\n * @param targets 1-D or higher `tf.Tensor`.\n * @param k Optional Number of top elements to look at for computing precision,\n *     default to 1.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nasync function inTopKAsync_<T extends Tensor, U extends Tensor>(\n    predictions: T|TensorLike, targets: U|TensorLike, k = 1): Promise<U> {\n  const $predictions = convertToTensor(predictions, 'predictions', 'inTopK');\n  const $targets = convertToTensor(targets, 'targets', 'inTopK');\n\n  assert(\n      $predictions.rank > 1,\n      () => 'inTopK() expects the predictions to be of rank 2 or higher, ' +\n          `but got ${$predictions.rank}`);\n  assert(\n      $predictions.rank - 1 === $targets.rank,\n      () => `predictions rank should be 1 larger than ` +\n          `targets rank, but got predictions rank ` +\n          `${$predictions.rank} and targets rank ${$targets.rank}`);\n  assertShapesMatch(\n      $predictions.shape.slice(0, $predictions.shape.length - 1),\n      $targets.shape,\n      `predictions's shape should be align with the targets' shape, ` +\n          'except the last dimension.');\n  const lastDim = $predictions.shape[$predictions.shape.length - 1];\n  assert(\n      k > 0 && k <= lastDim,\n      () => `'k' passed to inTopK() must be > 0 && <= the predictions last ` +\n          `dimension (${lastDim}), but got ${k}`);\n\n  const predictionsVals = await $predictions.data();\n  const targetsVals = await $targets.data();\n\n  // Reshape predictionsVals into a 2d tensor [batch, lastDim]\n  // and look up topK along lastDim.\n  const [batch, size] = [predictionsVals.length / lastDim, lastDim];\n  const precision = getTypedArrayFromDType('bool', batch);\n\n  for (let b = 0; b < batch; b++) {\n    const offset = b * size;\n    const vals = predictionsVals.subarray(offset, offset + size);\n    const valAndInd: Array<{value: number, index: number}> = [];\n    for (let i = 0; i < vals.length; i++) {\n      valAndInd.push({value: vals[i], index: i});\n    }\n    valAndInd.sort((a, b) => b.value - a.value);\n\n    precision[b] = 0;\n    for (let i = 0; i < k; i++) {\n      if (valAndInd[i].index === targetsVals[b]) {\n        precision[b] = 1;\n        break;\n      }\n    }\n  }\n\n  if (predictions !== $predictions) {\n    $predictions.dispose();\n  }\n  if (targets !== $targets) {\n    $targets.dispose();\n  }\n\n  // Output precision has the same shape as targets.\n  return tensor(precision, $targets.shape, 'bool') as U;\n}\n\nexport const inTopKAsync = inTopKAsync_;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\n\nimport * as conv_util from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the derivative of the filter of a 2D convolution.\n *\n * @param x The input tensor, of rank 4 or rank 3 of shape\n *     [batch, height, width, inChannels]. If rank 3, batch of 1 is assumed.\n * @param dy The dy image, of rank 4 or rank 3, of shape\n *     [batch, height, width, outDepth]. If rank 3, batch of 1 is assumed.\n * @param filterShape The shape of the filter, length 4,\n *     [filterHeight, filterWidth, inDepth, outDepth].\n * @param strides The strides of the convolution: [strideHeight,\n * strideWidth].\n * @param pad A string from: 'same', 'valid'. The type of padding algorithm\n *     used in the forward prop of the op.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels].\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n */\nfunction conv2DBackpropFilter_<T extends Tensor3D|Tensor4D>(\n    x: T, dy: T, filterShape: [number, number, number, number],\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n    dataFormat: 'NHWC'|'NCHW' = 'NHWC',\n    dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n  let x4D = x as Tensor4D;\n  if (x.rank === 3) {\n    x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n  }\n  let dy4D = dy as Tensor4D;\n  if (dy4D.rank === 3) {\n    dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n  }\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in conv2dDerFilter: input must be rank 4, but got shape ` +\n          `${x4D.shape}.`);\n  util.assert(\n      dy4D.rank === 4,\n      () => `Error in conv2dDerFilter: dy must be rank 4, but got shape ` +\n          `${dy4D.shape}.`);\n  util.assert(\n      filterShape.length === 4,\n      () => `Error in conv2dDerFilter: filterShape must be length 4, but got ` +\n          `${filterShape}.`);\n  const inDepth = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n  const outDepth = dataFormat === 'NHWC' ? dy4D.shape[3] : dy4D.shape[1];\n  util.assert(\n      inDepth === filterShape[2],\n      () => `Error in conv2dDerFilter: depth of input ${inDepth}) must ` +\n          `match input depth in filter (${filterShape[2]}.`);\n  util.assert(\n      outDepth === filterShape[3],\n      () => `Error in conv2dDerFilter: depth of dy (${outDepth}) must ` +\n          `match output depth for filter (${filterShape[3]}).`);\n  conv_util.checkPadOnDimRoundingMode('conv2dDerFilter', pad, dimRoundingMode);\n  const inputs: Conv2DBackpropFilterInputs = {x: x4D, dy: dy4D};\n  const attrs: Conv2DBackpropFilterAttrs =\n      {strides, pad, dataFormat, dimRoundingMode, filterShape};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             Conv2DBackpropFilter, inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as Tensor4D;\n}\n\nexport const conv2DBackpropFilter = /* @__PURE__ */ op({conv2DBackpropFilter_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\nimport * as broadcast_util from './broadcast_util';\nimport {elu} from './elu';\nimport {Activation} from './fused_types';\nimport {leakyRelu} from './leaky_relu';\nimport {mul} from './mul';\nimport {prelu} from './prelu';\nimport {relu} from './relu';\nimport {relu6} from './relu6';\nimport {reshape} from './reshape';\nimport {sigmoid} from './sigmoid';\nimport {step} from './step';\nimport {sum} from './sum';\n\n// Returns gradient for fused activation.\nexport function getFusedDyActivation(\n    dy: Tensor, y: Tensor, activation: Activation): Tensor {\n  if (activation == null || activation === 'linear') {\n    return dy;\n  }\n  if (activation === 'relu') {\n    return mul(dy, step(y));\n  }\n  throw new Error(\n      `Cannot compute gradient for fused activation ${activation}.`);\n}\n\n// Returns gradient for fused bias.\nexport function getFusedBiasGradient(\n    bias: Tensor, dyActivation: Tensor): Tensor {\n  let res = dyActivation;\n  const reduceAxes =\n      broadcast_util.getReductionAxes(bias.shape, dyActivation.shape);\n  if (reduceAxes.length > 0) {\n    res = sum(res, reduceAxes);\n  }\n  return reshape(res, bias.shape);\n}\n\nexport function applyActivation(\n    x: Tensor, activation: Activation, preluActivationWeights?: Tensor,\n    leakyreluAlpha?: number): Tensor {\n  if (activation === 'linear') {\n    return x;\n  } else if (activation === 'relu') {\n    return relu(x);\n  } else if (activation === 'elu') {\n    return elu(x);\n  } else if (activation === 'relu6') {\n    return relu6(x);\n  } else if (activation === 'prelu') {\n    return prelu(x, preluActivationWeights);\n  } else if (activation === 'leakyrelu') {\n    return leakyRelu(x, leakyreluAlpha);\n  } else if (activation === 'sigmoid') {\n    return sigmoid(x);\n  }\n  throw new Error(`Unknown fused activation ${activation}.`);\n}\n\n// Whether we should call fused ops.\nexport const shouldFuse = (gradientDepth: number, activation: Activation) => {\n  const gradientMode = gradientDepth > 0;\n  return !gradientMode || activation === 'linear';\n};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport {conv2d as unfusedConv2d} from '../conv2d';\nimport {conv2DBackpropFilter} from '../conv2d_backprop_filter';\nimport {conv2DBackpropInput} from '../conv2d_backprop_input';\nimport * as conv_util from '../conv_util';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes a 2D convolution over the input x, optionally fused with adding a\n * bias and applying an activation.\n *\n * ```js\n * const inputDepth = 2;\n * const inShape = [2, 2, 2, inputDepth];\n * const outputDepth = 2;\n * const fSize = 1;\n * const pad = 0;\n * const strides = 1;\n *\n * const x = tf.tensor4d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n * 16], inShape);\n * const w = tf.tensor4d([-1, 1, -2, 0.5], [fSize, fSize, inputDepth,\n * outputDepth]);\n *\n * tf.fused.conv2d({ x, filter: w, strides, pad, dataFormat: 'NHWC',\n * dilations: [1, 1], bias: tf.scalar(5), activation: 'relu' }).print();\n * ```\n *\n * @param obj An object with the following properties:\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter, rank 4, of shape\n *     `[filterHeight, filterWidth, inDepth, outDepth]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`.\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid` output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dataFormat An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `dilations` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @param bias Tensor to be added to the result.\n * @param activation Name of activation kernel (defaults to `linear`) to be\n *     applied\n *      after biasAdd.\n * @param preluActivationWeights Tensor of prelu weights to be applied as part\n *     of a `prelu` activation, typically the same shape as `x`.\n * @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`\n *     activation.\n */\nfunction fusedConv2d_<T extends Tensor3D|Tensor4D>({\n  x,\n  filter,\n  strides,\n  pad,\n  dataFormat = 'NHWC',\n  dilations = [1, 1],\n  dimRoundingMode,\n  bias,\n  activation = 'linear',\n  preluActivationWeights,\n  leakyreluAlpha\n}: {\n  x: T|TensorLike,\n  filter: Tensor4D|TensorLike,\n  strides: [number, number]|number,\n  pad: 'valid'|'same'|number|conv_util.ExplicitPadding,\n  dataFormat?: 'NHWC'|'NCHW',\n  dilations?: [number, number]|number,\n  dimRoundingMode?: 'floor'|'round'|'ceil',\n  bias?: Tensor|TensorLike,\n  activation?: Activation,\n  preluActivationWeights?: Tensor,\n  leakyreluAlpha?: number\n}): T {\n  activation = activation || 'linear';\n\n  if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n    // TODO: Transpose bias and preluActivationWeights properly for NCHW\n    // format before computation.\n    util.assert(\n        dataFormat === 'NHWC',\n        () => `Error in fused conv2d: got dataFormat of ${dataFormat} but ` +\n            `only NHWC is currently supported for the case of gradient depth ` +\n            `is 0 and the activation is not linear.`);\n\n    let result = unfusedConv2d(\n        x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);\n    if (bias != null) {\n      result = add(result, bias);\n    }\n\n    return applyActivation(\n               result, activation, preluActivationWeights, leakyreluAlpha) as T;\n  }\n\n  const $x = convertToTensor(x, 'x', 'conv2d', 'float32');\n  const $filter = convertToTensor(filter, 'filter', 'conv2d', 'float32');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in fused conv2d: input must be rank 4, but got rank ` +\n          `${x4D.rank}.`);\n  util.assert(\n      $filter.rank === 4,\n      () => `Error in fused conv2d: filter must be rank 4, but got rank ` +\n          `${$filter.rank}.`);\n  conv_util.checkPadOnDimRoundingMode('fused conv2d', pad, dimRoundingMode);\n  const inputChannels = dataFormat === 'NHWC' ? x4D.shape[3] : x4D.shape[1];\n  util.assert(\n      $filter.shape[2] === inputChannels,\n      () => `Error in conv2d: depth of input (${inputChannels}) must match ` +\n          `input depth for filter ${$filter.shape[2]}.`);\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () => 'Error in conv2D: Either strides or dilations must be 1. ' +\n          `Got strides ${strides} and dilations '${dilations}'`);\n\n  const convInfo = conv_util.computeConv2DInfo(\n      x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode);\n\n  let $bias: Tensor;\n  if (bias != null) {\n    $bias = convertToTensor(bias, 'bias', 'fused conv2d');\n    [$bias] = makeTypesMatch($bias, $x);\n\n    // According to TensorFlow, the bias is supposed be a 1-D tensor or a\n    // scalar.\n    //\n    // 3-D or 4-D bias is not disabled for NHWC format, because they are\n    // currently being used in some cases. For examplem in our code base,\n    // https://github.com/tensorflow/tfjs/blob/b53bd47e880367ae57493f0ea628abaf08db2d5d/tfjs-core/src/ops/fused/fused_conv2d_test.ts#L1972.\n    if (dataFormat === 'NHWC') {\n      broadcast_util.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);\n    } else {\n      util.assert(\n          $bias.shape.length <= 1,\n          () => `Error in fused conv2d: only supports scalar or 1-D Tensor ` +\n              `bias for NCHW format but got the bias of ` +\n              `rank-${$bias.shape.length}.`);\n\n      util.assert(\n          $bias.shape.length === 0 || $bias.shape[0] === convInfo.outChannels ||\n              $bias.shape[0] === 1,\n          () => `Error in fused conv2d: bias shape (${$bias.shape}) is not ` +\n              `compatible with the number of output channels ` +\n              `(${convInfo.outChannels})`);\n    }\n  }\n\n  let $preluActivationWeights: Tensor;\n  if (preluActivationWeights != null) {\n    // PReLU's activation weights could be a scalar, a 1-D tensor or a 3-D\n    // tensor.\n    const alphaShape = preluActivationWeights.shape;\n    util.assert(\n        alphaShape.length <= 1 || alphaShape.length === 3,\n        () => `Error in fused conv2d: only supports scalar, 1-D Tensor or ` +\n            `3-D Tensor PReLU activation weights but got a tensor of ` +\n            `rank-${alphaShape.length}.`);\n\n    if (alphaShape.length === 1) {\n      // Whether the data format is NCHW or NHWC, the 1-D PReLU activation\n      // weights tensor should be aligned with the output channels of conv2d\n      // result.\n      util.assert(\n          alphaShape[0] === 1 || alphaShape[0] === convInfo.outChannels,\n          () => `Error in fused conv2d: PReLU activation weights ` +\n              `(${alphaShape}) is not compatible with the number of output ` +\n              `channels (${convInfo.outChannels}).`);\n    } else if (alphaShape.length === 3) {\n      // Whether the data format is NCHW or NHWC, the PReLU activation weights\n      // tensor should has the compatible shape with the result of conv2d.\n      try {\n        broadcast_util.assertAndGetBroadcastShape(\n            alphaShape, convInfo.outShape);\n      } catch (e) {\n        const errMsg =\n            `Error in fused conv2d: PReLU activation weights (${alphaShape}) ` +\n            `is not compatible with the output shape of the conv2d ` +\n            `(${convInfo.outShape}).`;\n        throw Error(errMsg);\n      }\n    }\n\n    $preluActivationWeights = convertToTensor(\n        preluActivationWeights, 'prelu weights', 'fused conv2d');\n  }\n\n  const grad = (dy: Tensor4D, saved: Tensor[]) => {\n    util.assert(\n        dataFormat === 'NHWC',\n        () => `Error in gradient of fused conv2D: got dataFormat of ${\n            dataFormat} but only NHWC is currently supported.`);\n\n    const [$filter, x4D, y, $bias] =\n        saved as [Tensor4D, Tensor4D, Tensor4D, Tensor];\n\n    const dyActivation = getFusedDyActivation(dy, y, activation) as Tensor4D;\n\n    util.assert(\n        conv_util.tupleValuesAreOne(dilations),\n        () => 'Error in gradient of fused conv2D: ' +\n            `dilation rates greater than 1 ` +\n            `are not yet supported in gradients. Got dilations '${dilations}'`);\n\n    const xDer =\n        conv2DBackpropInput(x4D.shape, dyActivation, $filter, strides, pad);\n    const filterDer =\n        conv2DBackpropFilter(x4D, dyActivation, $filter.shape, strides, pad);\n    const der: Tensor[] = [xDer, filterDer];\n\n    if ($bias != null) {\n      const biasDer = getFusedBiasGradient($bias, dyActivation);\n      der.push(biasDer);\n    }\n    return der;\n  };\n\n  const inputs: FusedConv2DInputs = {\n    x: x4D,\n    filter: $filter,\n    bias: $bias,\n    preluActivationWeights: $preluActivationWeights\n  };\n\n  const attrs: FusedConv2DAttrs = {\n    strides,\n    pad,\n    dataFormat,\n    dilations,\n    dimRoundingMode,\n    activation,\n    leakyreluAlpha\n  };\n\n  // Depending on the the params passed in we will have different number of\n  // inputs and thus a a different number of elements in the gradient.\n  if (bias == null) {\n    const customOp =\n        customGrad((x4D: Tensor4D, filter: Tensor4D, save: GradSaveFunc) => {\n          let res: Tensor4D|Tensor3D =\n              // tslint:disable-next-line: no-unnecessary-type-assertion\n              ENGINE.runKernel(\n                  FusedConv2D, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap);\n\n          save([filter, x4D, res]);\n\n          if (reshapedTo4D) {\n            // tslint:disable-next-line: no-unnecessary-type-assertion\n            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n                Tensor3D;\n          }\n\n          return {value: res, gradFunc: grad};\n        });\n    return customOp(x4D, $filter) as T;\n  } else {\n    const customOpWithBias = customGrad(\n        (x4D: Tensor4D, filter: Tensor4D, bias: Tensor, save: GradSaveFunc) => {\n          let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n              FusedConv2D, inputs as unknown as NamedTensorMap,\n              attrs as unknown as NamedAttrMap);\n\n          save([filter, x4D, res, bias]);\n\n          if (reshapedTo4D) {\n            // tslint:disable-next-line: no-unnecessary-type-assertion\n            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n                Tensor3D;\n          }\n\n          return {value: res, gradFunc: grad};\n        });\n\n    return customOpWithBias(x4D, $filter, $bias) as T;\n  }\n}\nexport const conv2d = /* @__PURE__ */ op({fusedConv2d_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nfunction depthwiseConv2dNativeBackpropFilter_<T extends Tensor3D|Tensor4D>(\n    x: T, dy: T, filterShape: [number, number, number, number],\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|ExplicitPadding,\n    dilations: [number, number]|number = [1, 1],\n    dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n  let x4D = x as Tensor4D;\n  if (x.rank === 3) {\n    x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);\n  }\n  let dy4D = dy as Tensor4D;\n  if (dy4D.rank === 3) {\n    dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n  }\n\n  const inputs: DepthwiseConv2dNativeBackpropFilterInputs = {x: x4D, dy: dy4D};\n  const attrs: DepthwiseConv2dNativeBackpropFilterAttrs =\n      {strides, pad, dimRoundingMode, dilations, filterShape};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  return ENGINE.runKernel(\n             DepthwiseConv2dNativeBackpropFilter,\n             inputs as unknown as NamedTensorMap,\n             attrs as unknown as NamedAttrMap) as Tensor4D;\n}\n\nexport const depthwiseConv2dNativeBackpropFilter =\n    op({depthwiseConv2dNativeBackpropFilter_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {DepthwiseConv2dNativeBackpropInput, DepthwiseConv2dNativeBackpropInputAttrs, DepthwiseConv2dNativeBackpropInputInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\nfunction depthwiseConv2dNativeBackpropInput_<T extends Tensor3D|Tensor4D>(\n    xShape: [number, number, number, number], dy: T, filter: Tensor4D,\n    strides: [number, number]|number,\n    pad: 'valid'|'same'|number|ExplicitPadding,\n    dilations: [number, number]|number = [1, 1],\n    dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n  let dy4D = dy as Tensor4D;\n  let reshapedTo4D = false;\n  if (dy.rank === 3) {\n    reshapedTo4D = true;\n    dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);\n  }\n\n  const inputs: DepthwiseConv2dNativeBackpropInputInputs = {dy: dy4D, filter};\n  const attrs: DepthwiseConv2dNativeBackpropInputAttrs =\n      {strides, pad, dimRoundingMode, dilations, inputShape: xShape};\n\n  const res =\n      // tslint:disable-next-line: no-unnecessary-type-assertion\n      ENGINE.runKernel(\n          DepthwiseConv2dNativeBackpropInput,\n          inputs as unknown as NamedTensorMap,\n          attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const depthwiseConv2dNativeBackpropInput =\n    op({depthwiseConv2dNativeBackpropInput_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport * as conv_util from '../conv_util';\nimport {depthwiseConv2d as unfusedDepthwiseConv2d} from '../depthwise_conv2d';\nimport {depthwiseConv2dNativeBackpropFilter} from '../depthwise_conv2d_native_backprop_filter';\nimport {depthwiseConv2dNativeBackpropInput} from '../depthwise_conv2d_native_backprop_input';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes depthwise 2D convolution, optionally fused with adding a\n * bias and applying an activation.\n *\n * Given a 4D `input` array and a `filter` array of shape\n * `[filterHeight, filterWidth, inChannels, channelMultiplier]` containing\n * `inChannels` convolutional filters of depth 1, this op applies a\n * different filter to each input channel (expanding from 1 channel to\n * `channelMultiplier` channels for each), then concatenates the results\n * together. The output has `inChannels * channelMultiplier` channels.\n *\n * See\n * [https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d](\n *     https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d)\n * for more details.\n *\n * @param obj An object with the following properties:\n * @param x The input tensor, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is\n * assumed.\n * @param filter The filter tensor, rank 4, of shape\n *     `[filterHeight, filterWidth, inChannels, channelMultiplier]`.\n * @param strides The strides of the convolution: `[strideHeight,\n * strideWidth]`. If strides is a single number, then `strideHeight ==\n * strideWidth`.\n * @param pad The type of padding algorithm.\n *   - `same` and stride 1: output will be of same size as input,\n *       regardless of filter size.\n *   - `valid`: output will be smaller than input if filter is larger\n *       than 1x1.\n *   - For more info, see this guide:\n *     [https://www.tensorflow.org/api_docs/python/tf/nn/convolution](\n *          https://www.tensorflow.org/api_docs/python/tf/nn/convolution)\n * @param dilations The dilation rates: `[dilationHeight, dilationWidth]`\n *     in which we sample input values across the height and width dimensions\n *     in atrous convolution. Defaults to `[1, 1]`. If `rate` is a single\n *     number, then `dilationHeight == dilationWidth`. If it is greater than\n *     1, then all values of `strides` must be 1.\n * @param dataFormat: An optional string from: \"NHWC\", \"NCHW\". Defaults to\n *     \"NHWC\". Specify the data format of the input and output data. With the\n *     default format \"NHWC\", the data is stored in the order of: [batch,\n *     height, width, channels]. Only \"NHWC\" is currently supported.\n * @param dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n *     provided, it will default to truncate.\n * @param bias Tensor to be added to the result.\n * @param activation Name of activation kernel (defaults to `linear`).\n * @param preluActivationWeights Tensor of prelu weights to be applied as part\n *     of a `prelu` activation, typically the same shape as `x`.\n * @param leakyreluAlpha Optional. Alpha to be applied as part of a `leakyrelu`\n *     activation.\n */\nfunction fusedDepthwiseConv2d_<T extends Tensor3D|Tensor4D>({\n  x,\n  filter,\n  strides,\n  pad,\n  dataFormat = 'NHWC',\n  dilations = [1, 1],\n  dimRoundingMode,\n  bias,\n  activation = 'linear',\n  preluActivationWeights,\n  leakyreluAlpha\n}: {\n  x: T|TensorLike,\n  filter: Tensor4D|TensorLike,\n  strides: [number, number]|number,\n  pad: 'valid'|'same'|number,\n  dataFormat?: 'NHWC'|'NCHW',\n  dilations?: [number, number]|number,\n  dimRoundingMode?: 'floor'|'round'|'ceil',\n  bias?: Tensor|TensorLike,\n  activation?: Activation,\n  preluActivationWeights?: Tensor,\n  leakyreluAlpha?: number\n}): T {\n  if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n    let result = unfusedDepthwiseConv2d(\n        x, filter, strides, pad, dataFormat, dilations, dimRoundingMode);\n    if (bias != null) {\n      result = add(result, bias);\n    }\n\n    return applyActivation(\n               result, activation, preluActivationWeights, leakyreluAlpha) as T;\n  }\n\n  const $x = convertToTensor(x, 'x', 'depthwiseConv2d', 'float32');\n  const $filter =\n      convertToTensor(filter, 'filter', 'depthwiseConv2d', 'float32');\n\n  let x4D = $x as Tensor4D;\n  let reshapedTo4D = false;\n  if ($x.rank === 3) {\n    reshapedTo4D = true;\n    x4D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2]]);\n  }\n  util.assert(\n      x4D.rank === 4,\n      () => `Error in fused depthwiseConv2d: input must be rank 4, but got ` +\n          `rank ${x4D.rank}.`);\n  util.assert(\n      $filter.rank === 4,\n      () => `Error in fused depthwiseConv2d: filter must be rank 4, ` +\n          `but got rank ${$filter.rank}.`);\n  util.assert(\n      x4D.shape[3] === $filter.shape[2],\n      () => `Error in fused depthwiseConv2d: number of input channels ` +\n          `(${x4D.shape[3]}) must match the inChannels dimension in ` +\n          `filter ${$filter.shape[2]}.`);\n  if (dilations == null) {\n    dilations = [1, 1];\n  }\n  util.assert(\n      conv_util.eitherStridesOrDilationsAreOne(strides, dilations),\n      () =>\n          'Error in fused depthwiseConv2d: Either strides or dilations must ' +\n          `be 1. Got strides ${strides} and dilations '${dilations}'`);\n  conv_util.checkPadOnDimRoundingMode(\n      'fused depthwiseConv2d', pad, dimRoundingMode);\n  const convInfo = conv_util.computeConv2DInfo(\n      x4D.shape, $filter.shape, strides, dilations, pad, dimRoundingMode,\n      true /* depthwise */);\n\n  let $bias: Tensor;\n  if (bias != null) {\n    $bias = convertToTensor(bias, 'bias', 'fused conv2d');\n    [$bias] = makeTypesMatch($bias, $x);\n\n    broadcast_util.assertAndGetBroadcastShape(convInfo.outShape, $bias.shape);\n  }\n\n  let $preluActivationWeights: Tensor;\n  if (preluActivationWeights != null) {\n    $preluActivationWeights = convertToTensor(\n        preluActivationWeights, 'prelu weights', 'fused depthwiseConv2d');\n  }\n\n  const grad = (dy: Tensor4D, saved: Tensor[]) => {\n    util.assert(\n        conv_util.tupleValuesAreOne(dilations),\n        () => 'Error in gradient of fused depthwiseConv2d: dilation rates ' +\n            `greater than 1 are not yet supported. Got dilations ` +\n            `'${dilations}'`);\n    const [$filter, x4D, y, bias] = saved;\n\n    const dyActivation = getFusedDyActivation(dy, y, activation) as Tensor4D;\n\n    const xDer = depthwiseConv2dNativeBackpropInput(\n        (x4D as Tensor4D).shape, dyActivation, $filter as Tensor4D, strides,\n        pad, dilations, dimRoundingMode);\n    const filterDer = depthwiseConv2dNativeBackpropFilter(\n        x4D as Tensor4D, dyActivation, ($filter as Tensor4D).shape, strides,\n        pad, dilations, dimRoundingMode);\n\n    if (bias != null) {\n      const biasDer = getFusedBiasGradient($bias, dyActivation);\n      return [xDer, filterDer, biasDer];\n    }\n    return [xDer, filterDer];\n  };\n\n  const inputs: FusedDepthwiseConv2DInputs = {\n    x: x4D,\n    filter: $filter,\n    bias: $bias,\n    preluActivationWeights: $preluActivationWeights\n  };\n  const attrs: FusedDepthwiseConv2DAttrs = {\n    strides,\n    pad,\n    dataFormat,\n    dilations,\n    dimRoundingMode,\n    activation,\n    leakyreluAlpha\n  };\n\n  // Depending on the the params passed in we will have different number of\n  // inputs and thus a a different number of elements in the gradient.\n  if (bias == null) {\n    const customOp =\n        customGrad((x4D: Tensor4D, filter: Tensor4D, save: GradSaveFunc) => {\n          // tslint:disable-next-line: no-unnecessary-type-assertion\n          let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n              FusedDepthwiseConv2D, inputs as unknown as NamedTensorMap,\n              attrs as unknown as NamedAttrMap);\n\n          save([filter, x4D, res]);\n\n          if (reshapedTo4D) {\n            // tslint:disable-next-line: no-unnecessary-type-assertion\n            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n                Tensor3D;\n          }\n\n          return {value: res, gradFunc: grad};\n        });\n    return customOp(x4D, $filter) as T;\n  } else {\n    const customOpWithBias = customGrad(\n        (x4D: Tensor4D, filter: Tensor4D, bias: Tensor, save: GradSaveFunc) => {\n          // tslint:disable-next-line: no-unnecessary-type-assertion\n          let res: Tensor4D|Tensor3D = ENGINE.runKernel(\n              FusedDepthwiseConv2D, inputs as unknown as NamedTensorMap,\n              attrs as unknown as NamedAttrMap);\n\n          save([filter, x4D, res, bias]);\n\n          if (reshapedTo4D) {\n            // tslint:disable-next-line: no-unnecessary-type-assertion\n            res = reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as\n                Tensor3D;\n          }\n\n          return {value: res, gradFunc: grad};\n        });\n\n    return customOpWithBias(x4D, $filter, $bias) as T;\n  }\n}\nexport const depthwiseConv2d = /* @__PURE__ */ op({fusedDepthwiseConv2d_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {customGrad} from '../../gradients';\nimport {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor3D} from '../../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../../tensor_types';\nimport {makeTypesMatch} from '../../tensor_util';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {add} from '../add';\nimport * as broadcast_util from '../broadcast_util';\nimport {Activation} from '../fused_types';\nimport {applyActivation, getFusedBiasGradient, getFusedDyActivation, shouldFuse} from '../fused_util';\nimport {matMul as unfusedMatMul} from '../mat_mul';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Computes the dot product of two matrices with optional activation and bias.\n *\n * ```js\n * const a = tf.tensor2d([-1, -2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const bias = tf.tensor2d([1, 2], [1, 2]);\n *\n * tf.fused.matMul({a, b, bias, activation: 'relu'}).print();\n * ```\n *\n * @param obj An object with the following properties:\n * - `a` First matrix in dot product operation.\n * - `b` Second matrix in dot product operation.\n * - `transposeA` If true, `a` is transposed before multiplication.\n * - `transposeB` If true, `b` is transposed before multiplication.\n * - `bias` Matrix to be added to the result.\n * - `activation` Name of activation kernel (defaults to `linear`).\n * - `preluActivationWeights` Tensor of prelu weights.\n * - `leakyreluAlpha` Alpha of leakyrelu.\n */\nfunction fusedMatMul_({\n  a,\n  b,\n  transposeA = false,\n  transposeB = false,\n  bias,\n  activation = 'linear',\n  preluActivationWeights,\n  leakyreluAlpha = 0.2,\n}: {\n  a: Tensor|TensorLike,\n  b: Tensor|TensorLike,\n  transposeA?: boolean,\n  transposeB?: boolean,\n  bias?: Tensor|TensorLike,\n  activation?: Activation,\n  preluActivationWeights?: Tensor\n  leakyreluAlpha?: number\n}): Tensor {\n    if (shouldFuse(ENGINE.state.gradientDepth, activation) === false) {\n      let result = unfusedMatMul(a, b, transposeA, transposeB);\n      if (bias != null) {\n        result = add(result, bias);\n      }\n\n      return applyActivation(\n                 result, activation, preluActivationWeights, leakyreluAlpha);\n    }\n\n    let $a = convertToTensor(a, 'a', 'fused matMul');\n    let $b = convertToTensor(b, 'b', 'fused matMul');\n    [$a, $b] = makeTypesMatch($a, $b);\n\n    const innerShapeA =\n        transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];\n    const innerShapeB =\n        transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];\n\n    const outerShapeA =\n        transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];\n    const outerShapeB =\n        transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];\n\n    const outerDimsA = $a.shape.slice(0, -2);\n    const outerDimsB = $b.shape.slice(0, -2);\n    const batchDimA = util.sizeFromShape(outerDimsA);\n    const batchDimB = util.sizeFromShape(outerDimsB);\n\n    util.assert(\n        innerShapeA === innerShapeB,\n        () => `Error in fused matMul: inner shapes (${innerShapeA}) and (` +\n            `${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +\n            `${$b.shape} and transposeA=${transposeA}` +\n            ` and transposeB=${transposeB} must match.`);\n\n    const outShapeOuterDims = broadcast_util.assertAndGetBroadcastShape(\n        $a.shape.slice(0, -2), $b.shape.slice(0, -2));\n    const outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);\n\n    const a3D: Tensor3D = transposeA ?\n        reshape($a, [batchDimA, innerShapeA, outerShapeA]) :\n        reshape($a, [batchDimA, outerShapeA, innerShapeA]);\n    const b3D: Tensor3D = transposeB ?\n        reshape($b, [batchDimB, outerShapeB, innerShapeB]) :\n        reshape($b, [batchDimB, innerShapeB, outerShapeB]);\n\n    let $bias: Tensor;\n    if (bias != null) {\n      $bias = convertToTensor(bias, 'bias', 'fused matMul');\n      [$bias] = makeTypesMatch($bias, $a);\n\n      broadcast_util.assertAndGetBroadcastShape(outShape, $bias.shape);\n    }\n\n    let $preluActivationWeights: Tensor;\n    if (preluActivationWeights != null) {\n      $preluActivationWeights = convertToTensor(\n          preluActivationWeights, 'prelu weights', 'fused matMul');\n    }\n\n    const grad = (dy: Tensor3D, saved: Tensor[]) => {\n      const [a3D, b3D, y, $bias] = saved;\n      // we reshape dy because the result of the forward is not\n      // necessarily going to be a 3d tensor due to a reshape done at the end of\n      // the customOp.\n      const dyActivation =\n          getFusedDyActivation(reshape(dy, y.shape), y, activation);\n      let aDer: Tensor;\n      let bDer: Tensor;\n\n      if (!transposeA && !transposeB) {\n        aDer = unfusedMatMul(dyActivation, b3D, false, true);\n        bDer = unfusedMatMul(a3D, dyActivation, true, false);\n      } else if (!transposeA && transposeB) {\n        aDer = unfusedMatMul(dyActivation, b3D, false, false);\n        bDer = unfusedMatMul(dyActivation, a3D, true, false);\n      } else if (transposeA && !transposeB) {\n        aDer = unfusedMatMul(b3D, dyActivation, false, true);\n        bDer = unfusedMatMul(a3D, dyActivation, false, false);\n      } else {\n        aDer = unfusedMatMul(b3D, dyActivation, true, true);\n        bDer = unfusedMatMul(dyActivation, a3D, true, true);\n      }\n\n      if (bias != null) {\n        const biasDer = getFusedBiasGradient($bias, dyActivation);\n        return [aDer, bDer, biasDer];\n      } else {\n        return [aDer, bDer];\n      }\n    };\n\n    const inputs: _FusedMatMulInputs = {\n      a: a3D,\n      b: b3D,\n      bias: $bias,\n      preluActivationWeights: $preluActivationWeights\n    };\n    const attrs: _FusedMatMulAttrs =\n        {transposeA, transposeB, activation, leakyreluAlpha};\n\n    // Depending on the the params passed in we will have different number of\n    // inputs and thus a a different number of elements in the gradient.\n    if (bias == null) {\n      const customOp =\n          customGrad((a3D: Tensor3D, b3D: Tensor3D, save: GradSaveFunc) => {\n            const res =\n                // tslint:disable-next-line: no-unnecessary-type-assertion\n                ENGINE.runKernel(\n                    _FusedMatMul, inputs as unknown as NamedTensorMap,\n                    attrs as unknown as NamedAttrMap) as Tensor;\n\n            save([a3D, b3D, res]);\n\n            return {value: reshape(res, outShape), gradFunc: grad};\n          });\n      return customOp(a3D, b3D);\n    } else {\n      const customOpWithBias = customGrad(\n          (a3D: Tensor3D, b3D: Tensor3D, $bias: Tensor, save: GradSaveFunc) => {\n            const res =\n                // tslint:disable-next-line: no-unnecessary-type-assertion\n                ENGINE.runKernel(\n                    _FusedMatMul, inputs as unknown as NamedTensorMap,\n                    attrs as unknown as NamedAttrMap) as Tensor;\n\n            save([a3D, b3D, res, $bias]);\n\n            return {value: reshape(res, outShape), gradFunc: grad};\n          });\n\n      return customOpWithBias(a3D, b3D, $bias);\n    }\n  }\n\n  export const matMul = /* @__PURE__ */ op({fusedMatMul_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {conv2d} from './fused/conv2d';\nimport {depthwiseConv2d} from './fused/depthwise_conv2d';\nimport {matMul} from './fused/mat_mul';\nimport {Activation} from './fused_types';\n\nexport {Activation, conv2d, depthwiseConv2d, matMul};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../../tensor';\nimport {op} from '../operation';\nimport {cosineWindow} from '../signal_ops_util';\n\n/**\n * Generate a hamming window.\n *\n * See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows\n *\n * ```js\n * tf.signal.hammingWindow(10).print();\n * ```\n * @param The length of window\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction hammingWindow_(windowLength: number): Tensor1D {\n  return cosineWindow(windowLength, 0.54, 0.46);\n}\nexport const hammingWindow = /* @__PURE__ */ op({hammingWindow_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D} from '../../tensor';\nimport {op} from '../operation';\nimport {cosineWindow} from '../signal_ops_util';\n\n/**\n * Generate a Hann window.\n *\n * See: https://en.wikipedia.org/wiki/Window_function#Hann_and_Hamming_windows\n *\n * ```js\n * tf.signal.hannWindow(10).print();\n * ```\n * @param The length of window\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction hannWindow_(windowLength: number): Tensor1D {\n  return cosineWindow(windowLength, 0.5, 0.5);\n}\n\nexport const hannWindow = /* @__PURE__ */ op({hannWindow_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {concat} from '../concat';\nimport {fill} from '../fill';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {tensor2d} from '../tensor2d';\n\n/**\n * Expands input into frames of frameLength.\n * Slides a window size with frameStep.\n *\n * ```js\n * tf.signal.frame([1, 2, 3], 2, 1).print();\n * ```\n * @param signal The input tensor to be expanded\n * @param frameLength Length of each frame\n * @param frameStep The frame hop size in samples.\n * @param padEnd Whether to pad the end of signal with padValue.\n * @param padValue A number to use where the input signal does\n *     not exist when padEnd is True.\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction frame_(\n    signal: Tensor1D, frameLength: number, frameStep: number, padEnd = false,\n    padValue = 0): Tensor {\n  let start = 0;\n  const output: Tensor[] = [];\n  while (start + frameLength <= signal.size) {\n    output.push(slice(signal, start, frameLength));\n    start += frameStep;\n  }\n\n  if (padEnd) {\n    while (start < signal.size) {\n      const padLen = (start + frameLength) - signal.size;\n      const pad = concat([\n        slice(signal, start, frameLength - padLen), fill([padLen], padValue)\n      ]);\n      output.push(pad);\n      start += frameStep;\n    }\n  }\n\n  if (output.length === 0) {\n    return tensor2d([], [0, frameLength]);\n  }\n\n  return reshape(concat(output), [output.length, frameLength]);\n}\nexport const frame = /* @__PURE__ */ op({frame_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {enclosingPowerOfTwo} from '../signal_ops_util';\nimport {rfft} from '../spectral/rfft';\n\nimport {frame} from './frame';\nimport {hannWindow} from './hann_window';\n\n/**\n * Computes the Short-time Fourier Transform of signals\n * See: https://en.wikipedia.org/wiki/Short-time_Fourier_transform\n *\n * ```js\n * const input = tf.tensor1d([1, 1, 1, 1, 1])\n * tf.signal.stft(input, 3, 1).print();\n * ```\n * @param signal 1-dimensional real value tensor.\n * @param frameLength The window length of samples.\n * @param frameStep The number of samples to step.\n * @param fftLength The size of the FFT to apply.\n * @param windowFn A callable that takes a window length and returns 1-d tensor.\n *\n * @doc {heading: 'Operations', subheading: 'Signal', namespace: 'signal'}\n */\nfunction stft_(\n    signal: Tensor1D, frameLength: number, frameStep: number,\n    fftLength?: number,\n    windowFn: (length: number) => Tensor1D = hannWindow): Tensor {\n  if (fftLength == null) {\n    fftLength = enclosingPowerOfTwo(frameLength);\n  }\n  const framedSignal = frame(signal, frameLength, frameStep);\n  const windowedSignal = mul(framedSignal, windowFn(frameLength));\n  return rfft(windowedSignal, fftLength);\n}\nexport const stft = /* @__PURE__ */ op({stft_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {CropAndResize, CropAndResizeAttrs, CropAndResizeInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor1D, Tensor2D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Extracts crops from the input image tensor and resizes them using bilinear\n * sampling or nearest neighbor sampling (possibly with aspect ratio change)\n * to a common output size specified by cropSize.\n *\n * @param image 4d tensor of shape `[batch,imageHeight,imageWidth, depth]`,\n *     where imageHeight and imageWidth must be positive, specifying the\n *     batch of images from which to take crops\n * @param boxes 2d float32 tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the normalized\n *     coordinates of the box in the `boxInd[i]`th image in the batch\n * @param boxInd 1d int32 tensor of shape `[numBoxes]` with values in range\n *     `[0, batch)` that specifies the image that the `i`-th box refers to.\n * @param cropSize 1d int32 tensor of 2 elements `[cropHeigh, cropWidth]`\n *     specifying the size to which all crops are resized to.\n * @param method Optional string from `'bilinear' | 'nearest'`,\n *     defaults to bilinear, which specifies the sampling method for resizing\n * @param extrapolationValue A threshold for deciding when to remove boxes based\n *     on score. Defaults to 0.\n * @return A 4D tensor of the shape `[numBoxes,cropHeight,cropWidth,depth]`\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction cropAndResize_(\n    image: Tensor4D|TensorLike,\n    boxes: Tensor2D|TensorLike,\n    boxInd: Tensor1D|TensorLike,\n    cropSize: [number, number],\n    method: 'bilinear'|'nearest' = 'bilinear',\n    extrapolationValue = 0,\n    ): Tensor4D {\n  const $image = convertToTensor(image, 'image', 'cropAndResize');\n  const $boxes = convertToTensor(boxes, 'boxes', 'cropAndResize', 'float32');\n  const $boxInd = convertToTensor(boxInd, 'boxInd', 'cropAndResize', 'int32');\n\n  const numBoxes = $boxes.shape[0];\n\n  util.assert(\n      $image.rank === 4,\n      () => 'Error in cropAndResize: image must be rank 4,' +\n          `but got rank ${$image.rank}.`);\n  util.assert(\n      $boxes.rank === 2 && $boxes.shape[1] === 4,\n      () => `Error in cropAndResize: boxes must be have size [${numBoxes},4] ` +\n          `but had shape ${$boxes.shape}.`);\n  util.assert(\n      $boxInd.rank === 1 && $boxInd.shape[0] === numBoxes,\n      () => `Error in cropAndResize: boxInd must be have size [${numBoxes}] ` +\n          `but had shape ${$boxes.shape}.`);\n  util.assert(\n      cropSize.length === 2,\n      () => `Error in cropAndResize: cropSize must be of length 2, but got ` +\n          `length ${cropSize.length}.`);\n  util.assert(\n      cropSize[0] >= 1 && cropSize[1] >= 1,\n      () => `cropSize must be atleast [1,1], but was ${cropSize}`);\n  util.assert(\n      method === 'bilinear' || method === 'nearest',\n      () => `method must be bilinear or nearest, but was ${method}`);\n\n  const inputs:\n      CropAndResizeInputs = {image: $image, boxes: $boxes, boxInd: $boxInd};\n  const attrs: CropAndResizeAttrs = {method, extrapolationValue, cropSize};\n  const res = ENGINE.runKernel(\n      CropAndResize, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n  return res as Tensor4D;\n}\n\nexport const cropAndResize = /* @__PURE__ */ op({cropAndResize_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {FlipLeftRight, FlipLeftRightInputs} from '../../kernel_names';\nimport {Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {op} from '../operation';\n\n/**\n * Flips the image left to right. Currently available in the CPU, WebGL, and\n * WASM backends.\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n */\n/** @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'} */\nfunction flipLeftRight_(image: Tensor4D|TensorLike): Tensor4D {\n  const $image = convertToTensor(image, 'image', 'flipLeftRight', 'float32');\n\n  util.assert(\n      $image.rank === 4,\n      () => 'Error in flipLeftRight: image must be rank 4,' +\n          `but got rank ${$image.rank}.`);\n\n  const inputs: FlipLeftRightInputs = {image: $image};\n  const res =\n      ENGINE.runKernel(FlipLeftRight, inputs as unknown as NamedTensorMap, {});\n  return res as Tensor4D;\n}\n\nexport const flipLeftRight = /* @__PURE__ */ op({flipLeftRight_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D, Tensor3D, Tensor4D, Tensor5D, Tensor6D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {tile} from '../tile';\n\n/**\n * Converts images from grayscale to RGB format.\n *\n * @param image A grayscale tensor to convert. The `image`'s last dimension must\n *     be size 1 with at least a two-dimensional shape.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction grayscaleToRGB_<T extends Tensor2D|Tensor3D|Tensor4D|Tensor5D|\n                         Tensor6D>(image: T|TensorLike): T {\n  const $image = convertToTensor(image, 'image', 'grayscaleToRGB');\n\n  const lastDimsIdx = $image.rank - 1;\n  const lastDims = $image.shape[lastDimsIdx];\n\n  util.assert(\n      $image.rank >= 2,\n      () => 'Error in grayscaleToRGB: images must be at least rank 2, ' +\n          `but got rank ${$image.rank}.`);\n\n  util.assert(\n      lastDims === 1,\n      () => 'Error in grayscaleToRGB: last dimension of a grayscale image ' +\n          `should be size 1, but got size ${lastDims}.`);\n\n  const reps = new Array($image.rank);\n\n  reps.fill(1, 0, lastDimsIdx);\n  reps[lastDimsIdx] = 3;\n\n  return tile($image, reps);\n}\n\nexport const grayscaleToRGB = /* @__PURE__ */ op({grayscaleToRGB_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor2D, Tensor3D, Tensor4D, Tensor5D, Tensor6D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\nimport {cast} from '../cast';\nimport {einsum} from '../einsum';\nimport {expandDims} from '../expand_dims';\nimport {op} from '../operation';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Converts images from RGB format to grayscale.\n *\n * @param image A RGB tensor to convert. The `image`'s last dimension must\n *     be size 3 with at least a two-dimensional shape.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction rgbToGrayscale_<T extends Tensor2D|Tensor3D|Tensor4D|Tensor5D|\n                         Tensor6D>(image: T|TensorLike): T {\n  const $image = convertToTensor(image, 'image', 'RGBToGrayscale');\n\n  const lastDimsIdx = $image.rank - 1;\n  const lastDims = $image.shape[lastDimsIdx];\n\n  util.assert(\n      $image.rank >= 2,\n      () => 'Error in RGBToGrayscale: images must be at least rank 2, ' +\n          `but got rank ${$image.rank}.`);\n\n  util.assert(\n      lastDims === 3,\n      () => 'Error in RGBToGrayscale: last dimension of an RGB image ' +\n          `should be size 3, but got size ${lastDims}.`);\n\n  // Remember original dtype so we can convert back if needed\n  const origDtype = $image.dtype;\n  const fltImage = cast($image, 'float32');\n\n  const rgbWeights = tensor1d([0.2989, 0.5870, 0.1140]);\n\n  let grayFloat;\n  switch ($image.rank) {\n    case 2:\n      grayFloat = einsum('ij,j->i', fltImage, rgbWeights);\n      break;\n    case 3:\n      grayFloat = einsum('ijk,k->ij', fltImage, rgbWeights);\n      break;\n    case 4:\n      grayFloat = einsum('ijkl,l->ijk', fltImage, rgbWeights);\n      break;\n    case 5:\n      grayFloat = einsum('ijklm,m->ijkl', fltImage, rgbWeights);\n      break;\n    case 6:\n      grayFloat = einsum('ijklmn,n->ijklm', fltImage, rgbWeights);\n      break;\n    default:\n      throw new Error('Not a valid tensor rank.');\n  }\n  grayFloat = expandDims(grayFloat, -1);\n\n  return cast(grayFloat, origDtype) as T;\n}\n\nexport const rgbToGrayscale = /* @__PURE__ */ op({rgbToGrayscale_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Rotates the input image tensor counter-clockwise with an optional offset\n * center of rotation. Currently available in the CPU, WebGL, and WASM backends.\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n * @param radians The amount of rotation.\n * @param fillValue The value to fill in the empty space leftover\n *     after rotation. Can be either a single grayscale value (0-255), or an\n *     array of three numbers `[red, green, blue]` specifying the red, green,\n *     and blue channels. Defaults to `0` (black).\n * @param center The center of rotation. Can be either a single value (0-1), or\n *     an array of two numbers `[centerX, centerY]`. Defaults to `0.5` (rotates\n *     the image around its center).\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction rotateWithOffset_(\n    image: Tensor4D|TensorLike, radians: number,\n    fillValue: number|[number, number, number] = 0,\n    center: number|[number, number] = 0.5): Tensor4D {\n  const $image = convertToTensor(image, 'image', 'rotateWithOffset', 'float32');\n\n  util.assert(\n      $image.rank === 4,\n      () => 'Error in rotateWithOffset: image must be rank 4,' +\n          `but got rank ${$image.rank}.`);\n\n  const inputs: RotateWithOffsetInputs = {image: $image};\n  const attrs: RotateWithOffsetAttrs = {radians, fillValue, center};\n  const res = ENGINE.runKernel(\n      RotateWithOffset, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n  return res as Tensor4D;\n}\n\nexport const rotateWithOffset = /* @__PURE__ */ op({rotateWithOffset_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport * as util from '../util';\n\nfunction nonMaxSuppSanityCheck(\n    boxes: Tensor2D, scores: Tensor1D, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number, softNmsSigma?: number): {\n  maxOutputSize: number,\n  iouThreshold: number,\n  scoreThreshold: number,\n  softNmsSigma: number\n} {\n  if (iouThreshold == null) {\n    iouThreshold = 0.5;\n  }\n  if (scoreThreshold == null) {\n    scoreThreshold = Number.NEGATIVE_INFINITY;\n  }\n  if (softNmsSigma == null) {\n    softNmsSigma = 0.0;\n  }\n\n  const numBoxes = boxes.shape[0];\n  maxOutputSize = Math.min(maxOutputSize, numBoxes);\n\n  util.assert(\n      0 <= iouThreshold && iouThreshold <= 1,\n      () => `iouThreshold must be in [0, 1], but was '${iouThreshold}'`);\n  util.assert(\n      boxes.rank === 2,\n      () => `boxes must be a 2D tensor, but was of rank '${boxes.rank}'`);\n  util.assert(\n      boxes.shape[1] === 4,\n      () =>\n          `boxes must have 4 columns, but 2nd dimension was ${boxes.shape[1]}`);\n  util.assert(scores.rank === 1, () => 'scores must be a 1D tensor');\n  util.assert(\n      scores.shape[0] === numBoxes,\n      () => `scores has incompatible shape with boxes. Expected ${numBoxes}, ` +\n          `but was ${scores.shape[0]}`);\n  util.assert(\n      0 <= softNmsSigma && softNmsSigma <= 1,\n      () => `softNmsSigma must be in [0, 1], but was '${softNmsSigma}'`);\n  return {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma};\n}\n\nexport {nonMaxSuppSanityCheck};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV3} from '../../kernel_names';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @return A 1D tensor with the selected box indices.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppression_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY): Tensor1D {\n  const $boxes =\n      convertToTensor(boxes, 'boxes', 'nonMaxSuppression', 'float32');\n  const $scores =\n      convertToTensor(scores, 'scores', 'nonMaxSuppression', 'float32');\n\n  const inputs = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);\n  maxOutputSize = inputs.maxOutputSize;\n  iouThreshold = inputs.iouThreshold;\n  scoreThreshold = inputs.scoreThreshold;\n\n  const attrs = {maxOutputSize, iouThreshold, scoreThreshold};\n  return ENGINE.runKernel(\n      NonMaxSuppressionV3, {boxes: $boxes, scores: $scores}, attrs);\n}\n\nexport const nonMaxSuppression = /* @__PURE__ */ op({nonMaxSuppression_});\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Inserts a value into a sorted array. This method allows duplicate, meaning it\n * allows inserting duplicate value, in which case, the element will be inserted\n * at the lowest index of the value.\n * @param arr The array to modify.\n * @param element The element to insert.\n * @param comparator Optional. If no comparator is specified, elements are\n * compared using array_util.defaultComparator, which is suitable for Strings\n * and Numbers in ascending arrays. If the array contains multiple instances of\n * the target value, the left-most instance will be returned. To provide a\n * comparator, it should take 2 arguments to compare and return a negative,\n * zero, or a positive number.\n */\nexport function binaryInsert<T>(\n    arr: T[], element: T, comparator?: (a: T, b: T) => number) {\n  const index = binarySearch(arr, element, comparator);\n  const insertionPoint = index < 0 ? -(index + 1) : index;\n  arr.splice(insertionPoint, 0, element);\n}\n\n/**\n * Searches the array for the target using binary search, returns the index\n * of the found element, or position to insert if element not found. If no\n * comparator is specified, elements are compared using array_\n * util.defaultComparator, which is suitable for Strings and Numbers in\n * ascending arrays. If the array contains multiple instances of the target\n * value, the left-most instance will be returned.\n * @param arr The array to be searched in.\n * @param target The target to be searched for.\n * @param comparator Should take 2 arguments to compare and return a negative,\n *    zero, or a positive number.\n * @return Lowest index of the target value if found, otherwise the insertion\n *    point where the target should be inserted, in the form of\n *    (-insertionPoint - 1).\n */\nexport function binarySearch<T>(\n    arr: T[], target: T, comparator?: (a: T, b: T) => number) {\n  return binarySearch_(arr, target, comparator || defaultComparator);\n}\n\n/**\n * Compares its two arguments for order.\n * @param a The first element to be compared.\n * @param b The second element to be compared.\n * @return A negative number, zero, or a positive number as the first\n *     argument is less than, equal to, or greater than the second.\n */\nfunction defaultComparator<T>(a: T, b: T): number {\n  return a > b ? 1 : a < b ? -1 : 0;\n}\n\nfunction binarySearch_<T>(\n    arr: T[], target: T, comparator: (a: T, b: T) => number) {\n  let left = 0;\n  let right = arr.length;\n  let middle = 0;\n  let found = false;\n  while (left < right) {\n    middle = left + ((right - left) >>> 1);\n    const compareResult = comparator(target, arr[middle]);\n    if (compareResult > 0) {\n      left = middle + 1;\n    } else {\n      right = middle;\n      // If compareResult is 0, the value is found. We record it is found,\n      // and then keep looking because there may be duplicate.\n      found = !compareResult;\n    }\n  }\n\n  return found ? left : -left - 1;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TypedArray} from '../types';\nimport {binaryInsert} from './non_max_suppression_util';\n\n/**\n * Implementation of the NonMaxSuppression kernel shared between webgl and cpu.\n */\ninterface Candidate {\n  score: number;\n  boxIndex: number;\n  suppressBeginIndex: number;\n}\n\ninterface NonMaxSuppressionResult {\n  selectedIndices: number[];\n  selectedScores?: number[];\n  validOutputs?: number;\n}\n\nexport function nonMaxSuppressionV3Impl(\n    boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number): NonMaxSuppressionResult {\n  return nonMaxSuppressionImpl_(\n      boxes, scores, maxOutputSize, iouThreshold, scoreThreshold,\n      0 /* softNmsSigma */);\n}\n\nexport function nonMaxSuppressionV4Impl(\n    boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number,\n    padToMaxOutputSize: boolean): NonMaxSuppressionResult {\n  return nonMaxSuppressionImpl_(\n      boxes, scores, maxOutputSize, iouThreshold, scoreThreshold,\n      0 /* softNmsSigma */, false /* returnScoresTensor */,\n      padToMaxOutputSize /* padToMaxOutputSize */, true\n      /* returnValidOutputs */);\n}\n\nexport function nonMaxSuppressionV5Impl(\n    boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number,\n    softNmsSigma: number): NonMaxSuppressionResult {\n  return nonMaxSuppressionImpl_(\n      boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma,\n      true /* returnScoresTensor */);\n}\n\nfunction nonMaxSuppressionImpl_(\n    boxes: TypedArray, scores: TypedArray, maxOutputSize: number,\n    iouThreshold: number, scoreThreshold: number, softNmsSigma: number,\n    returnScoresTensor = false, padToMaxOutputSize = false,\n    returnValidOutputs = false): NonMaxSuppressionResult {\n  // The list is sorted in ascending order, so that we can always pop the\n  // candidate with the largest score in O(1) time.\n  const candidates = [];\n\n  for (let i = 0; i < scores.length; i++) {\n    if (scores[i] > scoreThreshold) {\n      candidates.push({score: scores[i], boxIndex: i, suppressBeginIndex: 0});\n    }\n  }\n\n  candidates.sort(ascendingComparator);\n\n  // If softNmsSigma is 0, the outcome of this algorithm is exactly same as\n  // before.\n  const scale = softNmsSigma > 0 ? (-0.5 / softNmsSigma) : 0.0;\n\n  const selectedIndices: number[] = [];\n  const selectedScores: number[] = [];\n\n  while (selectedIndices.length < maxOutputSize && candidates.length > 0) {\n    const candidate = candidates.pop();\n    const {score: originalScore, boxIndex, suppressBeginIndex} = candidate;\n\n    if (originalScore < scoreThreshold) {\n      break;\n    }\n\n    // Overlapping boxes are likely to have similar scores, therefore we\n    // iterate through the previously selected boxes backwards in order to\n    // see if candidate's score should be suppressed. We use\n    // suppressBeginIndex to track and ensure a candidate can be suppressed\n    // by a selected box no more than once. Also, if the overlap exceeds\n    // iouThreshold, we simply ignore the candidate.\n    let ignoreCandidate = false;\n    for (let j = selectedIndices.length - 1; j >= suppressBeginIndex; --j) {\n      const iou = intersectionOverUnion(boxes, boxIndex, selectedIndices[j]);\n\n      if (iou >= iouThreshold) {\n        ignoreCandidate = true;\n        break;\n      }\n\n      candidate.score =\n          candidate.score * suppressWeight(iouThreshold, scale, iou);\n\n      if (candidate.score <= scoreThreshold) {\n        break;\n      }\n    }\n\n    // At this point, if `candidate.score` has not dropped below\n    // `scoreThreshold`, then we know that we went through all of the\n    // previous selections and can safely update `suppressBeginIndex` to the\n    // end of the selected array. Then we can re-insert the candidate with\n    // the updated score and suppressBeginIndex back in the candidate list.\n    // If on the other hand, `candidate.score` has dropped below the score\n    // threshold, we will not add it back to the candidates list.\n    candidate.suppressBeginIndex = selectedIndices.length;\n\n    if (!ignoreCandidate) {\n      // Candidate has passed all the tests, and is not suppressed, so\n      // select the candidate.\n      if (candidate.score === originalScore) {\n        selectedIndices.push(boxIndex);\n        selectedScores.push(candidate.score);\n      } else if (candidate.score > scoreThreshold) {\n        // Candidate's score is suppressed but is still high enough to be\n        // considered, so add back to the candidates list.\n        binaryInsert(candidates, candidate, ascendingComparator);\n      }\n    }\n  }\n\n  // NonMaxSuppressionV4 feature: padding output to maxOutputSize.\n  const validOutputs = selectedIndices.length;\n  const elemsToPad = maxOutputSize - validOutputs;\n\n  if (padToMaxOutputSize && elemsToPad > 0) {\n    selectedIndices.push(...new Array(elemsToPad).fill(0));\n    selectedScores.push(...new Array(elemsToPad).fill(0.0));\n  }\n\n  const result: NonMaxSuppressionResult = {selectedIndices};\n\n  if (returnScoresTensor) {\n    result['selectedScores'] = selectedScores;\n  }\n\n  if (returnValidOutputs) {\n    result['validOutputs'] = validOutputs;\n  }\n\n  return result;\n}\n\nfunction intersectionOverUnion(boxes: TypedArray, i: number, j: number) {\n  const iCoord = boxes.subarray(i * 4, i * 4 + 4);\n  const jCoord = boxes.subarray(j * 4, j * 4 + 4);\n  const yminI = Math.min(iCoord[0], iCoord[2]);\n  const xminI = Math.min(iCoord[1], iCoord[3]);\n  const ymaxI = Math.max(iCoord[0], iCoord[2]);\n  const xmaxI = Math.max(iCoord[1], iCoord[3]);\n  const yminJ = Math.min(jCoord[0], jCoord[2]);\n  const xminJ = Math.min(jCoord[1], jCoord[3]);\n  const ymaxJ = Math.max(jCoord[0], jCoord[2]);\n  const xmaxJ = Math.max(jCoord[1], jCoord[3]);\n  const areaI = (ymaxI - yminI) * (xmaxI - xminI);\n  const areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);\n  if (areaI <= 0 || areaJ <= 0) {\n    return 0.0;\n  }\n  const intersectionYmin = Math.max(yminI, yminJ);\n  const intersectionXmin = Math.max(xminI, xminJ);\n  const intersectionYmax = Math.min(ymaxI, ymaxJ);\n  const intersectionXmax = Math.min(xmaxI, xmaxJ);\n  const intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0.0) *\n      Math.max(intersectionXmax - intersectionXmin, 0.0);\n  return intersectionArea / (areaI + areaJ - intersectionArea);\n}\n\n// A Gaussian penalty function, this method always returns values in [0, 1].\n// The weight is a function of similarity, the more overlap two boxes are, the\n// smaller the weight is,meaning highly overlapping boxes will be significantly\n// penalized. On the other hand, a non-overlapping box will not be penalized.\nfunction suppressWeight(iouThreshold: number, scale: number, iou: number) {\n  const weight = Math.exp(scale * iou * iou);\n  return iou <= iouThreshold ? weight : 0.0;\n}\n\nfunction ascendingComparator(c1: Candidate, c2: Candidate) {\n  // For objects with same scores, we make the object with the larger index go\n  // first. In an array that pops from the end, this means that the object with\n  // the smaller index will be popped first. This ensures the same output as\n  // the TensorFlow python version.\n  return (c1.score - c2.score) ||\n      ((c1.score === c2.score) && (c2.boxIndex - c1.boxIndex));\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {nonMaxSuppressionV3Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This is the async version of `nonMaxSuppression`\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @return A 1D tensor with the selected box indices.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionAsync_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY): Promise<Tensor1D> {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n  const inputs = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold);\n  maxOutputSize = inputs.maxOutputSize;\n  iouThreshold = inputs.iouThreshold;\n  scoreThreshold = inputs.scoreThreshold;\n\n  const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);\n  const boxesVals = boxesAndScores[0];\n  const scoresVals = boxesAndScores[1];\n\n  // We call a cpu based impl directly with the typedarray data  here rather\n  // than a kernel because all kernels are synchronous (and thus cannot await\n  // .data()).\n  const {selectedIndices} = nonMaxSuppressionV3Impl(\n      boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);\n  if ($boxes !== boxes) {\n    $boxes.dispose();\n  }\n  if ($scores !== scores) {\n    $scores.dispose();\n  }\n\n  return tensor1d(selectedIndices, 'int32');\n}\n\nexport const nonMaxSuppressionAsync = nonMaxSuppressionAsync_;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This op also supports a Soft-NMS mode (cf.\n * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\n * of other overlapping boxes, therefore favoring different regions of the image\n * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`\n * parameter to be larger than 0.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @param softNmsSigma A float representing the sigma parameter for Soft NMS.\n *     When sigma is 0, it falls back to nonMaxSuppression.\n * @return A map with the following properties:\n *     - selectedIndices: A 1D tensor with the selected box indices.\n *     - selectedScores: A 1D tensor with the corresponding scores for each\n *       selected box.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppressionWithScore_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY,\n    softNmsSigma = 0.0): NamedTensorMap {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\n\n  const params = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n      softNmsSigma);\n  maxOutputSize = params.maxOutputSize;\n  iouThreshold = params.iouThreshold;\n  scoreThreshold = params.scoreThreshold;\n  softNmsSigma = params.softNmsSigma;\n\n  const inputs: NonMaxSuppressionV5Inputs = {boxes: $boxes, scores: $scores};\n  const attrs: NonMaxSuppressionV5Attrs =\n      {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const result = ENGINE.runKernel(\n                     NonMaxSuppressionV5, inputs as unknown as NamedTensorMap,\n                     attrs as unknown as NamedAttrMap) as Tensor[];\n\n  return {selectedIndices: result[0], selectedScores: result[1]};\n}\n\nexport const nonMaxSuppressionWithScore = /* @__PURE__ */ op({nonMaxSuppressionWithScore_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {nonMaxSuppressionV5Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union).\n *\n * This op also supports a Soft-NMS mode (cf.\n * Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score\n * of other overlapping boxes, therefore favoring different regions of the image\n * with high scores. To enable this Soft-NMS mode, set the `softNmsSigma`\n * parameter to be larger than 0.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @param softNmsSigma A float representing the sigma parameter for Soft NMS.\n *     When sigma is 0, it falls back to nonMaxSuppression.\n * @return A map with the following properties:\n *     - selectedIndices: A 1D tensor with the selected box indices.\n *     - selectedScores: A 1D tensor with the corresponding scores for each\n *       selected box.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionWithScoreAsync_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY,\n    softNmsSigma = 0.0): Promise<NamedTensorMap> {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n  const params = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n      softNmsSigma);\n  maxOutputSize = params.maxOutputSize;\n  iouThreshold = params.iouThreshold;\n  scoreThreshold = params.scoreThreshold;\n  softNmsSigma = params.softNmsSigma;\n\n  const boxesAndScores = await Promise.all([$boxes.data(), $scores.data()]);\n  const boxesVals = boxesAndScores[0];\n  const scoresVals = boxesAndScores[1];\n\n  // We call a cpu based impl directly with the typedarray data  here rather\n  // than a kernel because all kernels are synchronous (and thus cannot await\n  // .data()).\n  const {selectedIndices, selectedScores} = nonMaxSuppressionV5Impl(\n      boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold,\n      softNmsSigma);\n\n  if ($boxes !== boxes) {\n    $boxes.dispose();\n  }\n  if ($scores !== scores) {\n    $scores.dispose();\n  }\n\n  return {\n    selectedIndices: tensor1d(selectedIndices, 'int32'),\n    selectedScores: tensor1d(selectedScores)\n  };\n}\n\nexport const nonMaxSuppressionWithScoreAsync = nonMaxSuppressionWithScoreAsync_;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {op} from '../operation';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union), with an option to pad results.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @param padToMaxOutputSize Defaults to false. If true, size of output\n *     `selectedIndices` is padded to maxOutputSize.\n * @return A map with the following properties:\n *     - selectedIndices: A 1D tensor with the selected box indices.\n *     - validOutputs: A scalar denoting how many elements in `selectedIndices`\n *       are valid. Valid elements occur first, then padding.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction nonMaxSuppressionPadded_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY,\n    padToMaxOutputSize = false): NamedTensorMap {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\n\n  const params = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n      null /* softNmsSigma */);\n  const $maxOutputSize = params.maxOutputSize;\n  const $iouThreshold = params.iouThreshold;\n  const $scoreThreshold = params.scoreThreshold;\n\n  const inputs: NonMaxSuppressionV4Inputs = {boxes: $boxes, scores: $scores};\n  const attrs: NonMaxSuppressionV4Attrs = {\n    maxOutputSize: $maxOutputSize,\n    iouThreshold: $iouThreshold,\n    scoreThreshold: $scoreThreshold,\n    padToMaxOutputSize\n  };\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const result = ENGINE.runKernel(\n                     NonMaxSuppressionV4, inputs as unknown as NamedTensorMap,\n                     attrs as unknown as NamedAttrMap) as Tensor[];\n\n  return {selectedIndices: result[0], validOutputs: result[1]};\n}\n\nexport const nonMaxSuppressionPadded = /* @__PURE__ */ op({nonMaxSuppressionPadded_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {nonMaxSuppressionV4Impl} from '../../backends/non_max_suppression_impl';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {nonMaxSuppSanityCheck} from '../nonmax_util';\nimport {scalar} from '../scalar';\nimport {tensor1d} from '../tensor1d';\n\n/**\n * Asynchronously performs non maximum suppression of bounding boxes based on\n * iou (intersection over union), with an option to pad results.\n *\n * @param boxes a 2d tensor of shape `[numBoxes, 4]`. Each entry is\n *     `[y1, x1, y2, x2]`, where `(y1, x1)` and `(y2, x2)` are the corners of\n *     the bounding box.\n * @param scores a 1d tensor providing the box scores of shape `[numBoxes]`.\n * @param maxOutputSize The maximum number of boxes to be selected.\n * @param iouThreshold A float representing the threshold for deciding whether\n *     boxes overlap too much with respect to IOU. Must be between [0, 1].\n *     Defaults to 0.5 (50% box overlap).\n * @param scoreThreshold A threshold for deciding when to remove boxes based\n *     on score. Defaults to -inf, which means any score is accepted.\n * @param padToMaxOutputSize Defaults to false. If true, size of output\n *     `selectedIndices` is padded to maxOutputSize.\n * @return A map with the following properties:\n *     - selectedIndices: A 1D tensor with the selected box indices.\n *     - validOutputs: A scalar denoting how many elements in `selectedIndices`\n *       are valid. Valid elements occur first, then padding.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nasync function nonMaxSuppressionPaddedAsync_(\n    boxes: Tensor2D|TensorLike, scores: Tensor1D|TensorLike,\n    maxOutputSize: number, iouThreshold = 0.5,\n    scoreThreshold = Number.NEGATIVE_INFINITY,\n    padToMaxOutputSize = false): Promise<NamedTensorMap> {\n  const $boxes = convertToTensor(boxes, 'boxes', 'nonMaxSuppressionAsync');\n  const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppressionAsync');\n\n  const params = nonMaxSuppSanityCheck(\n      $boxes, $scores, maxOutputSize, iouThreshold, scoreThreshold,\n      null /* softNmsSigma */);\n  const $maxOutputSize = params.maxOutputSize;\n  const $iouThreshold = params.iouThreshold;\n  const $scoreThreshold = params.scoreThreshold;\n\n  const [boxesVals, scoresVals] =\n      await Promise.all([$boxes.data(), $scores.data()]);\n\n  // We call a cpu based impl directly with the typedarray data here rather\n  // than a kernel because all kernels are synchronous (and thus cannot await\n  // .data()).\n  const {selectedIndices, validOutputs} = nonMaxSuppressionV4Impl(\n      boxesVals, scoresVals, $maxOutputSize, $iouThreshold, $scoreThreshold,\n      padToMaxOutputSize);\n\n  if ($boxes !== boxes) {\n    $boxes.dispose();\n  }\n  if ($scores !== scores) {\n    $scores.dispose();\n  }\n\n  return {\n    selectedIndices: tensor1d(selectedIndices, 'int32'),\n    validOutputs: scalar(validOutputs, 'int32')\n  };\n}\n\nexport const nonMaxSuppressionPaddedAsync = nonMaxSuppressionPaddedAsync_;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * Bilinear resize a single 3D image or a batch of 3D images to a new shape.\n *\n * @param images The images, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param size The new shape `[newHeight, newWidth]` to resize the\n *     images to. Each channel is resized individually.\n * @param alignCorners Defaults to `false`. If true, rescale\n *     input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4\n *     corners of images and resized images. If false, rescale by\n *     `new_height / height`. Treat similarly the width dimension.\n * @param halfPixelCenters Defaults to `false`. Whether to assume pixel centers\n *     are at 0.5, which would make the floating point coordinates of the top\n *     left pixel 0.5, 0.5.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction resizeBilinear_<T extends Tensor3D|Tensor4D>(\n    images: T|TensorLike, size: [number, number], alignCorners = false,\n    halfPixelCenters = false): T {\n  const $images = convertToTensor(images, 'images', 'resizeBilinear');\n\n  util.assert(\n      $images.rank === 3 || $images.rank === 4,\n      () => `Error in resizeBilinear: x must be rank 3 or 4, but got ` +\n          `rank ${$images.rank}.`);\n  util.assert(\n      size.length === 2,\n      () => `Error in resizeBilinear: new shape must 2D, but got shape ` +\n          `${size}.`);\n  util.assert(\n      halfPixelCenters === false || alignCorners === false,\n      () => `Error in resizeBilinear: If halfPixelCenters is true, ` +\n          `alignCorners must be false.`);\n\n  let batchImages = $images as Tensor4D;\n  let reshapedTo4D = false;\n  if ($images.rank === 3) {\n    reshapedTo4D = true;\n    batchImages = reshape(\n        $images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);\n  }\n\n  const [] = size;\n\n  const inputs: ResizeBilinearInputs = {images: batchImages};\n  const attrs: ResizeBilinearAttrs = {alignCorners, halfPixelCenters, size};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  ResizeBilinear, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const resizeBilinear = /* @__PURE__ */ op({resizeBilinear_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor3D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\n\n/**\n * NearestNeighbor resize a batch of 3D images to a new shape.\n *\n * @param images The images, of rank 4 or rank 3, of shape\n *     `[batch, height, width, inChannels]`. If rank 3, batch of 1 is assumed.\n * @param size The new shape `[newHeight, newWidth]` to resize the\n *     images to. Each channel is resized individually.\n * @param alignCorners Defaults to False. If true, rescale\n *     input by `(new_height - 1) / (height - 1)`, which exactly aligns the 4\n *     corners of images and resized images. If false, rescale by\n *     `new_height / height`. Treat similarly the width dimension.\n * @param halfPixelCenters Defaults to `false`. Whether to assume pixels are of\n *      half the actual dimensions, and yield more accurate resizes. This flag\n *      would also make the floating point coordinates of the top left pixel\n *      0.5, 0.5.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction resizeNearestNeighbor_<T extends Tensor3D|Tensor4D>(\n    images: T|TensorLike, size: [number, number], alignCorners = false,\n    halfPixelCenters = false): T {\n  const $images = convertToTensor(images, 'images', 'resizeNearestNeighbor');\n\n  util.assert(\n      $images.rank === 3 || $images.rank === 4,\n      () => `Error in resizeNearestNeighbor: x must be rank 3 or 4, but got ` +\n          `rank ${$images.rank}.`);\n  util.assert(\n      size.length === 2,\n      () =>\n          `Error in resizeNearestNeighbor: new shape must 2D, but got shape ` +\n          `${size}.`);\n  util.assert(\n      $images.dtype === 'float32' || $images.dtype === 'int32',\n      () => '`images` must have `int32` or `float32` as dtype');\n  util.assert(\n      halfPixelCenters === false || alignCorners === false,\n      () => `Error in resizeNearestNeighbor: If halfPixelCenters is true, ` +\n          `alignCorners must be false.`);\n  let batchImages = $images as Tensor4D;\n  let reshapedTo4D = false;\n  if ($images.rank === 3) {\n    reshapedTo4D = true;\n    batchImages = reshape(\n        $images, [1, $images.shape[0], $images.shape[1], $images.shape[2]]);\n  }\n  const [] = size;\n\n  const inputs: ResizeNearestNeighborInputs = {images: batchImages};\n  const attrs:\n      ResizeNearestNeighborAttrs = {alignCorners, halfPixelCenters, size};\n\n  // tslint:disable-next-line: no-unnecessary-type-assertion\n  const res = ENGINE.runKernel(\n                  ResizeNearestNeighbor, inputs as unknown as NamedTensorMap,\n                  attrs as unknown as NamedAttrMap) as T;\n\n  if (reshapedTo4D) {\n    return reshape(res, [res.shape[1], res.shape[2], res.shape[3]]) as T;\n  }\n  return res;\n}\n\nexport const resizeNearestNeighbor = /* @__PURE__ */ op({resizeNearestNeighbor_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport { Tensor1D, Tensor3D } from '../../tensor';\nimport { tensor1d } from '../tensor1d';\nimport { TensorLike } from '../../types';\nimport { op } from '../operation';\nimport { cast } from '../cast';\nimport { split } from '../split';\nimport { bincount } from '../bincount';\nimport { lessEqual } from '../less_equal';\nimport { greater } from '../greater';\nimport { sum } from '../sum';\nimport { add } from '../add';\nimport { mul } from '../mul';\nimport { div } from '../div';\nimport { sub } from '../sub';\nimport { round } from '../round';\nimport { where } from '../where';\nimport { fill } from '../fill';\nimport {slice} from '../slice';\nimport { range } from '../range';\nimport { tensor } from '../tensor';\nimport * as util from '../../util';\nimport { convertToTensor } from '../../tensor_util_env';\n\n/**\n * Performs image binarization with corresponding threshold\n * (depends on the method)value, which creates a binary image from a grayscale.\n * @param image 3d tensor of shape [imageHeight,imageWidth, depth],\n * where imageHeight and imageWidth must be positive.The image color\n * range should be [0, 255].\n * @param method Optional string from `'binary' | 'otsu'`\n * which specifies the method for thresholding. Defaults to 'binary'.\n * @param inverted Optional boolean whichspecifies\n * if colours should be inverted. Defaults to false.\n * @param threshValue Optional number which defines threshold value from 0 to 1.\n * Defaults to 0.5.\n * @return A 3d tensor of shape [imageHeight,imageWidth, depth], which\n * contains binarized image.\n */\n\nfunction threshold_(\n    image: Tensor3D | TensorLike,\n    method = 'binary',\n    inverted = false,\n    threshValue = 0.5\n): Tensor3D {\n    const $image = convertToTensor(image, 'image', 'threshold');\n\n    /* 0.2989, 0.5870, 0.1140 are represent luma coefficients in CCIR601.\n\tReference for converting between RGB and grayscale: https://en.wikipedia.org/wiki/Luma_%28video%29  */\n\n    const RED_INTENCITY_COEF = 0.2989;\n    const GREEN_INTENCITY_COEF = 0.5870;\n    const BLUE_INTENCITY_COEF = 0.1140;\n    const totalPixelsInImage = $image.shape[0] * $image.shape[1];\n\n    let $threshold = mul(tensor1d([threshValue]), 255);\n    let r, g, b, grayscale;\n\n    util.assert(\n        $image.rank === 3,\n        () => 'Error in threshold: image must be rank 3,' +\n            `but got rank ${$image.rank}.`);\n\n    util.assert(\n        $image.shape[2] === 3 || $image.shape[2]=== 1,\n        () => 'Error in threshold: ' +\n            'image color channel must be equal to 3 or 1' +\n            `but got ${$image.shape[2]}.`);\n\n    util.assert(\n      $image.dtype === 'int32' || $image.dtype === 'float32',\n      () => 'Error in dtype: image dtype must be int32 or float32,' +\n          `but got dtype ${$image.dtype}.`);\n\n    util.assert(\n      method === 'otsu' || method === 'binary',\n      () => `Method must be binary or otsu, but was ${method}`);\n\n    if ($image.shape[2] === 3) {\n        [r, g, b] = split($image, [1, 1, 1], -1);\n        const $r = mul(r,RED_INTENCITY_COEF);\n        const $g = mul(g,GREEN_INTENCITY_COEF);\n        const $b = mul(b,BLUE_INTENCITY_COEF);\n        grayscale = add(add($r, $g), $b);\n    } else {\n        grayscale = image;\n    }\n\n    if (method === 'otsu') {\n        const $histogram = bincount(cast(round(grayscale), 'int32') as Tensor1D,\n            tensor([]),\n            256);\n        $threshold = otsu($histogram, totalPixelsInImage);\n    }\n\n    const invCondition = inverted ?\n        lessEqual(grayscale, $threshold) : greater(grayscale, $threshold);\n\n    const result = cast(mul(invCondition,255), 'int32');\n\n    return result as Tensor3D;\n}\n\nfunction otsu(histogram: Tensor1D, total: number):Tensor1D {\n\n    let bestThresh = tensor1d([-1]);\n    let bestInBetVar = tensor1d([0]);\n    let cInBetVar = tensor1d([0]);\n    let classFirst, classSecond, meanFirst,\n        meanSec, weightForeground, weightBack;\n\n    for (let index = 0; index < histogram.size-1; index++) {\n\n        classFirst = slice(histogram, 0, index + 1);\n\n        classSecond = slice(histogram,index + 1);\n\n        weightForeground = div(sum(classFirst),total);\n\n        weightBack = div(sum(classSecond),total);\n\n        const meanFirstDivA = sum(mul(classFirst, range(0, classFirst.size)));\n\n        meanFirst = div(meanFirstDivA, sum(classFirst) );\n\n        const meanSecFill = fill(classSecond.shape, classFirst.size);\n        const meanSecAdd = add(range(0,classSecond.size),meanSecFill);\n        const meanSecMul = mul(classSecond, (meanSecAdd));\n        meanSec = div(sum(meanSecMul), sum(classSecond));\n\n        const cInBetVarSubA = sub(meanFirst, meanSec);\n        const cInBetVarSubB = sub(meanFirst, meanSec);\n        const cInBetVarMul = mul(weightForeground, weightBack);\n        cInBetVar = mul(mul(cInBetVarMul,cInBetVarSubA), cInBetVarSubB);\n\n        const condition = greater(cInBetVar, bestInBetVar);\n\n        bestInBetVar = where(condition, cInBetVar, bestInBetVar);\n\n        bestThresh = where(condition, tensor1d([index]), bestThresh);\n\n    }\n    return bestThresh;\n}\n\nexport const threshold = /* @__PURE__ */ op({ threshold_ });\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../../engine';\nimport {Transform, TransformAttrs, TransformInputs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor2D, Tensor4D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport * as util from '../../util';\n\nimport {op} from '../operation';\n\n/**\n * Applies the given transform(s) to the image(s).\n *\n * @param image 4d tensor of shape `[batch, imageHeight, imageWidth, depth]`.\n * @param transforms Projective transform matrix/matrices. A tensor1d of length\n *     8 or tensor of size N x 8. If one row of transforms is [a0, a1, a2, b0,\n *     b1, b2, c0, c1], then it maps the output point (x, y) to a transformed\n *     input point (x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k),\n *     where k = c0 x + c1 y + 1. The transforms are inverted compared to the\n *     transform mapping input points to output points.\n * @param interpolation Interpolation mode.\n *     Supported values: 'nearest', 'bilinear'. Default to 'nearest'.\n * @param fillMode Points outside the boundaries of the input are filled\n *     according to the given mode, one of 'constant', 'reflect', 'wrap',\n *     'nearest'. Default to 'constant'.\n *     'reflect': (d c b a | a b c d | d c b a ) The input is extended by\n *     reflecting about the edge of the last pixel.\n *     'constant': (k k k k | a b c d | k k k k) The input is extended by\n *     filling all values beyond the edge with the same constant value k.\n *     'wrap': (a b c d | a b c d | a b c d) The input is extended by\n *     wrapping around to the opposite edge.\n *     'nearest': (a a a a | a b c d | d d d d) The input is extended by\n *     the nearest pixel.\n * @param fillValue A float represents the value to be filled outside the\n *     boundaries when fillMode is 'constant'.\n * @param Output dimension after the transform, [height, width]. If undefined,\n *     output is the same size as input image.\n *\n * @doc {heading: 'Operations', subheading: 'Images', namespace: 'image'}\n */\nfunction transform_(\n    image: Tensor4D|TensorLike, transforms: Tensor2D|TensorLike,\n    interpolation: 'nearest'|'bilinear' = 'nearest',\n    fillMode: 'constant'|'reflect'|'wrap'|'nearest' = 'constant', fillValue = 0,\n    outputShape?: [number, number]): Tensor4D {\n  const $image = convertToTensor(image, 'image', 'transform', 'float32');\n  const $transforms =\n      convertToTensor(transforms, 'transforms', 'transform', 'float32');\n\n  util.assert(\n      $image.rank === 4,\n      () => 'Error in transform: image must be rank 4,' +\n          `but got rank ${$image.rank}.`);\n\n  util.assert(\n      $transforms.rank === 2 &&\n          ($transforms.shape[0] === $image.shape[0] ||\n           $transforms.shape[0] === 1) &&\n          $transforms.shape[1] === 8,\n      () => `Error in transform: Input transform should be batch x 8 or 1 x 8`);\n\n  util.assert(\n      outputShape == null || outputShape.length === 2,\n      () =>\n          'Error in transform: outputShape must be [height, width] or null, ' +\n          `but got ${outputShape}.`);\n\n  const inputs: TransformInputs = {image: $image, transforms: $transforms};\n  const attrs:\n      TransformAttrs = {interpolation, fillMode, fillValue, outputShape};\n\n  return ENGINE.runKernel(\n      Transform, inputs as unknown as NamedTensorMap,\n      attrs as unknown as NamedAttrMap);\n}\n\nexport const transform = /* @__PURE__ */ op({transform_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assert} from '../../util';\n\nimport {greaterEqual} from '../greater_equal';\nimport {less} from '../less';\nimport {lessEqual} from '../less_equal';\nimport {logicalAnd} from '../logical_and';\nimport {minimum} from '../minimum';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {range} from '../range';\nimport {reshape} from '../reshape';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {unstack} from '../unstack';\nimport {where} from '../where';\nimport {zeros} from '../zeros';\n\n/**\n * Copy a tensor setting everything outside a central band in each innermost\n * matrix to zero.\n *\n * The band part is computed as follows: Assume input has `k` dimensions\n * `[I, J, K, ..., M, N]`, then the output is a tensor with the same shape where\n * `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`.\n * The indicator function\n * `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)`\n * `&& (num_upper < 0 || (n-m) <= num_upper)`\n *\n * ```js\n * const x = tf.tensor2d([[ 0,  1,  2, 3],\n *                        [-1,  0,  1, 2],\n *                        [-2, -1,  0, 1],\n *                        [-3, -2, -1, 0]]);\n * let y = tf.linalg.bandPart(x, 1, -1);\n * y.print(); // [[ 0,  1,  2, 3],\n *            //  [-1,  0,  1, 2],\n *            //  [ 0, -1,  0, 1],\n *            //  [ 0, 0 , -1, 0]]\n * let z = tf.linalg.bandPart(x, 2, 1);\n * z.print(); // [[ 0,  1,  0, 0],\n *            //  [-1,  0,  1, 0],\n *            //  [-2, -1,  0, 1],\n *            //  [ 0, -2, -1, 0]]\n * ```\n *\n * @param x Rank `k` tensor\n * @param numLower Number of subdiagonals to keep.\n *   If negative, keep entire lower triangle.\n * @param numUpper Number of subdiagonals to keep.\n *   If negative, keep entire upper triangle.\n * @returns Rank `k` tensor of the same shape as input.\n *   The extracted banded tensor.\n *\n * @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}\n */\nfunction bandPart_<T extends Tensor>(\n    a: T|TensorLike, numLower: number|Scalar, numUpper: number|Scalar): T {\n  const $a = convertToTensor(a, 'a', 'bandPart');\n  assert(\n      $a.rank >= 2,\n      () => `bandPart(): Rank must be at least 2, got ${$a.rank}.`);\n\n  const shape = $a.shape;\n  const [M, N] = $a.shape.slice(-2);\n\n  let $numLower: Scalar;\n  let $numUpper: Scalar;\n  if (typeof numLower === 'number') {\n    assert(\n        numLower % 1 === 0,\n        () => `bandPart(): numLower must be an integer, got ${numLower}.`);\n    assert(\n        numLower <= M,\n        () => `bandPart(): numLower (${numLower})` +\n            ` must not be greater than the number of rows (${M}).`);\n    $numLower =\n        convertToTensor(numLower < 0 ? M : numLower, 'numLower', 'bandPart') as\n        Scalar;\n  } else {\n    assert(\n        numLower.dtype === 'int32',\n        () => `bandPart(): numLower's dtype must be an int32.`);\n    // If numLower is a Scalar, checking `numLower <= M` could hurt performance,\n    // but minimum(numLower, M) could avoid unexpected results.\n    $numLower = where(less(numLower, 0), M, minimum(numLower, M)) as Scalar;\n  }\n\n  if (typeof numUpper === 'number') {\n    assert(\n        numUpper % 1 === 0,\n        () => `bandPart(): numUpper must be an integer, got ${numUpper}.`);\n    assert(\n        numUpper <= N,\n        () => `bandPart(): numUpper (${numUpper})` +\n            ` must not be greater than the number of columns (${N}).`);\n    $numUpper =\n        convertToTensor(numUpper < 0 ? N : numUpper, 'numUpper', 'bandPart') as\n        Scalar;\n  } else {\n    assert(\n        numUpper.dtype === 'int32',\n        () => `bandPart(): numUpper's dtype must be an int32.`);\n    $numUpper = where(less(numUpper, 0), N, minimum(numUpper, N)) as Scalar;\n  }\n\n  const i = reshape(range(0, M, 1, 'int32'), [-1, 1]);\n  const j = range(0, N, 1, 'int32');\n  const ij = sub(i, j);\n\n  const inBand =\n      logicalAnd(lessEqual(ij, $numLower), greaterEqual(ij, neg($numUpper)));\n\n  const zero = zeros([M, N], $a.dtype);\n\n  return reshape(\n             stack(unstack(reshape($a, [-1, M, N]))\n                       .map(mat => where(inBand, mat, zero))),\n             shape) as T;\n}\n\nexport const bandPart = /* @__PURE__ */ op({bandPart_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {Tensor1D, Tensor2D} from '../../tensor';\nimport {assert} from '../../util';\n\nimport {div} from '../div';\nimport {mul} from '../mul';\nimport {norm} from '../norm';\nimport {op} from '../operation';\nimport {split} from '../split';\nimport {squeeze} from '../squeeze';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\n/**\n * Gram-Schmidt orthogonalization.\n *\n * ```js\n * const x = tf.tensor2d([[1, 2], [3, 4]]);\n * let y = tf.linalg.gramSchmidt(x);\n * y.print();\n * console.log('Orthogonalized:');\n * y.dot(y.transpose()).print();  // should be nearly the identity matrix.\n * console.log('First row direction maintained:');\n * const data = await y.array();\n * console.log(data[0][1] / data[0][0]);  // should be nearly 2.\n * ```\n *\n * @param xs The vectors to be orthogonalized, in one of the two following\n *   formats:\n *   - An Array of `tf.Tensor1D`.\n *   - A `tf.Tensor2D`, i.e., a matrix, in which case the vectors are the rows\n *     of `xs`.\n *   In each case, all the vectors must have the same length and the length\n *   must be greater than or equal to the number of vectors.\n * @returns The orthogonalized and normalized vectors or matrix.\n *   Orthogonalization means that the vectors or the rows of the matrix\n *   are orthogonal (zero inner products). Normalization means that each\n *   vector or each row of the matrix has an L2 norm that equals `1`.\n *\n * @doc {heading:'Operations', subheading:'Linear Algebra', namespace:'linalg'}\n */\nfunction gramSchmidt_(xs: Tensor1D[]|Tensor2D): Tensor1D[]|Tensor2D {\n  let inputIsTensor2D: boolean;\n  if (Array.isArray(xs)) {\n    inputIsTensor2D = false;\n    assert(\n        xs != null && xs.length > 0,\n        () => 'Gram-Schmidt process: input must not be null, undefined, or ' +\n            'empty');\n    const dim = xs[0].shape[0];\n    for (let i = 1; i < xs.length; ++i) {\n      assert(\n          xs[i].shape[0] === dim,\n          () =>\n              'Gram-Schmidt: Non-unique lengths found in the input vectors: ' +\n              `(${(xs as Tensor1D[])[i].shape[0]} vs. ${dim})`);\n    }\n  } else {\n    inputIsTensor2D = true;\n    xs = split(xs, xs.shape[0], 0).map(x => squeeze(x, [0]));\n  }\n\n  assert(\n      xs.length <= xs[0].shape[0],\n      () => `Gram-Schmidt: Number of vectors (${\n                (xs as Tensor1D[]).length}) exceeds ` +\n          `number of dimensions (${(xs as Tensor1D[])[0].shape[0]}).`);\n\n  const ys: Tensor1D[] = [];\n  const xs1d = xs;\n  for (let i = 0; i < xs.length; ++i) {\n    ys.push(ENGINE.tidy(() => {\n      let x = xs1d[i];\n      if (i > 0) {\n        for (let j = 0; j < i; ++j) {\n          const proj = mul(sum(mul(ys[j], x)), ys[j]);\n          x = sub(x, proj);\n        }\n      }\n      return div(x, norm(x, 'euclidean'));\n    }));\n  }\n\n  if (inputIsTensor2D) {\n    return stack(ys, 0) as Tensor2D;\n  } else {\n    return ys;\n  }\n}\n\nexport const gramSchmidt = /* @__PURE__ */ op({gramSchmidt_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../../engine';\nimport {dispose} from '../../globals';\nimport {Tensor, Tensor2D} from '../../tensor';\nimport {assert} from '../../util';\n\nimport {clone} from '../clone';\nimport {concat} from '../concat';\nimport {div} from '../div';\nimport {eye} from '../eye';\nimport {greater} from '../greater';\nimport {matMul} from '../mat_mul';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {norm} from '../norm';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {slice} from '../slice';\nimport {stack} from '../stack';\nimport {sub} from '../sub';\nimport {tensor2d} from '../tensor2d';\nimport {transpose} from '../transpose';\nimport {unstack} from '../unstack';\nimport {where} from '../where';\n\n/**\n * Compute QR decomposition of m-by-n matrix using Householder transformation.\n *\n * Implementation based on\n *   [http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf]\n * (http://www.cs.cornell.edu/~bindel/class/cs6210-f09/lec18.pdf)\n *\n * ```js\n * const a = tf.tensor2d([[1, 2], [3, 4]]);\n * let [q, r] = tf.linalg.qr(a);\n * console.log('Q');\n * q.print();\n * console.log('R');\n * r.print();\n * console.log('Orthogonalized');\n * q.dot(q.transpose()).print()  // should be nearly the identity matrix.\n * console.log('Reconstructed');\n * q.dot(r).print(); // should be nearly [[1, 2], [3, 4]];\n * ```\n *\n * @param x The `tf.Tensor` to be QR-decomposed. Must have rank >= 2. Suppose\n *   it has the shape `[..., M, N]`.\n * @param fullMatrices An optional boolean parameter. Defaults to `false`.\n *   If `true`, compute full-sized `Q`. If `false` (the default),\n *   compute only the leading N columns of `Q` and `R`.\n * @returns An `Array` of two `tf.Tensor`s: `[Q, R]`. `Q` is a unitary matrix,\n *   i.e., its columns all have unit norm and are mutually orthogonal.\n *   If `M >= N`,\n *     If `fullMatrices` is `false` (default),\n *       - `Q` has a shape of `[..., M, N]`,\n *       - `R` has a shape of `[..., N, N]`.\n *     If `fullMatrices` is `true` (default),\n *       - `Q` has a shape of `[..., M, M]`,\n *       - `R` has a shape of `[..., M, N]`.\n *   If `M < N`,\n *     - `Q` has a shape of `[..., M, M]`,\n *     - `R` has a shape of `[..., M, N]`.\n * @throws If the rank of `x` is less than 2.\n *\n * @doc {heading:'Operations',\n *       subheading:'Linear Algebra',\n *       namespace:'linalg'}\n */\nfunction qr_(x: Tensor, fullMatrices = false): [Tensor, Tensor] {\n  assert(\n      x.rank >= 2,\n      () => `qr() requires input tensor to have a rank >= 2, but got rank ${\n          x.rank}`);\n\n  if (x.rank === 2) {\n    return qr2d(x as Tensor2D, fullMatrices);\n  } else {\n    // Rank > 2.\n    // TODO(cais): Below we split the input into individual 2D tensors,\n    //   perform QR decomposition on them and then stack the results back\n    //   together. We should explore whether this can be parallelized.\n    const outerDimsProd = x.shape.slice(0, x.shape.length - 2)\n                              .reduce((value, prev) => value * prev);\n    const x2ds = unstack(\n        reshape(\n            x,\n            [\n              outerDimsProd, x.shape[x.shape.length - 2],\n              x.shape[x.shape.length - 1]\n            ]),\n        0);\n    const q2ds: Tensor2D[] = [];\n    const r2ds: Tensor2D[] = [];\n    x2ds.forEach(x2d => {\n      const [q2d, r2d] = qr2d(x2d as Tensor2D, fullMatrices);\n      q2ds.push(q2d);\n      r2ds.push(r2d);\n    });\n    const q = reshape(stack(q2ds, 0), x.shape);\n    const r = reshape(stack(r2ds, 0), x.shape);\n    return [q, r];\n  }\n}\n\nfunction qr2d(x: Tensor2D, fullMatrices = false): [Tensor2D, Tensor2D] {\n  return ENGINE.tidy(() => {\n    assert(\n        x.shape.length === 2,\n        () => `qr2d() requires a 2D Tensor, but got a ${\n            x.shape.length}D Tensor.`);\n\n    const m = x.shape[0];\n    const n = x.shape[1];\n\n    let q = eye(m);    // Orthogonal transform so far.\n    let r = clone(x);  // Transformed matrix so far.\n\n    const one2D = tensor2d([[1]], [1, 1]);\n    let w: Tensor2D = clone(one2D);\n\n    const iters = m >= n ? n : m;\n    for (let j = 0; j < iters; ++j) {\n      // This tidy within the for-loop ensures we clean up temporary\n      // tensors as soon as they are no longer needed.\n      const rTemp = r;\n      const wTemp = w;\n      const qTemp = q;\n      [w, r, q] = ENGINE.tidy((): [Tensor2D, Tensor2D, Tensor2D] => {\n        // Find H = I - tau * w * w', to put zeros below R(j, j).\n        const rjEnd1 = slice(r, [j, j], [m - j, 1]);\n        const normX = norm(rjEnd1);\n        const rjj = slice(r, [j, j], [1, 1]);\n\n        // The sign() function returns 0 on 0, which causes division by zero.\n        const s = where(greater(rjj, 0), tensor2d([[-1]]), tensor2d([[1]]));\n\n        const u1 = sub(rjj, mul(s, normX));\n        const wPre = div(rjEnd1, u1);\n        if (wPre.shape[0] === 1) {\n          w = clone(one2D);\n        } else {\n          w = concat(\n              [\n                one2D,\n                slice(wPre, [1, 0], [wPre.shape[0] - 1, wPre.shape[1]]) as\n                    Tensor2D\n              ],\n              0);\n        }\n        const tau = neg(div(matMul(s, u1), normX)) as Tensor2D;\n\n        // -- R := HR, Q := QH.\n        const rjEndAll = slice(r, [j, 0], [m - j, n]);\n        const tauTimesW: Tensor2D = mul(tau, w);\n        const wT: Tensor2D = transpose(w);\n        if (j === 0) {\n          r = sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));\n        } else {\n          const rTimesTau: Tensor2D =\n              sub(rjEndAll, matMul(tauTimesW, matMul(wT, rjEndAll)));\n          r = concat([slice(r, [0, 0], [j, n]), rTimesTau], 0);\n        }\n        const tawTimesWT: Tensor2D = transpose(tauTimesW);\n        const qAllJEnd = slice(q, [0, j], [m, q.shape[1] - j]);\n        if (j === 0) {\n          q = sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));\n        } else {\n          const qTimesTau: Tensor2D =\n              sub(qAllJEnd, matMul(matMul(qAllJEnd, w), tawTimesWT));\n          q = concat([slice(q, [0, 0], [m, j]), qTimesTau], 1);\n        }\n        return [w, r, q];\n      });\n      dispose([rTemp, wTemp, qTemp]);\n    }\n\n    if (!fullMatrices && m > n) {\n      q = slice(q, [0, 0], [m, n]);\n      r = slice(r, [0, 0], [n, n]);\n    }\n\n    return [q, r];\n  }) as [Tensor2D, Tensor2D];\n}\n\nexport const qr = /* @__PURE__ */ op({qr_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nexport enum Reduction {\n  NONE,\n  MEAN,\n  SUM,\n  SUM_BY_NONZERO_WEIGHTS\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\n\nimport {cast} from '../cast';\nimport {div} from '../div';\nimport {Reduction} from '../loss_ops_utils';\nimport {mean} from '../mean';\nimport {mul} from '../mul';\nimport {notEqual} from '../not_equal';\nimport {ones} from '../ones';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sum} from '../sum';\n\n/**\n * Computes the weighted loss between two tensors.\n *\n * @param losses Tensor of shape `[batch_size, d1, ..., dN]`.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `losses`, and must be broadcastable to `losses` (i.e., all\n *    dimensions must be either `1`, or the same as the corresponding\n *    `losses` dimension).\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction computeWeightedLoss_<T extends Tensor, O extends Tensor>(\n    losses: T|TensorLike, weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $losses = convertToTensor(losses, 'losses', 'computeWeightedLoss');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'computeWeightedLoss');\n  }\n\n  const weightedLoss = ($weights == null) ? $losses : mul($losses, $weights);\n\n  if (reduction === Reduction.NONE) {\n    return weightedLoss as O;\n  }\n  if (reduction === Reduction.SUM) {\n    return sum(weightedLoss);\n  }\n  if (reduction === Reduction.MEAN) {\n    if ($weights == null) {\n      return mean(weightedLoss);\n    } else {\n      const broadcastFactor = $losses.size / $weights.size;\n      const result = div(sum(weightedLoss), sum($weights));\n      return broadcastFactor > 1 ? div(result, scalar(broadcastFactor)) :\n                                   result as O;\n    }\n  }\n  if (reduction === Reduction.SUM_BY_NONZERO_WEIGHTS) {\n    if ($weights == null) {\n      return div(sum(weightedLoss), scalar($losses.size));\n    } else {\n      const broadcastedWeights = mul($weights, ones($losses.shape));\n\n      const numNonZeros =\n          cast(sum(notEqual(broadcastedWeights, scalar(0))), 'float32');\n      return div(sum(weightedLoss), numNonZeros);\n    }\n  }\n\n  throw Error(`Unknown reduction: ${reduction}`);\n}\nexport const computeWeightedLoss = /* @__PURE__ */ op({computeWeightedLoss_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {Reduction} from '../loss_ops_utils';\nimport {op} from '../operation';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the absolute difference loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction absoluteDifference_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'absoluteDifference');\n  const $predictions =\n      convertToTensor(predictions, 'predictions', 'absoluteDifference');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'absoluteDifference');\n  }\n  assertShapesMatch(\n      $labels.shape, $predictions.shape, 'Error in absoluteDifference: ');\n\n  const losses = abs(sub($labels, $predictions));\n  return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const absoluteDifference = /* @__PURE__ */ op({absoluteDifference_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the cosine distance loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param axis The dimension along which the cosine distance is computed.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction cosineDistance_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike, axis: number,\n    weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'cosineDistance');\n  const $predictions =\n      convertToTensor(predictions, 'predictions', 'cosineDistance');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'cosineDistance');\n  }\n  assertShapesMatch(\n      $labels.shape, $predictions.shape, 'Error in cosineDistance: ');\n\n  const one = scalar(1);\n  const losses = sub(one, sum(mul($labels, $predictions), axis, true));\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const cosineDistance = /* @__PURE__ */ op({cosineDistance_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {relu} from '../relu';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the Hinge loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction hingeLoss_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  let $labels = convertToTensor(labels, 'labels', 'hingeLoss');\n  const $predictions = convertToTensor(predictions, 'predictions', 'hingeLoss');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'hingeLoss');\n  }\n  assertShapesMatch($labels.shape, $predictions.shape, 'Error in hingeLoss: ');\n\n  const one = scalar(1);\n  // Convert binary labels to (-1, 1)\n  $labels = sub(mul(scalar(2), $labels), one);\n  const losses = relu(sub(one, mul($labels, $predictions)));\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const hingeLoss = /* @__PURE__ */ op({hingeLoss_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {add} from '../add';\nimport {Reduction} from '../loss_ops_utils';\nimport {minimum} from '../minimum';\nimport {mul} from '../mul';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {square} from '../square';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the Huber loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param delta Point where Huber loss changes from quadratic to linear.\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`.\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction huberLoss_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike, delta = 1.0,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'huberLoss');\n  const $predictions = convertToTensor(predictions, 'predictions', 'huberLoss');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'huberLoss');\n  }\n  assertShapesMatch($labels.shape, $predictions.shape, 'Error in huberLoss: ');\n\n  const deltaScalar = scalar(delta);\n  const error = abs(sub($predictions, $labels));\n  const quadratic = minimum(error, deltaScalar);\n  const linear = sub(error, quadratic);\n\n  const losses =\n      add(mul(scalar(0.5), square(quadratic)), mul(deltaScalar, linear));\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const huberLoss = /* @__PURE__ */ op({huberLoss_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {add} from '../add';\nimport {log} from '../log';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the log loss between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param epsilon A small increment to avoid taking log of zero\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction logLoss_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike, epsilon = 1e-7,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'logLoss');\n  const $predictions = convertToTensor(predictions, 'predictions', 'logLoss');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'logLoss');\n  }\n  assertShapesMatch($labels.shape, $predictions.shape, 'Error in logLoss: ');\n\n  const one = scalar(1);\n  const epsilonScalar = scalar(epsilon);\n\n  const l1 = neg(mul($labels, log(add($predictions, epsilonScalar))));\n  const l2 =\n      mul(sub(one, $labels), log(add(sub(one, $predictions), epsilonScalar)));\n  const losses = sub(l1, l2);\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const logLoss = /* @__PURE__ */ op({logLoss_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {Reduction} from '../loss_ops_utils';\nimport {op} from '../operation';\nimport {squaredDifference} from '../squared_difference';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes the mean squared error between two tensors.\n *\n * @param labels The ground truth output tensor, same dimensions as\n *    'predictions'.\n * @param predictions The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}\n */\nfunction meanSquaredError_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, predictions: T|TensorLike,\n    weights?: Tensor|TensorLike,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  const $labels = convertToTensor(labels, 'labels', 'meanSquaredError');\n  const $predictions =\n      convertToTensor(predictions, 'predictions', 'meanSquaredError');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'meanSquaredError');\n  }\n  assertShapesMatch(\n      $labels.shape, $predictions.shape, 'Error in meanSquaredError: ');\n\n  const losses = squaredDifference($labels, $predictions);\n  return computeWeightedLoss(losses, $weights, reduction);\n}\nexport const meanSquaredError = /* @__PURE__ */ op({meanSquaredError_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {abs} from '../abs';\nimport {add} from '../add';\nimport {exp} from '../exp';\nimport {log1p} from '../log1p';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {relu} from '../relu';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\nfunction sigmoidCrossEntropyWithLogits_<T extends Tensor, O extends Tensor>(\n    labels: T|TensorLike, logits: T|TensorLike): O {\n  const $labels =\n      convertToTensor(labels, 'labels', 'sigmoidCrossEntropyWithLogits');\n  const $logits =\n      convertToTensor(logits, 'logits', 'sigmoidCrossEntropyWithLogits');\n  assertShapesMatch(\n      $labels.shape, $logits.shape, 'Error in sigmoidCrossEntropyWithLogits: ');\n\n  /**\n   * Implementation Details:\n   *\n   * For brevity, let `x = logits`, `z = labels`.  The logistic loss is\n   *     z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n   *   = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))\n   *   = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))\n   *   = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))\n   *   = (1 - z) * x + log(1 + exp(-x))\n   *   = x - x * z + log(1 + exp(-x))\n   *\n   *   For x < 0, to avoid overflow in exp(-x), we reformulate the above\n   *     x - x * z + log(1 + exp(-x))\n   *   = log(exp(x)) - x * z + log(1 + exp(-x))\n   *   = - x * z + log(1 + exp(x))\n   *\n   * Hence, to ensure stability and avoid overflow, the implementation uses\n   * this equivalent formulation:\n   *     max(x, 0) - x * z + log(1 + exp(-abs(x)))\n   */\n  const maxOutput = relu($logits);\n  const outputXTarget = mul($logits, $labels);\n  const sigmoidOutput = log1p(exp(neg(abs($logits))));\n\n  return add(sub(maxOutput, outputXTarget), sigmoidOutput);\n}\n\n/**\n * Computes the sigmoid cross entropy loss between two tensors.\n *\n * If labelSmoothing is nonzero, smooth the labels towards 1/2:\n *\n *   newMulticlassLabels = multiclassLabels * (1 - labelSmoothing)\n *                         + 0.5 * labelSmoothing\n *\n * @param multiClassLabels The ground truth output tensor of shape\n * [batch_size, num_classes], same dimensions as 'predictions'.\n * @param logits The predicted outputs.\n * @param weights Tensor whose rank is either 0, or the same rank as\n *    `labels`, and must be broadcastable to `labels` (i.e., all dimensions\n *    must be either `1`, or the same as the corresponding `losses`\n *    dimension).\n * @param labelSmoothing If greater than 0, then smooth the labels.\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' }\n */\nfunction sigmoidCrossEntropy_<T extends Tensor, O extends Tensor>(\n    multiClassLabels: T|TensorLike, logits: T|TensorLike,\n    weights?: Tensor|TensorLike, labelSmoothing = 0,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  let $multiClassLabels = convertToTensor(\n      multiClassLabels, 'multiClassLabels', 'sigmoidCrossEntropy');\n  const $logits = convertToTensor(logits, 'logits', 'sigmoidCrossEntropy');\n  let $weights: Tensor = null;\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'sigmoidCrossEntropy');\n  }\n  assertShapesMatch(\n      $multiClassLabels.shape, $logits.shape, 'Error in sigmoidCrossEntropy: ');\n\n  if (labelSmoothing > 0) {\n    const labelSmoothingScalar = scalar(labelSmoothing);\n    const one = scalar(1);\n    const half = scalar(0.5);\n\n    $multiClassLabels =\n        add(mul($multiClassLabels, sub(one, labelSmoothingScalar)),\n            mul(half, labelSmoothingScalar));\n  }\n  const losses = sigmoidCrossEntropyWithLogits_($multiClassLabels, $logits);\n\n  return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const sigmoidCrossEntropy = /* @__PURE__ */ op({sigmoidCrossEntropy_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {customGrad} from '../../gradients';\nimport {Tensor} from '../../tensor';\nimport {GradSaveFunc} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assertShapesMatch} from '../../util';\nimport {add} from '../add';\nimport {expandShapeToKeepDim} from '../axis_util';\nimport {cast} from '../cast';\nimport {div} from '../div';\nimport {exp} from '../exp';\nimport {logSumExp} from '../log_sum_exp';\nimport {Reduction} from '../loss_ops_utils';\nimport {mul} from '../mul';\nimport {neg} from '../neg';\nimport {op} from '../operation';\nimport {reshape} from '../reshape';\nimport {scalar} from '../scalar';\nimport {sub} from '../sub';\nimport {sum} from '../sum';\n\nimport {computeWeightedLoss} from './compute_weighted_loss';\n\n/**\n * Computes softmax cross entropy between logits and labels.\n *\n * Measures the probability error in discrete classification tasks in which\n * the classes are mutually exclusive (each entry is in exactly one class).\n * For example, each CIFAR-10 image is labeled with one and only one label: an\n * image can be a dog or a truck, but not both.\n *\n * `NOTE`: While the classes are mutually exclusive, their probabilities need\n * not be. All that is required is that each row of labels is a valid\n * probability distribution. If they are not, the computation of the gradient\n * will be incorrect.\n *\n * `WARNING`: This op expects unscaled logits, since it performs a softmax on\n * logits internally for efficiency. Do not call this op with the output of\n * softmax, as it will produce incorrect results.\n *\n * logits and labels must have the same shape, e.g. [batch_size, num_classes]\n * and the same dtype.\n * @param labels The labels array.\n * @param logits The logits array.\n * @param dim The dimension softmax would be performed on. Defaults to `-1`\n *     which indicates the last dimension.\n */\nfunction softmaxCrossEntropyWithLogits_<T extends Tensor, O extends Tensor>(\n    labels: T, logits: T, dim = -1): O {\n  if (dim === -1) {\n    dim = logits.rank - 1;\n  }\n\n  if (dim !== logits.rank - 1) {\n    throw Error(\n        `Softmax cross entropy along a non-last dimension is not yet ` +\n        `supported. Labels / logits was rank ${logits.rank} ` +\n        `and dim was ${dim}`);\n  }\n  // Use a custom gradient for numerical stability.\n  const customOp =\n      customGrad((labels: Tensor, logits: Tensor, save: GradSaveFunc) => {\n        // Reference:\n        //   1. http://cs231n.github.io/linear-classify/#softmax\n        //   2. https://blog.feedly.com/tricks-of-the-trade-logsumexp/\n        const keepDims = true;\n        const lse = logSumExp(logits, [dim], keepDims);\n        const logResult = sub(cast(logits, 'float32'), lse);\n        save([labels, logResult]);\n\n        const costVector = neg(mul(logResult, labels));\n        const value: O = sum(costVector, [dim]);\n\n        const gradFunc = (dy: O, saved: Tensor[]) => {\n          const [labels, logResult] = saved;\n          const dyShape = expandShapeToKeepDim(dy.shape, [dim]);\n          return [\n            mul(reshape(dy, dyShape),\n                sub(cast(labels, 'float32'), exp(logResult))),\n            mul(reshape(dy, dyShape),\n                sub(exp(logResult), cast(labels, 'float32'))),\n          ];\n        };\n        return {value, gradFunc};\n      });\n\n  return customOp(labels, logits);\n}\n\n/**\n * Computes the softmax cross entropy loss between two tensors.\n *\n * If labelSmoothing is nonzero, smooth the labels towards 1/2:\n *\n *   newOnehotLabels = onehotLabels * (1 - labelSmoothing)\n *                         + labelSmoothing / numClasses\n *\n * @param onehotLabels One hot encoded labels\n *    [batch_size, num_classes], same dimensions as 'predictions'.\n * @param logits The predicted outputs.\n * @param weights Tensor whose rank is either 0, or 1, and must be\n *    broadcastable to `loss`  of shape [batch_size]\n * @param labelSmoothing If greater than 0, then smooth the labels.\n * @param reduction Type of reduction to apply to loss. Should be of type\n *    `Reduction`\n *\n * @doc { heading: 'Training', subheading: 'Losses', namespace: 'losses' }\n */\nfunction softmaxCrossEntropy_<T extends Tensor, O extends Tensor>(\n    onehotLabels: T|TensorLike, logits: T|TensorLike,\n    weights?: Tensor|TensorLike, labelSmoothing = 0,\n    reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {\n  let $onehotLabels =\n      convertToTensor(onehotLabels, 'onehotLabels', 'softmaxCrossEntropy');\n  const $logits = convertToTensor(logits, 'logits', 'softmaxCrossEntropy');\n  let $weights: Tensor = null;\n\n  if (weights != null) {\n    $weights = convertToTensor(weights, 'weights', 'softmaxCrossEntropy');\n  }\n\n  assertShapesMatch(\n      $onehotLabels.shape, $logits.shape, 'Error in softmaxCrossEntropy: ');\n\n  if (labelSmoothing > 0) {\n    const labelSmoothingScalar = scalar(labelSmoothing);\n    const one = scalar(1);\n    const numClasses = scalar($onehotLabels.shape[1]);\n\n    $onehotLabels =\n        add(mul($onehotLabels, sub(one, labelSmoothingScalar)),\n            div(labelSmoothingScalar, numClasses));\n  }\n\n  const losses = softmaxCrossEntropyWithLogits_($onehotLabels, $logits);\n\n  return computeWeightedLoss(losses, $weights, reduction);\n}\n\nexport const softmaxCrossEntropy = /* @__PURE__ */ op({softmaxCrossEntropy_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseFillEmptyRows, SparseFillEmptyRowsInputs} from '../../kernel_names';\nimport {Scalar, Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {ScalarLike, TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * The input SparseTensor is represented via the map of inputs {`indices`,\n * `values`, `denseShape`}. The output SparseTensor has the same `denseShape`\n * but with indices `outputIndices` and values `outputValues`. This op inserts a\n * single entry for every row that doesn't have any values. The index is created\n * as `[row, 0, ..., 0]` and the inserted value is `defaultValue`.\n *\n * For example, suppose `spInput` has shape [5, 6] and non-empty values:\n * [0, 1]: a\n * [0, 3]: b\n * [2, 0]: c\n * [3, 1]: d\n *\n * Rows 1 and 4 are empty, so the output will be of shape [5, 6] with values:\n * [0, 1]: a\n * [0, 3]: b\n * [1, 0]: `defaultValue`\n * [2, 0]: c\n * [3, 1]: d\n * [4, 0]: `defaultValue`\n *\n * The output SparseTensor will be in row-major order and will have the same\n * shape as the input.\n *\n * This op also returns an indicator vector shaped [dense_shape[0]] such that\n * emptyRowIndicator[i] = True iff row i was an empty row.\n *\n * And a reverse index map vector shaped [indices.shape[0]] that is used during\n * backpropagation, reverseIndexMap[i] = outi s.t. indices[i, j] ==\n * outputIndices[outi, j] for all j\n *\n * ```js\n * const result = tf.sparse.sparseFillEmptyRows(\n *   [[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]],\n *   [0, 10, 13, 14, 32, 33], [5, 6], -1);\n * console.log(result);\n * result['outputIndices'].print(); // [[0, 0], [1, 0], [1, 3], [1, 4],\n *                                  //  [2, 0], [3, 2], [3, 3], [4, 0]]\n * result['outputValues'].print(); // [0, 10, 13, 14,-1, 32, 33, -1]\n * result['emptyRowIndicator'].print(); // [false, false, true, false, true]\n * result['reverseIndexMap'].print(); // [0, 1, 2, 3, 5, 6]\n * ```\n * @param indices: 2-D. The indices of the sparse tensor.\n * @param values: 1-D. The values of the sparse tensor.\n * @param denseShape: 1-D. The shape of the sparse tensor.\n * @param defaultValue: 0-D. Default value to insert into location [row, 0, ...,\n *     0] for rows missing from the input sparse tensor.\n * @return A map with the following properties:\n *     - outputIndices\n *     - outputValues: 1-D. The values of the filled sparse tensor.\n *     - emptyRowIndicator: 1-D. Whether the dense row was missing in the input\n * sparse tensor.\n *     - reverseIndexMap: 1-D. A map from the input indices to the output\n * indices.\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseFillEmptyRows_(\n    indices: Tensor2D|TensorLike, values: Tensor1D|TensorLike,\n    denseShape: Tensor1D|TensorLike,\n    defaultValue: Scalar|ScalarLike): NamedTensorMap {\n  const $indices =\n      convertToTensor(indices, 'indices', 'sparseFillEmptyRows', 'int32');\n  const $values = convertToTensor(values, 'values', 'sparseFillEmptyRows');\n  const $denseShape =\n      convertToTensor(denseShape, 'denseShape', 'sparseFillEmptyRows', 'int32');\n  const $defaultValue = convertToTensor(\n      defaultValue, 'defaultValue', 'sparseFillEmptyRows', $values.dtype);\n\n  if ($indices.rank !== 2) {\n    throw new Error(`Indices should be Tensor2D but received shape\n        ${$indices.shape}`);\n  }\n  if ($values.rank !== 1) {\n    throw new Error(\n        `Values should be Tensor1D but received shape ${$values.shape}`);\n  }\n  if ($denseShape.rank !== 1) {\n    throw new Error(`Dense shape should be Tensor1D but received shape ${\n        $denseShape.shape}`);\n  }\n  if ($defaultValue.rank !== 0) {\n    throw new Error(`Default value should be a scalar but received shape ${\n        $defaultValue.shape}`);\n  }\n\n  const inputs: SparseFillEmptyRowsInputs = {\n    indices: $indices,\n    values: $values,\n    denseShape: $denseShape,\n    defaultValue: $defaultValue\n  };\n\n  const result: Tensor[] = ENGINE.runKernel(SparseFillEmptyRows, inputs as {});\n  return {\n    outputIndices: result[0],\n    outputValues: result[1],\n    emptyRowIndicator: result[2],\n    reverseIndexMap: result[3]\n  };\n}\n\nexport const sparseFillEmptyRows = /* @__PURE__ */ op({sparseFillEmptyRows_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseReshape, SparseReshapeInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D, Tensor2D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * This operation has the same semantics as reshape on the represented dense\n * tensor. The `inputIndices` are recomputed based on the requested `newShape`.\n * If one component of `newShape` is the special value -1, the size of that\n * dimension is computed so that the total dense size remains constant. At most\n * one component of `newShape` can be -1. The number of dense elements implied\n * by `newShape` must be the same as the number of dense elements originally\n * implied by `inputShape`. Reshaping does not affect the order of values in the\n * SparseTensor. If the input tensor has rank R_in and N non-empty values, and\n * `newShape` has length R_out, then `inputIndices` has shape [N, R_in],\n * `inputShape` has length R_in, `outputIndices` has shape [N, R_out], and\n * `outputShape` has length R_out.\n *\n * ```js\n * const result = tf.sparse.sparseReshape(\n *   [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 2, 3]],\n *   [2, 3, 6], [9, -1]);\n * console.log(result);\n * result['outputIndices'].print(); //[[0, 0], [0, 1], [1, 2], [4, 2], [8, 1]]\n * result['outputShape'].print(); // [9, 4]\n * ```\n * @param inputIndices: 2-D. N x R_in matrix with the indices of non-empty\n * values in a SparseTensor.\n * @param inputShape: 1-D. R_in Tensor1D with the input SparseTensor's dense\n * shape.\n * @param newShape: 1-D. R_out Tensor1D with the requested new dense shape.\n * @return A map with the following properties:\n *     - outputIndices: 2-D. N x R_out matrix with the updated indices of\n *       non-empty values in the output SparseTensor.\n *     - outputShape: 1-D. R_out vector with the full dense shape of the output\n *       SparseTensor. This is the same as newShape but with any -1 dimensions\n *        filled in.\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseReshape_(\n    inputIndices: Tensor2D|TensorLike, inputShape: Tensor1D|TensorLike,\n    newShape: Tensor1D|TensorLike): NamedTensorMap {\n  const $inputIndices =\n      convertToTensor(inputIndices, 'inputIndices', 'sparseReshape', 'int32');\n  const $inputShape =\n      convertToTensor(inputShape, 'inputShape', 'sparseReshape', 'int32');\n  const $newShape =\n      convertToTensor(newShape, 'newShape', 'sparseReshape', 'int32');\n\n  if ($inputIndices.rank !== 2) {\n    throw new Error(`Input indices should be Tensor2D but received shape\n        ${$inputIndices.shape}`);\n  }\n  if ($inputShape.rank !== 1) {\n    throw new Error(`Input shape should be Tensor1D but received shape ${\n        $inputShape.shape}`);\n  }\n  if ($newShape.rank !== 1) {\n    throw new Error(\n        `New shape should be Tensor1D but received shape ${$newShape.shape}`);\n  }\n\n  const inputs: SparseReshapeInputs = {\n    inputIndices: $inputIndices,\n    inputShape: $inputShape,\n    newShape: $newShape\n  };\n  const result: Tensor[] = ENGINE.runKernel(SparseReshape, inputs as {});\n  return {outputIndices: result[0], outputShape: result[1]};\n}\n\nexport const sparseReshape = /* @__PURE__ */ op({sparseReshape_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseSegmentMean, SparseSegmentMeanInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Computes the mean along sparse segments of a tensor.\n *\n * ```js\n * const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [6,7,8,9]]);\n * // Select two rows, one segment.\n * const result1 = tf.sparse.sparseSegmentMean(c,\n *                                           tf.tensor1d([0, 1], 'int32'),\n *                                           tf.tensor1d([0, 0], 'int32'));\n * result1.print(); // [[0, 0, 0, 0]]\n *\n * // Select two rows, two segments.\n * const result2 = tf.sparse.sparseSegmentMean(c,\n *                                             tf.tensor1d([0, 1], 'int32'),\n *                                             tf.tensor1d([0, 1], 'int32'));\n * result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]\n *\n * // Select all rows, two segments.\n * const result3 = tf.sparse.sparseSegmentMean(c,\n *                                             tf.tensor1d([0, 1, 2], 'int32'),\n *                                             tf.tensor1d([0, 1, 1], 'int32'));\n * result3.print(); // [[1.0, 2.0, 3.0, 4.0], [2.5, 2.5, 2.5, 2.5]]\n * ```\n * @param data: A Tensor of at least one dimension with data that will be\n *     assembled in the output.\n * @param indices: A 1-D Tensor with indices into data. Has same rank as\n *     segmentIds.\n * @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values\n *     should be sorted and can be repeated.\n * @return Has same shape as data, except for dimension 0 which has equal to\n *         the number of segments.\n *\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseSegmentMean_(\n    data: Tensor|TensorLike, indices: Tensor1D|TensorLike,\n    segmentIds: Tensor1D|TensorLike): Tensor {\n  const $data = convertToTensor(data, 'data', 'sparseSegmentMean');\n  const $indices =\n      convertToTensor(indices, 'indices', 'sparseSegmentMean', 'int32');\n  const $segmentIds =\n      convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentMean', 'int32');\n\n  if ($data.rank < 1) {\n    throw new Error(\n        `Data should be at least 1 dimensional but received scalar`);\n  }\n  if ($indices.rank !== 1) {\n    throw new Error(`Indices should be Tensor1D but received shape\n          ${$indices.shape}`);\n  }\n  if ($segmentIds.rank !== 1) {\n    throw new Error(`Segment ids should be Tensor1D but received shape\n          ${$segmentIds.shape}`);\n  }\n\n  const inputs: SparseSegmentMeanInputs = {\n    data: $data,\n    indices: $indices,\n    segmentIds: $segmentIds\n  };\n\n  return ENGINE.runKernel(SparseSegmentMean, inputs as {});\n}\n\nexport const sparseSegmentMean = /* @__PURE__ */ op({sparseSegmentMean_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {SparseSegmentSum, SparseSegmentSumInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Computes the sum along sparse segments of a tensor.\n *\n * ```js\n * const c = tf.tensor2d([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]);\n * // Select two rows, one segment.\n * const result1 = tf.sparse.sparseSegmentSum(c,\n *                                           tf.tensor1d([0, 1], 'int32'),\n *                                           tf.tensor1d([0, 0], 'int32'));\n * result1.print(); // [[0, 0, 0, 0]]\n *\n * // Select two rows, two segments.\n * const result2 = tf.sparse.sparseSegmentSum(c,\n *                                           tf.tensor1d([0, 1], 'int32'),\n *                                           tf.tensor1d([0, 1], 'int32'));\n * result2.print(); // [[1, 2, 3, 4], [-1, -2, -3, -4]]\n *\n * // Select all rows, two segments.\n * const result3 = tf.sparse.sparseSegmentSum(c,\n *                                           tf.tensor1d([0, 1, 2], 'int32'),\n *                                           tf.tensor1d([0, 0, 1], 'int32'));\n * result3.print(); // [[0, 0, 0, 0], [5, 6, 7, 8]]\n * ```\n * @param data: A Tensor of at least one dimension with data that will be\n *     assembled in the output.\n * @param indices: A 1-D Tensor with indices into data. Has same rank as\n *     segmentIds.\n * @param segmentIds: A 1-D Tensor with indices into the output Tensor. Values\n *     should be sorted and can be repeated.\n * @return Has same shape as data, except for dimension 0 which has equal to\n *         the number of segments.\n *\n * @doc {heading: 'Operations', subheading: 'Sparse'}\n */\nfunction sparseSegmentSum_(\n    data: Tensor|TensorLike, indices: Tensor1D|TensorLike,\n    segmentIds: Tensor1D|TensorLike): Tensor {\n  const $data = convertToTensor(data, 'data', 'sparseSegmentSum');\n  const $indices =\n      convertToTensor(indices, 'indices', 'sparseSegmentSum', 'int32');\n  const $segmentIds =\n      convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentSum', 'int32');\n\n  if ($data.rank < 1) {\n    throw new Error(\n        `Data should be at least 1 dimensional but received scalar`);\n  }\n  if ($indices.rank !== 1) {\n    throw new Error(`Indices should be Tensor1D but received shape\n         ${$indices.shape}`);\n  }\n  if ($segmentIds.rank !== 1) {\n    throw new Error(`Segment ids should be Tensor1D but received shape\n         ${$segmentIds.shape}`);\n  }\n\n  const inputs: SparseSegmentSumInputs = {\n    data: $data,\n    indices: $indices,\n    segmentIds: $segmentIds\n  };\n\n  return ENGINE.runKernel(SparseSegmentSum, inputs as {});\n}\n\nexport const sparseSegmentSum = /* @__PURE__ */ op({sparseSegmentSum_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringNGrams, StringNGramsAttrs, StringNGramsInputs} from '../../kernel_names';\nimport {Tensor, Tensor1D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Creates ngrams from ragged string data.\n *\n * This op accepts a ragged tensor with 1 ragged dimension containing only\n * strings and outputs a ragged tensor with 1 ragged dimension containing ngrams\n * of that string, joined along the innermost axis.\n *\n * ```js\n * const result = tf.string.stringNGrams(\n *   ['a', 'b', 'c', 'd'], tf.tensor1d([0, 2, 4], 'int32'),\n *   '|', [1, 2], 'LP', 'RP', -1, false);\n * result['nGrams'].print(); // ['a', 'b', 'LP|a', 'a|b', 'b|RP',\n *                           //  'c', 'd', 'LP|c', 'c|d', 'd|RP']\n * result['nGramsSplits'].print(); // [0, 5, 10]\n * ```\n * @param data: The values tensor of the ragged string tensor to make ngrams out\n *     of. Must be a 1D string tensor.\n * @param dataSplits: The splits tensor of the ragged string tensor to make\n *     ngrams out of.\n * @param separator: The string to append between elements of the token. Use \"\"\n *     for no separator.\n * @param nGramWidths: The sizes of the ngrams to create.\n * @param leftPad: The string to use to pad the left side of the ngram sequence.\n *     Only used if pad_width !== 0.\n * @param rightPad: The string to use to pad the right side of the ngram\n *     sequence. Only used if pad_width !== 0.\n * @param padWidth: The number of padding elements to add to each side of each\n *     sequence. Note that padding will never be greater than `nGramWidths`-1\n *     regardless of this value. If `padWidth`=-1, then add max(`nGramWidths`)-1\n *     elements.\n * @param preserveShortSequences: If true, then ensure that at least one ngram\n *     is generated for each input sequence. In particular, if an input sequence\n *     is shorter than min(ngramWidth) + 2*padWidth, then generate a single\n *     ngram containing the entire sequence. If false, then no ngrams are\n *     generated for these short input sequences.\n * @return A map with the following properties:\n *     - nGrams: The values tensor of the output ngrams ragged tensor.\n *     - nGramsSplits: The splits tensor of the output ngrams ragged tensor.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringNGrams_(\n    data: Tensor1D|TensorLike, dataSplits: Tensor|TensorLike, separator: string,\n    nGramWidths: number[], leftPad: string, rightPad: string, padWidth: number,\n    preserveShortSequences: boolean): NamedTensorMap {\n  const $data = convertToTensor(data, 'data', 'stringNGrams', 'string');\n  if ($data.dtype !== 'string') {\n    throw new Error('Data must be of datatype string');\n  }\n  if ($data.shape.length !== 1) {\n    throw new Error(`Data must be a vector, saw: ${$data.shape}`);\n  }\n\n  const $dataSplits = convertToTensor(dataSplits, 'dataSplits', 'stringNGrams');\n  if ($dataSplits.dtype !== 'int32') {\n    throw new Error('Data splits must be of datatype int32');\n  }\n\n  const attrs: StringNGramsAttrs = {\n    separator,\n    nGramWidths,\n    leftPad,\n    rightPad,\n    padWidth,\n    preserveShortSequences\n  };\n\n  const inputs: StringNGramsInputs = {data: $data, dataSplits: $dataSplits};\n  const result: Tensor[] =\n      ENGINE.runKernel(StringNGrams, inputs as {}, attrs as {});\n  return {nGrams: result[0], nGramsSplits: result[1]};\n}\n\nexport const stringNGrams = /* @__PURE__ */ op({stringNGrams_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringSplit, StringSplitAttrs, StringSplitInputs} from '../../kernel_names';\nimport {Scalar, Tensor, Tensor1D} from '../../tensor';\nimport {NamedTensorMap} from '../../tensor_types';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {ScalarLike, TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Split elements of `input` based on `delimiter` into a SparseTensor .\n *\n * Let N be the size of source (typically N will be the batch size). Split each\n * element of `input` based on `delimiter` and return a SparseTensor containing\n * the splitted tokens. Empty tokens are ignored if `skipEmpty` is set to True.\n *\n * `delimiter` can be empty, or a string of split characters. If `delimiter` is\n * an empty string, each element of `input` is split into individual\n * character strings. Otherwise every character of `delimiter` is a potential\n * split point.\n *\n * ```js\n * const result = tf.string.stringSplit(['hello world',  'a b c'], ' ');\n * result['indices'].print(); // [[0, 0], [0, 1], [1, 0], [1, 1], [1, 2]]\n * result['values'].print(); // ['hello', 'world', 'a', 'b', 'c']\n * result['shape'].print(); // [2, 3]\n * ```\n * @param input: 1-D. Strings to split.\n * @param delimiter: 0-D. Delimiter characters, or empty string.\n * @param skipEmpty: Optional. If true, skip the empty strings from the result.\n *     Defaults to true.\n * @return A map with the following properties:\n *     - indices: A dense matrix of int32 representing the indices of the sparse\n *       tensor.\n *     - values: A vector of strings corresponding to the splited values.\n *     - shape: a length-2 vector of int32 representing the shape of the sparse\n * tensor, where the first value is N and the second value is the maximum number\n * of tokens in a single input entry.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringSplit_(\n    input: Tensor1D|TensorLike, delimiter: Scalar|ScalarLike,\n    skipEmpty = true): NamedTensorMap {\n  const $input = convertToTensor(input, 'input', 'stringSplit', 'string');\n  const $delimiter =\n      convertToTensor(delimiter, 'delimiter', 'stringSplit', 'string');\n\n  if ($input.rank !== 1) {\n    throw new Error(\n        `Input should be Tensor1D but received shape ${$input.shape}`);\n  }\n  if ($delimiter.rank !== 0) {\n    throw new Error(\n        `Delimiter should be a scalar but received shape ${$delimiter.shape}`);\n  }\n\n  const attrs: StringSplitAttrs = {skipEmpty};\n  const inputs: StringSplitInputs = {input: $input, delimiter: $delimiter};\n  const result: Tensor[] =\n      ENGINE.runKernel(StringSplit, inputs as {}, attrs as {});\n  return {indices: result[0], values: result[1], shape: result[2]};\n}\n\nexport const stringSplit = /* @__PURE__ */ op({stringSplit_});\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StringToHashBucketFast, StringToHashBucketFastAttrs, StringToHashBucketFastInputs} from '../../kernel_names';\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Converts each string in the input Tensor to its hash mod by a number of\n * buckets.\n *\n * The hash function is deterministic on the content of the string within the\n * process and will never change. However, it is not suitable for cryptography.\n * This function may be used when CPU time is scarce and inputs are trusted or\n * unimportant. There is a risk of adversaries constructing inputs that all hash\n * to the same bucket.\n *\n * ```js\n * const result = tf.string.stringToHashBucketFast(\n *   ['Hello', 'TensorFlow', '2.x'], 3);\n * result.print(); // [0, 2, 2]\n * ```\n * @param input: The strings to assign a hash bucket.\n * @param numBuckets: The number of buckets.\n * @return A Tensor of the same shape as the input tensor.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction stringToHashBucketFast_(\n    input: Tensor|TensorLike, numBuckets: number): Tensor {\n  const $input =\n      convertToTensor(input, 'input', 'stringToHashBucketFast', 'string');\n  const attrs: StringToHashBucketFastAttrs = {numBuckets};\n\n  if (numBuckets <= 0) {\n    throw new Error(`Number of buckets must be at least 1`);\n  }\n\n  const inputs: StringToHashBucketFastInputs = {input: $input};\n  return ENGINE.runKernel(StringToHashBucketFast, inputs as {}, attrs as {});\n}\n\nexport const stringToHashBucketFast = /* @__PURE__ */ op({stringToHashBucketFast_});\n", "/**\n * @license\n * Copyright 2023 Google LLC.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../../engine';\nimport {StaticRegexReplace, StaticRegexReplaceAttrs} from '../../kernel_names';\nimport {NamedAttrMap} from '../../kernel_registry';\nimport {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {op} from '../operation';\n\n/**\n * Replace the match of a `pattern` in `input` with `rewrite`.\n *\n * ```js\n * const result = tf.string.staticRegexReplace(\n *     ['format       this   spacing      better'], ' +', ' ');\n * result.print(); // ['format this spacing better']\n * ```\n * @param input: A Tensor of type string. The text to be processed.\n * @param pattern: A string. The regular expression to match the input.\n * @param rewrite: A string. The rewrite to be applied to the matched\n *     expression.\n * @param replaceGlobal: An optional bool. Defaults to True. If True, the\n *     replacement is global, otherwise the replacement is done only on the\n *     first match.\n * @return A Tensor of type string.\n *\n * @doc {heading: 'Operations', subheading: 'String'}\n */\nfunction staticRegexReplace_(\n  input: Tensor | TensorLike, pattern: string, rewrite: string,\n  replaceGlobal=true): Tensor {\n\n  const $input = convertToTensor(input, 'input', 'staticRegexReplace',\n                                 'string');\n  const attrs: StaticRegexReplaceAttrs = {pattern, rewrite, replaceGlobal};\n  return ENGINE.runKernel(StaticRegexReplace, {x: $input},\n                          attrs as unknown as NamedAttrMap);\n}\n\nexport const staticRegexReplace = /* @__PURE__ */ op({staticRegexReplace_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Modularized ops.\nexport {abs} from './abs';\nexport {acos} from './acos';\nexport {acosh} from './acosh';\nexport {add} from './add';\nexport {addN} from './add_n';\nexport {all} from './all';\nexport {any} from './any';\nexport {argMax} from './arg_max';\nexport {argMin} from './arg_min';\nexport {asin} from './asin';\nexport {asinh} from './asinh';\nexport {atan} from './atan';\nexport {atan2} from './atan2';\nexport {atanh} from './atanh';\nexport {avgPool} from './avg_pool';\nexport {avgPool3d} from './avg_pool_3d';\nexport {basicLSTMCell} from './basic_lstm_cell';\nexport {batchToSpaceND} from './batch_to_space_nd';\nexport {batchNorm} from './batchnorm';\nexport {batchNorm2d} from './batchnorm2d';\nexport {batchNorm3d} from './batchnorm3d';\nexport {batchNorm4d} from './batchnorm4d';\nexport {bincount} from './bincount';\nexport {bitwiseAnd} from './bitwise_and';\nexport {broadcastArgs} from './broadcast_args';\nexport {broadcastTo} from './broadcast_to';\nexport {buffer} from './buffer';\nexport {cast} from './cast';\nexport {ceil} from './ceil';\nexport {clipByValue} from './clip_by_value';\nexport {clone} from './clone';\nexport {complex} from './complex';\nexport {concat} from './concat';\nexport {concat1d} from './concat_1d';\nexport {concat2d} from './concat_2d';\nexport {concat3d} from './concat_3d';\nexport {concat4d} from './concat_4d';\nexport {conv1d} from './conv1d';\nexport {conv2d} from './conv2d';\nexport {conv2dTranspose} from './conv2d_transpose';\nexport {conv3d} from './conv3d';\nexport {conv3dTranspose} from './conv3d_transpose';\nexport {cos} from './cos';\nexport {cosh} from './cosh';\nexport {cumprod} from './cumprod';\nexport {cumsum} from './cumsum';\nexport {denseBincount} from './dense_bincount';\nexport {depthToSpace} from './depth_to_space';\nexport {depthwiseConv2d} from './depthwise_conv2d';\nexport {diag} from './diag';\nexport {dilation2d} from './dilation2d';\nexport {div} from './div';\nexport {divNoNan} from './div_no_nan';\nexport {dot} from './dot';\nexport {einsum} from './einsum';\nexport {elu} from './elu';\nexport {ensureShape} from './ensure_shape';\nexport {equal} from './equal';\nexport {erf} from './erf';\nexport {euclideanNorm} from './euclidean_norm';\nexport {exp} from './exp';\nexport {expandDims} from './expand_dims';\nexport {expm1} from './expm1';\nexport {eye} from './eye';\nexport {fill} from './fill';\nexport {floor} from './floor';\nexport {floorDiv} from './floorDiv';\nexport {gather} from './gather';\nexport {greater} from './greater';\nexport {greaterEqual} from './greater_equal';\nexport {imag} from './imag';\nexport {isFinite} from './is_finite';\nexport {isInf} from './is_inf';\nexport {isNaN} from './is_nan';\nexport {leakyRelu} from './leaky_relu';\nexport {less} from './less';\nexport {lessEqual} from './less_equal';\nexport {linspace} from './linspace';\nexport {localResponseNormalization} from './local_response_normalization';\nexport {log} from './log';\nexport {log1p} from './log1p';\nexport {logSigmoid} from './log_sigmoid';\nexport {logSoftmax} from './log_softmax';\nexport {logSumExp} from './log_sum_exp';\nexport {logicalAnd} from './logical_and';\nexport {logicalNot} from './logical_not';\nexport {logicalOr} from './logical_or';\nexport {logicalXor} from './logical_xor';\nexport {lowerBound} from './lower_bound';\nexport {matMul} from './mat_mul';\nexport {max} from './max';\nexport {maxPool} from './max_pool';\nexport {maxPool3d} from './max_pool_3d';\nexport {maxPoolWithArgmax} from './max_pool_with_argmax';\nexport {maximum} from './maximum';\nexport {mean} from './mean';\nexport {meshgrid} from './meshgrid';\nexport {min} from './min';\nexport {minimum} from './minimum';\nexport {mirrorPad} from './mirror_pad';\nexport {mod} from './mod';\nexport {moments} from './moments';\nexport {mul} from './mul';\nexport {LSTMCellFunc, multiRNNCell} from './multi_rnn_cell';\nexport {multinomial} from './multinomial';\nexport {neg} from './neg';\nexport {notEqual} from './not_equal';\nexport {oneHot} from './one_hot';\nexport {ones} from './ones';\nexport {onesLike} from './ones_like';\nexport {outerProduct} from './outer_product';\nexport {pad} from './pad';\nexport {pad1d} from './pad1d';\nexport {pad2d} from './pad2d';\nexport {pad3d} from './pad3d';\nexport {pad4d} from './pad4d';\nexport {pool} from './pool';\nexport {pow} from './pow';\nexport {prelu} from './prelu';\nexport {print} from './print';\nexport {prod} from './prod';\nexport {raggedGather} from './ragged_gather';\nexport {raggedRange} from './ragged_range';\nexport {raggedTensorToTensor} from './ragged_tensor_to_tensor';\nexport {rand} from './rand';\nexport {randomGamma} from './random_gamma';\nexport {randomNormal} from './random_normal';\nexport {randomStandardNormal} from './random_standard_normal';\nexport {randomUniform} from './random_uniform';\nexport {randomUniformInt} from './random_uniform_int';\nexport {range} from './range';\nexport {real} from './real';\nexport {reciprocal} from './reciprocal';\nexport {relu} from './relu';\nexport {relu6} from './relu6';\nexport {reshape} from './reshape';\nexport {reverse} from './reverse';\nexport {reverse1d} from './reverse_1d';\nexport {reverse2d} from './reverse_2d';\nexport {reverse3d} from './reverse_3d';\nexport {reverse4d} from './reverse_4d';\nexport {round} from './round';\nexport {rsqrt} from './rsqrt';\nexport {scalar} from './scalar';\nexport {selu} from './selu';\nexport {separableConv2d} from './separable_conv2d';\nexport {setdiff1dAsync} from './setdiff1d_async';\nexport {sigmoid} from './sigmoid';\nexport {sign} from './sign';\nexport {sin} from './sin';\nexport {sinh} from './sinh';\nexport {slice} from './slice';\nexport {slice1d} from './slice1d';\nexport {slice2d} from './slice2d';\nexport {slice3d} from './slice3d';\nexport {slice4d} from './slice4d';\nexport {softmax} from './softmax';\nexport {softplus} from './softplus';\nexport {spaceToBatchND} from './space_to_batch_nd';\nexport {fft} from './spectral/fft';\nexport {ifft} from './spectral/ifft';\nexport {irfft} from './spectral/irfft';\nexport {rfft} from './spectral/rfft';\nexport {split} from './split';\nexport {sqrt} from './sqrt';\nexport {square} from './square';\nexport {squaredDifference} from './squared_difference';\nexport {squeeze} from './squeeze';\nexport {stack} from './stack';\nexport {step} from './step';\nexport {stridedSlice} from './strided_slice';\nexport {sub} from './sub';\nexport {sum} from './sum';\nexport {tan} from './tan';\nexport {tanh} from './tanh';\nexport {tensor} from './tensor';\nexport {tensor1d} from './tensor1d';\nexport {tensor2d} from './tensor2d';\nexport {tensor3d} from './tensor3d';\nexport {tensor4d} from './tensor4d';\nexport {tensor5d} from './tensor5d';\nexport {tensor6d} from './tensor6d';\nexport {tensorScatterUpdate} from './tensor_scatter_update';\nexport {tile} from './tile';\nexport {topk} from './topk';\nexport {truncatedNormal} from './truncated_normal';\nexport {unique} from './unique';\nexport {unsortedSegmentSum} from './unsorted_segment_sum';\nexport {unstack} from './unstack';\nexport {upperBound} from './upper_bound';\nexport {variable} from './variable';\nexport {where} from './where';\nexport {whereAsync} from './where_async';\nexport {zeros} from './zeros';\nexport {zerosLike} from './zeros_like';\n\nexport * from './boolean_mask';\nexport * from './transpose';\nexport * from './norm';\nexport * from './moving_average';\nexport * from './scatter_nd';\nexport * from './search_sorted';\nexport * from './sparse_to_dense';\nexport * from './gather_nd';\nexport * from './dropout';\nexport * from './signal_ops_util';\nexport * from './in_top_k';\n\nexport {op, OP_SCOPE_SUFFIX} from './operation';\n\nimport {rfft} from './spectral/rfft';\nimport {fft} from './spectral/fft';\nimport {ifft} from './spectral/ifft';\nimport {irfft} from './spectral/irfft';\nconst spectral = {\n  fft,\n  ifft,\n  rfft,\n  irfft\n};\n\nimport * as fused from './fused_ops';\n\nimport {hammingWindow} from './signal/hamming_window';\nimport {hannWindow} from './signal/hann_window';\nimport {frame} from './signal/frame';\nimport {stft} from './signal/stft';\nconst signal = {\n  hammingWindow,\n  hannWindow,\n  frame,\n  stft,\n};\n\n// Image Ops namespace\nimport {cropAndResize} from './image/crop_and_resize';\nimport {flipLeftRight} from './image/flip_left_right';\nimport {grayscaleToRGB} from './image/grayscale_to_rgb';\nimport {rgbToGrayscale} from './image/rgb_to_grayscale';\nimport {rotateWithOffset} from './image/rotate_with_offset';\nimport {nonMaxSuppression} from './image/non_max_suppression';\nimport {nonMaxSuppressionAsync} from './image/non_max_suppression_async';\nimport {nonMaxSuppressionWithScore} from './image/non_max_suppression_with_score';\nimport {nonMaxSuppressionWithScoreAsync} from './image/non_max_suppression_with_score_async';\nimport {nonMaxSuppressionPadded} from './image/non_max_suppression_padded';\nimport {nonMaxSuppressionPaddedAsync} from './image/non_max_suppression_padded_async';\nimport {resizeBilinear} from './image/resize_bilinear';\nimport {resizeNearestNeighbor} from './image/resize_nearest_neighbor';\nimport {threshold} from './image/threshold';\nimport {transform} from './image/transform';\nconst image = {\n  flipLeftRight,\n  grayscaleToRGB,\n  resizeNearestNeighbor,\n  resizeBilinear,\n  rgbToGrayscale,\n  rotateWithOffset,\n  cropAndResize,\n  nonMaxSuppression,\n  nonMaxSuppressionAsync,\n  nonMaxSuppressionWithScore,\n  nonMaxSuppressionWithScoreAsync,\n  nonMaxSuppressionPadded,\n  nonMaxSuppressionPaddedAsync,\n  threshold,\n  transform\n};\n\n// linalg namespace\nimport {bandPart} from './linalg/band_part';\nimport {gramSchmidt} from './linalg/gram_schmidt';\nimport {qr} from './linalg/qr';\nconst linalg = {\n  bandPart,\n  gramSchmidt,\n  qr\n};\n\n// losses namespace;\nimport {absoluteDifference} from './losses/absolute_difference';\nimport {computeWeightedLoss} from './losses/compute_weighted_loss';\nimport {cosineDistance} from './losses/cosine_distance';\nimport {hingeLoss} from './losses/hinge_loss';\nimport {huberLoss} from './losses/huber_loss';\nimport {logLoss} from './losses/log_loss';\nimport {meanSquaredError} from './losses/mean_squared_error';\nimport {sigmoidCrossEntropy} from './losses/sigmoid_cross_entropy';\nimport {softmaxCrossEntropy} from './losses/softmax_cross_entropy';\nconst losses = {\n  absoluteDifference,\n  computeWeightedLoss,\n  cosineDistance,\n  hingeLoss,\n  huberLoss,\n  logLoss,\n  meanSquaredError,\n  sigmoidCrossEntropy,\n  softmaxCrossEntropy\n};\n\nimport {sparseFillEmptyRows} from './sparse/sparse_fill_empty_rows';\nimport {sparseReshape} from './sparse/sparse_reshape';\nimport {sparseSegmentMean} from './sparse/sparse_segment_mean';\nimport {sparseSegmentSum} from './sparse/sparse_segment_sum';\nconst sparse = {\n  sparseFillEmptyRows,\n  sparseReshape,\n  sparseSegmentMean,\n  sparseSegmentSum\n};\n\nimport {stringNGrams} from './string/string_n_grams';\nimport {stringSplit} from './string/string_split';\nimport {stringToHashBucketFast} from './string/string_to_hash_bucket_fast';\nimport {staticRegexReplace} from './string/static_regex_replace';\n// tslint:disable-next-line:variable-name\nconst string = {\n  stringNGrams,\n  stringSplit,\n  stringToHashBucketFast,\n  staticRegexReplace,\n};\n\n// Second level exports.\nexport {image, linalg, losses, spectral, fused, signal, sparse, string};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * This file exports ops used by the converters executors. By default it\n * re-exports all ops. In a custom build this is aliased to a file that will\n * only exports ops for a given model.json.\n */\nexport * from './ops';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap,\n     context: ExecutionContext, ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'BiasAdd':\n        case 'AddV2':\n        case 'Add': {\n          return [ops.add(\n              (getParamValue('a', node, tensorMap, context) as Tensor),\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'AddN': {\n          return [ops.addN((\n              getParamValue('tensors', node, tensorMap, context) as Tensor[]))];\n        }\n        case 'FloorMod':\n        case 'Mod':\n          return [ops.mod(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        case 'Mul':\n          return [ops.mul(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        case 'RealDiv':\n        case 'Div': {\n          return [ops.div(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'DivNoNan': {\n          return [ops.divNoNan(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'FloorDiv': {\n          return [ops.floorDiv(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'Sub': {\n          return [ops.sub(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'Minimum': {\n          return [ops.minimum(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'Maximum': {\n          return [ops.maximum(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'Pow': {\n          return [ops.pow(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'SquaredDifference': {\n          return [ops.squaredDifference(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'arithmetic';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'Abs':\n        case 'ComplexAbs':\n          return [ops.abs(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Acos':\n          return [ops.acos(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Acosh':\n          return [ops.acosh(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Asin':\n          return [ops.asin(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Asinh':\n          return [ops.asinh(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Atan':\n          return [ops.atan(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Atan2':\n          return [ops.atan2(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('y', node, tensorMap, context) as Tensor)];\n        case 'Atanh':\n          return [ops.atanh(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Ceil':\n          return [ops.ceil(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Complex':\n          return [ops.complex(\n              getParamValue('real', node, tensorMap, context) as Tensor,\n              getParamValue('imag', node, tensorMap, context) as Tensor)];\n        case 'Cos':\n          return [ops.cos(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Cosh':\n          return [ops.cosh(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Elu':\n          return [ops.elu(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Erf':\n          return [ops.erf(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Exp':\n          return [ops.exp(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Expm1': {\n          return [ops.expm1(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Floor':\n          return [ops.floor(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Log':\n          return [ops.log(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Log1p': {\n          return [ops.log1p(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Imag':\n          return [ops.imag(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n\n        case 'Neg':\n          return [ops.neg(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Reciprocal': {\n          return [ops.reciprocal(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Real':\n          return [ops.real(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Relu':\n          return [ops.relu(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Round': {\n          return [ops.round(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Selu':\n          return [ops.selu(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Sigmoid':\n          return [ops.sigmoid(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Sin':\n          return [ops.sin(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Sign': {\n          return [ops.sign(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Sinh': {\n          return [ops.sinh(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Softplus': {\n          return [ops.softplus(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Sqrt': {\n          return [ops.sqrt(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Square': {\n          return [ops.square(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Tanh': {\n          return [ops.tanh(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'Tan':\n          return [ops.tan(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'ClipByValue':\n          return [ops.clipByValue(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('clipValueMin', node, tensorMap, context) as number,\n              getParamValue('clipValueMax', node, tensorMap, context) as\n                  number)];\n        case 'Relu6':\n          return [ops.relu6(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        case 'Rsqrt':\n          return [ops.rsqrt(getTensor(node.inputNames[0], tensorMap, context))];\n        case 'LeakyRelu':\n          return [ops.leakyRelu(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('alpha', node, tensorMap, context) as number)];\n        case 'Prelu':\n          return [ops.prelu(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('alpha', node, tensorMap, context) as Tensor)];\n        case 'IsNan':\n          return [ops.isNaN(getTensor(node.inputNames[0], tensorMap, context))];\n        case 'IsInf':\n          return [ops.isInf(getTensor(node.inputNames[0], tensorMap, context))];\n        case 'IsFinite':\n          return [ops.isFinite(\n              getTensor(node.inputNames[0], tensorMap, context))];\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'basic_math';\n", "\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * This differs from util.assertShapesMatch in that it allows values of\n * negative one, an undefined size of a dimensinon, in a shape to match\n * anything.\n */\n\nimport {Tensor, util} from '@tensorflow/tfjs-core';\n\n/**\n * Used by TensorList and TensorArray to verify if elementShape matches, support\n * negative value as the dim shape.\n * @param shapeA\n * @param shapeB\n * @param errorMessagePrefix\n */\nexport function assertShapesMatchAllowUndefinedSize(\n    shapeA: number|number[], shapeB: number|number[],\n    errorMessagePrefix = ''): void {\n  // constant shape means unknown rank\n  if (typeof shapeA === 'number' || typeof shapeB === 'number') {\n    return;\n  }\n  util.assert(\n      shapeA.length === shapeB.length,\n      () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n  for (let i = 0; i < shapeA.length; i++) {\n    const dim0 = shapeA[i];\n    const dim1 = shapeB[i];\n    util.assert(\n        dim0 < 0 || dim1 < 0 || dim0 === dim1,\n        () =>\n            errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n  }\n}\n\nexport function fullDefinedShape(elementShape: number|number[]): boolean {\n  if (typeof elementShape === 'number' || elementShape.some(dim => dim < 0)) {\n    return false;\n  }\n  return true;\n}\n/**\n * Generate the output element shape from the list elementShape, list tensors\n * and input param.\n * @param listElementShape\n * @param tensors\n * @param elementShape\n */\nexport function inferElementShape(\n    listElementShape: number|number[], tensors: Tensor[],\n    elementShape: number|number[]): number[] {\n  let partialShape = mergeElementShape(listElementShape, elementShape);\n  const notfullDefinedShape = !fullDefinedShape(partialShape);\n  if (notfullDefinedShape && tensors.length === 0) {\n    throw new Error(\n        `Tried to calculate elements of an empty list` +\n        ` with non-fully-defined elementShape: ${partialShape}`);\n  }\n  if (notfullDefinedShape) {\n    tensors.forEach(tensor => {\n      partialShape = mergeElementShape(tensor.shape, partialShape);\n    });\n  }\n  if (!fullDefinedShape(partialShape)) {\n    throw new Error(`Non-fully-defined elementShape: ${partialShape}`);\n  }\n  return partialShape as number[];\n}\n\nexport function mergeElementShape(\n    elementShapeA: number|number[], elementShapeB: number|number[]): number|\n    number[] {\n  if (typeof elementShapeA === 'number') {\n    return elementShapeB;\n  }\n  if (typeof elementShapeB === 'number') {\n    return elementShapeA;\n  }\n\n  if (elementShapeA.length !== elementShapeB.length) {\n    throw new Error(`Incompatible ranks during merge: ${elementShapeA} vs. ${\n        elementShapeB}`);\n  }\n\n  const result: number[] = [];\n  for (let i = 0; i < elementShapeA.length; ++i) {\n    const dim0 = elementShapeA[i];\n    const dim1 = elementShapeB[i];\n    if (dim0 >= 0 && dim1 >= 0 && dim0 !== dim1) {\n      throw new Error(`Incompatible shape during merge: ${elementShapeA} vs. ${\n          elementShapeB}`);\n    }\n    result[i] = dim0 >= 0 ? dim0 : dim1;\n  }\n  return result;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {concat, DataType, keep, reshape, scalar, slice, stack, Tensor, tensor, tidy, unstack} from '@tensorflow/tfjs-core';\n\nimport {assertShapesMatchAllowUndefinedSize} from './tensor_utils';\n\nexport interface TensorWithState {\n  tensor?: Tensor;\n  written?: boolean;\n  read?: boolean;\n  cleared?: boolean;\n}\n/**\n * The TensorArray object keeps an array of Tensors.  It\n * allows reading from the array and writing to the array.\n */\nexport class TensorArray {\n  private tensors: TensorWithState[] = [];\n  private closed_ = false;\n  readonly idTensor: Tensor;\n  constructor(\n      readonly name: string, readonly dtype: DataType, private maxSize: number,\n      private elementShape: number[], readonly identicalElementShapes: boolean,\n      readonly dynamicSize: boolean, readonly clearAfterRead: boolean) {\n    this.idTensor = scalar(0);\n    keep(this.idTensor);\n  }\n\n  get id() {\n    return this.idTensor.id;\n  }\n\n  get closed() {\n    return this.closed_;\n  }\n\n  /**\n   * Dispose the tensors and idTensor and mark the TensoryArray as closed.\n   */\n  clearAndClose(keepIds?: Set<number>) {\n    this.tensors.forEach(tensor => {\n      if (keepIds == null || !keepIds.has(tensor.tensor.id)) {\n        tensor.tensor.dispose();\n      }\n    });\n    this.tensors = [];\n    this.closed_ = true;\n    this.idTensor.dispose();\n  }\n\n  size(): number {\n    return this.tensors.length;\n  }\n\n  /**\n   * Read the value at location index in the TensorArray.\n   * @param index Number the index to read from.\n   */\n  read(index: number): Tensor {\n    if (this.closed_) {\n      throw new Error(`TensorArray ${this.name} has already been closed.`);\n    }\n\n    if (index < 0 || index >= this.size()) {\n      throw new Error(`Tried to read from index ${index}, but array size is: ${\n          this.size()}`);\n    }\n\n    const tensorWithState = this.tensors[index];\n    if (tensorWithState.cleared) {\n      throw new Error(\n          `TensorArray ${this.name}: Could not read index ${\n              index} twice because it was cleared after a previous read ` +\n          `(perhaps try setting clear_after_read = false?).`);\n    }\n\n    if (this.clearAfterRead) {\n      tensorWithState.cleared = true;\n    }\n\n    tensorWithState.read = true;\n    return tensorWithState.tensor;\n  }\n\n  /**\n   * Helper method to read multiple tensors from the specified indices.\n   */\n  readMany(indices: number[]): Tensor[] {\n    return indices.map(index => this.read(index));\n  }\n\n  /**\n   * Write value into the index of the TensorArray.\n   * @param index number the index to write to.\n   * @param tensor\n   */\n  write(index: number, tensor: Tensor) {\n    if (this.closed_) {\n      throw new Error(`TensorArray ${this.name} has already been closed.`);\n    }\n\n    if (index < 0 || !this.dynamicSize && index >= this.maxSize) {\n      throw new Error(`Tried to write to index ${\n          index}, but array is not resizeable and size is: ${this.maxSize}`);\n    }\n\n    const t = this.tensors[index] || {};\n\n    if (tensor.dtype !== this.dtype) {\n      throw new Error(`TensorArray ${\n          this.name}: Could not write to TensorArray index ${index},\n          because the value dtype is ${\n          tensor.dtype}, but TensorArray dtype is ${this.dtype}.`);\n    }\n\n    // Set the shape for the first time write to unknow shape tensor array\n    if (this.size() === 0 &&\n        (this.elementShape == null || this.elementShape.length === 0)) {\n      this.elementShape = tensor.shape;\n    }\n\n    assertShapesMatchAllowUndefinedSize(\n        this.elementShape, tensor.shape,\n        `TensorArray ${this.name}: Could not write to TensorArray index ${\n            index}.`);\n\n    if (t.read) {\n      throw new Error(\n          `TensorArray ${this.name}: Could not write to TensorArray index ${\n              index}, because it has already been read.`);\n    }\n\n    if (t.written) {\n      throw new Error(\n          `TensorArray ${this.name}: Could not write to TensorArray index ${\n              index}, because it has already been written.`);\n    }\n\n    t.tensor = tensor;\n    keep(tensor);\n    t.written = true;\n\n    this.tensors[index] = t;\n  }\n\n  /**\n   * Helper method to write multiple tensors to the specified indices.\n   */\n  writeMany(indices: number[], tensors: Tensor[]) {\n    if (indices.length !== tensors.length) {\n      throw new Error(\n          `TensorArray ${this.name}: could not write multiple tensors,` +\n          `because the index size: ${\n              indices.length} is not the same as tensors size: ${\n              tensors.length}.`);\n    }\n\n    indices.forEach((i, index) => this.write(i, tensors[index]));\n  }\n\n  /**\n   * Return selected values in the TensorArray as a packed Tensor. All of\n   * selected values must have been written and their shapes must all match.\n   * @param [indices] number[] Optional. Taking values in [0, max_value). If the\n   *    TensorArray is not dynamic, max_value=size(). If not specified returns\n   *    all tensors in the original order.\n   * @param [dtype]\n   */\n  gather(indices?: number[], dtype?: DataType): Tensor {\n    if (!!dtype && dtype !== this.dtype) {\n      throw new Error(`TensorArray dtype is ${\n          this.dtype} but gather requested dtype ${dtype}`);\n    }\n\n    if (!indices) {\n      indices = [];\n      for (let i = 0; i < this.size(); i++) {\n        indices.push(i);\n      }\n    } else {\n      indices = indices.slice(0, this.size());\n    }\n\n    if (indices.length === 0) {\n      return tensor([], [0].concat(this.elementShape));\n    }\n\n    // Read all the PersistentTensors into a vector to keep track of\n    // their memory.\n    const tensors = this.readMany(indices);\n\n    assertShapesMatchAllowUndefinedSize(\n        this.elementShape, tensors[0].shape, 'TensorArray shape mismatch: ');\n\n    return stack(tensors, 0);\n  }\n\n  /**\n   * Return the values in the TensorArray as a concatenated Tensor.\n   */\n  concat(dtype?: DataType): Tensor {\n    if (!!dtype && dtype !== this.dtype) {\n      throw new Error(`TensorArray dtype is ${\n          this.dtype} but concat requested dtype ${dtype}`);\n    }\n\n    if (this.size() === 0) {\n      return tensor([], [0].concat(this.elementShape));\n    }\n\n    const indices = [];\n    for (let i = 0; i < this.size(); i++) {\n      indices.push(i);\n    }\n    // Collect all the tensors from the tensors array.\n    const tensors = this.readMany(indices);\n\n    assertShapesMatchAllowUndefinedSize(\n        this.elementShape, tensors[0].shape,\n        `TensorArray shape mismatch: tensor array shape (${\n            this.elementShape}) vs first tensor shape (${tensors[0].shape})`);\n\n    return concat(tensors, 0);\n  }\n\n  /**\n   * Scatter the values of a Tensor in specific indices of a TensorArray.\n   * @param indices number[] values in [0, max_value). If the\n   *    TensorArray is not dynamic, max_value=size().\n   * @param tensor Tensor input tensor.\n   */\n  scatter(indices: number[], tensor: Tensor) {\n    if (tensor.dtype !== this.dtype) {\n      throw new Error(`TensorArray dtype is ${\n          this.dtype} but tensor has dtype ${tensor.dtype}`);\n    }\n\n    if (indices.length !== tensor.shape[0]) {\n      throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${\n          indices.length} vs. ${tensor.shape[0]}`);\n    }\n\n    const maxIndex = Math.max(...indices);\n\n    if (!this.dynamicSize && maxIndex >= this.maxSize) {\n      throw new Error(\n          `Max index must be < array size (${maxIndex}  vs. ${this.maxSize})`);\n    }\n\n    this.writeMany(indices, unstack(tensor, 0));\n  }\n\n  /**\n   * Split the values of a Tensor into the TensorArray.\n   * @param length number[] with the lengths to use when splitting value along\n   *    its first dimension.\n   * @param tensor Tensor, the tensor to split.\n   */\n  split(length: number[], tensor: Tensor) {\n    if (tensor.dtype !== this.dtype) {\n      throw new Error(`TensorArray dtype is ${\n          this.dtype} but tensor has dtype ${tensor.dtype}`);\n    }\n    let totalLength = 0;\n    const cumulativeLengths = length.map(len => {\n      totalLength += len;\n      return totalLength;\n    });\n\n    if (totalLength !== tensor.shape[0]) {\n      throw new Error(`Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n    }\n\n    if (!this.dynamicSize && length.length !== this.maxSize) {\n      throw new Error(\n          `TensorArray's size is not equal to the size of lengths (${\n              this.maxSize} vs. ${length.length}), ` +\n          'and the TensorArray is not marked as dynamically resizeable');\n    }\n\n    const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n    const tensors: Tensor[] = [];\n    tidy(() => {\n      tensor = reshape(tensor, [1, totalLength, elementPerRow]);\n      for (let i = 0; i < length.length; ++i) {\n        const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];\n        const indices = [0, previousLength, 0];\n        const sizes = [1, length[i], elementPerRow];\n        tensors[i] = reshape(slice(tensor, indices, sizes), this.elementShape);\n      }\n      return tensors;\n    });\n    const indices = [];\n    for (let i = 0; i < length.length; i++) {\n      indices[i] = i;\n    }\n    this.writeMany(indices, tensors);\n  }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {concat, DataType, keep, reshape, scalar, slice, stack, Tensor, tensor, tidy, unstack} from '@tensorflow/tfjs-core';\n\nimport {assertShapesMatchAllowUndefinedSize, inferElementShape, mergeElementShape} from './tensor_utils';\n\n/**\n * TensorList stores a container of `tf.Tensor` objects, which are accessible\n * via tensors field.\n *\n * In order to get a copy of the underlying list, use the copy method:\n * ```\n *    TensorList b = a.copy();\n *    b.tensors().pushBack(t);  // This does not modify a.tensors().\n * ```\n *\n * Note that this is not a deep copy: the memory locations of the underlying\n * tensors will still point to the same locations of the corresponding tensors\n * in the original.\n */\n\nexport class TensorList {\n  readonly idTensor: Tensor;\n  maxNumElements: number;\n\n  get id() {\n    return this.idTensor.id;\n  }\n  /**\n   *\n   * @param tensors list of tensors\n   * @param elementShape shape of each tensor, this can be a single number (any\n   * shape is allowed) or partial shape (dim = -1).\n   * @param elementDtype data type of each tensor\n   * @param maxNumElements The maximum allowed size of `tensors`. Defaults to -1\n   *   meaning that the size of `tensors` is unbounded.\n   */\n  constructor(\n      readonly tensors: Tensor[], readonly elementShape: number|number[],\n      readonly elementDtype: DataType, maxNumElements = -1) {\n    if (tensors != null) {\n      tensors.forEach(tensor => {\n        if (elementDtype !== tensor.dtype) {\n          throw new Error(`Invalid data types; op elements ${\n              elementDtype}, but list elements ${tensor.dtype}`);\n        }\n        assertShapesMatchAllowUndefinedSize(\n            elementShape, tensor.shape, 'TensorList shape mismatch: ');\n\n        keep(tensor);\n      });\n    }\n    this.idTensor = scalar(0);\n    this.maxNumElements = maxNumElements;\n    keep(this.idTensor);\n  }\n\n  /**\n   * Get a new TensorList containing a copy of the underlying tensor container.\n   */\n  copy(): TensorList {\n    return new TensorList(\n        [...this.tensors], this.elementShape, this.elementDtype);\n  }\n\n  /**\n   * Dispose the tensors and idTensor and clear the tensor list.\n   */\n  clearAndClose(keepIds?: Set<number>) {\n    this.tensors.forEach(tensor => {\n      if (keepIds == null || !keepIds.has(tensor.id)) {\n        tensor.dispose();\n      }\n    });\n    this.tensors.length = 0;\n    this.idTensor.dispose();\n  }\n  /**\n   * The size of the tensors in the tensor list.\n   */\n  size() {\n    return this.tensors.length;\n  }\n\n  /**\n   * Return a tensor that stacks a list of rank-R tf.Tensors into one rank-(R+1)\n   * tf.Tensor.\n   * @param elementShape shape of each tensor\n   * @param elementDtype data type of each tensor\n   * @param numElements the number of elements to stack\n   */\n  stack(elementShape: number[], elementDtype: DataType, numElements = -1):\n      Tensor {\n    if (elementDtype !== this.elementDtype) {\n      throw new Error(`Invalid data types; op elements ${\n          elementDtype}, but list elements ${this.elementDtype}`);\n    }\n    if (numElements !== -1 && this.tensors.length !== numElements) {\n      throw new Error(`Operation expected a list with ${\n          numElements} elements but got a list with ${\n          this.tensors.length} elements.`);\n    }\n    assertShapesMatchAllowUndefinedSize(\n        elementShape, this.elementShape, 'TensorList shape mismatch: ');\n    const outputElementShape =\n        inferElementShape(this.elementShape, this.tensors, elementShape);\n    return tidy(() => {\n      const reshapedTensors =\n          this.tensors.map(tensor => reshape(tensor, outputElementShape));\n      return stack(reshapedTensors, 0);\n    });\n  }\n\n  /**\n   * Pop a tensor from the end of the list.\n   * @param elementShape shape of the tensor\n   * @param elementDtype data type of the tensor\n   */\n  popBack(elementShape: number[], elementDtype: DataType): Tensor {\n    if (elementDtype !== this.elementDtype) {\n      throw new Error(`Invalid data types; op elements ${\n          elementDtype}, but list elements ${this.elementDtype}`);\n    }\n\n    if (this.size() === 0) {\n      throw new Error('Trying to pop from an empty list.');\n    }\n    const outputElementShape =\n        inferElementShape(this.elementShape, this.tensors, elementShape);\n    const tensor = this.tensors.pop();\n    tensor.kept = false;\n\n    assertShapesMatchAllowUndefinedSize(\n        tensor.shape, elementShape, 'TensorList shape mismatch: ');\n\n    return reshape(tensor, outputElementShape);\n  }\n\n  /**\n   * Push a tensor to the end of the list.\n   * @param tensor Tensor to be pushed.\n   */\n  pushBack(tensor: Tensor) {\n    if (tensor.dtype !== this.elementDtype) {\n      throw new Error(`Invalid data types; op elements ${\n          tensor.dtype}, but list elements ${this.elementDtype}`);\n    }\n\n    assertShapesMatchAllowUndefinedSize(\n        tensor.shape, this.elementShape, 'TensorList shape mismatch: ');\n\n    if (this.maxNumElements === this.size()) {\n      throw new Error(`Trying to push element into a full list.`);\n    }\n    keep(tensor);\n    this.tensors.push(tensor);\n  }\n\n  /**\n   * Update the size of the list.\n   * @param size the new size of the list.\n   */\n  resize(size: number) {\n    if (size < 0) {\n      throw new Error(\n          `TensorListResize expects size to be non-negative. Got: ${size}`);\n    }\n\n    if (this.maxNumElements !== -1 && size > this.maxNumElements) {\n      throw new Error(`TensorListResize input size ${\n          size} is greater maxNumElement ${this.maxNumElements}.`);\n    }\n\n    const destTensorList: TensorList = new TensorList(\n        [], this.elementShape, this.elementDtype, this.maxNumElements);\n    destTensorList.tensors.length = size;\n    for (let i = 0; i < Math.min(this.tensors.length, size); ++i) {\n      destTensorList.tensors[i] = this.tensors[i];\n    }\n    return destTensorList;\n  }\n\n  /**\n   * Retrieve the element at the provided index\n   * @param elementShape shape of the tensor\n   * @param elementDtype dtype of the tensor\n   * @param elementIndex index of the tensor\n   */\n  getItem(elementIndex: number, elementShape: number[], elementDtype: DataType):\n      Tensor {\n    if (elementDtype !== this.elementDtype) {\n      throw new Error(`Invalid data types; op elements ${\n          elementDtype}, but list elements ${this.elementDtype}`);\n    }\n    if (elementIndex < 0 || elementIndex > this.tensors.length) {\n      throw new Error(`Trying to access element ${\n          elementIndex} in a list with ${this.tensors.length} elements.`);\n    }\n\n    if (this.tensors[elementIndex] == null) {\n      throw new Error(`element at index ${elementIndex} is null.`);\n    }\n\n    assertShapesMatchAllowUndefinedSize(\n        this.tensors[elementIndex].shape, elementShape,\n        'TensorList shape mismatch: ');\n    const outputElementShape =\n        inferElementShape(this.elementShape, this.tensors, elementShape);\n    return reshape(this.tensors[elementIndex], outputElementShape);\n  }\n\n  /**\n   * Set the tensor at the index\n   * @param elementIndex index of the tensor\n   * @param tensor the tensor to be inserted into the list\n   */\n  setItem(elementIndex: number, tensor: Tensor) {\n    if (tensor.dtype !== this.elementDtype) {\n      throw new Error(`Invalid data types; op elements ${\n          tensor.dtype}, but list elements ${this.elementDtype}`);\n    }\n\n    if (elementIndex < 0 ||\n        this.maxNumElements !== -1 && elementIndex >= this.maxNumElements) {\n      throw new Error(`Trying to set element ${\n          elementIndex} in a list with max ${this.maxNumElements} elements.`);\n    }\n\n    assertShapesMatchAllowUndefinedSize(\n        this.elementShape, tensor.shape, 'TensorList shape mismatch: ');\n    keep(tensor);\n\n    // dispose the previous value if it is replacing.\n    if (this.tensors[elementIndex] != null) {\n      this.tensors[elementIndex].kept = false;\n    }\n\n    this.tensors[elementIndex] = tensor;\n  }\n\n  /**\n   * Return selected values in the TensorList as a stacked Tensor. All of\n   * selected values must have been written and their shapes must all match.\n   * @param indices indices of tensors to gather\n   * @param elementDtype output tensor dtype\n   * @param elementShape output tensor element shape\n   */\n  gather(indices: number[], elementDtype: DataType, elementShape: number[]):\n      Tensor {\n    if (elementDtype !== this.elementDtype) {\n      throw new Error(`Invalid data types; op elements ${\n          elementDtype}, but list elements ${this.elementDtype}`);\n    }\n\n    assertShapesMatchAllowUndefinedSize(\n        this.elementShape, elementShape, 'TensorList shape mismatch: ');\n\n    // When indices is greater than the size of the list, indices beyond the\n    // size of the list are ignored.\n    indices = indices.slice(0, this.size());\n    const outputElementShape =\n        inferElementShape(this.elementShape, this.tensors, elementShape);\n    if (indices.length === 0) {\n      return tensor([], [0].concat(outputElementShape));\n    }\n\n    return tidy(() => {\n      const tensors =\n          indices.map(i => reshape(this.tensors[i], outputElementShape));\n      return stack(tensors, 0);\n    });\n  }\n\n  /**\n   * Return the values in the TensorList as a concatenated Tensor.\n   * @param elementDtype output tensor dtype\n   * @param elementShape output tensor element shape\n   */\n  concat(elementDtype: DataType, elementShape: number[]): Tensor {\n    if (!!elementDtype && elementDtype !== this.elementDtype) {\n      throw new Error(`TensorList dtype is ${\n          this.elementDtype} but concat requested dtype ${elementDtype}`);\n    }\n\n    assertShapesMatchAllowUndefinedSize(\n        this.elementShape, elementShape, 'TensorList shape mismatch: ');\n    const outputElementShape =\n        inferElementShape(this.elementShape, this.tensors, elementShape);\n\n    if (this.size() === 0) {\n      return tensor([], [0].concat(outputElementShape));\n    }\n    return tidy(() => {\n      const tensors = this.tensors.map(t => reshape(t, outputElementShape));\n      return concat(tensors, 0);\n    });\n  }\n}\n\n/**\n * Creates a TensorList which, when stacked, has the value of tensor.\n * @param tensor from tensor\n * @param elementShape output tensor element shape\n */\nexport function fromTensor(\n    tensor: Tensor, elementShape: number[], elementDtype: DataType) {\n  const dtype = tensor.dtype;\n  if (tensor.shape.length < 1) {\n    throw new Error(\n        `Tensor must be at least a vector, but saw shape: ${tensor.shape}`);\n  }\n  if (tensor.dtype !== elementDtype) {\n    throw new Error(`Invalid data types; op elements ${\n        tensor.dtype}, but list elements ${elementDtype}`);\n  }\n  const tensorElementShape = tensor.shape.slice(1);\n  assertShapesMatchAllowUndefinedSize(\n      tensorElementShape, elementShape, 'TensorList shape mismatch: ');\n  const tensorList: Tensor[] = unstack(tensor);\n  return new TensorList(tensorList, elementShape, dtype);\n}\n\n/**\n * Return a TensorList of the given size with empty elements.\n * @param elementShape the shape of the future elements of the list\n * @param elementDtype the desired type of elements in the list\n * @param numElements the number of elements to reserve\n * @param maxNumElements the maximum number of elements in th list\n */\nexport function reserve(\n    elementShape: number[], elementDtype: DataType, numElements: number,\n    maxNumElements: number) {\n  return new TensorList([], elementShape, elementDtype, maxNumElements);\n}\n\n/**\n * Put tensors at specific indices of a stacked tensor into a TensorList.\n * @param indices list of indices on how to scatter the tensor.\n * @param tensor input tensor.\n * @param elementShape the shape of the future elements of the list\n * @param numElements the number of elements to scatter\n */\nexport function scatter(\n    tensor: Tensor, indices: number[], elementShape: number[],\n    numElements?: number): TensorList {\n  if (indices.length !== tensor.shape[0]) {\n    throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${\n        indices.length} vs. ${tensor.shape[0]}`);\n  }\n\n  const maxIndex = Math.max(...indices);\n\n  if (numElements != null && numElements !== -1 && maxIndex >= numElements) {\n    throw new Error(\n        `Max index must be < array size (${maxIndex}  vs. ${numElements})`);\n  }\n\n  const list = new TensorList([], elementShape, tensor.dtype, numElements);\n  const tensors = unstack(tensor, 0);\n  indices.forEach((value, index) => {\n    list.setItem(value, tensors[index]);\n  });\n  return list;\n}\n\n/**\n * Split the values of a Tensor into a TensorList.\n * @param length the lengths to use when splitting value along\n *    its first dimension.\n * @param tensor the tensor to split.\n * @param elementShape the shape of the future elements of the list\n */\nexport function split(\n    tensor: Tensor, length: number[], elementShape: number[]) {\n  let totalLength = 0;\n  const cumulativeLengths = length.map(len => {\n    totalLength += len;\n    return totalLength;\n  });\n\n  if (totalLength !== tensor.shape[0]) {\n    throw new Error(`Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n  }\n\n  const shapeWithoutFirstDim = tensor.shape.slice(1);\n  const outputElementShape =\n      mergeElementShape(shapeWithoutFirstDim, elementShape);\n  const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n  const tensors: Tensor[] = tidy(() => {\n    const tensors = [];\n    tensor = reshape(tensor, [1, totalLength, elementPerRow]);\n    for (let i = 0; i < length.length; ++i) {\n      const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];\n      const indices = [0, previousLength, 0];\n      const sizes = [1, length[i], elementPerRow];\n      tensors[i] = reshape(\n          slice(tensor, indices, sizes), outputElementShape as number[]);\n    }\n    tensor.dispose();\n    return tensors;\n  });\n\n  const list = new TensorList([], elementShape, tensor.dtype, length.length);\n\n  for (let i = 0; i < tensors.length; i++) {\n    list.setItem(i, tensors[i]);\n  }\n  return list;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, scalar, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {TensorArray} from '../../executor/tensor_array';\nimport {fromTensor, reserve, scatter, split} from '../../executor/tensor_list';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {cloneTensor, getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n    node: Node, tensorMap: NamedTensorsMap,\n    context: ExecutionContext): Promise<Tensor[]> => {\n  switch (node.op) {\n    case 'If':\n    case 'StatelessIf': {\n      const thenFunc =\n          getParamValue('thenBranch', node, tensorMap, context) as string;\n      const elseFunc =\n          getParamValue('elseBranch', node, tensorMap, context) as string;\n      const cond = getParamValue('cond', node, tensorMap, context) as Tensor;\n      const args = getParamValue('args', node, tensorMap, context) as Tensor[];\n      const condValue = await cond.data();\n      if (condValue[0]) {\n        return context.functionMap[thenFunc].executeFunctionAsync(\n            args, context.tensorArrayMap, context.tensorListMap);\n      } else {\n        return context.functionMap[elseFunc].executeFunctionAsync(\n            args, context.tensorArrayMap, context.tensorListMap);\n      }\n    }\n    case 'While':\n    case 'StatelessWhile': {\n      const bodyFunc =\n          getParamValue('body', node, tensorMap, context) as string;\n      const condFunc =\n          getParamValue('cond', node, tensorMap, context) as string;\n      const args = getParamValue('args', node, tensorMap, context) as Tensor[];\n\n      // Calculate the condition of the loop\n      const condResult =\n          (await context.functionMap[condFunc].executeFunctionAsync(\n              args, context.tensorArrayMap, context.tensorListMap));\n      const argIds = args.map(tensor => tensor.id);\n      let condValue = await condResult[0].data();\n      // Dispose the intermediate tensors for condition function\n      condResult.forEach(tensor => {\n        if (!tensor.kept && argIds.indexOf(tensor.id) === -1) {\n          tensor.dispose();\n        }\n      });\n\n      let result: Tensor[] = args;\n\n      while (condValue[0]) {\n        // Record the previous result for intermediate tensor tracking\n        const origResult = result;\n        // Execution the body of the loop\n        result = await context.functionMap[bodyFunc].executeFunctionAsync(\n            result, context.tensorArrayMap, context.tensorListMap);\n        const resultIds = result.map(tensor => tensor.id);\n\n        // Dispose the intermediate tensor for body function that is not global\n        // kept, not input/output of the body function\n        origResult.forEach(tensor => {\n          if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&\n              resultIds.indexOf(tensor.id) === -1) {\n            tensor.dispose();\n          }\n        });\n\n        // Recalcuate the condition of the loop using the latest results.\n        const condResult =\n            (await context.functionMap[condFunc].executeFunctionAsync(\n                result, context.tensorArrayMap, context.tensorListMap));\n        condValue = await condResult[0].data();\n        // Dispose the intermediate tensors for condition function\n        condResult.forEach(tensor => {\n          if (!tensor.kept && argIds.indexOf(tensor.id) === -1 &&\n              resultIds.indexOf(tensor.id) === -1) {\n            tensor.dispose();\n          }\n        });\n      }\n      return result;\n    }\n    case 'LoopCond': {\n      const pred = getParamValue('pred', node, tensorMap, context) as Tensor;\n      return [cloneTensor(pred)];\n    }\n    case 'Switch': {\n      const pred = getParamValue('pred', node, tensorMap, context) as Tensor;\n      let data = getParamValue('data', node, tensorMap, context) as Tensor;\n      if (!data.kept) {\n        data = cloneTensor(data);\n      }\n      // Outputs nodes :0 => false, :1 => true\n      return (await pred.data())[0] ? [undefined, data] : [data, undefined];\n    }\n    case 'Merge': {\n      const inputName = node.inputNames.find(\n          name => getTensor(name, tensorMap, context) !== undefined);\n      if (inputName) {\n        const data = getTensor(inputName, tensorMap, context);\n        return [cloneTensor(data)];\n      }\n      return undefined;\n    }\n    case 'Enter': {\n      const frameId =\n          getParamValue('frameName', node, tensorMap, context) as string;\n      const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n      context.enterFrame(frameId);\n      return [cloneTensor(data)];\n    }\n    case 'Exit': {\n      const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n      context.exitFrame();\n      return [cloneTensor(data)];\n    }\n    case 'NextIteration': {\n      const data = getParamValue('tensor', node, tensorMap, context) as Tensor;\n      context.nextIteration();\n      return [cloneTensor(data)];\n    }\n    case 'TensorArrayV3': {\n      const size = getParamValue('size', node, tensorMap, context) as number;\n      const dtype =\n          getParamValue('dtype', node, tensorMap, context) as DataType;\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      const dynamicSize =\n          getParamValue('dynamicSize', node, tensorMap, context) as boolean;\n      const clearAfterRead =\n          getParamValue('clearAfterRead', node, tensorMap, context) as boolean;\n      const identicalElementShapes =\n          getParamValue('identicalElementShapes', node, tensorMap, context) as\n          boolean;\n      const name = getParamValue('name', node, tensorMap, context) as string;\n      const tensorArray = new TensorArray(\n          name, dtype, size, elementShape, identicalElementShapes, dynamicSize,\n          clearAfterRead);\n      context.addTensorArray(tensorArray);\n      return [tensorArray.idTensor, scalar(1.0)];\n    }\n    case 'TensorArrayWriteV3': {\n      const id =\n          getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n      const index = getParamValue('index', node, tensorMap, context) as number;\n      const writeTensor =\n          getParamValue('tensor', node, tensorMap, context) as Tensor;\n      const writeTensorArray = context.getTensorArray(id.id);\n      writeTensorArray.write(index, writeTensor);\n      return [writeTensorArray.idTensor];\n    }\n    case 'TensorArrayReadV3': {\n      const readId =\n          getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n      const readIndex =\n          getParamValue('index', node, tensorMap, context) as number;\n      const readTensorArray = context.getTensorArray(readId.id);\n      return [readTensorArray.read(readIndex)];\n    }\n    case 'TensorArrayGatherV3': {\n      const gatherId =\n          getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n      const gatherIndices =\n          getParamValue('indices', node, tensorMap, context) as number[];\n      const gatherDtype =\n          getParamValue('dtype', node, tensorMap, context) as DataType;\n      const gatherTensorArray = context.getTensorArray(gatherId.id);\n      return [gatherTensorArray.gather(gatherIndices, gatherDtype)];\n    }\n    case 'TensorArrayScatterV3': {\n      const scatterId =\n          getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n      const scatterIndices =\n          getParamValue('indices', node, tensorMap, context) as number[];\n      const scatterTensor =\n          getParamValue('tensor', node, tensorMap, context) as Tensor;\n      const scatterTensorArray = context.getTensorArray(scatterId.id);\n      scatterTensorArray.scatter(scatterIndices, scatterTensor);\n      return [scatterTensorArray.idTensor];\n    }\n    case 'TensorArrayConcatV3': {\n      const concatId =\n          getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n      const concatTensorArray = context.getTensorArray(concatId.id);\n      const concatDtype =\n          getParamValue('dtype', node, tensorMap, context) as DataType;\n      return [concatTensorArray.concat(concatDtype)];\n    }\n    case 'TensorArraySplitV3': {\n      const splitId =\n          getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n      const splitTensor =\n          getParamValue('tensor', node, tensorMap, context) as Tensor;\n      const lengths =\n          getParamValue('lengths', node, tensorMap, context) as number[];\n      const splitTensorArray = context.getTensorArray(splitId.id);\n      splitTensorArray.split(lengths, splitTensor);\n      return [splitTensorArray.idTensor];\n    }\n    case 'TensorArraySizeV3': {\n      const sizeId =\n          getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n      const sizeTensorArray = context.getTensorArray(sizeId.id);\n      return [scalar(sizeTensorArray.size(), 'int32')];\n    }\n    case 'TensorArrayCloseV3': {\n      const closeId =\n          getParamValue('tensorArrayId', node, tensorMap, context) as Tensor;\n      const closeTensorArray = context.getTensorArray(closeId.id);\n      closeTensorArray.clearAndClose();\n      return [closeTensorArray.idTensor];\n    }\n    case 'TensorListSetItem': {\n      const idTensor =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const index = getParamValue('index', node, tensorMap, context) as number;\n      const writeTensor =\n          getParamValue('tensor', node, tensorMap, context) as Tensor;\n      const tensorList = context.getTensorList(idTensor.id);\n      tensorList.setItem(index, writeTensor);\n      return [tensorList.idTensor];\n    }\n    case 'TensorListGetItem': {\n      const idTensor =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const readIndex =\n          getParamValue('index', node, tensorMap, context) as number;\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n\n      const elementDType =\n          getParamValue('elementDType', node, tensorMap, context) as DataType;\n      const tensorList = context.getTensorList(idTensor.id);\n      return [tensorList.getItem(readIndex, elementShape, elementDType)];\n    }\n    case 'TensorListScatterV2':\n    case 'TensorListScatter': {\n      const scatterIndices =\n          getParamValue('indices', node, tensorMap, context) as number[];\n      const scatterTensor =\n          getParamValue('tensor', node, tensorMap, context) as Tensor;\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      const numElements =\n          getParamValue('numElements', node, tensorMap, context) as number;\n      const tensorList =\n          scatter(scatterTensor, scatterIndices, elementShape, numElements);\n      context.addTensorList(tensorList);\n      return [tensorList.idTensor];\n    }\n    case 'TensorListReserve':\n    case 'EmptyTensorList': {\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      const elementDtype =\n          getParamValue('elementDType', node, tensorMap, context) as DataType;\n      let numElementsParam;\n\n      if (node.op === 'TensorListReserve') {\n        numElementsParam = 'numElements';\n      } else {\n        numElementsParam = 'maxNumElements';\n      }\n\n      const numElements =\n          getParamValue(numElementsParam, node, tensorMap, context) as number;\n      const maxNumElements = node.op === 'TensorListReserve' ? -1 : numElements;\n      const tensorList =\n          reserve(elementShape, elementDtype, numElements, maxNumElements);\n      context.addTensorList(tensorList);\n      return [tensorList.idTensor];\n    }\n    case 'TensorListGather': {\n      const gatherId =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const gatherIndices =\n          getParamValue('indices', node, tensorMap, context) as number[];\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      const elementDtype =\n          getParamValue('elementDType', node, tensorMap, context) as DataType;\n      const tensorList = context.getTensorList(gatherId.id);\n      return [tensorList.gather(gatherIndices, elementDtype, elementShape)];\n    }\n    case 'TensorListStack': {\n      const idTensor =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      const elementDtype =\n          getParamValue('elementDType', node, tensorMap, context) as DataType;\n      const numElements =\n          getParamValue('numElements', node, tensorMap, context) as number;\n      const tensorList = context.getTensorList(idTensor.id);\n      return [tensorList.stack(elementShape, elementDtype, numElements)];\n    }\n    case 'TensorListFromTensor': {\n      const tensor =\n          getParamValue('tensor', node, tensorMap, context) as Tensor;\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      const elementDtype =\n          getParamValue('elementDType', node, tensorMap, context) as DataType;\n      const tensorList = fromTensor(tensor, elementShape, elementDtype);\n      context.addTensorList(tensorList);\n      return [tensorList.idTensor];\n    }\n    case 'TensorListConcat':\n    case 'TensorListConcatV2': {\n      const concatId =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const tensorList = context.getTensorList(concatId.id);\n      const concatDtype =\n          getParamValue('dtype', node, tensorMap, context) as DataType;\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      return [tensorList.concat(concatDtype, elementShape)];\n    }\n    case 'TensorListPushBack': {\n      const idTensor =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const writeTensor =\n          getParamValue('tensor', node, tensorMap, context) as Tensor;\n      const tensorList = context.getTensorList(idTensor.id);\n      tensorList.pushBack(writeTensor);\n      return [tensorList.idTensor];\n    }\n    case 'TensorListPopBack': {\n      const idTensor =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      const elementDType =\n          getParamValue('elementDType', node, tensorMap, context) as DataType;\n      const tensorList = context.getTensorList(idTensor.id);\n      return [tensorList.popBack(elementShape, elementDType)];\n    }\n    case 'TensorListSplit': {\n      const splitTensor =\n          getParamValue('tensor', node, tensorMap, context) as Tensor;\n      const elementShape =\n          getParamValue('elementShape', node, tensorMap, context) as number[];\n      const lengths =\n          getParamValue('lengths', node, tensorMap, context) as number[];\n\n      const tensorList = split(splitTensor, lengths, elementShape);\n      context.addTensorList(tensorList);\n      return [tensorList.idTensor];\n    }\n    case 'TensorListLength': {\n      const idTensor =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const tensorList = context.getTensorList(idTensor.id);\n      return [scalar(tensorList.size(), 'int32')];\n    }\n    case 'TensorListResize': {\n      const idTensor =\n          getParamValue('tensorListId', node, tensorMap, context) as Tensor;\n      const size = getParamValue('size', node, tensorMap, context) as number;\n\n      const srcTensorList = context.getTensorList(idTensor.id);\n      const destTensorList = srcTensorList.resize(size);\n      context.addTensorList(destTensorList);\n      return [destTensorList.idTensor];\n    }\n    default:\n      throw TypeError(`Node type ${node.op} is not implemented`);\n  }\n};\n\nexport const CATEGORY = 'control';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Rank, Tensor, Tensor3D, Tensor4D, Tensor5D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getPadding, getParamValue} from './utils';\n\nfunction fusedConvAndDepthWiseParams(\n    node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) {\n  const [extraOp, activationFunc] =\n      (getParamValue('fusedOps', node, tensorMap, context) as string[]);\n\n  const isBiasAdd = extraOp === 'biasadd';\n  const noBiasAdd = !isBiasAdd;\n  const isPrelu = activationFunc === 'prelu';\n  const isBatchNorm = extraOp === 'fusedbatchnorm';\n\n  const numArgs =\n      (getParamValue('numArgs', node, tensorMap, context) as number);\n  if (isBiasAdd) {\n    if (isPrelu && numArgs !== 2) {\n      throw new Error(\n          'FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu ' +\n          'must have two extra arguments: bias and alpha.');\n    }\n    if (!isPrelu && isBiasAdd && numArgs !== 1) {\n      throw new Error(\n          'FusedConv2d and DepthwiseConv2d with BiasAdd must have ' +\n          'one extra argument: bias.');\n    }\n  }\n  if (isBatchNorm) {\n    throw new Error(\n        'FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported');\n  }\n  const stride = getParamValue('strides', node, tensorMap, context) as number[];\n  const pad = getPadding(node, tensorMap, context);\n  const dataFormat =\n      (getParamValue('dataFormat', node, tensorMap, context) as string)\n          .toUpperCase();\n  const dilations =\n      getParamValue('dilations', node, tensorMap, context) as number[];\n  let [biasArg, preluArg] =\n      getParamValue('args', node, tensorMap, context) as Tensor[];\n  if (noBiasAdd) {\n    preluArg = biasArg;\n    biasArg = undefined;\n  }\n  const leakyreluAlpha =\n      getParamValue('leakyreluAlpha', node, tensorMap, context) as number;\n\n  return {\n    stride,\n    pad,\n    dataFormat,\n    dilations,\n    biasArg,\n    preluArg,\n    activationFunc,\n    leakyreluAlpha\n  };\n}\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap,\n     context: ExecutionContext, ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'Conv1D': {\n          const stride =\n              getParamValue('stride', node, tensorMap, context) as number;\n          const pad = getParamValue('pad', node, tensorMap, context);\n          const dataFormat =\n              (getParamValue('dataFormat', node, tensorMap, context) as string)\n                  .toUpperCase();\n          const dilation =\n              getParamValue('dilation', node, tensorMap, context) as number;\n          return [ops.conv1d(\n              getParamValue('x', node, tensorMap, context) as Tensor3D,\n              getParamValue('filter', node, tensorMap, context) as Tensor3D,\n              stride, pad as 'valid' | 'same', dataFormat as 'NWC' | 'NCW',\n              dilation)];\n        }\n        case 'Conv2D': {\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getPadding(node, tensorMap, context);\n          const dataFormat =\n              (getParamValue('dataFormat', node, tensorMap, context) as string)\n                  .toUpperCase();\n          const dilations =\n              getParamValue('dilations', node, tensorMap, context) as number[];\n          return [ops.conv2d(\n              getParamValue('x', node, tensorMap, context) as Tensor3D |\n                  Tensor4D,\n              getParamValue('filter', node, tensorMap, context) as Tensor4D,\n              [stride[1], stride[2]], pad as 'valid' | 'same',\n              dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])];\n        }\n        case '_FusedConv2D': {\n          const {\n            stride,\n            pad,\n            dataFormat,\n            dilations,\n            biasArg,\n            preluArg,\n            activationFunc,\n            leakyreluAlpha\n          } = fusedConvAndDepthWiseParams(node, tensorMap, context);\n\n          return [ops.fused.conv2d({\n            x: getParamValue('x', node, tensorMap, context) as Tensor3D |\n                Tensor4D,\n            filter: getParamValue('filter', node, tensorMap, context) as\n                Tensor4D,\n            strides: [stride[1], stride[2]],\n            pad: pad as 'valid' | 'same',\n            dataFormat: dataFormat as 'NHWC' | 'NCHW',\n            dilations: [dilations[1], dilations[2]],\n            bias: biasArg,\n            activation: activationFunc as tfOps.fused.Activation,\n            preluActivationWeights: preluArg,\n            leakyreluAlpha\n          })];\n        }\n\n        case 'FusedDepthwiseConv2dNative': {\n          const {\n            stride,\n            pad,\n            dataFormat,\n            dilations,\n            biasArg,\n            preluArg,\n            activationFunc,\n            leakyreluAlpha,\n          } = fusedConvAndDepthWiseParams(node, tensorMap, context);\n\n          return [ops.fused.depthwiseConv2d({\n            x: getParamValue('x', node, tensorMap, context) as Tensor3D |\n                Tensor4D,\n            filter: getParamValue('filter', node, tensorMap, context) as\n                Tensor4D,\n            strides: [stride[1], stride[2]],\n            pad: pad as 'valid' | 'same',\n            dataFormat: dataFormat as 'NHWC' | 'NCHW',\n            dilations: [dilations[1], dilations[2]],\n            bias: biasArg,\n            activation: activationFunc as tfOps.fused.Activation,\n            preluActivationWeights: preluArg,\n            leakyreluAlpha\n          })];\n        }\n        case 'Conv2DBackpropInput':\n        case 'Conv2dTranspose': {\n          const shape = getParamValue(\n                            'outputShape', node, tensorMap,\n                            context) as [number, number, number] |\n              [number, number, number, number];\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getPadding(node, tensorMap, context);\n          return [ops.conv2dTranspose(\n              getParamValue('x', node, tensorMap, context) as Tensor3D |\n                  Tensor4D,\n              getParamValue('filter', node, tensorMap, context) as Tensor4D,\n              shape, [stride[1], stride[2]], pad as 'valid' | 'same')];\n        }\n        case 'DepthwiseConv2dNative':\n        case 'DepthwiseConv2d': {\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getPadding(node, tensorMap, context);\n          const dilations =\n              getParamValue('dilations', node, tensorMap, context) as number[];\n          const dataFormat =\n              (getParamValue('dataFormat', node, tensorMap, context) as string)\n                  .toUpperCase();\n\n          return [ops.depthwiseConv2d(\n              getParamValue('input', node, tensorMap, context) as Tensor3D |\n                  Tensor4D,\n              getParamValue('filter', node, tensorMap, context) as Tensor4D,\n              [stride[1], stride[2]], pad as 'valid' | 'same',\n              dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])];\n        }\n        case 'Conv3D': {\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getParamValue('pad', node, tensorMap, context);\n          const dataFormat =\n              (getParamValue('dataFormat', node, tensorMap, context) as string)\n                  .toUpperCase();\n          const dilations =\n              getParamValue('dilations', node, tensorMap, context) as number[];\n          return [ops.conv3d(\n              getParamValue('x', node, tensorMap, context) as Tensor4D |\n                  Tensor<Rank.R5>,\n              getParamValue('filter', node, tensorMap, context) as\n                  Tensor<Rank.R5>,\n              [stride[1], stride[2], stride[3]], pad as 'valid' | 'same',\n              dataFormat as 'NDHWC' | 'NCDHW',\n              [dilations[1], dilations[2], dilations[3]])];\n        }\n        case 'AvgPool': {\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getParamValue('pad', node, tensorMap, context);\n          const kernelSize =\n              getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n          return [ops.avgPool(\n              getParamValue('x', node, tensorMap, context) as Tensor3D |\n                  Tensor4D,\n              [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n              pad as 'valid' | 'same')];\n        }\n        case 'MaxPool': {\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getParamValue('pad', node, tensorMap, context);\n          const kernelSize =\n              getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n          return [ops.maxPool(\n              getParamValue('x', node, tensorMap, context) as Tensor3D |\n                  Tensor4D,\n              [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n              pad as 'valid' | 'same')];\n        }\n        case 'MaxPoolWithArgmax': {\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getParamValue('pad', node, tensorMap, context);\n          const kernelSize =\n              getParamValue('kernelSize', node, tensorMap, context) as number[];\n          const includeBatchInIndex =\n              getParamValue('includeBatchInIndex', node, tensorMap, context) as\n              boolean;\n          const {result, indexes} = ops.maxPoolWithArgmax(\n              getParamValue('x', node, tensorMap, context) as Tensor4D,\n              [kernelSize[1], kernelSize[2]], [stride[1], stride[2]],\n              pad as 'valid' | 'same', includeBatchInIndex);\n          return [result, indexes];\n        }\n        case 'AvgPool3D': {\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getParamValue('pad', node, tensorMap, context);\n          const kernelSize =\n              getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n          return [ops.avgPool3d(\n              getParamValue('x', node, tensorMap, context) as Tensor5D,\n              [kernelSize[1], kernelSize[2], kernelSize[3]],\n              [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')];\n        }\n\n        case 'MaxPool3D': {\n          const stride =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getParamValue('pad', node, tensorMap, context);\n          const kernelSize =\n              getParamValue('kernelSize', node, tensorMap, context) as number[];\n\n          return [ops.maxPool3d(\n              getParamValue('x', node, tensorMap, context) as Tensor5D,\n              [kernelSize[1], kernelSize[2], kernelSize[3]],\n              [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')];\n        }\n\n        case 'Dilation2D': {\n          const strides =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const pad = getParamValue('pad', node, tensorMap, context);\n          const dilations =\n              getParamValue('dilations', node, tensorMap, context) as number[];\n\n          // strides: [1, stride_height, stride_width, 1].\n          const strideHeight = strides[1];\n          const strideWidth = strides[2];\n\n          // dilations: [1, dilation_height, dilation_width, 1].\n          const dilationHeight = dilations[1];\n          const dilationWidth = dilations[2];\n\n          return [ops.dilation2d(\n              getParamValue('x', node, tensorMap, context) as Tensor3D |\n                  Tensor4D,\n              getParamValue('filter', node, tensorMap, context) as Tensor3D,\n              [strideHeight, strideWidth], pad as 'valid' | 'same',\n              [dilationHeight, dilationWidth], 'NHWC' /* dataFormat */)];\n        }\n\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'convolution';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'Fill': {\n          const shape =\n              getParamValue('shape', node, tensorMap, context) as number[];\n          const dtype =\n              getParamValue('dtype', node, tensorMap, context) as DataType;\n          const value =\n              getParamValue('value', node, tensorMap, context) as number;\n          return [ops.fill(shape, value, dtype)];\n        }\n        case 'LinSpace': {\n          const start =\n              getParamValue('start', node, tensorMap, context) as number;\n          const stop =\n              getParamValue('stop', node, tensorMap, context) as number;\n          const num = getParamValue('num', node, tensorMap, context) as number;\n          return [ops.linspace(start, stop, num)];\n        }\n        case 'Multinomial': {\n          const logits =\n              getParamValue('logits', node, tensorMap, context) as Tensor1D;\n          const numSamples =\n              getParamValue('numSamples', node, tensorMap, context) as number;\n          const seed =\n              getParamValue('seed', node, tensorMap, context) as number;\n          return [ops.multinomial(logits, numSamples, seed)];\n        }\n        case 'OneHot': {\n          const indices =\n              getParamValue('indices', node, tensorMap, context) as Tensor1D;\n          const depth =\n              getParamValue('depth', node, tensorMap, context) as number;\n          const onValue =\n              getParamValue('onValue', node, tensorMap, context) as number;\n          const offValue =\n              getParamValue('offValue', node, tensorMap, context) as number;\n          const dtype =\n              getParamValue('dtype', node, tensorMap, context) as DataType;\n          return [ops.oneHot(indices, depth, onValue, offValue, dtype)];\n        }\n        case 'Ones': {\n          return [ops.ones(\n              getParamValue('shape', node, tensorMap, context) as number[],\n              getParamValue('dtype', node, tensorMap, context) as DataType)];\n        }\n        case 'OnesLike': {\n          return [ops.onesLike(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'RandomStandardNormal': {\n          return [ops.randomStandardNormal(\n              getParamValue('shape', node, tensorMap, context) as number[],\n              getParamValue('dtype', node, tensorMap, context) as 'float32' |\n                  'int32',\n              getParamValue('seed', node, tensorMap, context) as number)];\n        }\n        case 'RandomUniform': {\n          return [ops.randomUniform(\n              // tslint:disable-next-line:no-any\n              getParamValue('shape', node, tensorMap, context) as any,\n              getParamValue('minval', node, tensorMap, context) as number,\n              getParamValue('maxval', node, tensorMap, context) as number,\n              getParamValue('dtype', node, tensorMap, context) as DataType)];\n        }\n        case 'RandomUniformInt': {\n          return [ops.randomUniformInt(\n              getParamValue('shape', node, tensorMap, context) as number[],\n              getParamValue('minval', node, tensorMap, context) as number,\n              getParamValue('maxval', node, tensorMap, context) as number,\n              getParamValue('seed', node, tensorMap, context) as number)];\n        }\n        case 'Range': {\n          const start =\n              getParamValue('start', node, tensorMap, context) as number;\n          const stop =\n              getParamValue('stop', node, tensorMap, context) as number;\n          const step =\n              getParamValue('step', node, tensorMap, context) as number;\n          return [ops.range(\n              start, stop, step,\n              getParamValue('dtype', node, tensorMap, context) as 'float32' |\n                  'int32')];\n        }\n        case 'TruncatedNormal': {\n          const shape =\n              getParamValue('shape', node, tensorMap, context) as number[];\n          const mean =\n              getParamValue('mean', node, tensorMap, context) as number;\n          const stdDev =\n              getParamValue('stdDev', node, tensorMap, context) as number;\n          const seed =\n              getParamValue('seed', node, tensorMap, context) as number;\n          return [ops.truncatedNormal(\n              shape, mean, stdDev,\n              getParamValue('dtype', node, tensorMap, context) as 'float32' |\n                  'int32',\n              seed)];\n        }\n        case 'Zeros': {\n          return [ops.zeros(\n              getParamValue('shape', node, tensorMap, context) as number[],\n              getParamValue('dtype', node, tensorMap, context) as DataType)];\n        }\n        case 'ZerosLike': {\n          return [ops.zerosLike(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'creation';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport { ResourceManager } from '../../executor/resource_manager';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nfunction nmsParams(\n    node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) {\n  const boxes = getParamValue('boxes', node, tensorMap, context) as Tensor;\n  const scores = getParamValue('scores', node, tensorMap, context) as Tensor;\n  const maxOutputSize =\n      getParamValue('maxOutputSize', node, tensorMap, context) as number;\n  const iouThreshold =\n      getParamValue('iouThreshold', node, tensorMap, context) as number;\n  const scoreThreshold =\n      getParamValue('scoreThreshold', node, tensorMap, context) as number;\n  const softNmsSigma =\n      getParamValue('softNmsSigma', node, tensorMap, context) as number;\n\n  return {\n    boxes,\n    scores,\n    maxOutputSize,\n    iouThreshold,\n    scoreThreshold,\n    softNmsSigma\n  };\n}\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n    node: Node, tensorMap: NamedTensorsMap,\n    context: ExecutionContext, resourceManager: ResourceManager,\n    ops = tfOps): Promise<Tensor[]> => {\n  switch (node.op) {\n    case 'NonMaxSuppressionV5': {\n      const {\n        boxes,\n        scores,\n        maxOutputSize,\n        iouThreshold,\n        scoreThreshold,\n        softNmsSigma\n      } = nmsParams(node, tensorMap, context);\n\n      const result = await ops.image.nonMaxSuppressionWithScoreAsync(\n          boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n          scoreThreshold, softNmsSigma);\n\n      return [result.selectedIndices, result.selectedScores];\n    }\n    case 'NonMaxSuppressionV4': {\n      const {boxes, scores, maxOutputSize, iouThreshold, scoreThreshold} =\n          nmsParams(node, tensorMap, context);\n\n      const padToMaxOutputSize =\n          getParamValue('padToMaxOutputSize', node, tensorMap, context) as\n          boolean;\n\n      const result = await ops.image.nonMaxSuppressionPaddedAsync(\n          boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n          scoreThreshold, padToMaxOutputSize);\n\n      return [result.selectedIndices, result.validOutputs];\n    }\n    case 'NonMaxSuppressionV3':\n    case 'NonMaxSuppressionV2': {\n      const {boxes, scores, maxOutputSize, iouThreshold, scoreThreshold} =\n          nmsParams(node, tensorMap, context);\n\n      return [await ops.image.nonMaxSuppressionAsync(\n          boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n          scoreThreshold)];\n    }\n    case 'Where': {\n      const condition = ops.cast(\n          (getParamValue('condition', node, tensorMap, context) as Tensor),\n          'bool');\n      const result = [await ops.whereAsync(condition)];\n      condition.dispose();\n      return result;\n    }\n    case 'ListDiff': {\n      return ops.setdiff1dAsync(\n          getParamValue('x', node, tensorMap, context) as Tensor,\n          getParamValue('y', node, tensorMap, context) as Tensor);\n    }\n    default:\n      throw TypeError(`Node type ${node.op} is not implemented`);\n  }\n};\n\nexport const CATEGORY = 'dynamic';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps):\n        Tensor[] => {\n          switch (node.op) {\n            case 'LowerBound': {\n              const sortedSequence =\n                  getParamValue('sortedSequence', node, tensorMap, context) as\n                  Tensor;\n              const values =\n                  getParamValue('values', node, tensorMap, context) as Tensor;\n              return [ops.lowerBound(sortedSequence, values)];\n            }\n            case 'TopKV2': {\n              const x = getParamValue('x', node, tensorMap, context) as Tensor;\n              const k = getParamValue('k', node, tensorMap, context) as number;\n              const sorted =\n                  getParamValue('sorted', node, tensorMap, context) as boolean;\n              const result = ops.topk(x, k, sorted);\n              return [result.values, result.indices];\n            }\n            case 'UpperBound': {\n              const sortedSequence =\n                  getParamValue('sortedSequence', node, tensorMap, context) as\n                  Tensor;\n              const values =\n                  getParamValue('values', node, tensorMap, context) as Tensor;\n              return [ops.upperBound(sortedSequence, values)];\n            }\n            case 'Unique': {\n              const x = getParamValue('x', node, tensorMap, context) as Tensor;\n              const result = ops.unique(x);\n              return [result.values, result.indices];\n            }\n            case 'UniqueV2': {\n              const x = getParamValue('x', node, tensorMap, context) as Tensor;\n              const axis =\n                  getParamValue('axis', node, tensorMap, context) as number;\n              const result = ops.unique(x, axis);\n              return [result.values, result.indices];\n            }\n            default:\n              throw TypeError(`Node type ${node.op} is not implemented`);\n          }\n        };\n\nexport const CATEGORY = 'evaluation';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {cloneTensor, getParamValue, getTensor} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap,\n     context: ExecutionContext, ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'Const': {\n          return tensorMap[node.name];\n        }\n        case 'PlaceholderWithDefault':\n          const def =\n              getParamValue('default', node, tensorMap, context) as Tensor;\n          return [getTensor(node.name, tensorMap, context) || def];\n        case 'Placeholder':\n          return [getTensor(node.name, tensorMap, context)];\n        case 'Identity':\n        case 'StopGradient':\n        case 'FakeQuantWithMinMaxVars': {  // This op is currently ignored.\n          const data = getParamValue('x', node, tensorMap, context) as Tensor;\n          return [cloneTensor(data)];\n        }\n        case 'IdentityN':\n          return (getParamValue('x', node, tensorMap, context) as Tensor[])\n              .map((t: Tensor) => cloneTensor(t));\n        case 'Snapshot':\n          const snapshot =\n              (getParamValue('x', node, tensorMap, context) as Tensor);\n          return [cloneTensor(snapshot)];\n        case 'Shape':\n          return [ops.tensor1d(\n              (getParamValue('x', node, tensorMap, context) as Tensor).shape,\n              'int32')];\n        case 'ShapeN':\n          return (getParamValue('x', node, tensorMap, context) as Tensor[])\n              .map((t: Tensor) => ops.tensor1d(t.shape));\n        case 'Size':\n          return [ops.scalar(\n              (getParamValue('x', node, tensorMap, context) as Tensor).size,\n              'int32')];\n        case 'Rank':\n          return [ops.scalar(\n              (getParamValue('x', node, tensorMap, context) as Tensor).rank,\n              'int32')];\n        case 'NoOp':\n          return [ops.scalar(1)];\n        case 'Print':\n          const input = getParamValue('x', node, tensorMap, context) as Tensor;\n          const data =\n              getParamValue('data', node, tensorMap, context) as Tensor[];\n          const message =\n              getParamValue('message', node, tensorMap, context) as string;\n          const summarize =\n              getParamValue('summarize', node, tensorMap, context) as number;\n          console.warn(\n              'The graph has a tf.print() operation,' +\n              'usually used for debugging, which slows down performance.');\n          console.log(message);\n          for (let i = 0; i < data.length; i++) {\n            console.log(Array.prototype.slice.call(data[i].dataSync())\n                            .slice(0, summarize));\n          }\n          return [input];\n\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'graph';\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {DataType, keep, scalar, stack, Tensor, tidy, unstack, util} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\n/**\n * Hashtable contains a set of tensors, which can be accessed by key.\n */\nexport class HashTable {\n  readonly handle: Tensor;\n\n  // tslint:disable-next-line: no-any\n  private tensorMap: Map<any, Tensor>;\n\n  get id() {\n    return this.handle.id;\n  }\n\n  /**\n   * Constructor of HashTable. Creates a hash table.\n   *\n   * @param keyDType `dtype` of the table keys.\n   * @param valueDType `dtype` of the table values.\n   */\n  constructor(readonly keyDType: DataType, readonly valueDType: DataType) {\n    this.handle = scalar(0);\n    // tslint:disable-next-line: no-any\n    this.tensorMap = new Map<any, Tensor>();\n\n    keep(this.handle);\n  }\n\n  /**\n   * Dispose the tensors and handle and clear the hashtable.\n   */\n  clearAndClose() {\n    this.tensorMap.forEach(value => value.dispose());\n    this.tensorMap.clear();\n    this.handle.dispose();\n  }\n\n  /**\n   * The number of items in the hash table.\n   */\n  size(): number {\n    return this.tensorMap.size;\n  }\n\n  /**\n   * The number of items in the hash table as a rank-0 tensor.\n   */\n  tensorSize(): Tensor {\n    return tfOps.scalar(this.size(), 'int32');\n  }\n\n  /**\n   * Replaces the contents of the table with the specified keys and values.\n   * @param keys Keys to store in the hashtable.\n   * @param values Values to store in the hashtable.\n   */\n  async import(keys: Tensor, values: Tensor): Promise<Tensor> {\n    this.checkKeyAndValueTensor(keys, values);\n\n    // We only store the primitive values of the keys, this allows lookup\n    // to be O(1).\n    const $keys = await keys.data();\n\n    // Clear the hashTable before inserting new values.\n    this.tensorMap.forEach(value => value.dispose());\n    this.tensorMap.clear();\n\n    return tidy(() => {\n      const $values = unstack(values);\n\n      const keysLength = $keys.length;\n      const valuesLength = $values.length;\n\n      util.assert(\n          keysLength === valuesLength,\n          () => `The number of elements doesn't match, keys has ` +\n              `${keysLength} elements, the values has ${valuesLength} ` +\n              `elements.`);\n\n      for (let i = 0; i < keysLength; i++) {\n        const key = $keys[i];\n        const value = $values[i];\n\n        keep(value);\n        this.tensorMap.set(key, value);\n      }\n\n      return this.handle;\n    });\n  }\n\n  /**\n   * Looks up keys in a hash table, outputs the corresponding values.\n   *\n   * Performs batch lookups, for every element in the key tensor, `find`\n   * stacks the corresponding value into the return tensor.\n   *\n   * If an element is not present in the table, the given `defaultValue` is\n   * used.\n   *\n   * @param keys Keys to look up. Must have the same type as the keys of the\n   *     table.\n   * @param defaultValue The scalar `defaultValue` is the value output for keys\n   *     not present in the table. It must also be of the same type as the\n   *     table values.\n   */\n  async find(keys: Tensor, defaultValue: Tensor): Promise<Tensor> {\n    this.checkKeyAndValueTensor(keys, defaultValue);\n\n    const $keys = await keys.data();\n\n    return tidy(() => {\n      const result: Tensor[] = [];\n\n      for (let i = 0; i < $keys.length; i++) {\n        const key = $keys[i];\n\n        const value = this.findWithDefault(key, defaultValue);\n        result.push(value);\n      }\n\n      return stack(result);\n    });\n  }\n\n  // tslint:disable-next-line: no-any\n  private findWithDefault(key: any, defaultValue: Tensor): Tensor {\n    const result = this.tensorMap.get(key);\n\n    return result != null ? result : defaultValue;\n  }\n\n  private checkKeyAndValueTensor(key: Tensor, value: Tensor) {\n    if (key.dtype !== this.keyDType) {\n      throw new Error(\n          `Expect key dtype ${this.keyDType}, but got ` +\n          `${key.dtype}`);\n    }\n\n    if (value.dtype !== this.valueDType) {\n      throw new Error(\n          `Expect value dtype ${this.valueDType}, but got ` +\n          `${value.dtype}`);\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {HashTable} from '../../executor/hash_table';\nimport {ResourceManager} from '../../executor/resource_manager';\nimport {InternalOpAsyncExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpAsyncExecutor = async(\n    node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n    resourceManager: ResourceManager): Promise<Tensor[]> => {\n  switch (node.op) {\n    case 'HashTable':\n    case 'HashTableV2': {\n      const existingTableHandle =\n          resourceManager.getHashTableHandleByName(node.name);\n      // Table is shared with initializer.\n      if (existingTableHandle != null) {\n        return [existingTableHandle];\n      } else {\n        const keyDType =\n            getParamValue('keyDType', node, tensorMap, context) as DataType;\n        const valueDType =\n            getParamValue('valueDType', node, tensorMap, context) as DataType;\n\n        const hashTable = new HashTable(keyDType, valueDType);\n        resourceManager.addHashTable(node.name, hashTable);\n        return [hashTable.handle];\n      }\n    }\n    case 'InitializeTable':\n    case 'InitializeTableV2':\n    case 'LookupTableImport':\n    case 'LookupTableImportV2': {\n      const handle = getParamValue(\n                         'tableHandle', node, tensorMap, context,\n                         resourceManager) as Tensor;\n      const keys = getParamValue('keys', node, tensorMap, context) as Tensor;\n      const values =\n          getParamValue('values', node, tensorMap, context) as Tensor;\n\n      const hashTable = resourceManager.getHashTableById(handle.id);\n\n      return [await hashTable.import(keys, values)];\n    }\n    case 'LookupTableFind':\n    case 'LookupTableFindV2': {\n      const handle = getParamValue(\n                         'tableHandle', node, tensorMap, context,\n                         resourceManager) as Tensor;\n      const keys = getParamValue('keys', node, tensorMap, context) as Tensor;\n      const defaultValue =\n          getParamValue('defaultValue', node, tensorMap, context) as Tensor;\n\n      const hashTable = resourceManager.getHashTableById(handle.id);\n      return [await hashTable.find(keys, defaultValue)];\n    }\n    case 'LookupTableSize':\n    case 'LookupTableSizeV2': {\n      const handle = getParamValue(\n                         'tableHandle', node, tensorMap, context,\n                         resourceManager) as Tensor;\n\n      const hashTable = resourceManager.getHashTableById(handle.id);\n      return [hashTable.tensorSize()];\n    }\n    default:\n      throw TypeError(`Node type ${node.op} is not implemented`);\n  }\n};\n\nexport const CATEGORY = 'hash_table';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap,\n     context: ExecutionContext, ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'ResizeBilinear': {\n          const images =\n              getParamValue('images', node, tensorMap, context) as Tensor;\n          const size =\n              getParamValue('size', node, tensorMap, context) as number[];\n          const alignCorners =\n              getParamValue('alignCorners', node, tensorMap, context) as\n              boolean;\n          const halfPixelCenters =\n              getParamValue('halfPixelCenters', node, tensorMap, context) as\n              boolean;\n          return [ops.image.resizeBilinear(\n              images as Tensor3D | Tensor4D, [size[0], size[1]], alignCorners,\n              halfPixelCenters)];\n        }\n        case 'ResizeNearestNeighbor': {\n          const images =\n              getParamValue('images', node, tensorMap, context) as Tensor;\n          const size =\n              getParamValue('size', node, tensorMap, context) as number[];\n          const alignCorners =\n              getParamValue('alignCorners', node, tensorMap, context) as\n              boolean;\n          const halfPixelCenters =\n              getParamValue('halfPixelCenters', node, tensorMap, context) as\n              boolean;\n          return [ops.image.resizeNearestNeighbor(\n              images as Tensor3D | Tensor4D, [size[0], size[1]], alignCorners,\n              halfPixelCenters)];\n        }\n        case 'CropAndResize': {\n          const image =\n              getParamValue('image', node, tensorMap, context) as Tensor;\n          const boxes =\n              getParamValue('boxes', node, tensorMap, context) as Tensor;\n          const boxInd =\n              getParamValue('boxInd', node, tensorMap, context) as Tensor;\n          const cropSize =\n              getParamValue('cropSize', node, tensorMap, context) as number[];\n          const method =\n              getParamValue('method', node, tensorMap, context) as string;\n          const extrapolationValue =\n              getParamValue('extrapolationValue', node, tensorMap, context) as\n              number;\n          return [ops.image.cropAndResize(\n              image as Tensor4D, boxes as Tensor2D, boxInd as Tensor1D,\n              cropSize as [number, number], method as 'bilinear' | 'nearest',\n              extrapolationValue)];\n        }\n        case 'ImageProjectiveTransformV3': {\n          const images =\n              getParamValue('images', node, tensorMap, context) as Tensor;\n          const transforms =\n              getParamValue('transforms', node, tensorMap, context) as Tensor;\n          const outputShape =\n              getParamValue('outputShape', node, tensorMap, context) as\n              number[];\n          const fillValue =\n              getParamValue('fillValue', node, tensorMap, context) as number;\n          const interpolation =\n              getParamValue('interpolation', node, tensorMap, context) as\n              string;\n          const fillMode =\n              getParamValue('fillMode', node, tensorMap, context) as string;\n          return [ops.image.transform(\n              images as Tensor4D,\n              transforms as Tensor2D,\n              interpolation.toLowerCase() as 'bilinear' | 'nearest',\n              fillMode.toLowerCase() as 'constant' | 'reflect' | 'wrap' | 'nearest',\n              fillValue,\n              outputShape as [number, number])];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'image';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'Equal': {\n          return [ops.equal(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'NotEqual': {\n          return [ops.notEqual(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'Greater': {\n          return [ops.greater(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'GreaterEqual': {\n          return [ops.greaterEqual(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'Less': {\n          return [ops.less(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'LessEqual': {\n          return [ops.lessEqual(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'LogicalAnd': {\n          return [ops.logicalAnd(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'LogicalNot': {\n          return [ops.logicalNot(\n              getParamValue('a', node, tensorMap, context) as Tensor)];\n        }\n        case 'LogicalOr': {\n          return [ops.logicalOr(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'Select':\n        case 'SelectV2': {\n          return [ops.where(\n              getParamValue('condition', node, tensorMap, context) as Tensor,\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        case 'BitwiseAnd': {\n          return [ops.bitwiseAnd(\n              getParamValue('a', node, tensorMap, context) as Tensor,\n              getParamValue('b', node, tensorMap, context) as Tensor)];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'logical';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'BatchMatMul':\n        case 'BatchMatMulV2':\n        case 'MatMul':\n          return [ops.matMul(\n              getParamValue('a', node, tensorMap, context) as Tensor2D,\n              getParamValue('b', node, tensorMap, context) as Tensor2D,\n              getParamValue('transposeA', node, tensorMap, context) as boolean,\n              getParamValue('transposeB', node, tensorMap, context) as\n                  boolean)];\n\n        case 'Einsum':\n          return [ops.einsum(\n              getParamValue('equation', node, tensorMap, context) as string,\n              ...getParamValue('tensors', node, tensorMap, context) as\n                  Tensor[])];\n\n        case 'Transpose':\n          return [ops.transpose(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('perm', node, tensorMap, context) as number[])];\n\n        case '_FusedMatMul':\n          const [extraOp, activationFunc] =\n              (getParamValue('fusedOps', node, tensorMap, context) as string[]);\n\n          const isBiasAdd = extraOp === 'biasadd';\n          const isPrelu = activationFunc === 'prelu';\n\n          const numArgs =\n              (getParamValue('numArgs', node, tensorMap, context) as number);\n          const leakyreluAlpha =\n              getParamValue('leakyreluAlpha', node, tensorMap, context) as\n              number;\n\n          if (isBiasAdd) {\n            if (isPrelu && numArgs !== 2) {\n              throw new Error(\n                  'Fused MatMul with BiasAdd and Prelu must have two ' +\n                  'extra arguments: bias and alpha.');\n            }\n            if (!isPrelu && numArgs !== 1) {\n              throw new Error(\n                  'Fused MatMul with BiasAdd must have one extra argument: bias.');\n            }\n          }\n          const [biasArg, preluArg] =\n              getParamValue('args', node, tensorMap, context) as Tensor[];\n          return [ops.fused.matMul({\n            a: getParamValue('a', node, tensorMap, context) as Tensor2D,\n            b: getParamValue('b', node, tensorMap, context) as Tensor2D,\n            transposeA: getParamValue('transposeA', node, tensorMap, context) as\n                boolean,\n            transposeB: getParamValue('transposeB', node, tensorMap, context) as\n                boolean,\n            bias: biasArg,\n            activation: activationFunc as tfOps.fused.Activation,\n            preluActivationWeights: preluArg,\n            leakyreluAlpha\n          })];\n\n        case 'MatrixBandPart':\n          return [ops.linalg.bandPart(\n              getParamValue('a', node, tensorMap, context) as Tensor2D,\n              getParamValue('numLower', node, tensorMap, context) as Scalar,\n              getParamValue('numUpper', node, tensorMap, context) as Scalar)];\n\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'matrices';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor3D, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap,\n     context: ExecutionContext, ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'EuclideanNorm':\n          return [ops.euclideanNorm(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('axis', node, tensorMap, context) as number[],\n              getParamValue('keepDims', node, tensorMap, context) as boolean)];\n        case 'FusedBatchNorm':\n        case 'FusedBatchNormV2': {\n          return [ops.batchNorm(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('mean', node, tensorMap, context) as Tensor,\n              getParamValue('variance', node, tensorMap, context) as Tensor,\n              getParamValue('offset', node, tensorMap, context) as Tensor,\n              getParamValue('scale', node, tensorMap, context) as Tensor,\n              getParamValue('epsilon', node, tensorMap, context) as number)];\n        }\n        case 'FusedBatchNormV3': {\n          return [ops.batchNorm(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('mean', node, tensorMap, context) as Tensor,\n              getParamValue('variance', node, tensorMap, context) as Tensor,\n              getParamValue('offset', node, tensorMap, context) as Tensor,\n              getParamValue('scale', node, tensorMap, context) as Tensor,\n              getParamValue('epsilon', node, tensorMap, context) as number)];\n        }\n        case 'LRN': {\n          return [ops.localResponseNormalization(\n              getParamValue('x', node, tensorMap, context) as Tensor3D |\n                  Tensor4D,\n              getParamValue('radius', node, tensorMap, context) as number,\n              getParamValue('bias', node, tensorMap, context) as number,\n              getParamValue('alpha', node, tensorMap, context) as number,\n              getParamValue('beta', node, tensorMap, context) as number)];\n        }\n        case 'Softmax': {\n          return [ops.softmax(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        case 'LogSoftmax': {\n          return [ops.logSoftmax(\n              getParamValue('x', node, tensorMap, context) as Tensor)];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'normalization';\n", "/**\n * @license\n * Copyright 2022 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'RaggedGather': {\n          const {\n            outputNestedSplits,\n            outputDenseValues,\n          } =\n              ops.raggedGather(\n                  getParamValue(\n                      'paramsNestedSplits', node, tensorMap, context) as\n                      Tensor[],\n                  getParamValue(\n                      'paramsDenseValues', node, tensorMap, context) as Tensor,\n                  getParamValue('indices', node, tensorMap, context) as Tensor,\n                  getParamValue('outputRaggedRank', node, tensorMap, context) as\n                      number);\n          return outputNestedSplits.concat(outputDenseValues);\n        }\n        case 'RaggedRange': {\n          const {rtNestedSplits, rtDenseValues} = ops.raggedRange(\n              getParamValue('starts', node, tensorMap, context) as Tensor,\n              getParamValue('limits', node, tensorMap, context) as Tensor,\n              getParamValue('splits', node, tensorMap, context) as Tensor);\n          return [rtNestedSplits, rtDenseValues];\n        }\n        case 'RaggedTensorToTensor': {\n          return [ops.raggedTensorToTensor(\n              getParamValue('shape', node, tensorMap, context) as Tensor,\n              getParamValue('values', node, tensorMap, context) as Tensor1D,\n              getParamValue('defaultValue', node, tensorMap, context) as Tensor,\n              getParamValue('rowPartitionTensors', node, tensorMap, context) as\n                  Tensor[],\n              getParamValue('rowPartitionTypes', node, tensorMap, context) as\n                  string[])];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'ragged';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap,\n     context: ExecutionContext, ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'Max': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          const keepDims =\n              getParamValue('keepDims', node, tensorMap, context) as boolean;\n          return [ops.max(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              keepDims)];\n        }\n        case 'Mean': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          const keepDims =\n              getParamValue('keepDims', node, tensorMap, context) as boolean;\n          return [ops.mean(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              keepDims)];\n        }\n        case 'Min': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          const keepDims =\n              getParamValue('keepDims', node, tensorMap, context) as boolean;\n          return [ops.min(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              keepDims)];\n        }\n        case 'Sum': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          const keepDims =\n              getParamValue('keepDims', node, tensorMap, context) as boolean;\n          return [ops.sum(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              keepDims)];\n        }\n        case 'All': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          const keepDims =\n              getParamValue('keepDims', node, tensorMap, context) as boolean;\n          return [ops.all(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              keepDims)];\n        }\n        case 'Any': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          const keepDims =\n              getParamValue('keepDims', node, tensorMap, context) as boolean;\n          return [ops.any(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              keepDims)];\n        }\n        case 'ArgMax': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          return [ops.argMax(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n        }\n        case 'ArgMin': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          return [ops.argMin(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n        }\n        case 'Prod': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          const keepDims =\n              getParamValue('keepDims', node, tensorMap, context) as boolean;\n          return [ops.prod(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              keepDims)];\n        }\n        case 'Cumprod': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          const exclusive =\n              getParamValue('exclusive', node, tensorMap, context) as boolean;\n          const reverse =\n              getParamValue('reverse', node, tensorMap, context) as boolean;\n          return [ops.cumprod(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              exclusive, reverse)];\n        }\n        case 'Cumsum': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          const exclusive =\n              getParamValue('exclusive', node, tensorMap, context) as boolean;\n          const reverse =\n              getParamValue('reverse', node, tensorMap, context) as boolean;\n          return [ops.cumsum(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis,\n              exclusive, reverse)];\n        }\n        case 'Bincount':\n          const x = getParamValue('x', node, tensorMap, context) as Tensor1D;\n          const weights =\n              getParamValue('weights', node, tensorMap, context) as Tensor1D;\n          const size =\n              getParamValue('size', node, tensorMap, context) as number;\n\n          return [ops.bincount(x, weights, size)];\n        case 'DenseBincount': {\n          const x = getParamValue('x', node, tensorMap, context) as Tensor1D |\n              Tensor2D;\n          const weights =\n              getParamValue('weights', node, tensorMap, context) as Tensor1D |\n              Tensor2D;\n          const size =\n              getParamValue('size', node, tensorMap, context) as number;\n\n          const binaryOutput =\n              getParamValue('binaryOutput', node, tensorMap, context) as\n              boolean;\n\n          return [ops.denseBincount(x, weights, size, binaryOutput)];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'reduction';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D, tidy, util} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'ConcatV2':\n        case 'Concat': {\n          const n = getParamValue('n', node, tensorMap, context) as number;\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          let inputs =\n              getParamValue('tensors', node, tensorMap, context) as Tensor[];\n          inputs = inputs.slice(0, n);\n          return [ops.concat(inputs, axis)];\n        }\n        case 'Gather': {\n          const input = getParamValue('x', node, tensorMap, context) as Tensor;\n          const indices =\n              getParamValue('indices', node, tensorMap, context) as Tensor1D;\n          return [ops.gather(input, ops.cast(indices, 'int32'), 0)];\n        }\n        case 'GatherV2': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          const batchDims =\n              getParamValue('batchDims', node, tensorMap, context) as number;\n          const input = getParamValue('x', node, tensorMap, context) as Tensor;\n          const indices =\n              getParamValue('indices', node, tensorMap, context) as Tensor1D;\n          return [ops.gather(\n              input, ops.cast(indices, 'int32'), axis, batchDims)];\n        }\n        case 'Reverse': {\n          const dims =\n              getParamValue('dims', node, tensorMap, context) as boolean[];\n          const axis = [];\n          for (let i = 0; i < dims.length; i++) {\n            if (dims[i]) {\n              axis.push(i);\n            }\n          }\n          const input = getParamValue('x', node, tensorMap, context) as Tensor;\n          return [ops.reverse(input, axis)];\n        }\n        case 'ReverseV2': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          const input = getParamValue('x', node, tensorMap, context) as Tensor;\n          return [ops.reverse(input, axis)];\n        }\n        case 'Slice': {\n          // tslint:disable-next-line:no-any\n          const begin = getParamValue('begin', node, tensorMap, context) as any;\n          // tslint:disable-next-line:no-any\n          const size = getParamValue('size', node, tensorMap, context) as any;\n          return [ops.slice(\n              getParamValue('x', node, tensorMap, context) as Tensor, begin,\n              size)];\n        }\n        case 'StridedSlice': {\n          const begin =\n              getParamValue('begin', node, tensorMap, context) as number[];\n          const end =\n              getParamValue('end', node, tensorMap, context) as number[];\n          const strides =\n              getParamValue('strides', node, tensorMap, context) as number[];\n          const beginMask =\n              getParamValue('beginMask', node, tensorMap, context) as number;\n          const endMask =\n              getParamValue('endMask', node, tensorMap, context) as number;\n          const ellipsisMask =\n              getParamValue('ellipsisMask', node, tensorMap, context) as number;\n          const newAxisMask =\n              getParamValue('newAxisMask', node, tensorMap, context) as number;\n          const shrinkAxisMask =\n              getParamValue('shrinkAxisMask', node, tensorMap, context) as\n              number;\n          const tensor = getParamValue('x', node, tensorMap, context) as Tensor;\n\n          return [ops.stridedSlice(\n              tensor, begin, end, strides, beginMask, endMask, ellipsisMask,\n              newAxisMask, shrinkAxisMask)];\n        }\n        case 'Pack': {\n          return tidy(() => {\n            const axis =\n                getParamValue('axis', node, tensorMap, context) as number;\n            const tensors =\n                getParamValue('tensors', node, tensorMap, context) as Tensor[];\n            // Reshape the tensors to the first tensor's shape if they don't\n            // match.\n            const shape = tensors[0].shape;\n            const squeezedShape = ops.squeeze(tensors[0]).shape;\n            const mapped = tensors.map(tensor => {\n              const sameShape = util.arraysEqual(tensor.shape, shape);\n              if (!sameShape &&\n                  !util.arraysEqual(ops.squeeze(tensor).shape, squeezedShape)) {\n                throw new Error('the input tensors shape does not match');\n              }\n              return sameShape ? tensor : ops.reshape(tensor, shape);\n            });\n            return [ops.stack(mapped, axis)];\n          });\n        }\n        case 'Unpack': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          const tensor =\n              getParamValue('tensor', node, tensorMap, context) as Tensor;\n          return ops.unstack(tensor, axis);\n        }\n        case 'Tile': {\n          const reps =\n              getParamValue('reps', node, tensorMap, context) as number[];\n          return [ops.tile(\n              getParamValue('x', node, tensorMap, context) as Tensor, reps)];\n        }\n        case 'Split':\n        case 'SplitV': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          const numOrSizeSplits =\n              getParamValue('numOrSizeSplits', node, tensorMap, context) as\n                  number |\n              number[];\n          const tensor = getParamValue('x', node, tensorMap, context) as Tensor;\n\n          return ops.split(tensor, numOrSizeSplits, axis);\n        }\n        case 'ScatterNd': {\n          const indices =\n              getParamValue('indices', node, tensorMap, context) as Tensor;\n          const values =\n              getParamValue('values', node, tensorMap, context) as Tensor;\n          const shape =\n              getParamValue('shape', node, tensorMap, context) as number[];\n          return [ops.scatterND(indices, values, shape)];\n        }\n        case 'GatherNd': {\n          const x = getParamValue('x', node, tensorMap, context) as Tensor;\n          const indices =\n              getParamValue('indices', node, tensorMap, context) as Tensor;\n          return [ops.gatherND(x, indices)];\n        }\n        case 'SparseToDense': {\n          const indices =\n              getParamValue('sparseIndices', node, tensorMap, context) as\n              Tensor;\n          const shape =\n              getParamValue('outputShape', node, tensorMap, context) as\n              number[];\n          const sparseValues =\n              getParamValue('sparseValues', node, tensorMap, context) as Tensor;\n          const defaultValue =\n              getParamValue('defaultValue', node, tensorMap, context) as Scalar;\n          return [ops.sparseToDense(\n              indices, sparseValues, shape,\n              sparseValues.dtype === defaultValue.dtype ?\n                  defaultValue :\n                  ops.cast(defaultValue, sparseValues.dtype))];\n        }\n        case 'TensorScatterUpdate': {\n          const indices =\n              getParamValue('indices', node, tensorMap, context) as Tensor;\n          const values =\n              getParamValue('values', node, tensorMap, context) as Tensor;\n          const tensor =\n              getParamValue('tensor', node, tensorMap, context) as Tensor;\n          return [ops.tensorScatterUpdate(tensor, indices, values)];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'slice_join';\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D, Tensor2D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap,\n     context: ExecutionContext, ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'SparseFillEmptyRows': {\n          const {\n            outputIndices,\n            outputValues,\n            emptyRowIndicator,\n            reverseIndexMap\n          } =\n              ops.sparse.sparseFillEmptyRows(\n                  getParamValue('indices', node, tensorMap, context) as\n                      Tensor2D,\n                  getParamValue('values', node, tensorMap, context) as Tensor1D,\n                  getParamValue('denseShape', node, tensorMap, context) as\n                      Tensor1D,\n                  getParamValue('defaultValue', node, tensorMap, context) as\n                      Scalar);\n          return [\n            outputIndices, outputValues, emptyRowIndicator, reverseIndexMap\n          ];\n        }\n        case 'SparseReshape': {\n          const {outputIndices, outputShape} = ops.sparse.sparseReshape(\n              getParamValue('inputIndices', node, tensorMap, context) as\n                  Tensor2D,\n              getParamValue('inputShape', node, tensorMap, context) as Tensor1D,\n              getParamValue('newShape', node, tensorMap, context) as Tensor1D);\n          return [outputIndices, outputShape];\n        }\n        case 'SparseSegmentMean': {\n          const outputData = ops.sparse.sparseSegmentMean(\n              getParamValue('data', node, tensorMap, context) as Tensor,\n              getParamValue('indices', node, tensorMap, context) as Tensor1D,\n              getParamValue('segmentIds', node, tensorMap, context) as\n                  Tensor1D);\n          return [outputData];\n        }\n        case 'SparseSegmentSum': {\n          const outputData = ops.sparse.sparseSegmentSum(\n              getParamValue('data', node, tensorMap, context) as Tensor,\n              getParamValue('indices', node, tensorMap, context) as Tensor1D,\n              getParamValue('segmentIds', node, tensorMap, context) as\n                  Tensor1D);\n          return [outputData];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'sparse';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps): Tensor[] => {\n          switch (node.op) {\n            case 'FFT': {\n              return [ops.fft(\n                  getParamValue('x', node, tensorMap, context) as Tensor)];\n            }\n            case 'IFFT': {\n              return [ops.ifft(\n                  getParamValue('x', node, tensorMap, context) as Tensor)];\n            }\n            case 'RFFT': {\n              return [ops.rfft(\n                  getParamValue('x', node, tensorMap, context) as Tensor)];\n            }\n            case 'IRFFT': {\n              return [ops.irfft(\n                  getParamValue('x', node, tensorMap, context) as Tensor)];\n            }\n            default:\n              throw TypeError(`Node type ${node.op} is not implemented`);\n          }\n        };\n\nexport const CATEGORY = 'spectral';\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Scalar, Tensor, Tensor1D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap,\n     context: ExecutionContext, ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'StaticRegexReplace': {\n          return [ops.string.staticRegexReplace(\n            getParamValue('input', node, tensorMap, context) as Tensor,\n            getParamValue('pattern', node, tensorMap, context) as string,\n            getParamValue('rewrite', node, tensorMap, context) as string,\n            getParamValue('replaceGlobal', node, tensorMap, context) as boolean,\n          )];\n        }\n        case 'StringNGrams': {\n          const {nGrams, nGramsSplits} = ops.string.stringNGrams(\n              getParamValue('data', node, tensorMap, context) as Tensor1D,\n              getParamValue('dataSplits', node, tensorMap, context) as Tensor,\n              getParamValue('separator', node, tensorMap, context) as string,\n              getParamValue('nGramWidths', node, tensorMap, context) as\n                  number[],\n              getParamValue('leftPad', node, tensorMap, context) as string,\n              getParamValue('rightPad', node, tensorMap, context) as string,\n              getParamValue('padWidth', node, tensorMap, context) as number,\n              getParamValue(\n                  'preserveShortSequences', node, tensorMap, context) as\n                  boolean);\n          return [nGrams, nGramsSplits];\n        }\n        case 'StringSplit': {\n          const {indices, values, shape} = ops.string.stringSplit(\n              getParamValue('input', node, tensorMap, context) as Tensor1D,\n              getParamValue('delimiter', node, tensorMap, context) as Scalar,\n              getParamValue('skipEmpty', node, tensorMap, context) as boolean);\n          return [indices, values, shape];\n        }\n        case 'StringToHashBucketFast': {\n          const output = ops.string.stringToHashBucketFast(\n              getParamValue('input', node, tensorMap, context) as Tensor,\n              getParamValue('numBuckets', node, tensorMap, context) as number);\n          return [output];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'string';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor, Tensor4D} from '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter';\n\nimport {NamedTensorsMap} from '../../data/types';\nimport {ExecutionContext} from '../../executor/execution_context';\nimport {InternalOpExecutor, Node} from '../types';\n\nimport {getParamValue} from './utils';\n\nexport const executeOp: InternalOpExecutor =\n    (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n     ops = tfOps): Tensor[] => {\n      switch (node.op) {\n        case 'Cast': {\n          return [ops.cast(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('dtype', node, tensorMap, context) as 'int32' |\n                  'float32' | 'bool')];\n        }\n        case 'ExpandDims': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number;\n          return [ops.expandDims(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n        }\n        case 'Squeeze': {\n          const axis =\n              getParamValue('axis', node, tensorMap, context) as number[];\n          return [ops.squeeze(\n              getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n        }\n\n        case 'Reshape': {\n          return [ops.reshape(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('shape', node, tensorMap, context) as number[])];\n        }\n        case 'EnsureShape': {\n          return [ops.ensureShape(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('shape', node, tensorMap, context) as number[])];\n        }\n        case 'MirrorPad': {\n          return [ops.mirrorPad(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('padding', node, tensorMap, context) as\n                  Array<[number, number]>,\n              getParamValue('mode', node, tensorMap, context) as 'reflect' |\n                  'symmetric')];\n        }\n        case 'PadV2':\n        case 'Pad': {\n          return [ops.pad(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('padding', node, tensorMap, context) as\n                  Array<[number, number]>,\n              getParamValue('constantValue', node, tensorMap, context) as\n                  number)];\n        }\n        case 'SpaceToBatchND': {\n          const blockShape =\n              getParamValue('blockShape', node, tensorMap, context) as number[];\n          const paddings =\n              getParamValue('paddings', node, tensorMap, context) as number[][];\n          return [ops.spaceToBatchND(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              blockShape, paddings)];\n        }\n        case 'BatchToSpaceND': {\n          const blockShape =\n              getParamValue('blockShape', node, tensorMap, context) as number[];\n          const crops =\n              getParamValue('crops', node, tensorMap, context) as number[][];\n          return [ops.batchToSpaceND(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              blockShape, crops)];\n        }\n        case 'DepthToSpace': {\n          const blockSize =\n              getParamValue('blockSize', node, tensorMap, context) as number;\n          const dataFormat =\n              (getParamValue('dataFormat', node, tensorMap, context) as\n               string).toUpperCase() as 'NHWC' |\n              'NCHW';\n          return [ops.depthToSpace(\n              getParamValue('x', node, tensorMap, context) as Tensor4D,\n              blockSize, dataFormat)];\n        }\n        case 'BroadcastTo': {\n          return [ops.broadcastTo(\n              getParamValue('x', node, tensorMap, context) as Tensor,\n              getParamValue('shape', node, tensorMap, context) as number[])];\n        }\n        case 'BroadcastArgs': {\n          return [ops.broadcastArgs(\n              getParamValue('s0', node, tensorMap, context) as Tensor,\n              getParamValue('s1', node, tensorMap, context) as Tensor)];\n        }\n        default:\n          throw TypeError(`Node type ${node.op} is not implemented`);\n      }\n    };\n\nexport const CATEGORY = 'transformation';\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../data/types';\nimport {ExecutionContext} from '../executor/execution_context';\nimport {ResourceManager} from '../executor/resource_manager';\n\nimport {NodeValueImpl} from './custom_op/node_value_impl';\nimport {getRegisteredOp} from './custom_op/register';\nimport * as arithmetic from './executors/arithmetic_executor';\nimport * as basicMath from './executors/basic_math_executor';\nimport * as control from './executors/control_executor';\nimport * as convolution from './executors/convolution_executor';\nimport * as creation from './executors/creation_executor';\nimport * as dynamic from './executors/dynamic_executor';\nimport * as evaluation from './executors/evaluation_executor';\nimport * as graph from './executors/graph_executor';\nimport * as hashTable from './executors/hash_table_executor';\nimport * as image from './executors/image_executor';\nimport * as logical from './executors/logical_executor';\nimport * as matrices from './executors/matrices_executor';\nimport * as normalization from './executors/normalization_executor';\nimport * as ragged from './executors/ragged_executor';\nimport * as reduction from './executors/reduction_executor';\nimport * as sliceJoin from './executors/slice_join_executor';\nimport * as sparse from './executors/sparse_executor';\nimport * as spectral from './executors/spectral_executor';\nimport * as string from './executors/string_executor';\nimport * as transformation from './executors/transformation_executor';\nimport {Node} from './types';\n\n/**\n * Executes the op defined by the node object.\n * @param node\n * @param tensorMap contains tensors for executed nodes and weights\n * @param context contains tensors and information for running the current node.\n * @param resourceManager Optional. Contains global resources of the model.\n */\nexport function executeOp(\n    node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n    resourceManager?: ResourceManager, tidy = tfc.tidy): tfc.Tensor[]|\n    Promise<tfc.Tensor[]> {\n  const value =\n      ((node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) => {\n        switch (node.category) {\n          case 'arithmetic':\n            return tidy(() => arithmetic.executeOp(node, tensorMap, context));\n          case 'basic_math':\n            return tidy(() => basicMath.executeOp(node, tensorMap, context));\n          case 'control':\n            return control.executeOp(node, tensorMap, context);\n          case 'convolution':\n            return tidy(() => convolution.executeOp(node, tensorMap, context));\n          case 'creation':\n            return tidy(() => creation.executeOp(node, tensorMap, context));\n          case 'dynamic':\n            return dynamic.executeOp(node, tensorMap, context);\n          case 'evaluation':\n            return tidy(() => evaluation.executeOp(node, tensorMap, context));\n          case 'image':\n            return tidy(() => image.executeOp(node, tensorMap, context));\n          case 'graph':\n            return tidy(() => graph.executeOp(node, tensorMap, context));\n          case 'logical':\n            return tidy(() => logical.executeOp(node, tensorMap, context));\n          case 'matrices':\n            return tidy(() => matrices.executeOp(node, tensorMap, context));\n          case 'normalization':\n            return tidy(\n                () => normalization.executeOp(node, tensorMap, context));\n          case 'ragged':\n            return tidy(() => ragged.executeOp(node, tensorMap, context));\n          case 'reduction':\n            return tidy(() => reduction.executeOp(node, tensorMap, context));\n          case 'slice_join':\n            return tidy(() => sliceJoin.executeOp(node, tensorMap, context));\n          case 'sparse':\n            return tidy(() => sparse.executeOp(node, tensorMap, context));\n          case 'spectral':\n            return tidy(() => spectral.executeOp(node, tensorMap, context));\n          case 'string':\n            return tidy(() => string.executeOp(node, tensorMap, context));\n          case 'transformation':\n            return tidy(\n                () => transformation.executeOp(node, tensorMap, context));\n          case 'hash_table':\n            return hashTable.executeOp(\n                node, tensorMap, context, resourceManager);\n          case 'custom':\n            const opMapper = getRegisteredOp(node.op);\n            if (opMapper && opMapper.customExecutor) {\n              return opMapper.customExecutor(\n                  new NodeValueImpl(node, tensorMap, context));\n            } else {\n              throw TypeError(`Custom op ${node.op} is not registered.`);\n            }\n          default:\n            throw TypeError(\n                `Unknown op '${node.op}'. File an issue at ` +\n                `https://github.com/tensorflow/tfjs/issues so we can add it` +\n                `, or register a custom execution with tf.registerOp()`);\n        }\n      })(node, tensorMap, context);\n  if (tfc.util.isPromise(value)) {\n    return value.then((data) => [].concat(data));\n  }\n  return [].concat(value);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Tensor} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap, TensorArrayMap, TensorListMap} from '../data/types';\n\nimport {TensorArray} from './tensor_array';\nimport {TensorList} from './tensor_list';\nimport {FunctionExecutor} from './types';\n\nexport interface ExecutionContextInfo {\n  id: number;           // the unique id of the context info\n  frameName: string;    // The frame name of the loop, this comes from\n                        // the TensorFlow NodeDef.\n  iterationId: number;  // The iteration id of the loop\n}\n\n/**\n * ExecutionContext captures the runtime environment of the node. It keeps\n * track of the current frame and iteration for the control flow ops.\n *\n * For example, typical Dynamic RNN model may contain loops, for which\n * TensorFlow will generate graphs with Enter/Exit nodes to control the\n * current execution frame, and NextIteration Nodes for iteration id increment.\n * For model with branch logic, TensorFLow will generate Switch/Merge ops.\n */\nexport class ExecutionContext {\n  private rootContext = {id: 0, frameName: '', iterationId: 0};\n  private contexts: ExecutionContextInfo[] = [this.rootContext];\n  private lastId = 0;\n  private _currentContextIds: string[];\n\n  constructor(\n      readonly weightMap: NamedTensorsMap = {},\n      readonly tensorArrayMap: TensorArrayMap = {},\n      readonly tensorListMap: TensorListMap = {},\n      readonly functionMap: {[key: string]: FunctionExecutor} = {},\n      readonly parseNodeNameCache?: Map<string, [string, number, string?]>) {\n    this.generateCurrentContextIds();\n  }\n\n  private newFrame(id: number, frameName: string) {\n    return {id, frameName, iterationId: 0};\n  }\n\n  /**\n   * Set the current context\n   * @param contexts: ExecutionContextInfo[] the current path of execution\n   * frames\n   */\n  set currentContext(contexts: ExecutionContextInfo[]) {\n    if (this.contexts !== contexts) {\n      this.contexts = contexts;\n      this.generateCurrentContextIds();\n    }\n  }\n\n  get currentContext(): ExecutionContextInfo[] {\n    return this.contexts;\n  }\n\n  /**\n   * Returns the current context in string format.\n   */\n  get currentContextId(): string {\n    return this._currentContextIds[0];\n  }\n\n  /**\n   * Returns the current context and all parent contexts in string format.\n   * This allow access to the nodes in the current and parent frames.\n   */\n  get currentContextIds(): string[] {\n    return this._currentContextIds;\n  }\n\n  private generateCurrentContextIds() {\n    const names = [];\n    for (let i = 0; i < this.contexts.length - 1; i++) {\n      const contexts = this.contexts.slice(0, this.contexts.length - i);\n      names.push(this.contextIdforContexts(contexts));\n    }\n    names.push('');\n    this._currentContextIds = names;\n  }\n\n  private contextIdforContexts(contexts: ExecutionContextInfo[]) {\n    return contexts ?\n        contexts\n            .map(\n                context => (context.id === 0 && context.iterationId === 0) ?\n                    '' :\n                    `${context.frameName}-${context.iterationId}`)\n            .join('/') :\n        '';\n  }\n\n  /**\n   * Enter a new frame, a new context is pushed on the current context list.\n   * @param frameId new frame id\n   */\n  enterFrame(frameId: string) {\n    if (this.contexts) {\n      this.lastId++;\n      this.contexts = this.contexts.slice();\n      this.contexts.push(this.newFrame(this.lastId, frameId));\n      this._currentContextIds.unshift(this.contextIdforContexts(this.contexts));\n    }\n  }\n\n  /**\n   * Exit the current frame, the last context is removed from the current\n   * context list.\n   */\n  exitFrame() {\n    if (this.contexts && this.contexts.length > 1) {\n      this.contexts = this.contexts.slice();\n      this.contexts.splice(-1);\n      this.currentContextIds.shift();\n    } else {\n      throw new Error('Cannot exit frame, the context is empty');\n    }\n  }\n\n  /**\n   * Enter the next iteration of a loop, the iteration id of last context is\n   * increased.\n   */\n  nextIteration() {\n    if (this.contexts && this.contexts.length > 0) {\n      this.contexts = this.contexts.slice();\n      this.lastId++;\n      const context =\n          Object.assign({}, this.contexts[this.contexts.length - 1]);\n      context.iterationId += 1;\n      context.id = this.lastId;\n      this.contexts.splice(-1, 1, context);\n      this._currentContextIds.splice(\n          0, 1, this.contextIdforContexts(this.contexts));\n    } else {\n      throw new Error('Cannot increase frame iteration, the context is empty');\n    }\n  }\n\n  getWeight(name: string): Tensor[] {\n    return this.weightMap[name];\n  }\n\n  addTensorArray(tensorArray: TensorArray) {\n    this.tensorArrayMap[tensorArray.id] = tensorArray;\n  }\n\n  getTensorArray(id: number): TensorArray {\n    return this.tensorArrayMap[id];\n  }\n\n  addTensorList(tensorList: TensorList) {\n    this.tensorListMap[tensorList.id] = tensorList;\n  }\n\n  getTensorList(id: number): TensorList {\n    return this.tensorListMap[id];\n  }\n\n  dispose(keepIds: Set<number>) {\n    for (const key in this.tensorArrayMap) {\n      this.tensorArrayMap[key].clearAndClose(keepIds);\n    }\n\n    for (const key in this.tensorListMap) {\n      this.tensorListMap[key].clearAndClose(keepIds);\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {NamedTensorMap} from '@tensorflow/tfjs-core';\n\nimport {NamedTensorsMap} from '../data/types';\nimport {parseNodeName} from '../operations/executors/utils';\nimport {Graph, Node} from '../operations/types';\n\nexport interface ExecutionInfo {\n  inputs: NamedTensorMap;\n  outputs: Node[];\n  usedNodes: Set<string>;\n  missingInputs: string[];\n  dynamicNode: Node;\n  syncInputs: string[];\n}\n\n/**\n * Given graph inputs and desired outputs, find the minimal set of nodes\n * to execute in order to compute the outputs. In addition return other useful\n * info such:\n * - Missing inputs needed to compute the output.\n * - Whether the subgraph contains dynamic ops (control flow, dynamic shape).\n * - Alternative inputs in order to avoid async (dynamic op) execution.\n */\nexport function getExecutionSubgraph(\n    inputs: NamedTensorMap, outputs: Node[], weightMap: NamedTensorsMap,\n    initNodes?: Node[]): ExecutionInfo {\n  const usedNodes = new Set<string>();\n  const missingInputs: string[] = [];\n  let dynamicNode: Node = null;\n  let syncInputs: string[] = null;\n\n  // Start with the outputs, going backwards and find all the nodes that are\n  // needed to compute those outputs.\n  const seen = new Set<string>();\n  const inputNodeNames =\n      new Set(Object.keys(inputs).map((name) => parseNodeName(name)[0]));\n\n  initNodes = initNodes || [];\n  const initNodeNames =\n      new Set(initNodes.map((node) => parseNodeName(node.name)[0]));\n\n  const frontier = [...outputs];\n  while (frontier.length > 0) {\n    const node = frontier.pop();\n    if (isControlFlow(node) || isDynamicShape(node) || isHashTable(node)) {\n      if (dynamicNode == null) {\n        dynamicNode = node;\n        syncInputs = dynamicNode.children.map(child => child.name)\n                         .filter(name => usedNodes.has(name));\n      }\n    }\n    usedNodes.add(node.name);\n\n    // Weights are dead end since we already have their values.\n    if (weightMap[node.name] != null) {\n      continue;\n    }\n    // This node is a dead end since it's one of the user-provided inputs.\n    if (inputNodeNames.has(node.name)) {\n      continue;\n    }\n    // This node is a dead end since it doesn't have any inputs.\n    if (initNodeNames.has(node.name)) {\n      continue;\n    }\n    if (node.inputs.length === 0) {\n      missingInputs.push(node.name);\n      continue;\n    }\n    node.inputs.forEach(input => {\n      // Don't add to the frontier if it is already there.\n      if (seen.has(input.name)) {\n        return;\n      }\n      seen.add(input.name);\n      frontier.push(input);\n    });\n  }\n  return {inputs, outputs, usedNodes, missingInputs, dynamicNode, syncInputs};\n}\n\n/**\n * Given the execution info, return a list of nodes in topological order that\n * need to be executed to compute the output.\n */\nexport function getNodesInTopologicalOrder(\n    graph: Graph, executionInfo: ExecutionInfo): Node[] {\n  const {usedNodes, inputs} = executionInfo;\n  const inputNodes = Object.keys(inputs)\n                         .map(name => parseNodeName(name)[0])\n                         .map(name => graph.nodes[name]);\n  const initNodes = graph.initNodes || [];\n\n  const isUsed = (node: Node|string) =>\n      usedNodes.has(typeof node === 'string' ? node : node.name);\n\n  function unique(nodes: Node[]): Node[] {\n    return [...new Map(nodes.map((node) => [node.name, node])).values()];\n  }\n  const predefinedNodes = unique([\n                            ...inputNodes,\n                            ...graph.weights,\n                            ...initNodes,\n                          ]).filter(isUsed);\n  const allNodes = unique([\n                     ...predefinedNodes,\n                     ...Object.values(graph.nodes),\n                   ]).filter(isUsed);\n  const nameToNode =\n      new Map<string, Node>(allNodes.map((node) => [node.name, node]));\n\n  const inCounts: Record<string, number> = {};\n  for (const node of allNodes) {\n    inCounts[node.name] = inCounts[node.name] || 0;\n    for (const child of node.children) {\n      // When the child is unused, set in counts to infinity so that it will\n      // never be decreased to 0 and added to the execution list.\n      if (!isUsed(child)) {\n        inCounts[child.name] = Number.POSITIVE_INFINITY;\n      }\n      inCounts[child.name] = (inCounts[child.name] || 0) + 1;\n    }\n  }\n\n  // Build execution order for all used nodes regardless whether they are\n  // predefined or not.\n  const frontier = Object.entries(inCounts)\n                       .filter(([, inCount]) => inCount === 0)\n                       .map(([name]) => name);\n  const orderedNodeNames = [...frontier];\n  while (frontier.length > 0) {\n    const nodeName = frontier.pop();\n    const node = nameToNode.get(nodeName)!;\n    for (const child of node.children.filter(isUsed)) {\n      if (--inCounts[child.name] === 0) {\n        orderedNodeNames.push(child.name);\n        frontier.push(child.name);\n      }\n    }\n  }\n\n  const orderedNodes = orderedNodeNames.map((name) => nameToNode.get(name));\n  const filteredOrderedNodes =\n      filterPredefinedReachableNodes(orderedNodes, predefinedNodes);\n\n  // TODO: Turn validation on/off with tf env flag.\n  validateNodesExecutionOrder(filteredOrderedNodes, predefinedNodes);\n\n  return filteredOrderedNodes;\n}\n\n/**\n * This is a helper function of `getNodesInTopologicalOrder`.\n * Returns ordered nodes reachable by at least one predefined node.\n * This can help us filter out redundant nodes from the returned node list.\n * For example:\n * If we have four nodes with dependencies like this:\n *   a --> b --> c --> d\n * when node `c` is predefined (e.g. given as an input tensor), we can\n * skip node `a` and `b` since their outputs will never be used.\n *\n * @param orderedNodes Graph nodes in execution order.\n * @param predefinedNodes Graph inputs, weights, and init nodes. Nodes in this\n *     list must have distinct names.\n */\nfunction filterPredefinedReachableNodes(\n    orderedNodes: Node[], predefinedNodes: Node[]) {\n  const nameToNode =\n      new Map<string, Node>(orderedNodes.map((node) => [node.name, node]));\n\n  // TODO: Filter out more nodes when >=2 nodes are predefined in a path.\n  const stack = predefinedNodes.map((node) => node.name);\n  const predefinedReachableNodeNames = new Set(stack);\n  // Perform a DFS starting from the set of all predefined nodes\n  // to find the set of all nodes reachable from the predefined nodes.\n  while (stack.length > 0) {\n    const nodeName = stack.pop();\n    const node = nameToNode.get(nodeName)!;\n    for (const child of node.children) {\n      if (!nameToNode.has(child.name) ||\n          predefinedReachableNodeNames.has(child.name)) {\n        continue;\n      }\n      predefinedReachableNodeNames.add(child.name);\n      stack.push(child.name);\n    }\n  }\n\n  // Filter out unreachable nodes and build the ordered node list.\n  const filteredOrderedNodes = orderedNodes.filter(\n      (node) => predefinedReachableNodeNames.has(node.name));\n\n  return filteredOrderedNodes;\n}\n\nclass NodesExecutionOrderError extends Error {\n  constructor(message: string) {\n    super(`NodesExecutionOrderError: ${message}`);\n  }\n}\n\n/**\n * This is a helper function of `getNodesInTopologicalOrder`.\n * Validates property: given nodes `a` and `b`, Order(a) > Order(b) if `a`\n * is a child of `b`. This function throws an error if validation fails.\n *\n * @param orderedNodes Graph nodes in execution order.\n * @param predefinedNodes Graph inputs, weights, and init nodes. Nodes in this\n *     list must have distinct names.\n */\nfunction validateNodesExecutionOrder(\n    orderedNodes: Node[], predefinedNodes: Node[]) {\n  const nodeNameToOrder = new Map<string, number>(\n      orderedNodes.map((node, order) => [node.name, order]));\n  const predefinedNodeNames = new Set(predefinedNodes.map((node) => node.name));\n  const isPredefined = (node: Node|string) =>\n      predefinedNodeNames.has(typeof node === 'string' ? node : node.name);\n  const willBeExecutedNodeNames =\n      new Set(orderedNodes.map((node) => node.name));\n  const willBeExecuted = (node: Node|string) =>\n      willBeExecutedNodeNames.has(typeof node === 'string' ? node : node.name);\n\n  for (const node of orderedNodes) {\n    for (const child of node.children.filter(willBeExecuted)) {\n      if (!nodeNameToOrder.has(child.name)) {\n        throw new NodesExecutionOrderError(\n            `Child ${child.name} of node ${node.name} is unreachable.`);\n      }\n      if (nodeNameToOrder.get(node.name) > nodeNameToOrder.get(child.name)) {\n        throw new NodesExecutionOrderError(`Node ${\n            node.name} is scheduled to run after its child ${child.name}.`);\n      }\n    }\n    if (!isPredefined(node)) {\n      for (const input of node.inputs) {\n        if (!nodeNameToOrder.has(input.name)) {\n          throw new NodesExecutionOrderError(\n              `Input ${input.name} of node ${node.name} is unreachable.`);\n        }\n        if (nodeNameToOrder.get(input.name) > nodeNameToOrder.get(node.name)) {\n          throw new NodesExecutionOrderError(`Node ${\n              node.name} is scheduled to run before its input ${input.name}.`);\n        }\n      }\n    }\n  }\n}\n\n/**\n * Given the execution info, return a map from node name to the disposable\n * node name list after its execution.\n *\n * @returns A map from node name to disposable nodes after its\n *     execution. That is, for a node `x`, `nodeLiveUntilMap[x]` indicates\n *     all nodes which their intermediate tensors should be disposed after `x`\n *     being executed.\n */\nexport function getNodeLiveUntilMap(orderedNodes: Node[]): Map<string, Node[]> {\n  const nodeNameToOrder = new Map<string, number>(\n      orderedNodes.map((node, order) => [node.name, order]));\n\n  const INF_LIFE = Number.MAX_SAFE_INTEGER;\n  // Make control flow nodes (and consequently their direct parents)\n  // live forever since they're tricky to track correctly.\n  const selfLifespans = orderedNodes.map(\n      (node, nodeOrder) => isControlFlow(node) ? INF_LIFE : nodeOrder);\n  const getSelfLifeSpan = (node: Node) => {\n    const selfLife = selfLifespans[nodeNameToOrder.get(node.name)!];\n    if (selfLife == null) {\n      // If nodeToOrder does not contain the node, it is unused or\n      // unreachable in graph.\n      return -1;\n    }\n    return selfLife;\n  };\n\n  // `liveUntil[i]` points to the last node in the `orderedNodes` array that\n  // may depend on tensors from node `i`. It indicates that all the\n  // intermediate tensors from `orderedNodes[i]` should be disposed after\n  // `orderedNodes[liveUntil[i]]` is executed.\n  // A node lives long enough to pass on its tensors to its children.\n  // It lives until at least `max(node's position, children's positions)`.\n  const liveUntilOrders = orderedNodes.map((node, nodeOrder) => {\n    return node.children.map(getSelfLifeSpan)\n        .reduce((a, b) => Math.max(a, b), selfLifespans[nodeOrder]);\n  });\n\n  // liveUntilMap:\n  // - Key: Name of a node `x`\n  // - Values: All nodes whose intermediate tensors should be disposed\n  //           after `x` is executed.\n  const liveUntilMap = new Map<string, Node[]>();\n  for (let nodeOrder = 0; nodeOrder < orderedNodes.length; ++nodeOrder) {\n    const liveUntilOrder = liveUntilOrders[nodeOrder];\n    if (liveUntilOrder === INF_LIFE) {\n      continue;\n    }\n    const node = orderedNodes[nodeOrder];\n    const liveUntilNode = orderedNodes[liveUntilOrder];\n    if (!liveUntilMap.has(liveUntilNode.name)) {\n      liveUntilMap.set(liveUntilNode.name, []);\n    }\n    liveUntilMap.get(liveUntilNode.name)!.push(node);\n  }\n  return liveUntilMap;\n}\n\nconst CONTROL_FLOW_OPS = new Set([\n  'Switch', 'Merge', 'Enter', 'Exit', 'NextIteration', 'StatelessIf',\n  'StatelessWhile', 'if', 'While'\n]);\nconst DYNAMIC_SHAPE_OPS = new Set([\n  'NonMaxSuppressionV2', 'NonMaxSuppressionV3', 'NonMaxSuppressionV5', 'Where'\n]);\nconst HASH_TABLE_OPS = new Set([\n  'HashTable', 'HashTableV2', 'LookupTableImport', 'LookupTableImportV2',\n  'LookupTableFind', 'LookupTableFindV2', 'LookupTableSize', 'LookupTableSizeV2'\n]);\n\nexport function isControlFlow(node: Node) {\n  return CONTROL_FLOW_OPS.has(node.op);\n}\n\nexport function isDynamicShape(node: Node) {\n  return DYNAMIC_SHAPE_OPS.has(node.op);\n}\n\nexport function isHashTable(node: Node) {\n  return HASH_TABLE_OPS.has(node.op);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, env, keep, NamedTensorMap, Tensor, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {ISignatureDef} from '../data/compiled_api';\nimport {NamedTensorsMap, TensorArrayMap, TensorInfo, TensorListMap} from '../data/types';\nimport {getNodeNameAndIndex, getParamValue, getTensor, getTensorsForCurrentContext, parseNodeName} from '../operations/executors/utils';\nimport {executeOp} from '../operations/operation_executor';\nimport {Graph, Node} from '../operations/types';\n\nimport {ExecutionContext, ExecutionContextInfo} from './execution_context';\nimport {getExecutionSubgraph, getNodeLiveUntilMap, getNodesInTopologicalOrder, isControlFlow} from './model_analysis';\nimport {ResourceManager} from './resource_manager';\nimport {FunctionExecutor} from './types';\n\ninterface NodeWithContexts {\n  contexts: ExecutionContextInfo[];\n  node: Node;\n}\n\nexport class GraphExecutor implements FunctionExecutor {\n  private compiledMap = new Map<string, ReturnType<typeof this.compile>>();\n  private parseNodeNameCache = new Map<string, [string, number, string?]>();\n  private _weightMap: NamedTensorsMap = {};\n  private _weightIds: number[];\n  private _signature: ISignatureDef;\n  private _inputs: Node[];\n  private _outputs: Node[];\n  private _initNodes: Node[];  // Internal init nodes to start initialization.\n  private SEPARATOR = ',';\n  private _functions: {[key: string]: Graph} = {};\n  private _functionExecutorMap: {[key: string]: FunctionExecutor} = {};\n  private _resourceManager: ResourceManager;\n  private clonedTensorsMap: NamedTensorsMap;\n  private keepIntermediateTensors = false;\n\n  get weightIds(): number[] {\n    return this.parent ? this.parent.weightIds : this._weightIds;\n  }\n\n  get functionExecutorMap(): {[key: string]: FunctionExecutor} {\n    return this.parent ? this.parent.functionExecutorMap :\n                         this._functionExecutorMap;\n  }\n\n  get weightMap(): NamedTensorsMap {\n    return this.parent ? this.parent.weightMap : this._weightMap;\n  }\n\n  set weightMap(weightMap: NamedTensorsMap) {\n    const weightIds = Object.keys(weightMap).map(\n        key => weightMap[key].map(tensor => tensor.id));\n    this._weightIds = [].concat(...weightIds);\n    this._weightMap = weightMap;\n  }\n\n  /**\n   * Set `ResourceManager` shared by executors of a model.\n   * @param resourceManager: `ResourceManager` of the `GraphModel`.\n   */\n  set resourceManager(resourceManager: ResourceManager) {\n    this._resourceManager = resourceManager;\n  }\n\n  get inputs(): TensorInfo[] {\n    return this._inputs.map(node => {\n      return {\n        name: node.name,\n        shape: node.attrParams['shape'] ?\n            node.attrParams['shape'].value as number[] :\n            undefined,\n        dtype: node.attrParams['dtype'] ?\n            node.attrParams['dtype'].value as DataType :\n            undefined\n      };\n    });\n  }\n\n  get outputs(): TensorInfo[] {\n    return this._outputs.map(node => {\n      return {\n        name: node.name,\n        shape: node.attrParams['shape'] ?\n            node.attrParams['shape'].value as number[] :\n            undefined,\n        dtype: node.attrParams['dtype'] ?\n            node.attrParams['dtype'].value as DataType :\n            undefined\n      };\n    });\n  }\n\n  get inputNodes(): string[] {\n    return this._inputs.map(node => node.signatureKey || node.name);\n  }\n\n  get outputNodes(): string[] {\n    return this._outputs.map((node) => {\n      const name = node.signatureKey || node.name;\n      return node.defaultOutput ? (`${name}:${node.defaultOutput}`) : name;\n    });\n  }\n\n  get functions(): {[key: string]: ISignatureDef} {\n    return Object.keys(this._functions).reduce((map, key) => {\n      map[key] = this._functions[key].signature;\n      return map;\n    }, {} as {[key: string]: ISignatureDef});\n  }\n\n  /**\n   *\n   * @param graph Graph the model or function graph to be executed.\n   * @param parent When building function exector you need to set the parent\n   * executor. Since the weights and function executor maps are set at parant\n   * level, that function executor can access the function maps and weight maps\n   * through the parent.\n   */\n  constructor(private graph: Graph, private parent?: GraphExecutor) {\n    this._outputs = graph.outputs;\n    this._inputs = graph.inputs;\n    this._initNodes = graph.initNodes;\n    this._signature = graph.signature;\n    this._functions = graph.functions;\n    // create sub-graph executors\n    if (graph.functions != null) {\n      Object.keys(graph.functions).forEach(name => {\n        this._functionExecutorMap[name] =\n            new GraphExecutor(graph.functions[name], this);\n      });\n    }\n  }\n\n  private getCompilationKey(inputs: Node[], outputs: Node[]): string {\n    const sortedInputs = inputs.map(node => node.name).sort();\n    const sortedOutputs = outputs.map(node => node.name).sort();\n    return sortedInputs.join(this.SEPARATOR) + '--' +\n        sortedOutputs.join(this.SEPARATOR);\n  }\n\n  /**\n   * Compiles the inference graph and returns the minimal set of nodes that are\n   * required for execution, in the correct execution order.\n   * @returns {Object} compilation The compile result.\n   * @returns {Node[]} compilation.orderedNodes Nodes in the correct execution\n   *     order.\n   * @returns {Map<string, Node[]>} compilation.nodeLiveUntilMap A map from node\n   *     to disposable nodes after its execution. That is, for a node `x`,\n   *     `nodeLiveUntilMap[x]` indicates all nodes whose intermediate\n   *     tensors should be disposed after `x` is executed.\n   */\n  private compile(inputs: NamedTensorMap, outputs: Node[]):\n      {orderedNodes: Node[], nodeLiveUntilMap: Map<string, Node[]>} {\n    const executionInfo =\n        getExecutionSubgraph(inputs, outputs, this.weightMap, this._initNodes);\n    const {missingInputs, dynamicNode, syncInputs} = executionInfo;\n    if (dynamicNode != null) {\n      throw new Error(\n          `This execution contains the node '${dynamicNode.name}', which has ` +\n          `the dynamic op '${dynamicNode.op}'. Please use ` +\n          `model.executeAsync() instead. Alternatively, to avoid the ` +\n          `dynamic ops, specify the inputs [${syncInputs}]`);\n    }\n\n    if (missingInputs.length > 0) {\n      const outNames = outputs.map(n => n.name);\n      const inNames = Object.keys(inputs);\n      throw new Error(\n          `Cannot compute the outputs [${outNames}] from the provided inputs ` +\n          `[${inNames}]. Missing the following inputs: [${missingInputs}]`);\n    }\n\n    const orderedNodes = getNodesInTopologicalOrder(this.graph, executionInfo);\n    const nodeLiveUntilMap = getNodeLiveUntilMap(orderedNodes);\n    return {orderedNodes, nodeLiveUntilMap};\n  }\n\n  private cloneAndKeepTensor(tensor: Tensor) {\n    if (tensor == null) {\n      return null;\n    }\n    const clone = tensor.clone();\n    // Keep the clone because`model.execute()` may be called within\n    // a `tidy()`, but the user may inspect these tensors after the\n    // tidy.\n    keep(clone);\n    return clone;\n  }\n\n  private cloneTensorList(tensors: Tensor[]) {\n    if (!tensors) {\n      return null;\n    }\n    const clonedTensor = tensors.map(tensor => {\n      return this.cloneAndKeepTensor(tensor);\n    });\n    return clonedTensor;\n  }\n\n  private cloneTensorMap(tensorsMap: NamedTensorsMap): NamedTensorsMap {\n    return Object.fromEntries(\n        Object.entries(tensorsMap).map(([name, tensorsList]) => {\n          return [name, this.cloneTensorList(tensorsList)];\n        }));\n  }\n\n  /**\n   * Executes the inference for given input tensors.\n   * @param inputs Tensor map for the model inputs, keyed by the input node\n   * names.\n   * @param outputs Optional. output node name from the Tensorflow model, if\n   * no outputs are specified, the default outputs of the model would be used.\n   * You can inspect intermediate nodes of the model by adding them to the\n   * outputs array.\n   */\n  execute(inputs: NamedTensorMap, outputs?: string[]): Tensor[] {\n    // Dispose any tensors from a prior run to avoid leaking them.\n    this.disposeIntermediateTensors();\n    inputs = this.mapInputs(inputs);\n    const names = Object.keys(inputs).sort();\n    this.checkInputs(inputs);\n    this.checkInputShapeAndType(inputs);\n    outputs = this.mapOutputs(outputs);\n    this.checkOutputs(outputs);\n    const inputNodes =\n        names.map(name => this.graph.nodes[parseNodeName(name)[0]]);\n    const outputNodeNames = outputs.map(name => parseNodeName(name)[0]);\n    const outputNodeNameSet = new Set(outputNodeNames);\n    let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);\n    // If no outputs are specified, then use the default outputs of the model.\n    if (outputNodes.length === 0) {\n      outputNodes = this._outputs;\n    }\n\n    const compilationKey = this.getCompilationKey(inputNodes, outputNodes);\n\n    // Do nothing if the compiled graph cache contains the input.\n    let compilation = this.compiledMap.get(compilationKey);\n    if (compilation == null) {\n      compilation = this.compile(inputs, outputNodes);\n      this.compiledMap.set(compilationKey, compilation);\n    }\n\n    // Keep tensors if KEEP_INTERMEDIATE_TENSORS is on.\n    try {\n      this.keepIntermediateTensors = env().getBool('KEEP_INTERMEDIATE_TENSORS');\n    } catch (e) {\n      this.keepIntermediateTensors = false;\n      console.warn(e.message);\n    }\n    const tensorArrayMap: TensorArrayMap = {};\n    const tensorListMap: TensorListMap = {};\n\n    return tidy(() => {\n      const context = new ExecutionContext(\n          this.weightMap, tensorArrayMap, tensorListMap,\n          this.functionExecutorMap, this.parseNodeNameCache);\n      const tensorsMap: NamedTensorsMap = {...this.weightMap};\n      if (this.keepIntermediateTensors) {\n        this.clonedTensorsMap = this.cloneTensorMap(this.weightMap);\n      }\n\n      Object.keys(inputs).forEach(name => {\n        const [nodeName, index] = parseNodeName(name, context);\n        const tensors: Tensor[] = [];\n        tensors[index] = inputs[name];\n        tensorsMap[nodeName] = tensors;\n        if (this.keepIntermediateTensors) {\n          this.clonedTensorsMap[nodeName] = this.cloneTensorList(tensors);\n        }\n      });\n\n      const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);\n      const {orderedNodes, nodeLiveUntilMap} = compilation;\n      for (const node of orderedNodes) {\n        if (tensorsMap[node.name]) {\n          continue;\n        }\n        const tensors =\n            executeOp(node, tensorsMap, context, this._resourceManager) as\n            Tensor[];\n        if (util.isPromise(tensors)) {\n          throw new Error(\n              `The execution of the op '${node.op}' returned a promise. ` +\n              `Please use model.executeAsync() instead.`);\n        }\n        tensorsMap[node.name] = tensors;\n        if (this.keepIntermediateTensors) {\n          this.clonedTensorsMap[node.name] = this.cloneTensorList(tensors);\n        }\n        this.checkTensorForDisposalWithNodeLiveUntilInfo(\n            node, tensorsMap, context, tensorsToKeep, outputNodeNameSet,\n            nodeLiveUntilMap.get(node.name));\n      }\n\n      // dispose the context for the root executor\n      if (this.parent == null) {\n        context.dispose(tensorsToKeep);\n      }\n\n      return outputs.map(name => getTensor(name, tensorsMap, context));\n    });\n  }\n\n  private getFrozenTensorIds(tensorMap: NamedTensorsMap): Set<number> {\n    const ids = [].concat.apply(\n        [],\n        Object.keys(tensorMap)\n            .map(key => tensorMap[key])\n            .map(tensors => tensors.map(tensor => tensor.id)));\n    return new Set(ids);\n  }\n\n  private checkTensorForDisposal(\n      nodeName: string, node: Node, tensorMap: NamedTensorsMap,\n      context: ExecutionContext, tensorsToKeep: Set<number>,\n      outputNodeNameSet: Set<string>,\n      intermediateTensorConsumerCount: {[key: string]: number}) {\n    // Skip output nodes and any control flow nodes, since its dependency is\n    // tricky to track correctly.\n    if (isControlFlow(node) || outputNodeNameSet.has(nodeName)) {\n      return;\n    }\n\n    for (const tensor of tensorMap[nodeName]) {\n      if (tensor == null) {\n        continue;\n      }\n      intermediateTensorConsumerCount[tensor.id] =\n          (intermediateTensorConsumerCount[tensor.id] || 0) +\n          node.children.length;\n    }\n\n    for (const input of node.inputs) {\n      // Skip any control flow nodes, since its dependency is tricky to track\n      // correctly.\n      if (isControlFlow(input)) {\n        continue;\n      }\n\n      const tensors =\n          getTensorsForCurrentContext(input.name, tensorMap, context);\n      if (tensors == null) {\n        continue;\n      }\n\n      for (const tensor of tensors) {\n        if (!tensor || tensor.kept || tensorsToKeep.has(tensor.id)) {\n          continue;\n        }\n\n        // Only intermediate nodes' tensors have counts set, not marked as\n        // kept, and not in `tensorsToKeep`.\n        // Input and weight nodes' tensors should exist in `tensorsToKeep`.\n        // Output and control flow nodes' tensors should never have count set.\n        const count = intermediateTensorConsumerCount[tensor.id];\n        if (count === 1) {\n          tensor.dispose();\n          delete intermediateTensorConsumerCount[tensor.id];\n        } else if (count != null) {\n          intermediateTensorConsumerCount[tensor.id]--;\n        }\n      }\n    }\n  }\n\n  private checkTensorForDisposalWithNodeLiveUntilInfo(\n      node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext,\n      tensorsToKeep: Set<number>, outputNodeNameSet: Set<string>,\n      liveUntilNodes?: Node[]) {\n    function isNonDisposableNode(node: Node) {\n      // Skip output nodes and any control flow nodes, since its dependency is\n      // tricky to track correctly.\n      return isControlFlow(node) || outputNodeNameSet.has(node.name);\n    }\n\n    if (isControlFlow(node) || liveUntilNodes == null) {\n      return;\n    }\n\n    for (const nodeToDispose of liveUntilNodes) {\n      if (isNonDisposableNode(nodeToDispose)) {\n        continue;\n      }\n      const tensors = getTensorsForCurrentContext(\n          nodeToDispose.name, tensorMap, context);\n      for (const tensor of tensors) {\n        if (!tensor || tensor.kept || tensorsToKeep.has(tensor.id)) {\n          continue;\n        }\n        tensor.dispose();\n      }\n    }\n  }\n\n  /**\n   * Executes the inference for given input tensors in Async fashion.\n   * @param inputs Tensor map for the model inputs, keyed by the input node\n   * names.\n   * @param outputs output node name from the Tensorflow model, if no outputs\n   * are specified, the default outputs of the model would be used. You can\n   * inspect intermediate nodes of the model by adding them to the outputs\n   * array.\n   */\n  async executeAsync(inputs: NamedTensorMap, outputs?: string[]):\n      Promise<Tensor[]> {\n    return this._executeAsync(inputs, outputs);\n  }\n\n  disposeIntermediateTensors() {\n    if (!this.clonedTensorsMap) {\n      return;\n    }\n    Object.values(this.clonedTensorsMap).forEach(tensorsList => {\n      for (const tensor of tensorsList) {\n        if (tensor && !tensor.isDisposed) {\n          tensor.dispose();\n        }\n      }\n    });\n\n    this.clonedTensorsMap = null;\n  }\n\n  getIntermediateTensors(): NamedTensorsMap {\n    return this.clonedTensorsMap;\n  }\n\n  /**\n   * Executes the inference for given input tensors in Async fashion.\n   * @param inputs Tensor map for the model inputs, keyed by the input node\n   * names.\n   * @param outputs Optional. output node name from the Tensorflow model,\n   * if no outputs are specified, the default outputs of the model would be\n   * used. You can inspect intermediate nodes of the model by adding them to\n   * the outputs array.\n   * @param isFunctionExecution Optional. Flag for executing a function.\n   * @param tensorArrayMap Optional, global TensorArray map by id. Used for\n   * function execution.\n   * @param tensorArrayMap Optional global TensorList map by id. Used for\n   * function execution.\n   */\n  private async _executeAsync(\n      inputs: NamedTensorMap, outputs?: string[], isFunctionExecution = false,\n      tensorArrayMap: TensorArrayMap = {},\n      tensorListMap: TensorListMap = {}): Promise<Tensor[]> {\n    // Dispose any tensors from a prior run to avoid leaking them.\n    this.disposeIntermediateTensors();\n    if (!isFunctionExecution) {\n      inputs = this.mapInputs(inputs);\n      this.checkInputs(inputs);\n      this.checkInputShapeAndType(inputs);\n      outputs = this.mapOutputs(outputs);\n      this.checkOutputs(outputs);\n    }\n\n    // Keep tensors if KEEP_INTERMEDIATE_TENSORS is on.\n    try {\n      this.keepIntermediateTensors = env().getBool('KEEP_INTERMEDIATE_TENSORS');\n    } catch (e) {\n      this.keepIntermediateTensors = false;\n      console.warn(e.message);\n    }\n\n    const context = new ExecutionContext(\n        this.weightMap, tensorArrayMap, tensorListMap, this.functionExecutorMap,\n        this.parseNodeNameCache);\n\n    if (this.keepIntermediateTensors) {\n      this.clonedTensorsMap = this.cloneTensorMap(this.weightMap);\n    }\n\n    // Graph with control flow op requires runtime evaluation of the execution\n    // order, while without control flow the execution order is pre-determined\n    // in the compile method.\n    const tensorsMap = await this.executeWithControlFlow(\n        inputs, context, outputs, isFunctionExecution);\n    const results = outputs.map(name => getTensor(name, tensorsMap, context));\n\n    // dispose all the intermediate tensors\n    const outputIds = results.map(t => t.id);\n    const inputIds = Object.keys(inputs).map(name => inputs[name].id);\n    const keepIds =\n        new Set<number>([...outputIds, ...inputIds, ...this.weightIds]);\n\n    Object.values(tensorsMap).forEach(tensorsList => {\n      tensorsList.forEach(tensor => {\n        if (tensor && !tensor.isDisposed && !keepIds.has(tensor.id)) {\n          tensor.dispose();\n        }\n      });\n    });\n\n    // dispose the context for the root executor\n    if (this.parent == null) {\n      context.dispose(keepIds);\n    }\n\n    return results;\n  }\n\n  async executeFunctionAsync(\n      inputs: Tensor[], tensorArrayMap: TensorArrayMap,\n      tensorListMap: TensorListMap): Promise<Tensor[]> {\n    const mappedInputs = inputs.reduce((map, tensor, index) => {\n      map[this.inputs[index].name] = tensor;\n      return map;\n    }, {} as NamedTensorMap);\n\n    return this._executeAsync(\n        mappedInputs, this.outputNodes, true, tensorArrayMap, tensorListMap);\n  }\n\n  /**\n   * When there are control flow nodes in the graph, the graph execution use\n   * ExecutionContext to keep track of the frames and loop iterators.\n   * @param inputs placeholder tensors for the graph.\n   * @param context the execution context object for current execution.\n   * @param outputNames Optional. output node name from the Tensorflow model,\n   * if no outputs are specified, the default outputs of the model would be\n   * used. You can inspect intermediate nodes of the model by adding them to\n   * the outputs array.\n   * @param isFunctionExecution Flag for executing a function.\n   */\n  private async executeWithControlFlow(\n      inputs: NamedTensorMap, context: ExecutionContext, outputNames?: string[],\n      isFunctionExecution?: boolean): Promise<NamedTensorsMap> {\n    const names = Object.keys(inputs);\n    const inputNodes =\n        names.map(name => this.graph.nodes[parseNodeName(name)[0]]);\n    const outputNodeNames = outputNames.map(name => parseNodeName(name)[0]);\n    const outputNodeNameSet = new Set(outputNodeNames);\n    let outputNodes = outputNodeNames.map(name => this.graph.nodes[name]);\n\n    // If no outputs are specified, then use the default outputs of the model.\n    if (outputNodes.length === 0) {\n      outputNodes = this._outputs;\n    }\n\n    const {usedNodes, missingInputs, dynamicNode, syncInputs} =\n        getExecutionSubgraph(\n            inputs, outputNodes, this.weightMap, this._initNodes);\n\n    // First nodes to execute include inputNodes, weights, and initNodes.\n    const stack: NodeWithContexts[] = [\n      ...inputNodes, ...this.graph.weights, ...(this._initNodes || [])\n    ].map(node => {\n      return {node, contexts: context.currentContext};\n    });\n    const tensorsMap: NamedTensorsMap = {...this.weightMap};\n    Object.keys(inputs).forEach(name => {\n      const [nodeName, index] = parseNodeName(name);\n      const tensors: Tensor[] = [];\n      tensors[index] = inputs[name];\n      tensorsMap[nodeName] = tensors;\n    });\n    const intermediateTensorConsumerCount: {[key: number]: number} = {};\n    const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);\n    const added: {[key: string]: boolean} = {};\n    while (stack.length > 0) {\n      const promises = this.processStack(\n          inputNodes, stack, context, tensorsMap, added, tensorsToKeep,\n          outputNodeNameSet, intermediateTensorConsumerCount, usedNodes);\n      await Promise.all(promises);\n    }\n    if (dynamicNode == null && !isFunctionExecution) {\n      console.warn(\n          `This model execution did not contain any nodes with control flow ` +\n          `or dynamic output shapes. You can use model.execute() instead.`);\n    }\n    const missingOutputs =\n        outputNodes\n            .filter(\n                node => !isControlFlow(node) &&\n                    !getTensor(node.name, tensorsMap, context))\n            .map(node => node.name);\n    if (missingOutputs.length > 0) {\n      let alternativeMsg = '';\n      if (dynamicNode != null) {\n        alternativeMsg =\n            `Alternatively, to avoid the dynamic ops, use model.execute() ` +\n            `and specify the inputs [${syncInputs}]`;\n      }\n      throw new Error(\n          `Cannot compute the outputs [${missingOutputs}] from the provided ` +\n          `inputs [${names}]. Consider providing the following inputs: ` +\n          `[${missingInputs}]. ${alternativeMsg}`);\n    }\n    return tensorsMap;\n  }\n\n  private processStack(\n      inputNodes: Node[], stack: NodeWithContexts[], context: ExecutionContext,\n      tensorMap: NamedTensorsMap, added: {[key: string]: boolean},\n      tensorsToKeep: Set<number>, outputNodeNameSet: Set<string>,\n      intermediateTensorConsumerCount: {[key: number]: number},\n      usedNodes: Set<string>) {\n    const promises: Array<Promise<Tensor[]>> = [];\n    while (stack.length > 0) {\n      const item = stack.pop();\n      context.currentContext = item.contexts;\n      let nodeName = '';\n      // The tensor of the Enter op with isConstant set should be set\n      // in the parent scope, so it will be available as constant for the\n      // whole loop.\n      if (item.node.op === 'Enter' &&\n          getParamValue('isConstant', item.node, tensorMap, context)) {\n        [nodeName] = getNodeNameAndIndex(item.node.name, context);\n      }\n\n      // only process nodes that are not in the tensorMap yet, this include\n      // inputNodes and internal initNodes.\n      if (tensorMap[item.node.name] == null) {\n        const tensors =\n            executeOp(item.node, tensorMap, context, this._resourceManager);\n        if (!nodeName) {\n          [nodeName] = getNodeNameAndIndex(item.node.name, context);\n        }\n        const currentContext = context.currentContext;\n        if (util.isPromise(tensors)) {\n          promises.push(tensors.then(t => {\n            tensorMap[nodeName] = t;\n            if (this.keepIntermediateTensors) {\n              this.clonedTensorsMap[nodeName] = this.cloneTensorList(t);\n            }\n            context.currentContext = currentContext;\n            this.checkTensorForDisposal(\n                nodeName, item.node, tensorMap, context, tensorsToKeep,\n                outputNodeNameSet, intermediateTensorConsumerCount);\n            this.processChildNodes(\n                item.node, stack, context, tensorMap, added, usedNodes);\n            return t;\n          }));\n        } else {\n          tensorMap[nodeName] = tensors;\n          if (this.keepIntermediateTensors) {\n            this.clonedTensorsMap[nodeName] = this.cloneTensorList(tensors);\n          }\n          this.checkTensorForDisposal(\n              nodeName, item.node, tensorMap, context, tensorsToKeep,\n              outputNodeNameSet, intermediateTensorConsumerCount);\n          this.processChildNodes(\n              item.node, stack, context, tensorMap, added, usedNodes);\n        }\n      } else {\n        this.processChildNodes(\n            item.node, stack, context, tensorMap, added, usedNodes);\n      }\n    }\n    return promises;\n  }\n\n  private processChildNodes(\n      node: Node, stack: NodeWithContexts[], context: ExecutionContext,\n      tensorMap: NamedTensorsMap, added: {[key: string]: boolean},\n      usedNodes: Set<string>) {\n    node.children.forEach((childNode) => {\n      const [nodeName, ] = getNodeNameAndIndex(childNode.name, context);\n      if (added[nodeName] || !usedNodes.has(childNode.name)) {\n        return;\n      }\n      // Merge op can be pushed if any of its inputs has value.\n      if (childNode.op === 'Merge') {\n        if (childNode.inputNames.some(name => {\n              return !!getTensor(name, tensorMap, context);\n            })) {\n          added[nodeName] = true;\n          stack.push({contexts: context.currentContext, node: childNode});\n        }\n      } else  // Otherwise all inputs must to have value.\n          if (childNode.inputNames.every(name => {\n                return !!getTensor(name, tensorMap, context);\n              })) {\n        added[nodeName] = true;\n        stack.push({contexts: context.currentContext, node: childNode});\n      }\n    });\n  }\n\n  /**\n   * Releases the memory used by the weight tensors.\n   */\n  dispose() {\n    Object.keys(this.weightMap)\n        .forEach(\n            key => this.weightMap[key].forEach(tensor => tensor.dispose()));\n  }\n\n  private checkInputShapeAndType(inputs: NamedTensorMap) {\n    Object.keys(inputs).forEach(name => {\n      const input = inputs[name];\n      const [nodeName, ] = parseNodeName(name);\n      const node = this.graph.nodes[nodeName];\n      if (node.attrParams['shape'] && node.attrParams['shape'].value) {\n        const shape = node.attrParams['shape'].value as number[];\n        const match = shape.length === input.shape.length &&\n            input.shape.every(\n                (dim, index) => shape[index] === -1 || shape[index] === dim);\n        util.assert(\n            match,\n            () => `The shape of dict['${node.name}'] provided in ` +\n                `model.execute(dict) must be [${shape}], but was ` +\n                `[${input.shape}]`);\n      }\n      if (node.attrParams['dtype'] && node.attrParams['dtype'].value) {\n        util.assert(\n            input.dtype === node.attrParams['dtype'].value as string,\n            () => `The dtype of dict['${node.name}'] provided in ` +\n                `model.execute(dict) must be ` +\n                `${node.attrParams['dtype'].value}, but was ${input.dtype}`);\n      }\n    });\n  }\n\n  private mapInputs(inputs: NamedTensorMap) {\n    const result: NamedTensorMap = {};\n    for (const inputName in inputs) {\n      const tensor = this._signature ?.inputs ?.[inputName];\n      if (tensor != null) {\n        result[tensor.name] = inputs[inputName];\n      } else {\n        result[inputName] = inputs[inputName];\n      }\n    }\n    return result;\n  }\n\n  private checkInputs(inputs: NamedTensorMap) {\n    const notInGraph = Object.keys(inputs).filter(name => {\n      const [nodeName] = parseNodeName(name);\n      return this.graph.nodes[nodeName] == null;\n    });\n    if (notInGraph.length > 0) {\n      throw new Error(\n          `The dict provided in model.execute(dict) has ` +\n          `keys: [${notInGraph}] that are not part of graph`);\n    }\n  }\n\n  private mapOutputs(outputs: string[]) {\n    return outputs.map(name => {\n      const tensor = this._signature ?.outputs ?.[name];\n      if (tensor != null) {\n        return tensor.name;\n      }\n      return name;\n    }, {});\n  }\n\n  private checkOutputs(outputs: string[]): void {\n    outputs.forEach(name => {\n      const [normalizedName] = parseNodeName(name);\n      if (!this.graph.nodes[normalizedName]) {\n        throw new Error(`The output '${name}' is not found in the graph`);\n      }\n    });\n  }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {HashTableMap, NamedTensorMap} from '../data/types';\nimport {HashTable} from './hash_table';\n\n/**\n * Contains global resources of a model.\n */\nexport class ResourceManager {\n  constructor(\n      readonly hashTableNameToHandle: NamedTensorMap = {},\n      readonly hashTableMap: HashTableMap = {}) {}\n\n  /**\n   * Register a `HashTable` in the resource manager.\n   *\n   * The `HashTable` can be retrieved by `resourceManager.getHashTableById`,\n   * where id is the table handle tensor's id.\n   *\n   * @param name Op node name that creates the `HashTable`.\n   * @param hashTable The `HashTable` to be added to resource manager.\n   */\n  addHashTable(name: string, hashTable: HashTable) {\n    this.hashTableNameToHandle[name] = hashTable.handle;\n    this.hashTableMap[hashTable.id] = hashTable;\n  }\n\n  /**\n   * Get the table handle by node name.\n   * @param name Op node name that creates the `HashTable`. This name is also\n   *     used in the inputs list of lookup and import `HashTable` ops.\n   */\n  getHashTableHandleByName(name: string) {\n    return this.hashTableNameToHandle[name];\n  }\n\n  /**\n   * Get the actual `HashTable` by its handle tensor's id.\n   * @param id The id of the handle tensor.\n   */\n  getHashTableById(id: number): HashTable {\n    return this.hashTableMap[id];\n  }\n\n  /**\n   * Dispose `ResourceManager`, including its hashTables and tensors in them.\n   */\n  dispose() {\n    for (const key in this.hashTableMap) {\n      this.hashTableMap[key].clearAndClose();\n      delete this.hashTableMap[key];\n    }\n\n    for (const name in this.hashTableNameToHandle) {\n      this.hashTableNameToHandle[name].dispose();\n      delete this.hashTableNameToHandle[name];\n    }\n  }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/* Type definitions for exporting and importing of models. */\n\n/**\n * A map from Tensor dtype to number of bytes per element of the Tensor.\n */\nexport const DTYPE_VALUE_SIZE_MAP: {[dtype: string]: number} = {\n  'float32': 4,\n  'float16': 2,\n  'int32': 4,\n  'uint16': 2,\n  'uint8': 1,\n  'bool': 1,\n  'complex64': 8\n};\n\n/**\n * A weight manifest.\n *\n * The weight manifest consists of an ordered list of weight-manifest groups.\n * Each weight-manifest group (\"group\" for short hereafter) consists of a\n * number of weight values stored in a number of paths.\n * See the documentation of `WeightManifestGroupConfig` below for more details.\n */\nexport declare type WeightsManifestConfig = WeightsManifestGroupConfig[];\n\n/**\n * A weight-manifest group.\n *\n * Consists of an ordered list of weight values encoded in binary format,\n * stored in an ordered list of paths.\n */\nexport declare interface WeightsManifestGroupConfig {\n  /**\n   * An ordered list of paths.\n   *\n   * Paths are intentionally abstract in order to be general. For example, they\n   * can be relative URL paths or relative paths on the file system.\n   */\n  paths: string[];\n\n  /**\n   * Specifications of the weights stored in the paths.\n   */\n  weights: WeightsManifestEntry[];\n}\n\n/**\n * Group to which the weight belongs.\n *\n * - 'optimizer': Weight from a stateful optimizer.\n */\nexport type WeightGroup = 'model'|'optimizer';\n\n/**\n * An entry in the weight manifest.\n *\n * The entry contains specification of a weight.\n */\nexport declare interface WeightsManifestEntry {\n  /**\n   * Name of the weight, e.g., 'Dense_1/bias'\n   */\n  name: string;\n\n  /**\n   * Shape of the weight.\n   */\n  shape: number[];\n\n  /**\n   * Data type of the weight.\n   */\n  dtype: 'float32'|'int32'|'bool'|'string'|'complex64';\n\n  /**\n   * Type of the weight.\n   *\n   * Optional.\n   *\n   * The value 'optimizer' indicates the weight belongs to an optimizer\n   * (i.e., used only during model training and not during inference).\n   */\n  group?: WeightGroup;\n\n  /**\n   * Information for dequantization of the weight.\n   */\n  quantization?: {\n    scale?: number,  // The scaling constant to multiply by.\n    min?: number,    // The (possibly nudged) minimum weight to add.\n       dtype: 'uint16'|'uint8'|'float16'  // The dtype of the quantized weights.\n  };\n}\n\n/**\n * Options for saving a model.\n * @innamespace io\n */\nexport interface SaveConfig {\n  /**\n   * Whether to save only the trainable weights of the model, ignoring the\n   * non-trainable ones.\n   */\n  trainableOnly?: boolean;\n\n  /**\n   * Whether the optimizer will be saved (if exists).\n   *\n   * Default: `false`.\n   */\n  includeOptimizer?: boolean;\n}\n\n/**\n * Result of a saving operation.\n */\nexport interface SaveResult {\n  /**\n   * Information about the model artifacts saved.\n   */\n  modelArtifactsInfo: ModelArtifactsInfo;\n\n  /**\n   * HTTP responses from the server that handled the model-saving request (if\n   * any). This is applicable only to server-based saving routes.\n   */\n  responses?: Response[];\n\n  /**\n   * Error messages and related data (if any).\n   */\n  errors?: Array<{}|string>;\n}\n\nexport declare interface ModelArtifactsInfo {\n  /**\n   * Timestamp for when the model is saved.\n   */\n  dateSaved: Date;\n\n  /**\n   * TODO (cais,yassogba) consider removing GraphDef as GraphDefs now\n   * come in a JSON format and none of our IOHandlers support a non json\n   * format. We could conder replacing this with 'Binary' if we want to\n   * allow future handlers to save to non json formats (though they will\n   * probably want more information than 'Binary').\n   * Type of the model topology\n   *\n   * Type of the model topology\n   *\n   * Possible values:\n   *   - JSON: JSON config (human-readable, e.g., Keras JSON).\n   *   - GraphDef: TensorFlow\n   *     [GraphDef](https://www.tensorflow.org/extend/tool_developers/#graphdef)\n   *     protocol buffer (binary).\n   */\n  modelTopologyType: 'JSON'|'GraphDef';\n\n  /**\n   * Size of model topology (Keras JSON or GraphDef), in bytes.\n   */\n  modelTopologyBytes?: number;\n\n  /**\n   * Size of weight specification or manifest, in bytes.\n   */\n  weightSpecsBytes?: number;\n\n  /**\n   * Size of weight value data, in bytes.\n   */\n  weightDataBytes?: number;\n}\n\n/** Model training configuration. */\nexport declare interface TrainingConfig {\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  // See\n  // tslint:disable-next-line:max-line-length\n  // https://github.com/tensorflow/tfjs-layers/blob/master/src/keras_format/training_config.ts\n  /** Optimizer used for the model training. */\n  optimizer_config: {};\n\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  /** Loss function(s) for the model's output(s). */\n  loss: string|string[]|{[key: string]: string};\n\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  /** Metric function(s) for the model's output(s). */\n  metrics?: string[]|{[key: string]: string};\n\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  weighted_metrics?: string[];\n\n  // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n  sample_weight_mode?: string;\n\n  loss_weights?: number[]|{[key: string]: number};\n}\n\nexport type WeightData = ArrayBuffer | ArrayBuffer[];\n\n/**\n * The serialized artifacts of a model, including topology and weights.\n *\n * The `modelTopology`, `trainingConfig`, `weightSpecs` and `weightData` fields\n * of this interface are optional, in order to support topology- or weights-only\n * saving and loading.\n *\n * Note this interface is used internally in IOHandlers.  For the file format\n * written to disk as `model.json`, see `ModelJSON`.\n */\nexport declare interface ModelArtifacts {\n  /**\n   * Model topology.\n   *\n   * For Keras-style `tf.Model`s, this is a JSON object.\n   * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n   * encoding of the `GraphDef` protocol buffer.\n   */\n  modelTopology?: {}|ArrayBuffer;\n\n  /**\n   * Serialized configuration for the model's training.\n   */\n  trainingConfig?: TrainingConfig;\n\n  /**\n   * Weight specifications.\n   *\n   * This corresponds to the weightsData below.\n   */\n  weightSpecs?: WeightsManifestEntry[];\n\n  /**\n   * Binary buffer(s) for all weight values in the order specified by\n   * `weightSpecs`. This may be a single ArrayBuffer of all the weights\n   * concatenated together or an Array of ArrayBuffers containing the weights\n   * (weights may be sharded across multiple ArrayBuffers).\n   */\n  weightData?: WeightData;\n\n  /**\n   * Returns a stream of the weights. Some models are too large to fit in\n   * V8's memory heap, and `getWeightStream` loads their weights without storing\n   * them all in memory at the same time.\n   */\n  getWeightStream?: () => ReadableStream<ArrayBuffer>;\n\n  /**\n   * Hard-coded format name for models saved from TensorFlow.js or converted\n   * by TensorFlow.js Converter.\n   */\n  format?: string;\n\n  /**\n   * What library is responsible for originally generating this artifact.\n   *\n   * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n   */\n  generatedBy?: string;\n\n  /**\n   * What library or tool is responsible for converting the original model\n   * to this format, applicable only if the model is output by a converter.\n   *\n   * Used for debugging purposes.  E.g., 'TensorFlow.js Converter v1.0.0'.\n   *\n   * A value of `null` means the model artifacts are generated without any\n   * conversion process (e.g., saved directly from a TensorFlow.js\n   * `tf.LayersModel` instance.)\n   */\n  convertedBy?: string|null;\n\n  /**\n   * Inputs and outputs signature for saved model.\n   */\n  signature?: {};\n\n  /**\n   * User-defined metadata about the model.\n   */\n  userDefinedMetadata?: {[key: string]: {}};\n\n  /**\n   * Initializer for the model.\n   */\n  modelInitializer?: {};\n\n  /**\n   * Inputs and outputs signature for model initializer.\n   */\n  initializerSignature?: {};\n}\n\n/**\n * The on-disk format of the `model.json` file.\n *\n * TF.js 1.0 always populates the optional fields when writing model.json.\n * Prior versions did not provide those fields.\n */\nexport declare interface ModelJSON {\n  /**\n   * Model topology.\n   *\n   * For Keras-style `tf.Model`s, this is a JSON object.\n   * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n   * encoding of the `GraphDef` protocol buffer.\n   */\n  modelTopology: {};\n\n  /** Model training configuration. */\n  trainingConfig?: TrainingConfig;\n\n  /**\n   * Weights manifest.\n   *\n   * The weights manifest consists of an ordered list of weight-manifest\n   * groups. Each weight-manifest group consists of a number of weight values\n   * stored in a number of paths. See the documentation of\n   * `WeightsManifestConfig` for more details.\n   */\n  weightsManifest: WeightsManifestConfig;\n\n  /**\n   * Hard-coded format name for models saved from TensorFlow.js or converted\n   * by TensorFlow.js Converter.\n   */\n  format?: string;\n\n  /**\n   * What library is responsible for originally generating this artifact.\n   *\n   * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n   */\n  generatedBy?: string;\n\n  /**\n   * What library or tool is responsible for converting the original model\n   * to this format, applicable only if the model is output by a converter.\n   *\n   * Used for debugging purposes.  E.g., 'TensorFlow.js Converter v1.0.0'.\n   *\n   * A value of `null` means the model artifacts are generated without any\n   * conversion process (e.g., saved directly from a TensorFlow.js\n   * `tf.LayersModel` instance.)\n   */\n  convertedBy?: string|null;\n\n  /**\n   * Inputs and outputs signature for saved model.\n   */\n  signature?: {};\n\n  /**\n   * User-defined metadata about the model.\n   */\n  userDefinedMetadata?: {[key: string]: {}};\n\n  /**\n   * Initializer for the model.\n   */\n  modelInitializer?: {};\n\n  /**\n   * Inputs and outputs signature for model initializer.\n   */\n  initializerSignature?: {};\n}\n\n/**\n * Type definition for handlers of loading operations.\n */\nexport type LoadHandler = () => Promise<ModelArtifacts>;\n\n/**\n * Type definition for handlers of saving operations.\n */\nexport type SaveHandler = (modelArtifact: ModelArtifacts) =>\n    Promise<SaveResult>;\n\n/**\n * Interface for a model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport interface IOHandler {\n  save?: SaveHandler;\n  load?: LoadHandler;\n}\n\n/**\n * Type definition for handlers of synchronous loading operations.\n */\nexport type LoadHandlerSync = () => ModelArtifacts;\n\n/**\n * Type definition for handlers of synchronous saving operations.\n */\nexport type SaveHandlerSync = (modelArtifact: ModelArtifacts) => SaveResult;\n\n/**\n * Interface for a synchronous model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport type IOHandlerSync = {\n  save?: SaveHandlerSync;\n  load?: LoadHandlerSync;\n};\n\n/**\n * An interface for the manager of a model store.\n *\n * A model store is defined as a storage medium on which multiple models can\n * be stored. Each stored model has a unique `path` as its identifier.\n * A `ModelStoreManager` for the store allows actions including\n *\n * - Listing the models stored in the store.\n * - Deleting a model from the store.\n */\nexport interface ModelStoreManager {\n  /**\n   * List all models in the model store.\n   *\n   * @returns A dictionary mapping paths of existing models to their\n   *   model artifacts info. Model artifacts info include type of the model's\n   *   topology, byte sizes of the topology, weights, etc.\n   */\n  listModels(): Promise<{[path: string]: ModelArtifactsInfo}>;\n\n  /**\n   * Remove a model specified by `path`.\n   *\n   * @param path\n   * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n   *   is successful).\n   * @throws Error if deletion fails, e.g., if no model exists at `path`.\n   */\n  removeModel(path: string): Promise<ModelArtifactsInfo>;\n}\n\n/**\n * Callback for the progress of a long-running action such as an HTTP\n * request for a large binary object.\n *\n * `fraction` should be a number in the [0, 1] interval, indicating how\n * much of the action has completed.\n */\nexport type OnProgressCallback = (fraction: number) => void;\n\n/** @innamespace io */\nexport interface LoadOptions {\n  /**\n   * RequestInit (options) for HTTP requests.\n   *\n   * For detailed information on the supported fields, see\n   * [https://developer.mozilla.org/en-US/docs/Web/API/Request/Request](\n   *     https://developer.mozilla.org/en-US/docs/Web/API/Request/Request)\n   */\n  requestInit?: RequestInit;\n\n  /**\n   * Progress callback.\n   */\n  onProgress?: OnProgressCallback;\n\n  /**\n   * A function used to override the `window.fetch` function.\n   */\n  fetchFunc?: typeof fetch;\n\n  /**\n   * Strict loading model: whether extraneous weights or missing\n   * weights should trigger an `Error`.\n   *\n   * If `true`, require that the provided weights exactly match those\n   * required by the layers. `false` means that both extra weights\n   * and missing weights will be silently ignored.\n   *\n   * Default: `true`.\n   */\n  strict?: boolean;\n\n  /**\n   * Path prefix for weight files, by default this is calculated from the\n   * path of the model JSON file.\n   *\n   * For instance, if the path to the model JSON file is\n   * `http://localhost/foo/model.json`, then the default path prefix will be\n   * `http://localhost/foo/`. If a weight file has the path value\n   * `group1-shard1of2` in the weight manifest, then the weight file will be\n   * loaded from `http://localhost/foo/group1-shard1of2` by default. However,\n   * if you provide a `weightPathPrefix` value of\n   * `http://localhost/foo/alt-weights`, then the weight file will be loaded\n   * from the path `http://localhost/foo/alt-weights/group1-shard1of2` instead.\n   */\n  weightPathPrefix?: string;\n\n  /**\n   * Whether the module or model is to be loaded from TF Hub.\n   *\n   * Setting this to `true` allows passing a TF-Hub module URL, omitting the\n   * standard model file name and the query parameters.\n   *\n   * Default: `false`.\n   */\n  fromTFHub?: boolean;\n\n  /**\n   * An async function to convert weight file name to URL. The weight file\n   * names are stored in model.json's weightsManifest.paths field. By default we\n   * consider weight files are colocated with the model.json file. For example:\n   *     model.json URL: https://www.google.com/models/1/model.json\n   *     group1-shard1of1.bin url:\n   *        https://www.google.com/models/1/group1-shard1of1.bin\n   *\n   * With this func you can convert the weight file name to any URL.\n   */\n  weightUrlConverter?: (weightFileName: string) => Promise<string>;\n\n  /**\n   * Whether to stream the model directly to the backend or cache all its\n   * weights on CPU first. Useful for large models.\n   */\n  streamWeights?: boolean;\n}\n\n/**\n * Additional options for Platform.fetch\n */\nexport interface RequestDetails {\n  /**\n   * Is this request for a binary file (as opposed to a json file)\n   */\n  isBinary?: boolean;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, ModelJSON, WeightData, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {CompositeArrayBuffer} from './composite_array_buffer';\nimport {Tensor} from '../tensor';\nimport {backend} from '../globals';\nimport {DataId} from '../tensor_info';\nimport {env} from '../environment';\nimport {getBackend} from '../globals';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n *   - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n *     concatenated.\n *   - An `Array` of `WeightManifestEntry`s, carrying information including\n *     tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n    tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n    Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n  // TODO(adarob, cais): Support quantization.\n  const specs: WeightsManifestEntry[] = [];\n  const dataPromises: Array<Promise<TypedArray>> = [];\n\n  const names: string[] = Array.isArray(tensors) ?\n      tensors.map(tensor => tensor.name) :\n      Object.keys(tensors);\n\n  for (let i = 0; i < names.length; ++i) {\n    const name = names[i];\n    const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name];\n    if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool' &&\n        t.dtype !== 'string' && t.dtype !== 'complex64') {\n      throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`);\n    }\n    const spec: WeightsManifestEntry = {name, shape: t.shape, dtype: t.dtype};\n    if (t.dtype === 'string') {\n      const utf8bytes = new Promise<TypedArray>(async resolve => {\n        const vals = await t.bytes() as Uint8Array[];\n        const totalNumBytes = vals.reduce((p, c) => p + c.length, 0) +\n            NUM_BYTES_STRING_LENGTH * vals.length;\n        const bytes = new Uint8Array(totalNumBytes);\n        let offset = 0;\n        for (let i = 0; i < vals.length; i++) {\n          const val = vals[i];\n          const bytesOfLength =\n              new Uint8Array(new Uint32Array([val.length]).buffer);\n          bytes.set(bytesOfLength, offset);\n          offset += NUM_BYTES_STRING_LENGTH;\n          bytes.set(val, offset);\n          offset += val.length;\n        }\n        resolve(bytes);\n      });\n      dataPromises.push(utf8bytes);\n    } else {\n      dataPromises.push(t.data());\n    }\n    if (group != null) {\n      spec.group = group;\n    }\n    specs.push(spec);\n  }\n\n  const tensorValues = await Promise.all(dataPromises);\n  return {data: concatenateTypedArrays(tensorValues), specs};\n}\n\n/**\n * Decode flat ArrayBuffer as weights.\n *\n * This function does not handle sharding.\n *\n * This function is the reverse of `encodeWeights`.\n *\n * @param weightData A flat ArrayBuffer or an array of ArrayBuffers carrying the\n *   binary values of the tensors concatenated in the order specified in\n *   `specs`.\n * @param specs Specifications of the names, dtypes and shapes of the tensors\n *   whose value are encoded by `buffer`.\n * @return A map from tensor name to tensor value, with the names corresponding\n *   to names in `specs`.\n * @throws Error, if any of the tensors has unsupported dtype.\n */\nexport function decodeWeights(\n    weightData: WeightData,\n    specs: WeightsManifestEntry[]): NamedTensorMap {\n  // TODO(adarob, cais): Support quantization.\n  const compositeBuffer = new CompositeArrayBuffer(weightData);\n  const out: NamedTensorMap = {};\n  let offset = 0;\n  for (const spec of specs) {\n    const byteLength = getWeightBytelength(spec, (start, end) => {\n      return compositeBuffer.slice(offset + start, offset + end);\n    });\n    out[spec.name] = decodeWeight(spec, compositeBuffer\n      .slice(offset, offset + byteLength));\n    offset += byteLength;\n  }\n  return out;\n}\n\nfunction getWeightBytelength(spec: WeightsManifestEntry,\n  slice: (start: number, end: number) => ArrayBuffer): number {\n\n  const size = sizeFromShape(spec.shape);\n  let bytesPerValue: number;\n  if ('quantization' in spec) {\n    const quantization = spec.quantization;\n    bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n  } else if (spec.dtype === 'string') {\n    // Can not statically determine string length.\n    let byteLength = 0;\n    for (let i = 0; i < size; i++) {\n      byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(\n        slice(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];\n    }\n    return byteLength;\n  } else {\n    bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];\n  }\n\n  return size * bytesPerValue;\n}\n\nasync function getWeightBytelengthAsync(\n  spec: WeightsManifestEntry,\n  slice: (start: number, end: number) => Promise<ArrayBuffer>\n): Promise<number> {\n\n  const size = sizeFromShape(spec.shape);\n  let bytesPerValue: number;\n  if ('quantization' in spec) {\n    const quantization = spec.quantization;\n    bytesPerValue = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n  } else if (spec.dtype === 'string') {\n    // Can not statically determine string length.\n    let byteLength = 0;\n    for (let i = 0; i < size; i++) {\n      byteLength += NUM_BYTES_STRING_LENGTH + new Uint32Array(\n        await slice(byteLength, byteLength + NUM_BYTES_STRING_LENGTH))[0];\n    }\n    return byteLength;\n  } else {\n    bytesPerValue = DTYPE_VALUE_SIZE_MAP[spec.dtype];\n  }\n\n  return size * bytesPerValue;\n}\n\nfunction decodeWeight(\n  spec: WeightsManifestEntry,\n  byteBuffer: ArrayBuffer): Tensor {\n\n  const name = spec.name;\n  const dtype = spec.dtype;\n  const shape = spec.shape;\n  const size = sizeFromShape(shape);\n  let values: TypedArray | string[] | Uint8Array[];\n  let offset = 0;\n\n  if ('quantization' in spec) {\n    const quantization = spec.quantization;\n    if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n      if (!('min' in quantization && 'scale' in quantization)) {\n        throw new Error(\n            `Weight ${spec.name} with quantization ${quantization.dtype} ` +\n            `doesn't have corresponding metadata min and scale.`);\n      }\n    } else if (quantization.dtype === 'float16') {\n      if (dtype !== 'float32') {\n        throw new Error(\n            `Weight ${spec.name} is quantized with ${quantization.dtype} ` +\n            `which only supports weights of type float32 not ${dtype}.`);\n      }\n    } else {\n      throw new Error(\n          `Weight ${spec.name} has unknown ` +\n          `quantization dtype ${quantization.dtype}. ` +\n          `Supported quantization dtypes are: ` +\n          `'uint8', 'uint16', and 'float16'.`);\n    }\n    const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n    const quantizedArray = (quantization.dtype === 'uint8') ?\n      new Uint8Array(byteBuffer) :\n      new Uint16Array(byteBuffer);\n    if (dtype === 'float32') {\n      if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n        values = new Float32Array(quantizedArray.length);\n        for (let i = 0; i < quantizedArray.length; i++) {\n          const v = quantizedArray[i];\n          values[i] = v * quantization.scale + quantization.min;\n        }\n      } else if (quantization.dtype === 'float16') {\n        // TODO: This is inefficient. Make getFloat16Decoder efficient.\n        const float16Decode = getFloat16Decoder();\n        values = float16Decode(quantizedArray as Uint16Array);\n      } else {\n        throw new Error(\n          `Unsupported quantization type ${quantization.dtype} ` +\n          `for weight type float32.`);\n      }\n    } else if (dtype === 'int32') {\n      if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {\n        throw new Error(\n          `Unsupported quantization type ${quantization.dtype} ` +\n          `for weight type int32.`);\n      }\n      values = new Int32Array(quantizedArray.length);\n      for (let i = 0; i < quantizedArray.length; i++) {\n        const v = quantizedArray[i];\n        values[i] = Math.round(v * quantization.scale + quantization.min);\n      }\n    } else {\n      throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n    }\n    offset += size * quantizationSizeFactor;\n  } else if (dtype === 'string') {\n    const size = sizeFromShape(spec.shape);\n    values = [];\n    for (let i = 0; i < size; i++) {\n      const byteLength = new Uint32Array(\n        byteBuffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n      offset += NUM_BYTES_STRING_LENGTH;\n      const bytes = new Uint8Array(\n        byteBuffer.slice(offset, offset + byteLength));\n      (values as Uint8Array[]).push(bytes);\n      offset += byteLength;\n    }\n  } else {\n    const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];\n    if (dtype === 'float32') {\n      values = new Float32Array(byteBuffer);\n    } else if (dtype === 'int32') {\n      values = new Int32Array(byteBuffer);\n    } else if (dtype === 'bool') {\n      values = new Uint8Array(byteBuffer);\n    } else if (dtype === 'complex64') {\n      values = new Float32Array(byteBuffer);\n      const real = new Float32Array(values.length / 2);\n      const image = new Float32Array(values.length / 2);\n      for (let i = 0; i < real.length; i++) {\n        real[i] = values[i * 2];\n        image[i] = values[i * 2 + 1];\n      }\n      const realTensor = tensor(real, shape, 'float32');\n      const imageTensor = tensor(image, shape, 'float32');\n      const complexTensor = complex(realTensor, imageTensor);\n      realTensor.dispose();\n      imageTensor.dispose();\n      return complexTensor;\n    } else {\n      throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n    }\n    offset += size * dtypeFactor;\n  }\n  return tensor(values, shape, dtype);\n}\n\nasync function readToLength(reader: ReadableStreamDefaultReader<ArrayBuffer>,\n                            initialData: ArrayBuffer,\n                            length: number): Promise<ArrayBuffer> {\n  let data = new Uint8Array(initialData);\n\n  while (data.byteLength < length) {\n    const {done, value} = await reader.read();\n    if (done && value == null) {\n      const missing  = length - data.byteLength;\n      throw new Error(`Reader is done but ${missing} bytes are still expected`);\n    }\n\n    // TODO: Don't create a new array every loop.\n    const newData = new Uint8Array(data.length + value.byteLength);\n    newData.set(data, 0);\n    newData.set(new Uint8Array(value), data.length);\n    data = newData;\n  }\n\n  return data.buffer;\n}\n\nexport async function decodeWeightsStream(\n  weightStream: ReadableStream<ArrayBuffer>,\n  specs: WeightsManifestEntry[]): Promise<NamedTensorMap> {\n\n  const tensors: NamedTensorMap = {};\n  const reader = weightStream.getReader();\n  let data = new ArrayBuffer(0);\n\n  for (const spec of specs) {\n    const byteLength = await getWeightBytelengthAsync(spec,\n                                                      async (start, end) => {\n      data = await readToLength(reader, data, end);\n      return data.slice(start, end);\n    });\n    data = await readToLength(reader, data, byteLength);\n\n    // Slice the tensor out\n    const tensorData = data.slice(0, byteLength);\n    data = data.slice(byteLength);\n\n    const weightTensor = decodeWeight(spec, tensorData);\n    tensors[spec.name] = weightTensor;\n\n    // TODO(mattsoulanille): Better way to call uploadToGPU.\n    // TODO(mattsoulanille): Make this work for webgl too.\n    if (getBackend() === 'webgpu') {\n      const b = backend();\n\n      if ('uploadToGPU' in b &&\n        sizeFromShape(weightTensor.shape) >= (env()\n          .get('WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD') as number)) {\n        (b.uploadToGPU as (dataId: DataId) => void)(weightTensor.dataId);\n      }\n    }\n  }\n\n  return tensors;\n}\n\n/**\n * Concatenate TypedArrays into an ArrayBuffer.\n */\nexport function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {\n  // TODO(adarob, cais): Support quantization.\n  if (xs === null) {\n    throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);\n  }\n\n  let totalByteLength = 0;\n\n  // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'\n  // can have a different byte length from that of the `TypedArray` itself,\n  // for example, when the `TypedArray` is created from an offset in an\n  // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match\n  // the `TypedArray` in byte length. If an element of `xs` does not show\n  // this property, a new `TypedArray` that satisfy this property will be\n  // constructed and pushed into `normalizedXs`.\n  const normalizedXs: TypedArray[] = [];\n  xs.forEach((x: TypedArray) => {\n    totalByteLength += x.byteLength;\n    // tslint:disable:no-any\n    normalizedXs.push(\n        x.byteLength === x.buffer.byteLength ? x :\n                                               new (x.constructor as any)(x));\n    if (!(x as any instanceof Float32Array || x as any instanceof Int32Array ||\n          x as any instanceof Uint8Array)) {\n      throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);\n    }\n    // tslint:enable:no-any\n  });\n\n  const y = new Uint8Array(totalByteLength);\n  let offset = 0;\n  normalizedXs.forEach((x: TypedArray) => {\n    y.set(new Uint8Array(x.buffer), offset);\n    offset += x.byteLength;\n  });\n\n  return y.buffer;\n}\n\n// Use Buffer on Node.js instead of Blob/atob/btoa\nconst useNodeBuffer = typeof Buffer !== 'undefined' &&\n    (typeof Blob === 'undefined' || typeof atob === 'undefined' ||\n     typeof btoa === 'undefined');\n\n/**\n * Calculate the byte length of a JavaScript string.\n *\n * Note that a JavaScript string can contain wide characters, therefore the\n * length of the string is not necessarily equal to the byte length.\n *\n * @param str Input string.\n * @returns Byte length.\n */\nexport function stringByteLength(str: string): number {\n  if (useNodeBuffer) {\n    return Buffer.byteLength(str, 'utf8');\n  }\n  return new Blob([str]).size;\n}\n\n/**\n * Encode an ArrayBuffer as a base64 encoded string.\n *\n * @param buffer `ArrayBuffer` to be converted.\n * @returns A string that base64-encodes `buffer`.\n */\nexport function arrayBufferToBase64String(buffer: ArrayBuffer): string {\n  if (useNodeBuffer) {\n    return Buffer.from(buffer).toString('base64');\n  }\n  const buf = new Uint8Array(buffer);\n  let s = '';\n  for (let i = 0, l = buf.length; i < l; i++) {\n    s += String.fromCharCode(buf[i]);\n  }\n  return btoa(s);\n}\n\n/**\n * Decode a base64 string as an ArrayBuffer.\n *\n * @param str Base64 string.\n * @returns Decoded `ArrayBuffer`.\n */\nexport function base64StringToArrayBuffer(str: string): ArrayBuffer {\n  if (useNodeBuffer) {\n    const buf = Buffer.from(str, 'base64');\n    return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n  }\n  const s = atob(str);\n  const buffer = new Uint8Array(s.length);\n  for (let i = 0; i < s.length; ++i) {\n    buffer.set([s.charCodeAt(i)], i);\n  }\n  return buffer.buffer;\n}\n\n/**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers An array of ArrayBuffers to concatenate, or a single\n *     ArrayBuffer.\n * @returns Result of concatenating `buffers` in order.\n *\n * @deprecated Use tf.io.CompositeArrayBuffer.join() instead.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]\n      | ArrayBuffer): ArrayBuffer {\n  return CompositeArrayBuffer.join(buffers);\n}\n\n/**\n * Get the basename of a path.\n *\n * Behaves in a way analogous to Linux's basename command.\n *\n * @param path\n */\nexport function basename(path: string): string {\n  const SEPARATOR = '/';\n  path = path.trim();\n  while (path.endsWith(SEPARATOR)) {\n    path = path.slice(0, path.length - 1);\n  }\n  const items = path.split(SEPARATOR);\n  return items[items.length - 1];\n}\n\n/**\n * Create `ModelJSON` from `ModelArtifacts`.\n *\n * @param artifacts Model artifacts, describing the model and its weights.\n * @param manifest Weight manifest, describing where the weights of the\n *     `ModelArtifacts` are stored, and some metadata about them.\n * @returns Object representing the `model.json` file describing the model\n *     artifacts and weights\n */\nexport function getModelJSONForModelArtifacts(\n    artifacts: ModelArtifacts, manifest: WeightsManifestConfig): ModelJSON {\n  const result: ModelJSON = {\n    modelTopology: artifacts.modelTopology,\n    format: artifacts.format,\n    generatedBy: artifacts.generatedBy,\n    convertedBy: artifacts.convertedBy,\n    weightsManifest: manifest\n  };\n  if (artifacts.signature != null) {\n    result.signature = artifacts.signature;\n  }\n  if (artifacts.userDefinedMetadata != null) {\n    result.userDefinedMetadata = artifacts.userDefinedMetadata;\n  }\n  if (artifacts.modelInitializer != null) {\n    result.modelInitializer = artifacts.modelInitializer;\n  }\n  if (artifacts.initializerSignature != null) {\n    result.initializerSignature = artifacts.initializerSignature;\n  }\n  if (artifacts.trainingConfig != null) {\n    result.trainingConfig = artifacts.trainingConfig;\n  }\n  return result;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file and weights.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param weightSpecs The list of WeightsManifestEntry for the model. Must be\n *     passed if the modelJSON has a weightsManifest.\n * @param weightData An ArrayBuffer or array of ArrayBuffers of weight data for\n *     the model corresponding to the weights in weightSpecs. Must be passed if\n *     the modelJSON has a weightsManifest.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport function getModelArtifactsForJSONSync(\n    modelJSON: ModelJSON, weightSpecs?: WeightsManifestEntry[],\n    weightData?: WeightData): ModelArtifacts {\n\n  const modelArtifacts: ModelArtifacts = {\n    modelTopology: modelJSON.modelTopology,\n    format: modelJSON.format,\n    generatedBy: modelJSON.generatedBy,\n    convertedBy: modelJSON.convertedBy\n  };\n\n  if (modelJSON.trainingConfig != null) {\n    modelArtifacts.trainingConfig = modelJSON.trainingConfig;\n  }\n  if (modelJSON.weightsManifest != null) {\n    if (!weightSpecs) {\n      throw new Error('modelJSON has weightsManifest but weightSpecs is null');\n    }\n    if (!weightData) {\n      throw new Error('modelJSON has weightsManifest but weightData is null');\n    }\n    modelArtifacts.weightSpecs = weightSpecs;\n    modelArtifacts.weightData = weightData;\n  }\n  if (modelJSON.signature != null) {\n    modelArtifacts.signature = modelJSON.signature;\n  }\n  if (modelJSON.userDefinedMetadata != null) {\n    modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata;\n  }\n  if (modelJSON.modelInitializer != null) {\n    modelArtifacts.modelInitializer = modelJSON.modelInitializer;\n  }\n  if (modelJSON.initializerSignature != null) {\n    modelArtifacts.initializerSignature = modelJSON.initializerSignature;\n  }\n\n  return modelArtifacts;\n}\n\n/**\n * Create `ModelArtifacts` from a JSON file.\n *\n * @param modelJSON Object containing the parsed JSON of `model.json`\n * @param loadWeights Function that takes the JSON file's weights manifest,\n *     reads weights from the listed path(s), and returns a Promise of the\n *     weight manifest entries along with the weights data.\n * @returns A Promise of the `ModelArtifacts`, as described by the JSON file.\n */\nexport async function getModelArtifactsForJSON(\n    modelJSON: ModelJSON,\n    loadWeights: (weightsManifest: WeightsManifestConfig) => Promise<[\n      /* weightSpecs */ WeightsManifestEntry[], WeightData,\n    ]>): Promise<ModelArtifacts> {\n  let weightSpecs: WeightsManifestEntry[] | undefined;\n  let weightData: WeightData | undefined;\n\n  if (modelJSON.weightsManifest != null) {\n    [weightSpecs, weightData] = await loadWeights(modelJSON.weightsManifest);\n  }\n\n  return getModelArtifactsForJSONSync(modelJSON, weightSpecs, weightData);\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n    ModelArtifactsInfo {\n  if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n    throw new Error('Expected JSON model topology, received ArrayBuffer.');\n  }\n\n  return {\n    dateSaved: new Date(),\n    modelTopologyType: 'JSON',\n    modelTopologyBytes: modelArtifacts.modelTopology == null ?\n        0 :\n        stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n    weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n        0 :\n        stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n    weightDataBytes: modelArtifacts.weightData == null ?\n        0 :\n        new CompositeArrayBuffer(modelArtifacts.weightData).byteLength,\n  };\n}\n\n/**\n * Concatenate the weights stored in a WeightsManifestConfig into a list of\n * WeightsManifestEntry\n *\n * @param weightsManifest The WeightsManifestConfig to extract weights from.\n * @returns A list of WeightsManifestEntry of the weights in the weightsManifest\n */\nexport function getWeightSpecs(weightsManifest: WeightsManifestConfig):\n    WeightsManifestEntry[] {\n  const weightSpecs: WeightsManifestEntry[] = [];\n  for (const entry of weightsManifest) {\n    weightSpecs.push(...entry.weights);\n  }\n  return weightSpecs;\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n  const convertMantissa = (i: number): number => {\n    let m = i << 13;\n    let e = 0;\n\n    while ((m & 0x00800000) === 0) {\n      e -= 0x00800000;\n      m <<= 1;\n    }\n    m &= ~0x00800000;\n    e += 0x38800000;\n\n    return m | e;\n  };\n\n  const mantisaTable = new Uint32Array(2048);\n\n  mantisaTable[0] = 0;\n  for (let i = 1; i < 1024; i++) {\n    mantisaTable[i] = convertMantissa(i);\n  }\n  for (let i = 1024; i < 2048; i++) {\n    mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n  }\n\n  return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n  const exponentTable = new Uint32Array(64);\n\n  exponentTable[0] = 0;\n  exponentTable[31] = 0x47800000;\n  exponentTable[32] = 0x80000000;\n  exponentTable[63] = 0xc7800000;\n  for (let i = 1; i < 31; i++) {\n    exponentTable[i] = i << 23;\n  }\n  for (let i = 33; i < 63; i++) {\n    exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n  }\n\n  return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n  const offsetTable = new Uint32Array(64);\n\n  for (let i = 0; i < 64; i++) {\n    offsetTable[i] = 1024;\n  }\n  offsetTable[0] = offsetTable[32] = 0;\n\n  return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n *          the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n  // Algorithm is based off of\n  // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n  // Cache lookup tables\n  const mantisaTable = computeFloat16MantisaTable();\n  const exponentTable = computeFloat16ExponentTable();\n  const offsetTable = computeFloat16OffsetTable();\n\n  return (quantizedArray: Uint16Array) => {\n    const buffer = new ArrayBuffer(4 * quantizedArray.length);\n    const bufferUint32View = new Uint32Array(buffer);\n    for (let index = 0; index < quantizedArray.length; index++) {\n      const float16Bits = quantizedArray[index];\n      const float32Bits =\n          mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n          exponentTable[float16Bits >> 10];\n      bufferUint32View[index] = float32Bits;\n    }\n    return new Float32Array(buffer);\n  };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {dispose, InferenceModel, io, ModelPredictConfig, NamedTensorMap, Tensor, util} from '@tensorflow/tfjs-core';\n\nimport * as tensorflow from '../data/compiled_api';\nimport {NamedTensorsMap, TensorInfo} from '../data/types';\nimport {OperationMapper} from '../operations/operation_mapper';\n\nimport {GraphExecutor} from './graph_executor';\nimport {ResourceManager} from './resource_manager';\n// tslint:disable-next-line: no-imports-from-dist\nimport {decodeWeightsStream} from '@tensorflow/tfjs-core/dist/io/io_utils';\n\nexport const TFHUB_SEARCH_PARAM = '?tfjs-format=file';\nexport const DEFAULT_MODEL_NAME = 'model.json';\ntype Url = string|io.IOHandler|io.IOHandlerSync;\ntype UrlIOHandler<T extends Url> = T extends string ? io.IOHandler : T;\n\n/**\n * A `tf.GraphModel` is a directed, acyclic graph built from a\n * SavedModel GraphDef and allows inference execution.\n *\n * A `tf.GraphModel` can only be created by loading from a model converted from\n * a [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) using\n * the command line converter tool and loaded via `tf.loadGraphModel`.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\nexport class GraphModel<ModelURL extends Url = string | io.IOHandler> implements\n    InferenceModel {\n  private executor: GraphExecutor;\n  private version = 'n/a';\n  private handler: UrlIOHandler<ModelURL>;\n  private artifacts: io.ModelArtifacts;\n  private initializer: GraphExecutor;\n  private resourceIdToCapturedInput: {[key: number]: Tensor};\n  private resourceManager: ResourceManager;\n  private signature: tensorflow.ISignatureDef;\n  private initializerSignature: tensorflow.ISignatureDef;\n  private structuredOutputKeys: string[];\n  private readonly io: typeof io;\n\n  // Returns the version information for the tensorflow model GraphDef.\n  get modelVersion(): string {\n    return this.version;\n  }\n\n  get inputNodes(): string[] {\n    return this.executor.inputNodes;\n  }\n\n  get outputNodes(): string[] {\n    return this.executor.outputNodes;\n  }\n\n  get inputs(): TensorInfo[] {\n    return this.executor.inputs;\n  }\n\n  get outputs(): TensorInfo[] {\n    return this.executor.outputs;\n  }\n\n  get weights(): NamedTensorsMap {\n    return this.executor.weightMap;\n  }\n\n  get metadata(): {} {\n    return this.artifacts.userDefinedMetadata;\n  }\n\n  get modelSignature(): {} {\n    return this.signature;\n  }\n\n  get modelStructuredOutputKeys(): {} {\n    return this.structuredOutputKeys;\n  }\n\n  /**\n   * @param modelUrl url for the model, or an `io.IOHandler`.\n   * @param weightManifestUrl url for the weight file generated by\n   * scripts/convert.py script.\n   * @param requestOption options for Request, which allows to send credentials\n   * and custom headers.\n   * @param onProgress Optional, progress callback function, fired periodically\n   * before the load is completed.\n   */\n  constructor(\n      private modelUrl: ModelURL, private loadOptions: io.LoadOptions = {},\n      tfio = io) {\n    this.io = tfio;\n    if (loadOptions == null) {\n      this.loadOptions = {};\n    }\n    this.resourceManager = new ResourceManager();\n  }\n\n  private findIOHandler() {\n    type IOHandler = UrlIOHandler<ModelURL>;\n    const path = this.modelUrl;\n    if ((path as io.IOHandler).load != null) {\n      // Path is an IO Handler.\n      this.handler = path as IOHandler;\n    } else if (this.loadOptions.requestInit != null) {\n      this.handler = this.io.browserHTTPRequest(\n                         path as string, this.loadOptions) as IOHandler;\n    } else {\n      const handlers =\n          this.io.getLoadHandlers(path as string, this.loadOptions);\n      if (handlers.length === 0) {\n        // For backward compatibility: if no load handler can be found,\n        // assume it is a relative http path.\n        handlers.push(\n            this.io.browserHTTPRequest(path as string, this.loadOptions));\n      } else if (handlers.length > 1) {\n        throw new Error(\n            `Found more than one (${handlers.length}) load handlers for ` +\n            `URL '${[path]}'`);\n      }\n      this.handler = handlers[0] as IOHandler;\n    }\n  }\n\n  /**\n   * Loads the model and weight files, construct the in memory weight map and\n   * compile the inference graph.\n   */\n  load(): UrlIOHandler<ModelURL> extends io.IOHandlerSync? boolean:\n                                             Promise<boolean> {\n    type IOHandler = UrlIOHandler<ModelURL>;\n    this.findIOHandler();\n    if (this.handler.load == null) {\n      throw new Error(\n          'Cannot proceed with model loading because the IOHandler provided ' +\n          'does not have the `load` method implemented.');\n    }\n\n    type Result =\n        IOHandler extends io.IOHandlerSync ? boolean : Promise<boolean>;\n\n    const loadResult = this.handler.load() as ReturnType<IOHandler['load']>;\n    if (util.isPromise(loadResult)) {\n      return loadResult.then(artifacts => {\n        if (artifacts.getWeightStream == null) {\n          return this.loadSync(artifacts);\n        }\n        return this.loadStreaming(artifacts);\n      }) as Result;\n    }\n\n    return this.loadSync(loadResult) as Result;\n  }\n\n  /**\n   * Synchronously construct the in memory weight map and\n   * compile the inference graph.\n   *\n   * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}\n   */\n  loadSync(artifacts: io.ModelArtifacts) {\n    const weightMap = this.io.decodeWeights(\n        artifacts.weightData, artifacts.weightSpecs);\n\n    return this.loadWithWeightMap(artifacts, weightMap);\n  }\n\n  private async loadStreaming(artifacts: io.ModelArtifacts): Promise<boolean> {\n    if (artifacts.getWeightStream == null) {\n      throw new Error('Model artifacts missing streamWeights function');\n    }\n\n    const weightMap = await decodeWeightsStream(\n      artifacts.getWeightStream(), artifacts.weightSpecs);\n\n    return this.loadWithWeightMap(artifacts, weightMap);\n  }\n\n  private loadWithWeightMap(artifacts: io.ModelArtifacts,\n                            weightMap: NamedTensorMap) {\n    this.artifacts = artifacts;\n    const graph = this.artifacts.modelTopology as tensorflow.IGraphDef;\n\n    let signature = this.artifacts.signature;\n    if (this.artifacts.userDefinedMetadata != null) {\n      const metadata = this.artifacts.userDefinedMetadata;\n      if (metadata.signature != null) {\n        signature = metadata.signature;\n      }\n\n      if (metadata.structuredOutputKeys != null) {\n        this.structuredOutputKeys = metadata.structuredOutputKeys as string[];\n      }\n    }\n    this.signature = signature;\n\n    this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`;\n    this.executor = new GraphExecutor(\n        OperationMapper.Instance.transformGraph(graph, this.signature));\n    this.executor.weightMap = this.convertTensorMapToTensorsMap(weightMap);\n    // Attach a model-level resourceManager to each executor to share resources,\n    // such as `HashTable`.\n    this.executor.resourceManager = this.resourceManager;\n\n    if (artifacts.modelInitializer != null &&\n        (artifacts.modelInitializer as tensorflow.IGraphDef).node != null) {\n      const initializer =\n          OperationMapper.Instance.transformGraph(artifacts.modelInitializer);\n      this.initializer = new GraphExecutor(initializer);\n      this.initializer.weightMap = this.executor.weightMap;\n      // Attach a model-level resourceManager to the initializer, the\n      // hashTables created from when executing the initializer will be stored\n      // in the resourceManager.\n      this.initializer.resourceManager = this.resourceManager;\n      this.initializerSignature = artifacts.initializerSignature;\n    }\n\n    return true;\n  }\n\n  /**\n   * Save the configuration and/or weights of the GraphModel.\n   *\n   * An `IOHandler` is an object that has a `save` method of the proper\n   * signature defined. The `save` method manages the storing or\n   * transmission of serialized data (\"artifacts\") that represent the\n   * model's topology and weights onto or via a specific medium, such as\n   * file downloads, local storage, IndexedDB in the web browser and HTTP\n   * requests to a server. TensorFlow.js provides `IOHandler`\n   * implementations for a number of frequently used saving mediums, such as\n   * `tf.io.browserDownloads` and `tf.io.browserLocalStorage`. See `tf.io`\n   * for more details.\n   *\n   * This method also allows you to refer to certain types of `IOHandler`s\n   * as URL-like string shortcuts, such as 'localstorage://' and\n   * 'indexeddb://'.\n   *\n   * Example 1: Save `model`'s topology and weights to browser [local\n   * storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage);\n   * then load it back.\n   *\n   * ```js\n   * const modelUrl =\n   *    'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';\n   * const model = await tf.loadGraphModel(modelUrl);\n   * const zeros = tf.zeros([1, 224, 224, 3]);\n   * model.predict(zeros).print();\n   *\n   * const saveResults = await model.save('localstorage://my-model-1');\n   *\n   * const loadedModel = await tf.loadGraphModel('localstorage://my-model-1');\n   * console.log('Prediction from loaded model:');\n   * model.predict(zeros).print();\n   * ```\n   *\n   * @param handlerOrURL An instance of `IOHandler` or a URL-like,\n   * scheme-based string shortcut for `IOHandler`.\n   * @param config Options for saving the model.\n   * @returns A `Promise` of `SaveResult`, which summarizes the result of\n   * the saving, such as byte sizes of the saved artifacts for the model's\n   *   topology and weight values.\n   *\n   * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}\n   */\n  async save(handlerOrURL: io.IOHandler|string, config?: io.SaveConfig):\n      Promise<io.SaveResult> {\n    if (typeof handlerOrURL === 'string') {\n      const handlers = this.io.getSaveHandlers(handlerOrURL);\n      if (handlers.length === 0) {\n        throw new Error(\n            `Cannot find any save handlers for URL '${handlerOrURL}'`);\n      } else if (handlers.length > 1) {\n        throw new Error(\n            `Found more than one (${handlers.length}) save handlers for ` +\n            `URL '${handlerOrURL}'`);\n      }\n      handlerOrURL = handlers[0];\n    }\n    if (handlerOrURL.save == null) {\n      throw new Error(\n          'GraphModel.save() cannot proceed because the IOHandler ' +\n          'provided does not have the `save` attribute defined.');\n    }\n\n    return handlerOrURL.save(this.artifacts);\n  }\n\n  private addStructuredOutputNames(outputTensors: Tensor|Tensor[]) {\n    if (this.structuredOutputKeys) {\n      const outputTensorsArray =\n          outputTensors instanceof Tensor ? [outputTensors] : outputTensors;\n      const outputTensorMap: NamedTensorMap = {};\n\n      outputTensorsArray.forEach(\n          (outputTensor, i) => outputTensorMap[this.structuredOutputKeys[i]] =\n              outputTensor);\n\n      return outputTensorMap;\n    }\n    return outputTensors;\n  }\n\n  /**\n   * Execute the inference for the input tensors.\n   *\n   * @param input The input tensors, when there is single input for the model,\n   * inputs param should be a `tf.Tensor`. For models with multiple inputs,\n   * inputs params should be in either `tf.Tensor`[] if the input order is\n   * fixed, or otherwise NamedTensorMap format.\n   *\n   * For model with multiple inputs, we recommend you use NamedTensorMap as the\n   * input type, if you use `tf.Tensor`[], the order of the array needs to\n   * follow the\n   * order of inputNodes array. @see {@link GraphModel.inputNodes}\n   *\n   * You can also feed any intermediate nodes using the NamedTensorMap as the\n   * input type. For example, given the graph\n   *    InputNode => Intermediate => OutputNode,\n   * you can execute the subgraph Intermediate => OutputNode by calling\n   *    model.execute('IntermediateNode' : tf.tensor(...));\n   *\n   * This is useful for models that uses tf.dynamic_rnn, where the intermediate\n   * state needs to be fed manually.\n   *\n   * For batch inference execution, the tensors for each input need to be\n   * concatenated together. For example with mobilenet, the required input shape\n   * is [1, 244, 244, 3], which represents the [batch, height, width, channel].\n   * If we are provide a batched data of 100 images, the input tensor should be\n   * in the shape of [100, 244, 244, 3].\n   *\n   * @param config Prediction configuration for specifying the batch size.\n   * Currently the batch size option is ignored for graph model.\n   *\n   * @returns Inference result tensors. If the model is converted and it\n   * originally had structured_outputs in tensorflow, then a NamedTensorMap\n   * will be returned matching the structured_outputs. If no structured_outputs\n   * are present, the output will be single `tf.Tensor` if the model has single\n   * output node, otherwise Tensor[].\n   *\n   * @doc {heading: 'Models', subheading: 'Classes'}\n   */\n  predict(inputs: Tensor|Tensor[]|NamedTensorMap, config?: ModelPredictConfig):\n      Tensor|Tensor[]|NamedTensorMap {\n    const outputTensors = this.execute(inputs, this.outputNodes);\n    return this.addStructuredOutputNames(outputTensors);\n  }\n\n  /**\n   * Execute the inference for the input tensors in async fashion, use this\n   * method when your model contains control flow ops.\n   *\n   * @param input The input tensors, when there is single input for the model,\n   * inputs param should be a `tf.Tensor`. For models with mutliple inputs,\n   * inputs params should be in either `tf.Tensor`[] if the input order is\n   * fixed, or otherwise NamedTensorMap format.\n   *\n   * For model with multiple inputs, we recommend you use NamedTensorMap as the\n   * input type, if you use `tf.Tensor`[], the order of the array needs to\n   * follow the\n   * order of inputNodes array. @see {@link GraphModel.inputNodes}\n   *\n   * You can also feed any intermediate nodes using the NamedTensorMap as the\n   * input type. For example, given the graph\n   *    InputNode => Intermediate => OutputNode,\n   * you can execute the subgraph Intermediate => OutputNode by calling\n   *    model.execute('IntermediateNode' : tf.tensor(...));\n   *\n   * This is useful for models that uses tf.dynamic_rnn, where the intermediate\n   * state needs to be fed manually.\n   *\n   * For batch inference execution, the tensors for each input need to be\n   * concatenated together. For example with mobilenet, the required input shape\n   * is [1, 244, 244, 3], which represents the [batch, height, width, channel].\n   * If we are provide a batched data of 100 images, the input tensor should be\n   * in the shape of [100, 244, 244, 3].\n   *\n   * @param config Prediction configuration for specifying the batch size.\n   * Currently the batch size option is ignored for graph model.\n   *\n   * @returns A Promise of inference result tensors. If the model is converted\n   * and it originally had structured_outputs in tensorflow, then a\n   * NamedTensorMap will be returned matching the structured_outputs. If no\n   * structured_outputs are present, the output will be single `tf.Tensor` if\n   * the model has single output node, otherwise Tensor[].\n   *\n   * @doc {heading: 'Models', subheading: 'Classes'}\n   */\n  async predictAsync(\n      inputs: Tensor|Tensor[]|NamedTensorMap,\n      config?: ModelPredictConfig): Promise<Tensor|Tensor[]|NamedTensorMap> {\n    const outputTensors = await this.executeAsync(inputs, this.outputNodes);\n    return this.addStructuredOutputNames(outputTensors);\n  }\n\n  private normalizeInputs(inputs: Tensor|Tensor[]|\n                          NamedTensorMap): NamedTensorMap {\n    if (!(inputs instanceof Tensor) && !Array.isArray(inputs)) {\n      // The input is already a NamedTensorMap.\n      const signatureInputs = this.signature?.inputs;\n      if (signatureInputs != null) {\n        for (const input in signatureInputs) {\n          const tensor = signatureInputs[input];\n          if (tensor.resourceId != null) {\n            inputs[input] = this.resourceIdToCapturedInput[tensor.resourceId];\n          }\n        }\n      }\n      return inputs;\n    }\n    inputs = Array.isArray(inputs) ? inputs : [inputs];\n\n    const numCapturedInputs =\n        Object.keys(this.resourceIdToCapturedInput).length;\n    if (inputs.length + numCapturedInputs !== this.inputNodes.length) {\n      throw new Error(`Input tensor count mismatch, the graph model has ${\n          this.inputNodes.length -\n          numCapturedInputs} non-resource placeholders, while there are ${\n          inputs.length} input tensors provided.`);\n    }\n\n    let inputIndex = 0;\n    return this.inputNodes.reduce((map, inputName) => {\n      const resourceId = this.signature?.inputs?.[inputName]?.resourceId;\n      if (resourceId != null) {\n        map[inputName] = this.resourceIdToCapturedInput[resourceId];\n      } else {\n        map[inputName] = (inputs as Tensor[])[inputIndex++];\n      }\n      return map;\n    }, {} as NamedTensorMap);\n  }\n\n  private normalizeOutputs(outputs: string|string[]): string[] {\n    outputs = outputs || this.outputNodes;\n    return !Array.isArray(outputs) ? [outputs] : outputs;\n  }\n\n  private executeInitializerGraph() {\n    if (this.initializer == null) {\n      return [];\n    }\n    if (this.initializerSignature == null) {\n      return this.initializer.execute({}, []);\n    } else {\n      return this.initializer.execute(\n          {}, Object.keys(this.initializerSignature.outputs));\n    }\n  }\n\n  private async executeInitializerGraphAsync() {\n    if (this.initializer == null) {\n      return [];\n    }\n    if (this.initializerSignature == null) {\n      return this.initializer.executeAsync({}, []);\n    } else {\n      return this.initializer.executeAsync(\n          {}, Object.keys(this.initializerSignature.outputs));\n    }\n  }\n\n  private setResourceIdToCapturedInput(outputs: Tensor[]) {\n    this.resourceIdToCapturedInput = {};\n\n    if (this.initializerSignature) {\n      const signatureOutputs = this.initializerSignature.outputs;\n      const outputNames = Object.keys(signatureOutputs);\n      for (let i = 0; i < outputNames.length; i++) {\n        const outputName = outputNames[i];\n        const tensorInfo = signatureOutputs[outputName];\n        this.resourceIdToCapturedInput[tensorInfo.resourceId] = outputs[i];\n      }\n    }\n  }\n\n  /**\n   * Executes inference for the model for given input tensors.\n   * @param inputs tensor, tensor array or tensor map of the inputs for the\n   * model, keyed by the input node names.\n   * @param outputs output node name from the TensorFlow model, if no\n   * outputs are specified, the default outputs of the model would be used.\n   * You can inspect intermediate nodes of the model by adding them to the\n   * outputs array.\n   *\n   * @returns A single tensor if provided with a single output or no outputs\n   * are provided and there is only one default output, otherwise return a\n   * tensor array. The order of the tensor array is the same as the outputs\n   * if provided, otherwise the order of outputNodes attribute of the model.\n   *\n   * @doc {heading: 'Models', subheading: 'Classes'}\n   */\n  execute(inputs: Tensor|Tensor[]|NamedTensorMap, outputs?: string|string[]):\n      Tensor|Tensor[] {\n    if (this.resourceIdToCapturedInput == null) {\n      this.setResourceIdToCapturedInput(this.executeInitializerGraph());\n    }\n    inputs = this.normalizeInputs(inputs);\n    outputs = this.normalizeOutputs(outputs);\n    const result = this.executor.execute(inputs, outputs);\n    return result.length > 1 ? result : result[0];\n  }\n\n  /**\n   * Executes inference for the model for given input tensors in async\n   * fashion, use this method when your model contains control flow ops.\n   * @param inputs tensor, tensor array or tensor map of the inputs for the\n   * model, keyed by the input node names.\n   * @param outputs output node name from the TensorFlow model, if no outputs\n   * are specified, the default outputs of the model would be used. You can\n   * inspect intermediate nodes of the model by adding them to the outputs\n   * array.\n   *\n   * @returns A Promise of single tensor if provided with a single output or\n   * no outputs are provided and there is only one default output, otherwise\n   * return a tensor map.\n   *\n   * @doc {heading: 'Models', subheading: 'Classes'}\n   */\n  async executeAsync(\n      inputs: Tensor|Tensor[]|NamedTensorMap,\n      outputs?: string|string[]): Promise<Tensor|Tensor[]> {\n    if (this.resourceIdToCapturedInput == null) {\n      this.setResourceIdToCapturedInput(\n          await this.executeInitializerGraphAsync());\n    }\n    inputs = this.normalizeInputs(inputs);\n    outputs = this.normalizeOutputs(outputs);\n    const result = await this.executor.executeAsync(inputs, outputs);\n    return result.length > 1 ? result : result[0];\n  }\n\n  /**\n   * Get intermediate tensors for model debugging mode (flag\n   * KEEP_INTERMEDIATE_TENSORS is true).\n   *\n   * @doc {heading: 'Models', subheading: 'Classes'}\n   */\n  getIntermediateTensors(): NamedTensorsMap {\n    return this.executor.getIntermediateTensors();\n  }\n\n  /**\n   * Dispose intermediate tensors for model debugging mode (flag\n   * KEEP_INTERMEDIATE_TENSORS is true).\n   *\n   * @doc {heading: 'Models', subheading: 'Classes'}\n   */\n  disposeIntermediateTensors() {\n    this.executor.disposeIntermediateTensors();\n  }\n\n  private convertTensorMapToTensorsMap(map: NamedTensorMap): NamedTensorsMap {\n    return Object.keys(map).reduce((newMap: NamedTensorsMap, key) => {\n      newMap[key] = [map[key]];\n      return newMap;\n    }, {});\n  }\n\n  /**\n   * Releases the memory used by the weight tensors and resourceManager.\n   *\n   * @doc {heading: 'Models', subheading: 'Classes'}\n   */\n  dispose() {\n    this.executor.dispose();\n\n    if (this.initializer) {\n      this.initializer.dispose();\n      if (this.resourceIdToCapturedInput) {\n        dispose(this.resourceIdToCapturedInput);\n      }\n    }\n\n    this.resourceManager.dispose();\n  }\n}\n\n/**\n * Load a graph model given a URL to the model definition.\n *\n * Example of loading MobileNetV2 from a URL and making a prediction with a\n * zeros input:\n *\n * ```js\n * const modelUrl =\n *    'https://storage.googleapis.com/tfjs-models/savedmodel/mobilenet_v2_1.0_224/model.json';\n * const model = await tf.loadGraphModel(modelUrl);\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n * ```\n *\n * Example of loading MobileNetV2 from a TF Hub URL and making a prediction\n * with a zeros input:\n *\n * ```js\n * const modelUrl =\n *    'https://tfhub.dev/google/imagenet/mobilenet_v2_140_224/classification/2';\n * const model = await tf.loadGraphModel(modelUrl, {fromTFHub: true});\n * const zeros = tf.zeros([1, 224, 224, 3]);\n * model.predict(zeros).print();\n * ```\n * @param modelUrl The url or an `io.IOHandler` that loads the model.\n * @param options Options for the HTTP request, which allows to send\n *     credentials\n *    and custom headers.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport async function loadGraphModel(\n    modelUrl: string|io.IOHandler, options: io.LoadOptions = {},\n    tfio = io): Promise<GraphModel> {\n  if (modelUrl == null) {\n    throw new Error(\n        'modelUrl in loadGraphModel() cannot be null. Please provide a url ' +\n        'or an IOHandler that loads the model');\n  }\n  if (options == null) {\n    options = {};\n  }\n\n  if (options.fromTFHub && typeof modelUrl === 'string') {\n    modelUrl = getTFHubUrl(modelUrl);\n  }\n  const model = new GraphModel(modelUrl, options, tfio);\n  await model.load();\n  return model;\n}\n\n/**\n * Load a graph model given a synchronous IO handler with a 'load' method.\n *\n * @param modelSource The `io.IOHandlerSync` that loads the model, or the\n *     `io.ModelArtifacts` that encode the model, or a tuple of\n *     `[io.ModelJSON, ArrayBuffer]` of which the first element encodes the\n *      model and the second contains the weights.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport function loadGraphModelSync(\n    modelSource: io.IOHandlerSync|\n    io.ModelArtifacts|[io.ModelJSON, /* Weights */ ArrayBuffer]):\n    GraphModel<io.IOHandlerSync> {\n  if (modelSource == null) {\n    throw new Error(\n        'modelUrl in loadGraphModelSync() cannot be null. Please provide ' +\n        'model artifacts or an IOHandler that loads the model');\n  }\n\n  let ioHandler: io.IOHandlerSync;\n  if (modelSource instanceof Array) {\n    const [modelJSON, weights] = modelSource;\n    if (!modelJSON) {\n      throw new Error('modelJSON must be the first element of the array');\n    }\n    if (!weights || !(weights instanceof ArrayBuffer)) {\n      throw new Error(\n          'An ArrayBuffer of weights must be the second element of' +\n          ' the array');\n    }\n    if (!('modelTopology' in modelJSON)) {\n      throw new Error('Model JSON is missing \\'modelTopology\\'');\n    }\n    if (!('weightsManifest' in modelJSON)) {\n      throw new Error('Model JSON is missing \\'weightsManifest\\'');\n    }\n\n    const weightSpecs = io.getWeightSpecs(modelJSON.weightsManifest);\n    const modelArtifacts =\n        io.getModelArtifactsForJSONSync(modelJSON, weightSpecs, weights);\n    ioHandler = io.fromMemorySync(modelArtifacts);\n  } else if ('load' in modelSource) {\n    // Then modelSource is already an IOHandlerSync.\n    ioHandler = modelSource;\n  } else if (\n      'modelTopology' in modelSource && 'weightSpecs' in modelSource &&\n      'weightData' in modelSource) {\n    // modelSource is of type ModelArtifacts.\n    ioHandler = io.fromMemorySync(modelSource);\n  } else {\n    throw new Error('Unknown model format');\n  }\n\n  const model = new GraphModel(ioHandler);\n  model.load();\n  return model;\n}\n\nfunction getTFHubUrl(modelUrl: string): string {\n  if (!modelUrl.endsWith('/')) {\n    modelUrl = (modelUrl) + '/';\n  }\n  return `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`;\n}\n", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '4.22.0';\nexport {version};\n", "import fs from \"fs\";\nimport path from \"path\";\nimport zlib from \"zlib\";\nimport { TfjsEmbedder } from \"./tfjs-embedder.ts\";\nimport { logToolResult } from \"./logger.ts\";\n\nexport interface UseCaseResult {\n  id: string;\n  description: string;\n  category: string;\n  featuresUsed?: string[];\n  tokenCount: number;\n  similarity: number;\n}\n\nlet cachedVectors: { id: string; description: string; category: string; featuresUsed: string[]; tokenCount: number; vector: number[]; norm: number }[] | null = null;\n\nfunction dotProduct(a: number[], b: number[]): number {\n  let dotProduct = 0;\n  for (let i = 0; i < a.length; i++) {\n    dotProduct += a[i] * b[i];\n  }\n  return dotProduct;\n}\n\nfunction calculateNorm(v: number[]): number {\n  let sum = 0;\n  for (const val of v) {\n    sum += val * val;\n  }\n  return Math.sqrt(sum);\n}\n\nexport async function searchUseCases(query: string, limit = 5, minSimilarity = 0.3, embedder?: any): Promise<UseCaseResult[]> {\n  const actualEmbedder = embedder || TfjsEmbedder.getInstance();\n  const queryVector = await actualEmbedder.embed(query);\n  const queryNorm = calculateNorm(queryVector);\n\n  if (!cachedVectors) {\n    const VECTORS_FILE = path.join(import.meta.dirname, \"use-cases.vectors.gen.json.gz\");\n    if (!fs.existsSync(VECTORS_FILE)) {\n      return [];\n    }\n\n    const compressed = fs.readFileSync(VECTORS_FILE);\n    const jsonContent = zlib.gunzipSync(compressed).toString(\"utf-8\");\n    const items: any[] = JSON.parse(jsonContent);\n\n    cachedVectors = items.map(item => ({\n      id: item.id,\n      description: item.description,\n      category: item.category,\n      featuresUsed: item.featuresUsed || [],\n      tokenCount: item.tokenCount || 0,\n      vector: item.vector,\n      norm: item.vector ? calculateNorm(item.vector) : 0\n    })).filter(item => item.vector);\n  }\n\n  const resultsMap = new Map<string, { item: (typeof cachedVectors)[0]; similarity: number }>();\n\n  for (const item of cachedVectors) {\n    if (item.norm === 0 || queryNorm === 0) continue;\n    \n    const sim = dotProduct(queryVector, item.vector) / (queryNorm * item.norm);\n    \n    if (sim < minSimilarity) continue;\n\n    const existing = resultsMap.get(item.id);\n    if (!existing || sim > existing.similarity) {\n      resultsMap.set(item.id, { item, similarity: sim });\n    }\n  }\n\n  const results = Array.from(resultsMap.values());\n\n  // Sort by similarity descending\n  results.sort((a, b) => b.similarity - a.similarity);\n\n  const limitedResults = results.slice(0, limit).map(r => ({\n    id: r.item.id,\n    description: r.item.description,\n    category: r.item.category,\n    featuresUsed: r.item.featuresUsed?.length ? r.item.featuresUsed : undefined,\n    tokenCount: r.item.tokenCount,\n    similarity: parseFloat(r.similarity.toFixed(4))\n  }));\n\n  // Log the result\n  logToolResult(\"search_use_cases\", limitedResults.map(r => ({ id: r.id, similarity: r.similarity })));\n\n  return limitedResults;\n}\n", "import { setBackend, tensor2d, Tensor } from \"@tensorflow/tfjs-core\";\nimport { loadGraphModel, GraphModel } from \"@tensorflow/tfjs-converter\";\nimport { BertTokenizer } from \"@huggingface/transformers\";\nimport \"./tfjs-kernels.ts\";\nimport path from \"path\";\nimport fs from \"fs\";\n\n// Custom IOHandler for loading TFJS models from disk in Node without fetch\nfunction createNodeFileSystemIOHandler(modelJsonPath: string) {\n  return {\n    load: async () => {\n      const dir = path.dirname(modelJsonPath);\n      const modelJson = JSON.parse(await fs.promises.readFile(modelJsonPath, \"utf-8\"));\n      const modelTopology = modelJson.modelTopology;\n      const weightsManifest = modelJson.weightsManifest;\n      const weightSpecs: any[] = [];\n\n      // NOTE: Simplified assuming 1 shard for MiniLM (group1-shard1of1.bin).\n      // If we go back to multiple shards in the future, restore the loops:\n      // for (const manifest of weightsManifest) { weightSpecs.push(...manifest.weights); for (const shardPath of manifest.paths) shardPromises.push(fs.promises.readFile(path.resolve(dir, shardPath))); }\n      const manifest = weightsManifest[0];\n      weightSpecs.push(...manifest.weights);\n      const shardPath = manifest.paths[0];\n      const fullPath = path.resolve(dir, shardPath);\n      const weightData = (await fs.promises.readFile(fullPath)).buffer;\n\n      return {\n        modelTopology,\n        weightSpecs,\n        weightData\n      };\n    }\n  };\n}\n\nexport class TfjsEmbedder {\n  private static instance: TfjsEmbedder;\n  private model: GraphModel | null = null;\n  private tokenizer: any = null;\n  public modelName = \"tfjs:all-MiniLM-L6-v2\";\n\n  private constructor() {}\n\n  public static getInstance(): TfjsEmbedder {\n    if (!TfjsEmbedder.instance) {\n      TfjsEmbedder.instance = new TfjsEmbedder();\n    }\n    return TfjsEmbedder.instance;\n  }\n\n  public static clearInstance() {\n    TfjsEmbedder.instance = null as any;\n  }\n\n  public async init() {\n    if (this.model) return;\n\n    const benchmarkDir = path.resolve(import.meta.dirname);\n    const modelPath = path.resolve(benchmarkDir, \"tfjs_model_minilm/model.json\");\n\n    try {\n        const ioHandler = createNodeFileSystemIOHandler(modelPath);\n\n        // Silence TFJS console warning about node backend\n        const oldLog = console.log;\n        const oldWarn = console.warn;\n        console.log = () => {};\n        console.warn = () => {};\n\n        try {\n            await setBackend('cpu');\n            this.model = await loadGraphModel(ioHandler as any);\n        } finally {\n            console.log = oldLog;\n            console.warn = oldWarn;\n        }\n\n        // Use local_files_only first to avoid a network request to huggingface.\n        try {\n            this.tokenizer = await BertTokenizer.from_pretrained(\"Xenova/all-MiniLM-L6-v2\", { local_files_only: true });\n        } catch (e) {\n            this.tokenizer = await BertTokenizer.from_pretrained(\"Xenova/all-MiniLM-L6-v2\");\n        }\n    } catch (e) {\n        console.error(\"Failed to load TFJS model:\", e);\n        throw e;\n    }\n  }\n\n  public async embed(text: string): Promise<number[]> {\n    if (!this.model || !this.tokenizer) {\n        await this.init();\n    }\n    if (!this.model || !this.tokenizer) {\n        throw new Error(\"Failed to initialize TFJS Embedder\");\n    }\n\n    const tokenized = await this.tokenizer(text, { padding: true, truncation: true });\n\n    // Extract data and convert to numbers (handling BigInt if present)\n    const extractData = (tensor: any) => {\n        const data = tensor.data || tensor;\n        return Array.from(data).map((x: any) => Number(x));\n    };\n\n    const inputIdsData = extractData(tokenized.input_ids);\n    const attentionMaskData = extractData(tokenized.attention_mask);\n    const tokenTypeIdsData = extractData(tokenized.token_type_ids);\n\n    const inputIds = tensor2d([inputIdsData], undefined, 'int32');\n    const attentionMask = tensor2d([attentionMaskData], undefined, 'int32');\n    const tokenTypeIds = tensor2d([tokenTypeIdsData], undefined, 'int32');\n\n    const result = this.model.predict({\n        \"input_ids\": inputIds,\n        \"attention_mask\": attentionMask,\n        \"token_type_ids\": tokenTypeIds\n    }) as Tensor;\n\n    const data = await result.data();\n\n    // Cleanup tensors\n    inputIds.dispose();\n    attentionMask.dispose();\n    tokenTypeIds.dispose();\n    result.dispose();\n\n    return Array.from(data);\n  }\n\n  public shutdown() {\n    // No-op: we use custom IO handler instead of local server now\n  }\n}\n", "\n/**\n * A base class for creating callable objects.\n * See [here](https://stackoverflow.com/q/76073890) for more information.\n * \n * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}\n */\nexport const Callable = /** @type {any} */ (class {\n    /**\n    * Creates a new instance of the Callable class.\n    */\n    constructor() {\n        /**\n         * Creates a closure that delegates to a private method '_call' with the given arguments.\n         * @type {any}\n         * @param {...any} args Zero or more arguments to pass to the '_call' method.\n         * @returns {*} The result of calling the '_call' method.\n         */\n        let closure = function (...args) {\n            return closure._call(...args)\n        }\n        return Object.setPrototypeOf(closure, new.target.prototype)\n    }\n\n    /**\n     * This method should be implemented in subclasses to provide the\n     * functionality of the callable object.\n     *\n     * @param {any[]} args\n     * @throws {Error} If the subclass does not implement the `_call` method.\n     */\n    _call(...args) {\n        throw Error('Must implement _call method in subclass')\n    }\n});\n", "\n/**\n * @file Core utility functions/classes for Transformers.js.\n *\n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n *\n * @module utils/core\n */\n\n/**\n * @typedef {Object} InitiateProgressInfo\n * @property {'initiate'} status\n * @property {string} name The model id or directory path.\n * @property {string} file The name of the file.\n */\n\n/**\n * @typedef {Object} DownloadProgressInfo\n * @property {'download'} status\n * @property {string} name The model id or directory path.\n * @property {string} file The name of the file.\n */\n\n/**\n * @typedef {Object} ProgressStatusInfo\n * @property {'progress'} status\n * @property {string} name The model id or directory path.\n * @property {string} file The name of the file.\n * @property {number} progress A number between 0 and 100.\n * @property {number} loaded The number of bytes loaded.\n * @property {number} total The total number of bytes to be loaded.\n */\n\n/**\n * @typedef {Object} DoneProgressInfo\n * @property {'done'} status\n * @property {string} name The model id or directory path.\n * @property {string} file The name of the file.\n */\n\n/**\n * @typedef {Object} ReadyProgressInfo\n * @property {'ready'} status\n * @property {string} task The loaded task.\n * @property {string} model The loaded model.\n */\n\n/**\n * @typedef {InitiateProgressInfo | DownloadProgressInfo | ProgressStatusInfo | DoneProgressInfo | ReadyProgressInfo} ProgressInfo\n */\n\n/**\n * A callback function that is called with progress information.\n * @callback ProgressCallback\n * @param {ProgressInfo} progressInfo\n * @returns {void}\n */\n\n/**\n * Helper function to dispatch progress callbacks.\n *\n * @param {ProgressCallback | null | undefined} progress_callback The progress callback function to dispatch.\n * @param {ProgressInfo} data The data to pass to the progress callback function.\n * @returns {void}\n * @private\n */\nexport function dispatchCallback(progress_callback, data) {\n    if (progress_callback) progress_callback(data);\n}\n\n/**\n * Reverses the keys and values of an object.\n *\n * @param {Object} data The object to reverse.\n * @returns {Object} The reversed object.\n * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n */\nexport function reverseDictionary(data) {\n    // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n    return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));\n}\n\n/**\n * Escapes regular expression special characters from a string by replacing them with their escaped counterparts.\n *\n * @param {string} string The string to escape.\n * @returns {string} The escaped string.\n */\nexport function escapeRegExp(string) {\n    return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n}\n\n/**\n * Check if a value is a typed array.\n * @param {*} val The value to check.\n * @returns {boolean} True if the value is a `TypedArray`, false otherwise.\n *\n * Adapted from https://stackoverflow.com/a/71091338/13989043\n */\nexport function isTypedArray(val) {\n    return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';\n}\n\n\n/**\n * Check if a value is an integer.\n * @param {*} x The value to check.\n * @returns {boolean} True if the value is a string, false otherwise.\n */\nexport function isIntegralNumber(x) {\n    return Number.isInteger(x) || typeof x === 'bigint'\n}\n\n/**\n * Determine if a provided width or height is nullish.\n * @param {*} x The value to check.\n * @returns {boolean} True if the value is `null`, `undefined` or `-1`, false otherwise.\n */\nexport function isNullishDimension(x) {\n    return x === null || x === undefined || x === -1;\n}\n\n/**\n * Calculates the dimensions of a nested array.\n *\n * @param {any[]} arr The nested array to calculate dimensions for.\n * @returns {number[]} An array containing the dimensions of the input array.\n */\nexport function calculateDimensions(arr) {\n    const dimensions = [];\n    let current = arr;\n    while (Array.isArray(current)) {\n        dimensions.push(current.length);\n        current = current[0];\n    }\n    return dimensions;\n}\n\n/**\n * Replicate python's .pop() method for objects.\n * @param {Object} obj The object to pop from.\n * @param {string} key The key to pop.\n * @param {*} defaultValue The default value to return if the key does not exist.\n * @returns {*} The value of the popped key.\n * @throws {Error} If the key does not exist and no default value is provided.\n */\nexport function pop(obj, key, defaultValue = undefined) {\n    const value = obj[key];\n    if (value !== undefined) {\n        delete obj[key];\n        return value;\n    }\n    if (defaultValue === undefined) {\n        throw Error(`Key ${key} does not exist in object.`)\n    }\n    return defaultValue;\n}\n\n/**\n * Efficiently merge arrays, creating a new copy.\n * Adapted from https://stackoverflow.com/a/6768642/13989043\n * @param  {Array[]} arrs Arrays to merge.\n * @returns {Array} The merged array.\n */\nexport function mergeArrays(...arrs) {\n    return Array.prototype.concat.apply([], arrs);\n}\n\n/**\n * Compute the Cartesian product of given arrays\n * @param {...Array} a Arrays to compute the product\n * @returns {Array} Returns the computed Cartesian product as an array\n * @private\n */\nexport function product(...a) {\n    // Cartesian product of items\n    // Adapted from https://stackoverflow.com/a/43053803\n    return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));\n}\n\n/**\n * Calculates the index offset for a given index and window size.\n * @param {number} i The index.\n * @param {number} w The window size.\n * @returns {number} The index offset.\n */\nexport function calculateReflectOffset(i, w) {\n    return Math.abs((i + w) % (2 * w) - w);\n}\n\n/**\n * Save blob file on the web.\n * @param {string} path The path to save the blob to\n * @param {Blob} blob The blob to save\n */\nexport function saveBlob(path, blob){\n    // Convert the canvas content to a data URL\n    const dataURL = URL.createObjectURL(blob);\n\n    // Create an anchor element with the data URL as the href attribute\n    const downloadLink = document.createElement('a');\n    downloadLink.href = dataURL;\n\n    // Set the download attribute to specify the desired filename for the downloaded image\n    downloadLink.download = path;\n\n    // Trigger the download\n    downloadLink.click();\n\n    // Clean up: remove the anchor element from the DOM\n    downloadLink.remove();\n\n    // Revoke the Object URL to free up memory\n    URL.revokeObjectURL(dataURL);\n}\n\n/**\n *\n * @param {Object} o\n * @param {string[]} props\n * @returns {Object}\n */\nexport function pick(o, props) {\n    return Object.assign(\n        {},\n        ...props.map((prop) => {\n            if (o[prop] !== undefined) {\n                return { [prop]: o[prop] };\n            }\n        })\n    );\n}\n\n/**\n * Calculate the length of a string, taking multi-byte characters into account.\n * This mimics the behavior of Python's `len` function.\n * @param {string} s The string to calculate the length of.\n * @returns {number} The length of the string.\n */\nexport function len(s) {\n    let length = 0;\n    for (const c of s) ++length;\n    return length;\n}\n\n/**\n * Count the occurrences of a value in an array or string.\n * This mimics the behavior of Python's `count` method.\n * @param {any[]|string} arr The array or string to search.\n * @param {any} value The value to count.\n */\nexport function count(arr, value) {\n    let count = 0;\n    for (const v of arr) {\n        if (v === value) ++count;\n    }\n    return count;\n}\n", "\n/**\n * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models)\n *\n * @module utils/hub\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { apis, env } from '../env.js';\nimport { dispatchCallback } from './core.js';\n\n/**\n * @typedef {boolean|number} ExternalData Whether to load the model using the external data format (used for models >= 2GB in size).\n * If `true`, the model will be loaded using the external data format.\n * If a number, this many chunks will be loaded using the external data format (of the form: \"model.onnx_data[_{chunk_number}]\").\n */\nexport const MAX_EXTERNAL_DATA_CHUNKS = 100;\n\n/**\n * @typedef {Object} PretrainedOptions Options for loading a pretrained model.\n * @property {import('./core.js').ProgressCallback} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.\n * @property {import('../configs.js').PretrainedConfig} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:\n * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).\n * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.\n * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.\n * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model).\n * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id,\n * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.\n * NOTE: This setting is ignored for local requests.\n */\n\n/**\n * @typedef {Object} ModelSpecificPretrainedOptions Options for loading a pretrained model.\n * @property {string} [subfolder='onnx'] In case the relevant files are located inside a subfolder of the model repo on huggingface.co,\n * you can specify the folder name here.\n * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.\n * @property {import(\"./devices.js\").DeviceType|Record<string, import(\"./devices.js\").DeviceType>} [device=null] The device to run the model on. If not specified, the device will be chosen from the environment settings.\n * @property {import(\"./dtypes.js\").DataType|Record<string, import(\"./dtypes.js\").DataType>} [dtype=null] The data type to use for the model. If not specified, the data type will be chosen from the environment settings.\n * @property {ExternalData|Record<string, ExternalData>} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n * @property {import('onnxruntime-common').InferenceSession.SessionOptions} [session_options] (Optional) User-specified session options passed to the runtime. If not provided, suitable defaults will be chosen.\n */\n\n/**\n * @typedef {PretrainedOptions & ModelSpecificPretrainedOptions} PretrainedModelOptions Options for loading a pretrained model.\n */\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = {\n    'txt': 'text/plain',\n    'html': 'text/html',\n    'css': 'text/css',\n    'js': 'text/javascript',\n    'json': 'application/json',\n    'png': 'image/png',\n    'jpg': 'image/jpeg',\n    'jpeg': 'image/jpeg',\n    'gif': 'image/gif',\n}\nclass FileResponse {\n\n    /**\n     * Creates a new `FileResponse` object.\n     * @param {string} filePath\n     */\n    constructor(filePath) {\n        this.filePath = filePath;\n        this.headers = new Headers();\n\n        this.exists = fs.existsSync(filePath);\n        if (this.exists) {\n            this.status = 200;\n            this.statusText = 'OK';\n\n            let stats = fs.statSync(filePath);\n            this.headers.set('content-length', stats.size.toString());\n\n            this.updateContentType();\n\n            const stream = fs.createReadStream(filePath);\n            this.body = new ReadableStream({\n                start(controller) {\n                    stream.on('data', (chunk) => controller.enqueue(chunk));\n                    stream.on('end', () => controller.close());\n                    stream.on('error', (err) => controller.error(err));\n                },\n                cancel() {\n                    stream.destroy();\n                }\n            });\n        } else {\n            this.status = 404;\n            this.statusText = 'Not Found';\n            this.body = null;\n        }\n    }\n\n    /**\n     * Updates the 'content-type' header property of the response based on the extension of\n     * the file specified by the filePath property of the current object.\n     * @returns {void}\n     */\n    updateContentType() {\n        // Set content-type header based on file extension\n        const extension = this.filePath.toString().split('.').pop().toLowerCase();\n        this.headers.set('content-type', CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream');\n    }\n\n    /**\n     * Clone the current FileResponse object.\n     * @returns {FileResponse} A new FileResponse object with the same properties as the current object.\n     */\n    clone() {\n        let response = new FileResponse(this.filePath);\n        response.exists = this.exists;\n        response.status = this.status;\n        response.statusText = this.statusText;\n        response.headers = new Headers(this.headers);\n        return response;\n    }\n\n    /**\n     * Reads the contents of the file specified by the filePath property and returns a Promise that\n     * resolves with an ArrayBuffer containing the file's contents.\n     * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.\n     * @throws {Error} If the file cannot be read.\n     */\n    async arrayBuffer() {\n        const data = await fs.promises.readFile(this.filePath);\n        return /** @type {ArrayBuffer} */ (data.buffer);\n    }\n\n    /**\n     * Reads the contents of the file specified by the filePath property and returns a Promise that\n     * resolves with a Blob containing the file's contents.\n     * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.\n     * @throws {Error} If the file cannot be read.\n     */\n    async blob() {\n        const data = await fs.promises.readFile(this.filePath);\n        return new Blob([data], { type: this.headers.get('content-type') });\n    }\n\n    /**\n     * Reads the contents of the file specified by the filePath property and returns a Promise that\n     * resolves with a string containing the file's contents.\n     * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.\n     * @throws {Error} If the file cannot be read.\n     */\n    async text() {\n        const data = await fs.promises.readFile(this.filePath, 'utf8');\n        return data;\n    }\n\n    /**\n     * Reads the contents of the file specified by the filePath property and returns a Promise that\n     * resolves with a parsed JavaScript object containing the file's contents.\n     *\n     * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.\n     * @throws {Error} If the file cannot be read.\n     */\n    async json() {\n        return JSON.parse(await this.text());\n    }\n}\n\n/**\n * Determines whether the given string is a valid URL.\n * @param {string|URL} string The string to test for validity as an URL.\n * @param {string[]} [protocols=null] A list of valid protocols. If specified, the protocol must be in this list.\n * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list.\n * @returns {boolean} True if the string is a valid URL, false otherwise.\n */\nfunction isValidUrl(string, protocols = null, validHosts = null) {\n    let url;\n    try {\n        url = new URL(string);\n    } catch (_) {\n        return false;\n    }\n    if (protocols && !protocols.includes(url.protocol)) {\n        return false;\n    }\n    if (validHosts && !validHosts.includes(url.hostname)) {\n        return false;\n    }\n    return true;\n}\n\nconst REPO_ID_REGEX = /^(\\b[\\w\\-.]+\\b\\/)?\\b[\\w\\-.]{1,96}\\b$/;\n\n/**\n * Tests whether a string is a valid Hugging Face model ID or not.\n * Adapted from https://github.com/huggingface/huggingface_hub/blob/6378820ebb03f071988a96c7f3268f5bdf8f9449/src/huggingface_hub/utils/_validators.py#L119-L170\n *\n * @param {string} string The string to test\n * @returns {boolean} True if the string is a valid model ID, false otherwise.\n */\nfunction isValidHfModelId(string) {\n    if (!REPO_ID_REGEX.test(string)) return false;\n    if (string.includes(\"..\") || string.includes(\"--\")) return false;\n    if (string.endsWith(\".git\") || string.endsWith(\".ipynb\")) return false;\n    return true;\n}\n\n/**\n * Helper function to get a file, using either the Fetch API or FileSystem API.\n *\n * @param {URL|string} urlOrPath The URL/path of the file to get.\n * @returns {Promise<FileResponse|Response>} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).\n */\nexport async function getFile(urlOrPath) {\n\n    if (env.useFS && !isValidUrl(urlOrPath, [\"http:\", \"https:\", \"blob:\"])) {\n        return new FileResponse(\n          urlOrPath instanceof URL\n            ? urlOrPath.protocol === \"file:\"\n              ? urlOrPath.pathname\n              : urlOrPath.toString()\n            : urlOrPath,\n        );\n    } else if (typeof process !== 'undefined' && process?.release?.name === 'node') {\n        const IS_CI = !!process.env?.TESTING_REMOTELY;\n        const version = env.version;\n\n        const headers = new Headers();\n        headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`);\n\n        // Check whether we are making a request to the Hugging Face Hub.\n        const isHFURL = isValidUrl(urlOrPath, ['http:', 'https:'], ['huggingface.co', 'hf.co']);\n        if (isHFURL) {\n            // If an access token is present in the environment variables,\n            // we add it to the request headers.\n            // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).\n            const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;\n            if (token) {\n                headers.set('Authorization', `Bearer ${token}`);\n            }\n        }\n        return fetch(urlOrPath, { headers });\n    } else {\n        // Running in a browser-environment, so we use default headers\n        // NOTE: We do not allow passing authorization headers in the browser,\n        // since this would require exposing the token to the client.\n        return fetch(urlOrPath);\n    }\n}\n\nconst ERROR_MAPPING = {\n    // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)\n    400: 'Bad request error occurred while trying to load file',\n    401: 'Unauthorized access to file',\n    403: 'Forbidden access to file',\n    404: 'Could not locate file',\n    408: 'Request timeout error occurred while trying to load file',\n\n    // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)\n    500: 'Internal server error error occurred while trying to load file',\n    502: 'Bad gateway error occurred while trying to load file',\n    503: 'Service unavailable error occurred while trying to load file',\n    504: 'Gateway timeout error occurred while trying to load file',\n}\n/**\n * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub.\n * @param {number} status The HTTP status code of the error.\n * @param {string} remoteURL The URL of the file that could not be loaded.\n * @param {boolean} fatal Whether to raise an error if the file could not be loaded.\n * @returns {null} Returns `null` if `fatal = true`.\n * @throws {Error} If `fatal = false`.\n */\nfunction handleError(status, remoteURL, fatal) {\n    if (!fatal) {\n        // File was not loaded correctly, but it is optional.\n        // TODO in future, cache the response?\n        return null;\n    }\n\n    const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;\n    throw Error(`${message}: \"${remoteURL}\".`);\n}\n\nclass FileCache {\n    /**\n     * Instantiate a `FileCache` object.\n     * @param {string} path\n     */\n    constructor(path) {\n        this.path = path;\n    }\n\n    /**\n     * Checks whether the given request is in the cache.\n     * @param {string} request\n     * @returns {Promise<FileResponse | undefined>}\n     */\n    async match(request) {\n\n        let filePath = path.join(this.path, request);\n        let file = new FileResponse(filePath);\n\n        if (file.exists) {\n            return file;\n        } else {\n            return undefined;\n        }\n    }\n\n    /**\n     * Adds the given response to the cache.\n     * @param {string} request\n     * @param {Response} response\n     * @param {(data: {progress: number, loaded: number, total: number}) => void} [progress_callback] Optional.\n     * The function to call with progress updates\n     * @returns {Promise<void>}\n     */\n    async put(request, response, progress_callback = undefined) {\n        let filePath = path.join(this.path, request);\n\n        try {\n            const contentLength = response.headers.get('Content-Length');\n            const total = parseInt(contentLength ?? '0');\n            let loaded = 0;\n\n            await fs.promises.mkdir(path.dirname(filePath), { recursive: true });\n            const fileStream = fs.createWriteStream(filePath);\n            const reader = response.body.getReader();\n\n            while (true) {\n                const { done, value } = await reader.read();\n                if (done) {\n                    break;\n                }\n\n                await new Promise((resolve, reject) => {\n                    fileStream.write(value, (err) => {\n                        if (err) {\n                            reject(err);\n                            return;\n                        }\n                        resolve();\n                    });\n                });\n\n                loaded += value.length;\n                const progress = total ? (loaded / total) * 100 : 0;\n\n                progress_callback?.({ progress, loaded, total });\n            }\n\n            fileStream.close();\n        } catch (error) {\n            // Clean up the file if an error occurred during download\n            try {\n                await fs.promises.unlink(filePath);\n            } catch { }\n            throw error;\n        }\n    }\n\n    // TODO add the rest?\n    // addAll(requests: RequestInfo[]): Promise<void>;\n    // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;\n    // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Request>>;\n    // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;\n    // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Response>>;\n}\n\n/**\n *\n * @param {FileCache|Cache} cache The cache to search\n * @param {string[]} names The names of the item to search for\n * @returns {Promise<FileResponse|Response|undefined>} The item from the cache, or undefined if not found.\n */\nasync function tryCache(cache, ...names) {\n    for (let name of names) {\n        try {\n            let result = await cache.match(name);\n            if (result) return result;\n        } catch (e) {\n            continue;\n        }\n    }\n    return undefined;\n}\n\n/**\n * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.\n * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached.\n *\n * @param {string} path_or_repo_id This can be either:\n * - a string, the *model id* of a model repo on huggingface.co.\n * - a path to a *directory* potentially containing the file.\n * @param {string} filename The name of the file to locate in `path_or_repo`.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * @param {boolean} [return_path=false] Whether to return the path of the file instead of the file content.\n *\n * @throws Will throw an error if the file is not found and `fatal` is true.\n * @returns {Promise<string|Uint8Array>} A Promise that resolves with the file content as a Uint8Array if `return_path` is false, or the file path as a string if `return_path` is true.\n */\nexport async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}, return_path = false) {\n\n    if (!env.allowLocalModels) {\n        // User has disabled local models, so we just make sure other settings are correct.\n\n        if (options.local_files_only) {\n            throw Error(\"Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).\")\n        } else if (!env.allowRemoteModels) {\n            throw Error(\"Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.\")\n        }\n    }\n\n    // Initiate file retrieval\n    dispatchCallback(options.progress_callback, {\n        status: 'initiate',\n        name: path_or_repo_id,\n        file: filename\n    })\n\n    // First, check if the a caching backend is available\n    // If no caching mechanism available, will download the file every time\n    let cache;\n    if (!cache && env.useCustomCache) {\n        // Allow the user to specify a custom cache system.\n        if (!env.customCache) {\n            throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.')\n        }\n\n        // Check that the required methods are defined:\n        if (!env.customCache.match || !env.customCache.put) {\n            throw new Error(\n                \"`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. \" +\n                \"For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\"\n            )\n        }\n        cache = env.customCache;\n    }\n\n    if (!cache && env.useBrowserCache) {\n        if (typeof caches === 'undefined') {\n            throw Error('Browser cache is not available in this environment.')\n        }\n        try {\n            // In some cases, the browser cache may be visible, but not accessible due to security restrictions.\n            // For example, when running an application in an iframe, if a user attempts to load the page in\n            // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':\n            // An attempt was made to break through the security policy of the user agent.`\n            // So, instead of crashing, we just ignore the error and continue without using the cache.\n            cache = await caches.open('transformers-cache');\n        } catch (e) {\n            console.warn('An error occurred while opening the browser cache:', e);\n        }\n    }\n\n    if (!cache && env.useFSCache) {\n        if (!apis.IS_FS_AVAILABLE) {\n            throw Error('File System Cache is not available in this environment.');\n        }\n\n        // If `cache_dir` is not specified, use the default cache directory\n        cache = new FileCache(options.cache_dir ?? env.cacheDir);\n    }\n\n    const revision = options.revision ?? 'main';\n    const requestURL = pathJoin(path_or_repo_id, filename);\n\n    const validModelId = isValidHfModelId(path_or_repo_id);\n    const localPath = validModelId\n        ? pathJoin(env.localModelPath, requestURL)\n        : requestURL;\n    const remoteURL = pathJoin(\n        env.remoteHost,\n        env.remotePathTemplate\n            .replaceAll('{model}', path_or_repo_id)\n            .replaceAll('{revision}', encodeURIComponent(revision)),\n        filename\n    );\n\n    /** @type {string} */\n    let cacheKey;\n    const proposedCacheKey = cache instanceof FileCache\n        // Choose cache key for filesystem cache\n        // When using the main revision (default), we use the request URL as the cache key.\n        // If a specific revision is requested, we account for this in the cache key.\n        ? revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename)\n        : remoteURL;\n\n    // Whether to cache the final response in the end.\n    let toCacheResponse = false;\n\n    /** @type {Response|FileResponse|undefined} */\n    let response;\n\n    if (cache) {\n        // A caching system is available, so we try to get the file from it.\n        //  1. We first try to get from cache using the local path. In some environments (like deno),\n        //     non-URL cache keys are not allowed. In these cases, `response` will be undefined.\n        //  2. If no response is found, we try to get from cache using the remote URL or file system cache.\n        response = await tryCache(cache, localPath, proposedCacheKey);\n    }\n\n    const cacheHit = response !== undefined;\n    if (response === undefined) {\n        // Caching not available, or file is not cached, so we perform the request\n\n        if (env.allowLocalModels) {\n            // Accessing local models is enabled, so we try to get the file locally.\n            // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.\n            const isURL = isValidUrl(requestURL, ['http:', 'https:']);\n            if (!isURL) {\n                try {\n                    response = await getFile(localPath);\n                    cacheKey = localPath; // Update the cache key to be the local path\n                } catch (e) {\n                    // Something went wrong while trying to get the file locally.\n                    // NOTE: error handling is done in the next step (since `response` will be undefined)\n                    console.warn(`Unable to load from local path \"${localPath}\": \"${e}\"`);\n                }\n            } else if (options.local_files_only) {\n                throw new Error(`\\`local_files_only=true\\`, but attempted to load a remote file from: ${requestURL}.`);\n            } else if (!env.allowRemoteModels) {\n                throw new Error(`\\`env.allowRemoteModels=false\\`, but attempted to load a remote file from: ${requestURL}.`);\n            }\n        }\n\n        if (response === undefined || response.status === 404) {\n            // File not found locally. This means either:\n            // - The user has disabled local file access (`env.allowLocalModels=false`)\n            // - the path is a valid HTTP url (`response === undefined`)\n            // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)\n\n            if (options.local_files_only || !env.allowRemoteModels) {\n                // User requested local files only, but the file is not found locally.\n                if (fatal) {\n                    throw Error(`\\`local_files_only=true\\` or \\`env.allowRemoteModels=false\\` and file was not found locally at \"${localPath}\".`);\n                } else {\n                    // File not found, but this file is optional.\n                    // TODO in future, cache the response?\n                    return null;\n                }\n            }\n            if (!validModelId) {\n                // Before making any requests to the remote server, we check if the model ID is valid.\n                // This prevents unnecessary network requests for invalid model IDs.\n                throw Error(`Local file missing at \"${localPath}\" and download aborted due to invalid model ID \"${path_or_repo_id}\".`);\n            }\n\n            // File not found locally, so we try to download it from the remote server\n            response = await getFile(remoteURL);\n\n            if (response.status !== 200) {\n                return handleError(response.status, remoteURL, fatal);\n            }\n\n            // Success! We use the proposed cache key from earlier\n            cacheKey = proposedCacheKey;\n        }\n\n        // Only cache the response if:\n        toCacheResponse =\n            cache                              // 1. A caching system is available\n            && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment)\n            && response instanceof Response    // 3. result is a `Response` object (i.e., not a `FileResponse`)\n            && response.status === 200         // 4. request was successful (status code 200)\n    }\n\n    // Start downloading\n    dispatchCallback(options.progress_callback, {\n        status: 'download',\n        name: path_or_repo_id,\n        file: filename\n    })\n\n    let result;\n    if (!(apis.IS_NODE_ENV && return_path)) {\n        /** @type {Uint8Array} */\n        let buffer;\n\n        if (!options.progress_callback) {\n            // If no progress callback is specified, we can use the `.arrayBuffer()`\n            // method to read the response.\n            buffer = new Uint8Array(await response.arrayBuffer());\n\n        } else if (\n            cacheHit // The item is being read from the cache\n            &&\n            typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox\n        ) {\n            // Due to bug in Firefox, we cannot display progress when loading from cache.\n            // Fortunately, since this should be instantaneous, this should not impact users too much.\n            buffer = new Uint8Array(await response.arrayBuffer());\n\n            // For completeness, we still fire the final progress callback\n            dispatchCallback(options.progress_callback, {\n                status: 'progress',\n                name: path_or_repo_id,\n                file: filename,\n                progress: 100,\n                loaded: buffer.length,\n                total: buffer.length,\n            })\n        } else {\n            buffer = await readResponse(response, data => {\n                dispatchCallback(options.progress_callback, {\n                    status: 'progress',\n                    name: path_or_repo_id,\n                    file: filename,\n                    ...data,\n                })\n            })\n        }\n        result = buffer;\n    }\n\n    if (\n        // Only cache web responses\n        // i.e., do not cache FileResponses (prevents duplication)\n        toCacheResponse && cacheKey\n        &&\n        // Check again whether request is in cache. If not, we add the response to the cache\n        (await cache.match(cacheKey) === undefined)\n    ) {\n        if (!result) {\n            // We haven't yet read the response body, so we need to do so now.\n            // Ensure progress updates include consistent metadata.\n            const wrapped_progress = options.progress_callback\n                ? (data) => dispatchCallback(options.progress_callback, {\n                    status: 'progress',\n                    name: path_or_repo_id,\n                    file: filename,\n                    ...data,\n                })\n                : undefined;\n            await cache.put(cacheKey, /** @type {Response} */(response), wrapped_progress);\n        } else {\n            // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files\n            await cache.put(cacheKey, new Response(result, {\n                headers: response.headers\n            }))\n                .catch(err => {\n                    // Do not crash if unable to add to cache (e.g., QuotaExceededError).\n                    // Rather, log a warning and proceed with execution.\n                    console.warn(`Unable to add response to browser cache: ${err}.`);\n                });\n        }\n    }\n    dispatchCallback(options.progress_callback, {\n        status: 'done',\n        name: path_or_repo_id,\n        file: filename\n    });\n\n    if (result) {\n        if (!apis.IS_NODE_ENV && return_path) {\n            throw new Error(\"Cannot return path in a browser environment.\")\n        }\n        return result;\n    }\n    if (response instanceof FileResponse) {\n        return response.filePath;\n    }\n\n    // Otherwise, return the cached response (most likely a `FileResponse`).\n    // NOTE: A custom cache may return a Response, or a string (file path)\n    const cachedResponse = await cache?.match(cacheKey);\n    if (cachedResponse instanceof FileResponse) {\n        return cachedResponse.filePath;\n    } else if (cachedResponse instanceof Response) {\n        return new Uint8Array(await cachedResponse.arrayBuffer());\n    } else if (typeof cachedResponse === 'string') {\n        return cachedResponse;\n    }\n\n    throw new Error(\"Unable to get model file path or buffer.\");\n}\n\n/**\n * Fetches a text file from a given path and file name.\n *\n * @param {string} modelPath The path to the directory containing the file.\n * @param {string} fileName The name of the file to fetch.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * @returns {Promise<string|null>} The text content of the file.\n * @throws Will throw an error if the file is not found and `fatal` is true.\n */\nexport async function getModelText(modelPath, fileName, fatal = true, options = {}) {\n    const buffer = await getModelFile(modelPath, fileName, fatal, options, false);\n    if (buffer === null) {\n        return null;\n    }\n\n    const decoder = new TextDecoder('utf-8');\n    return decoder.decode(/** @type {Uint8Array} */(buffer));\n}\n\n/**\n * Fetches a JSON file from a given path and file name.\n *\n * @param {string} modelPath The path to the directory containing the file.\n * @param {string} fileName The name of the file to fetch.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * @returns {Promise<Object>} The JSON data parsed into a JavaScript object.\n * @throws Will throw an error if the file is not found and `fatal` is true.\n */\nexport async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {\n    const text = await getModelText(modelPath, fileName, fatal, options);\n    if (text === null) {\n        // Return empty object\n        return {};\n    }\n\n    return JSON.parse(text);\n}\n/**\n * Read and track progress when reading a Response object\n *\n * @param {Response|FileResponse} response The Response object to read\n * @param {(data: {progress: number, loaded: number, total: number}) => void} progress_callback The function to call with progress updates\n * @returns {Promise<Uint8Array>} A Promise that resolves with the Uint8Array buffer\n */\nasync function readResponse(response, progress_callback) {\n\n    const contentLength = response.headers.get('Content-Length');\n    if (contentLength === null) {\n        console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.')\n    }\n    let total = parseInt(contentLength ?? '0');\n    let buffer = new Uint8Array(total);\n    let loaded = 0;\n\n    const reader = response.body.getReader();\n    async function read() {\n        const { done, value } = await reader.read();\n        if (done) return;\n\n        const newLoaded = loaded + value.length;\n        if (newLoaded > total) {\n            total = newLoaded;\n\n            // Adding the new data will overflow buffer.\n            // In this case, we extend the buffer\n            const newBuffer = new Uint8Array(total);\n\n            // copy contents\n            newBuffer.set(buffer);\n\n            buffer = newBuffer;\n        }\n        buffer.set(value, loaded);\n        loaded = newLoaded;\n\n        const progress = (loaded / total) * 100;\n\n        // Call your function here\n        progress_callback({ progress, loaded, total });\n\n        return read();\n    }\n\n    // Actually read\n    await read();\n\n    return buffer;\n}\n\n/**\n * Joins multiple parts of a path into a single path, while handling leading and trailing slashes.\n *\n * @param {...string} parts Multiple parts of a path.\n * @returns {string} A string representing the joined path.\n */\nfunction pathJoin(...parts) {\n    // https://stackoverflow.com/a/55142565\n    parts = parts.map((part, index) => {\n        if (index) {\n            part = part.replace(new RegExp('^/'), '');\n        }\n        if (index !== parts.length - 1) {\n            part = part.replace(new RegExp('/$'), '');\n        }\n        return part;\n    })\n    return parts.join('/');\n}\n", "/**\n * @file Module used to configure Transformers.js.\n * \n * **Example:** Disable remote models.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.allowRemoteModels = false;\n * ```\n * \n * **Example:** Set local model path.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.localModelPath = '/path/to/local/models/';\n * ```\n * \n * **Example:** Set cache directory.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.cacheDir = '/path/to/cache/directory/';\n * ```\n * \n * @module env\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport url from 'node:url';\n\nconst VERSION = '3.8.1';\n\n// Check if various APIs are available (depends on environment)\nconst IS_BROWSER_ENV = typeof window !== \"undefined\" && typeof window.document !== \"undefined\";\nconst IS_WEBWORKER_ENV = typeof self !== \"undefined\" && (['DedicatedWorkerGlobalScope', 'ServiceWorkerGlobalScope', 'SharedWorkerGlobalScope'].includes(self.constructor?.name));\nconst IS_WEB_CACHE_AVAILABLE = typeof self !== \"undefined\" && 'caches' in self;\nconst IS_WEBGPU_AVAILABLE = typeof navigator !== 'undefined' && 'gpu' in navigator;\nconst IS_WEBNN_AVAILABLE = typeof navigator !== 'undefined' && 'ml' in navigator;\n\nconst IS_PROCESS_AVAILABLE = typeof process !== 'undefined';\nconst IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === 'node';\nconst IS_FS_AVAILABLE = !isEmpty(fs);\nconst IS_PATH_AVAILABLE = !isEmpty(path);\n\n// Runtime detection\nconst IS_DENO_RUNTIME = typeof globalThis.Deno !== 'undefined';\nconst IS_BUN_RUNTIME = typeof globalThis.Bun !== 'undefined';\n\n/**\n * A read-only object containing information about the APIs available in the current environment.\n */\nexport const apis = Object.freeze({\n    /** Whether we are running in a browser environment (and not a web worker) */\n    IS_BROWSER_ENV,\n\n    /** Whether we are running in a web worker environment */\n    IS_WEBWORKER_ENV,\n\n    /** Whether the Cache API is available */\n    IS_WEB_CACHE_AVAILABLE,\n\n    /** Whether the WebGPU API is available */\n    IS_WEBGPU_AVAILABLE,\n\n    /** Whether the WebNN API is available */\n    IS_WEBNN_AVAILABLE,\n\n    /** Whether the Node.js process API is available */\n    IS_PROCESS_AVAILABLE,\n\n    /** Whether we are running in a Node.js-like environment (node, deno, bun) */\n    IS_NODE_ENV,\n\n    /** Whether the filesystem API is available */\n    IS_FS_AVAILABLE,\n\n    /** Whether the path API is available */\n    IS_PATH_AVAILABLE,\n});\n\nconst RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE;\n\nlet dirname__ = './';\nif (RUNNING_LOCALLY) {\n    // NOTE: We wrap `import.meta` in a call to `Object` to prevent Webpack from trying to bundle it in CommonJS.\n    // Although we get the warning: \"Accessing import.meta directly is unsupported (only property access or destructuring is supported)\",\n    // it is safe to ignore since the bundled value (`{}`) isn't used for CommonJS environments (we use __dirname instead).\n    const _import_meta_url = Object(import.meta).url;\n\n    if (_import_meta_url) {\n        dirname__ = path.dirname(path.dirname(url.fileURLToPath(_import_meta_url))) // ESM\n    } else if (typeof __dirname !== 'undefined') {\n        dirname__ = path.dirname(__dirname) // CommonJS\n    }\n}\n\n// Only used for environments with access to file system\nconst DEFAULT_CACHE_DIR = RUNNING_LOCALLY\n    ? path.join(dirname__, '/.cache/')\n    : null;\n\n// Set local model path, based on available APIs\nconst DEFAULT_LOCAL_MODEL_PATH = '/models/';\nconst localModelPath = RUNNING_LOCALLY\n    ? path.join(dirname__, DEFAULT_LOCAL_MODEL_PATH)\n    : DEFAULT_LOCAL_MODEL_PATH;\n\n/**\n * Global variable given visible to users to control execution. This provides users a simple way to configure Transformers.js.\n * @typedef {Object} TransformersEnvironment\n * @property {string} version This version of Transformers.js.\n * @property {{onnx: Partial<import('onnxruntime-common').Env>}} backends Expose environment variables of different backends,\n * allowing users to set these variables if they want to.\n * @property {boolean} allowRemoteModels Whether to allow loading of remote files, defaults to `true`.\n * If set to `false`, it will have the same effect as setting `local_files_only=true` when loading pipelines, models, tokenizers, processors, etc.\n * @property {string} remoteHost Host URL to load models from. Defaults to the Hugging Face Hub.\n * @property {string} remotePathTemplate Path template to fill in and append to `remoteHost` when loading models.\n * @property {boolean} allowLocalModels Whether to allow loading of local files, defaults to `false` if running in-browser, and `true` otherwise.\n * If set to `false`, it will skip the local file check and try to load the model from the remote host.\n * @property {string} localModelPath Path to load local models from. Defaults to `/models/`.\n * @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available.\n * @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available.\n * @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available.\n * @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`.\n * @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`.\n * @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this must be an object which\n * implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache.\n * If you wish, you may also return a `Promise<string>` from the `match` function if you'd like to use a file path instead of `Promise<Response>`.\n */\n\n/** @type {TransformersEnvironment} */\nexport const env = {\n    version: VERSION,\n\n    /////////////////// Backends settings ///////////////////\n    // NOTE: These will be populated later by the backends themselves.\n    backends: {\n        // onnxruntime-web/onnxruntime-node\n        onnx: {},\n    },\n\n    /////////////////// Model settings ///////////////////\n    allowRemoteModels: true,\n    remoteHost: 'https://huggingface.co/',\n    remotePathTemplate: '{model}/resolve/{revision}/',\n\n    allowLocalModels: !(IS_BROWSER_ENV || IS_WEBWORKER_ENV),\n    localModelPath: localModelPath,\n    useFS: IS_FS_AVAILABLE,\n\n    /////////////////// Cache settings ///////////////////\n    useBrowserCache: IS_WEB_CACHE_AVAILABLE && !IS_DENO_RUNTIME,\n\n    useFSCache: IS_FS_AVAILABLE,\n    cacheDir: DEFAULT_CACHE_DIR,\n\n    useCustomCache: false,\n    customCache: null,\n    //////////////////////////////////////////////////////\n}\n\n\n/**\n * @param {Object} obj\n * @private\n */\nfunction isEmpty(obj) {\n    return Object.keys(obj).length === 0;\n}\n", "\n/**\n * @file Helper module for mathematical processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/maths\n */\n\n/**\n * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float16Array | Float32Array | Float64Array} TypedArray\n * @typedef {BigInt64Array | BigUint64Array} BigTypedArray\n * @typedef {TypedArray | BigTypedArray} AnyTypedArray\n */\n\n/**\n * @param {TypedArray} input\n */\nexport function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) {\n    // TODO use mode and align_corners\n\n    // Output image dimensions\n    const x_scale = out_width / in_width;\n    const y_scale = out_height / in_height;\n\n    // Output image\n    // @ts-ignore\n    const out_img = new input.constructor(out_height * out_width * in_channels);\n\n    // Pre-calculate strides\n    const inStride = in_height * in_width;\n    const outStride = out_height * out_width;\n\n    for (let i = 0; i < out_height; ++i) {\n        for (let j = 0; j < out_width; ++j) {\n            // Calculate output offset\n            const outOffset = i * out_width + j;\n\n            // Calculate input pixel coordinates\n            const x = (j + 0.5) / x_scale - 0.5;\n            const y = (i + 0.5) / y_scale - 0.5;\n\n            // Calculate the four nearest input pixels\n            // We also check if the input pixel coordinates are within the image bounds\n            let x1 = Math.floor(x);\n            let y1 = Math.floor(y);\n            const x2 = Math.min(x1 + 1, in_width - 1);\n            const y2 = Math.min(y1 + 1, in_height - 1);\n\n            x1 = Math.max(x1, 0);\n            y1 = Math.max(y1, 0);\n\n\n            // Calculate the fractional distances between the input pixel and the four nearest pixels\n            const s = x - x1;\n            const t = y - y1;\n\n            // Perform bilinear interpolation\n            const w1 = (1 - s) * (1 - t);\n            const w2 = s * (1 - t);\n            const w3 = (1 - s) * t;\n            const w4 = s * t;\n\n            // Calculate the four nearest input pixel indices\n            const yStride = y1 * in_width;\n            const xStride = y2 * in_width;\n            const idx1 = yStride + x1;\n            const idx2 = yStride + x2;\n            const idx3 = xStride + x1;\n            const idx4 = xStride + x2;\n\n            for (let k = 0; k < in_channels; ++k) {\n                // Calculate channel offset\n                const cOffset = k * inStride;\n\n                out_img[k * outStride + outOffset] =\n                    w1 * input[cOffset + idx1] +\n                    w2 * input[cOffset + idx2] +\n                    w3 * input[cOffset + idx3] +\n                    w4 * input[cOffset + idx4];\n            }\n        }\n    }\n\n    return out_img;\n}\n\n\n/**\n * Helper method to permute a `AnyTypedArray` directly\n * @template {AnyTypedArray} T \n * @param {T} array \n * @param {number[]} dims \n * @param {number[]} axes \n * @returns {[T, number[]]} The permuted array and the new shape.\n */\nexport function permute_data(array, dims, axes) {\n    // Calculate the new shape of the permuted array\n    // and the stride of the original array\n    const shape = new Array(axes.length);\n    const stride = new Array(axes.length);\n\n    for (let i = axes.length - 1, s = 1; i >= 0; --i) {\n        stride[i] = s;\n        shape[i] = dims[axes[i]];\n        s *= shape[i];\n    }\n\n    // Precompute inverse mapping of stride\n    const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);\n\n    // Create the permuted array with the new shape\n    // @ts-ignore\n    const permutedData = new array.constructor(array.length);\n\n    // Permute the original array to the new array\n    for (let i = 0; i < array.length; ++i) {\n        let newIndex = 0;\n        for (let j = dims.length - 1, k = i; j >= 0; --j) {\n            newIndex += (k % dims[j]) * invStride[j];\n            k = Math.floor(k / dims[j]);\n        }\n        permutedData[newIndex] = array[i];\n    }\n\n    return [permutedData, shape];\n}\n\n\n/**\n * Compute the softmax of an array of numbers.\n * @template {TypedArray|number[]} T\n * @param {T} arr The array of numbers to compute the softmax of.\n * @returns {T} The softmax array.\n */\nexport function softmax(arr) {\n    // Compute the maximum value in the array\n    const maxVal = max(arr)[0];\n\n    // Compute the exponentials of the array values\n    const exps = arr.map(x => Math.exp(x - maxVal));\n\n    // Compute the sum of the exponentials\n    // @ts-ignore\n    const sumExps = exps.reduce((acc, val) => acc + val, 0);\n\n    // Compute the softmax values\n    const softmaxArr = exps.map(x => x / sumExps);\n\n    return /** @type {T} */(softmaxArr);\n}\n\n/**\n * Calculates the logarithm of the softmax function for the input array.\n * @template {TypedArray|number[]} T\n * @param {T} arr The input array to calculate the log_softmax function for.\n * @returns {T} The resulting log_softmax array.\n */\nexport function log_softmax(arr) {\n    // Compute the maximum value in the array\n    const maxVal = max(arr)[0];\n\n    // Compute the sum of the exponentials\n    let sumExps = 0;\n    for(let i = 0; i < arr.length; ++i) {\n        sumExps += Math.exp(arr[i] - maxVal);\n    }\n\n    // Compute the log of the sum\n    const logSum = Math.log(sumExps);\n\n    // Compute the softmax values\n    const logSoftmaxArr = arr.map(x => x - maxVal - logSum);\n\n    return /** @type {T} */(logSoftmaxArr);\n}\n\n/**\n * Calculates the dot product of two arrays.\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The dot product of arr1 and arr2.\n */\nexport function dot(arr1, arr2) {\n    let result = 0;\n    for (let i = 0; i < arr1.length; ++i) {\n        result += arr1[i] * arr2[i];\n    }\n    return result;\n}\n\n/**\n * Computes the cosine similarity between two arrays.\n *\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The cosine similarity between the two arrays.\n */\nexport function cos_sim(arr1, arr2) {\n    // Calculate dot product of the two arrays\n    const dotProduct = dot(arr1, arr2);\n\n    // Calculate the magnitude of the first array\n    const magnitudeA = magnitude(arr1);\n\n    // Calculate the magnitude of the second array\n    const magnitudeB = magnitude(arr2);\n\n    // Calculate the cosine similarity\n    const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);\n\n    return cosineSimilarity;\n}\n\n/**\n * Calculates the magnitude of a given array.\n * @param {number[]} arr The array to calculate the magnitude of.\n * @returns {number} The magnitude of the array.\n */\nexport function magnitude(arr) {\n    return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));\n}\n\n\n/**\n * Returns the value and index of the minimum element in an array.\n * @template {number[]|bigint[]|AnyTypedArray} T\n * @param {T} arr array of numbers.\n * @returns {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin]\n * @throws {Error} If array is empty.\n */\nexport function min(arr) {\n    if (arr.length === 0) throw Error('Array must not be empty');\n    let min = arr[0];\n    let indexOfMin = 0;\n    for (let i = 1; i < arr.length; ++i) {\n        if (arr[i] < min) {\n            min = arr[i];\n            indexOfMin = i;\n        }\n    }\n    return /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */([min, indexOfMin]);\n}\n\n\n/**\n * Returns the value and index of the maximum element in an array.\n * @template {number[]|bigint[]|AnyTypedArray} T\n * @param {T} arr array of numbers.\n * @returns {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax]\n * @throws {Error} If array is empty.\n */\nexport function max(arr) {\n    if (arr.length === 0) throw Error('Array must not be empty');\n    let max = arr[0];\n    let indexOfMax = 0;\n    for (let i = 1; i < arr.length; ++i) {\n        if (arr[i] > max) {\n            max = arr[i];\n            indexOfMax = i;\n        }\n    }\n    return /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */([max, indexOfMax]);\n}\n\nfunction isPowerOfTwo(number) {\n    // Check if the number is greater than 0 and has only one bit set to 1\n    return (number > 0) && ((number & (number - 1)) === 0);\n}\n\n/**\n * Implementation of Radix-4 FFT.\n * \n * P2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are a power of two in length.\n * Code adapted from https://www.npmjs.com/package/fft.js\n */\nclass P2FFT {\n    /**\n     * @param {number} size The size of the input array. Must be a power of two larger than 1.\n     * @throws {Error} FFT size must be a power of two larger than 1.\n     */\n    constructor(size) {\n        this.size = size | 0; // convert to a 32-bit signed integer\n        if (this.size <= 1 || !isPowerOfTwo(this.size))\n            throw new Error('FFT size must be a power of two larger than 1');\n\n        this._csize = size << 1;\n\n        this.table = new Float64Array(this.size * 2);\n        for (let i = 0; i < this.table.length; i += 2) {\n            const angle = Math.PI * i / this.size;\n            this.table[i] = Math.cos(angle);\n            this.table[i + 1] = -Math.sin(angle);\n        }\n\n        // Find size's power of two\n        let power = 0;\n        for (let t = 1; this.size > t; t <<= 1)\n            ++power;\n\n        // Calculate initial step's width:\n        //   * If we are full radix-4, it is 2x smaller to give inital len=8\n        //   * Otherwise it is the same as `power` to give len=4\n        this._width = power % 2 === 0 ? power - 1 : power;\n\n        // Pre-compute bit-reversal patterns\n        this._bitrev = new Int32Array(1 << this._width);\n        for (let j = 0; j < this._bitrev.length; ++j) {\n            this._bitrev[j] = 0;\n            for (let shift = 0; shift < this._width; shift += 2) {\n                const revShift = this._width - shift - 2;\n                this._bitrev[j] |= ((j >>> shift) & 3) << revShift;\n            }\n        }\n    }\n\n    /**\n     * Create a complex number array with size `2 * size`\n     *\n     * @returns {Float64Array} A complex number array with size `2 * size`\n     */\n    createComplexArray() {\n        return new Float64Array(this._csize);\n    }\n\n    /**\n     * Converts a complex number representation stored in a Float64Array to an array of real numbers.\n     * \n     * @param {Float64Array} complex The complex number representation to be converted.\n     * @param {number[]} [storage] An optional array to store the result in.\n     * @returns {number[]} An array of real numbers representing the input complex number representation.\n     */\n    fromComplexArray(complex, storage) {\n        const res = storage || new Array(complex.length >>> 1);\n        for (let i = 0; i < complex.length; i += 2)\n            res[i >>> 1] = complex[i];\n        return res;\n    }\n\n    /**\n     * Convert a real-valued input array to a complex-valued output array.\n     * @param {Float64Array} input The real-valued input array.\n     * @param {Float64Array} [storage] Optional buffer to store the output array.\n     * @returns {Float64Array} The complex-valued output array.\n     */\n    toComplexArray(input, storage) {\n        const res = storage || this.createComplexArray();\n        for (let i = 0; i < res.length; i += 2) {\n            res[i] = input[i >>> 1];\n            res[i + 1] = 0;\n        }\n        return res;\n    }\n\n    /**\n     * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.\n     * \n     * @param {Float64Array} out The output buffer to store the result.\n     * @param {Float64Array} data The input data to transform.\n     * \n     * @throws {Error} Input and output buffers must be different.\n     * \n     * @returns {void}\n     */\n    transform(out, data) {\n        if (out === data)\n            throw new Error('Input and output buffers must be different');\n\n        this._transform4(out, data, 1 /* DONE */);\n    }\n\n    /**\n     * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.\n     * The input buffer must contain real values only, while the output buffer will contain complex values. The input and\n     * output buffers must be different.\n     *\n     * @param {Float64Array} out The output buffer.\n     * @param {Float64Array} data The input buffer containing real values.\n     *\n     * @throws {Error} If the input and output buffers are the same.\n     */\n    realTransform(out, data) {\n        if (out === data)\n            throw new Error('Input and output buffers must be different');\n\n        this._realTransform4(out, data, 1 /* DONE */);\n    }\n\n    /**\n     * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.\n     * The `out` array must be a different buffer than the `data` array. The `out` array will contain the\n     * result of the transformation. The `data` array will not be modified.\n     * \n     * @param {Float64Array} out The output buffer for the transformed data.\n     * @param {Float64Array} data The input data to transform.\n     * @throws {Error} If `out` and `data` refer to the same buffer.\n     * @returns {void}\n     */\n    inverseTransform(out, data) {\n        if (out === data)\n            throw new Error('Input and output buffers must be different');\n\n        this._transform4(out, data, -1 /* DONE */);\n        for (let i = 0; i < out.length; ++i)\n            out[i] /= this.size;\n    }\n\n    /**\n     * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.\n     *\n     * @param {Float64Array} out The output buffer for the transformed data.\n     * @param {Float64Array} data The input buffer of data to be transformed.\n     * @param {number} inv A scaling factor to apply to the transform.\n     * @returns {void}\n     */\n    _transform4(out, data, inv) {\n        // radix-4 implementation\n\n        const size = this._csize;\n\n        // Initial step (permute and transform)\n        const width = this._width;\n        let step = 1 << width;\n        let len = (size / step) << 1;\n\n        let outOff;\n        let t;\n        const bitrev = this._bitrev;\n        if (len === 4) {\n            for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n                const off = bitrev[t];\n                this._singleTransform2(data, out, outOff, off, step);\n            }\n        } else {\n            // len === 8\n            for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n                const off = bitrev[t];\n                this._singleTransform4(data, out, outOff, off, step, inv);\n            }\n        }\n\n        // Loop through steps in decreasing order\n        const table = this.table;\n        for (step >>= 2; step >= 2; step >>= 2) {\n            len = (size / step) << 1;\n            const quarterLen = len >>> 2;\n\n            // Loop through offsets in the data\n            for (outOff = 0; outOff < size; outOff += len) {\n                // Full case\n                const limit = outOff + quarterLen - 1;\n                for (let i = outOff, k = 0; i < limit; i += 2, k += step) {\n                    const A = i;\n                    const B = A + quarterLen;\n                    const C = B + quarterLen;\n                    const D = C + quarterLen;\n\n                    // Original values\n                    const Ar = out[A];\n                    const Ai = out[A + 1];\n                    const Br = out[B];\n                    const Bi = out[B + 1];\n                    const Cr = out[C];\n                    const Ci = out[C + 1];\n                    const Dr = out[D];\n                    const Di = out[D + 1];\n\n                    const tableBr = table[k];\n                    const tableBi = inv * table[k + 1];\n                    const MBr = Br * tableBr - Bi * tableBi;\n                    const MBi = Br * tableBi + Bi * tableBr;\n\n                    const tableCr = table[2 * k];\n                    const tableCi = inv * table[2 * k + 1];\n                    const MCr = Cr * tableCr - Ci * tableCi;\n                    const MCi = Cr * tableCi + Ci * tableCr;\n\n                    const tableDr = table[3 * k];\n                    const tableDi = inv * table[3 * k + 1];\n                    const MDr = Dr * tableDr - Di * tableDi;\n                    const MDi = Dr * tableDi + Di * tableDr;\n\n                    // Pre-Final values\n                    const T0r = Ar + MCr;\n                    const T0i = Ai + MCi;\n                    const T1r = Ar - MCr;\n                    const T1i = Ai - MCi;\n                    const T2r = MBr + MDr;\n                    const T2i = MBi + MDi;\n                    const T3r = inv * (MBr - MDr);\n                    const T3i = inv * (MBi - MDi);\n\n                    // Final values\n                    out[A] = T0r + T2r;\n                    out[A + 1] = T0i + T2i;\n                    out[B] = T1r + T3i;\n                    out[B + 1] = T1i - T3r;\n                    out[C] = T0r - T2r;\n                    out[C + 1] = T0i - T2i;\n                    out[D] = T1r - T3i;\n                    out[D + 1] = T1i + T3r;\n                }\n            }\n        }\n    }\n\n    /**\n     * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.\n     *\n     * @param {Float64Array} data The input buffer of data to be transformed.\n     * @param {Float64Array} out The output buffer for the transformed data.\n     * @param {number} outOff The offset at which to write the output data.\n     * @param {number} off The offset at which to begin reading the input data.\n     * @param {number} step The step size for indexing the input data.\n     * @returns {void}\n     */\n    _singleTransform2(data, out, outOff, off, step) {\n        // radix-2 implementation\n        // NOTE: Only called for len=4\n\n        const evenR = data[off];\n        const evenI = data[off + 1];\n        const oddR = data[off + step];\n        const oddI = data[off + step + 1];\n\n        out[outOff] = evenR + oddR;\n        out[outOff + 1] = evenI + oddI;\n        out[outOff + 2] = evenR - oddR;\n        out[outOff + 3] = evenI - oddI;\n    }\n\n    /**\n     * Performs radix-4 transformation on input data of length 8\n     *\n     * @param {Float64Array} data Input data array of length 8\n     * @param {Float64Array} out Output data array of length 8\n     * @param {number} outOff Index of output array to start writing from\n     * @param {number} off Index of input array to start reading from\n     * @param {number} step Step size between elements in input array\n     * @param {number} inv Scaling factor for inverse transform\n     * \n     * @returns {void}\n     */\n    _singleTransform4(data, out, outOff, off, step, inv) {\n        // radix-4\n        // NOTE: Only called for len=8\n        const step2 = step * 2;\n        const step3 = step * 3;\n\n        // Original values\n        const Ar = data[off];\n        const Ai = data[off + 1];\n        const Br = data[off + step];\n        const Bi = data[off + step + 1];\n        const Cr = data[off + step2];\n        const Ci = data[off + step2 + 1];\n        const Dr = data[off + step3];\n        const Di = data[off + step3 + 1];\n\n        // Pre-Final values\n        const T0r = Ar + Cr;\n        const T0i = Ai + Ci;\n        const T1r = Ar - Cr;\n        const T1i = Ai - Ci;\n        const T2r = Br + Dr;\n        const T2i = Bi + Di;\n        const T3r = inv * (Br - Dr);\n        const T3i = inv * (Bi - Di);\n\n        // Final values\n        out[outOff] = T0r + T2r;\n        out[outOff + 1] = T0i + T2i;\n        out[outOff + 2] = T1r + T3i;\n        out[outOff + 3] = T1i - T3r;\n        out[outOff + 4] = T0r - T2r;\n        out[outOff + 5] = T0i - T2i;\n        out[outOff + 6] = T1r - T3i;\n        out[outOff + 7] = T1i + T3r;\n    }\n\n    /**\n     * Real input radix-4 implementation\n     * @param {Float64Array} out Output array for the transformed data\n     * @param {Float64Array} data Input array of real data to be transformed\n     * @param {number} inv The scale factor used to normalize the inverse transform\n     */\n    _realTransform4(out, data, inv) {\n        // Real input radix-4 implementation\n        const size = this._csize;\n\n        // Initial step (permute and transform)\n        const width = this._width;\n        let step = 1 << width;\n        let len = (size / step) << 1;\n\n        let outOff;\n        let t;\n        const bitrev = this._bitrev;\n        if (len === 4) {\n            for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n                const off = bitrev[t];\n                this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1);\n            }\n        } else {\n            // len === 8\n            for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n                const off = bitrev[t];\n                this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv);\n            }\n        }\n\n        // Loop through steps in decreasing order\n        const table = this.table;\n        for (step >>= 2; step >= 2; step >>= 2) {\n            len = (size / step) << 1;\n            const halfLen = len >>> 1;\n            const quarterLen = halfLen >>> 1;\n            const hquarterLen = quarterLen >>> 1;\n\n            // Loop through offsets in the data\n            for (outOff = 0; outOff < size; outOff += len) {\n                for (let i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {\n                    const A = outOff + i;\n                    const B = A + quarterLen;\n                    const C = B + quarterLen;\n                    const D = C + quarterLen;\n\n                    // Original values\n                    const Ar = out[A];\n                    const Ai = out[A + 1];\n                    const Br = out[B];\n                    const Bi = out[B + 1];\n                    const Cr = out[C];\n                    const Ci = out[C + 1];\n                    const Dr = out[D];\n                    const Di = out[D + 1];\n\n                    // Middle values\n                    const MAr = Ar;\n                    const MAi = Ai;\n\n                    const tableBr = table[k];\n                    const tableBi = inv * table[k + 1];\n                    const MBr = Br * tableBr - Bi * tableBi;\n                    const MBi = Br * tableBi + Bi * tableBr;\n\n                    const tableCr = table[2 * k];\n                    const tableCi = inv * table[2 * k + 1];\n                    const MCr = Cr * tableCr - Ci * tableCi;\n                    const MCi = Cr * tableCi + Ci * tableCr;\n\n                    const tableDr = table[3 * k];\n                    const tableDi = inv * table[3 * k + 1];\n                    const MDr = Dr * tableDr - Di * tableDi;\n                    const MDi = Dr * tableDi + Di * tableDr;\n\n                    // Pre-Final values\n                    const T0r = MAr + MCr;\n                    const T0i = MAi + MCi;\n                    const T1r = MAr - MCr;\n                    const T1i = MAi - MCi;\n                    const T2r = MBr + MDr;\n                    const T2i = MBi + MDi;\n                    const T3r = inv * (MBr - MDr);\n                    const T3i = inv * (MBi - MDi);\n\n                    // Final values\n                    out[A] = T0r + T2r;\n                    out[A + 1] = T0i + T2i;\n                    out[B] = T1r + T3i;\n                    out[B + 1] = T1i - T3r;\n\n                    // Output final middle point\n                    if (i === 0) {\n                        out[C] = T0r - T2r;\n                        out[C + 1] = T0i - T2i;\n                        continue;\n                    }\n\n                    // Do not overwrite ourselves\n                    if (i === hquarterLen)\n                        continue;\n\n                    const SA = outOff + quarterLen - i;\n                    const SB = outOff + halfLen - i;\n\n                    out[SA] = T1r - inv * T3i;\n                    out[SA + 1] = -T1i - inv * T3r;\n                    out[SB] = T0r - inv * T2r;\n                    out[SB + 1] = -T0i + inv * T2i;\n                }\n            }\n        }\n\n        // Complete the spectrum by adding its mirrored negative frequency components.\n        const half = size >>> 1;\n        for (let i = 2; i < half; i += 2) {\n            out[size - i] = out[i];\n            out[size - i + 1] = -out[i + 1];\n        }\n    }\n\n    /**\n     * Performs a single real input radix-2 transformation on the provided data\n     * \n     * @param {Float64Array} data The input data array\n     * @param {Float64Array} out The output data array\n     * @param {number} outOff The output offset\n     * @param {number} off The input offset\n     * @param {number} step The step\n     * \n     * @returns {void}\n     */\n    _singleRealTransform2(data, out, outOff, off, step) {\n        // radix-2 implementation\n        // NOTE: Only called for len=4\n\n        const evenR = data[off];\n        const oddR = data[off + step];\n\n        out[outOff] = evenR + oddR;\n        out[outOff + 1] = 0;\n        out[outOff + 2] = evenR - oddR;\n        out[outOff + 3] = 0;\n    }\n\n    /**\n     * Computes a single real-valued transform using radix-4 algorithm.\n     * This method is only called for len=8.\n     *\n     * @param {Float64Array} data The input data array.\n     * @param {Float64Array} out The output data array.\n     * @param {number} outOff The offset into the output array.\n     * @param {number} off The offset into the input array.\n     * @param {number} step The step size for the input array.\n     * @param {number} inv The value of inverse.\n     */\n    _singleRealTransform4(data, out, outOff, off, step, inv) {\n        // radix-4\n        // NOTE: Only called for len=8\n        const step2 = step * 2;\n        const step3 = step * 3;\n\n        // Original values\n        const Ar = data[off];\n        const Br = data[off + step];\n        const Cr = data[off + step2];\n        const Dr = data[off + step3];\n\n        // Pre-Final values\n        const T0r = Ar + Cr;\n        const T1r = Ar - Cr;\n        const T2r = Br + Dr;\n        const T3r = inv * (Br - Dr);\n\n        // Final values\n        out[outOff] = T0r + T2r;\n        out[outOff + 1] = 0;\n        out[outOff + 2] = T1r;\n        out[outOff + 3] = -T3r;\n        out[outOff + 4] = T0r - T2r;\n        out[outOff + 5] = 0;\n        out[outOff + 6] = T1r;\n        out[outOff + 7] = T3r;\n    }\n}\n\n/**\n * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are not a power of two in length. In such cases, the chirp-z transform is used.\n * \n * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156\n */\nclass NP2FFT {\n\n    /**\n     * Constructs a new NP2FFT object.\n     * @param {number} fft_length The length of the FFT\n     */\n    constructor(fft_length) {\n        // Helper variables\n        const a = 2 * (fft_length - 1);\n        const b = 2 * (2 * fft_length - 1);\n        const nextP2 = 2 ** (Math.ceil(Math.log2(b)))\n        this.bufferSize = nextP2;\n        this._a = a;\n\n        // Define buffers\n        // Compute chirp for transform\n        const chirp = new Float64Array(b);\n        const ichirp = new Float64Array(nextP2);\n        this._chirpBuffer = new Float64Array(nextP2);\n        this._buffer1 = new Float64Array(nextP2);\n        this._buffer2 = new Float64Array(nextP2);\n        this._outBuffer1 = new Float64Array(nextP2);\n        this._outBuffer2 = new Float64Array(nextP2);\n\n        // Compute complex exponentiation\n        const theta = -2 * Math.PI / fft_length;\n        const baseR = Math.cos(theta);\n        const baseI = Math.sin(theta);\n\n        // Precompute helper for chirp-z transform\n        for (let i = 0; i < b >> 1; ++i) {\n            // Compute complex power:\n            const e = (i + 1 - fft_length) ** 2 / 2.0;\n\n            // Compute the modulus and argument of the result\n            const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;\n            const result_arg = e * Math.atan2(baseI, baseR);\n\n            // Convert the result back to rectangular form\n            // and assign to chirp and ichirp\n            const i2 = 2 * i;\n            chirp[i2] = result_mod * Math.cos(result_arg);\n            chirp[i2 + 1] = result_mod * Math.sin(result_arg);\n\n            // conjugate\n            ichirp[i2] = chirp[i2];\n            ichirp[i2 + 1] = - chirp[i2 + 1];\n        }\n        this._slicedChirpBuffer = chirp.subarray(a, b);\n\n        // create object to perform Fast Fourier Transforms\n        // with `nextP2` complex numbers\n        this._f = new P2FFT(nextP2 >> 1);\n        this._f.transform(this._chirpBuffer, ichirp);\n    }\n\n    _transform(output, input, real) {\n        const ib1 = this._buffer1;\n        const ib2 = this._buffer2;\n        const ob2 = this._outBuffer1;\n        const ob3 = this._outBuffer2;\n        const cb = this._chirpBuffer;\n        const sb = this._slicedChirpBuffer;\n        const a = this._a;\n\n        if (real) {\n            // Real multiplication\n            for (let j = 0; j < sb.length; j += 2) {\n                const j2 = j + 1\n                const j3 = j >> 1;\n\n                const a_real = input[j3];\n                ib1[j] = a_real * sb[j];\n                ib1[j2] = a_real * sb[j2];\n            }\n        } else {\n            // Complex multiplication\n            for (let j = 0; j < sb.length; j += 2) {\n                const j2 = j + 1\n                ib1[j] = input[j] * sb[j] - input[j2] * sb[j2];\n                ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j];\n            }\n        }\n        this._f.transform(ob2, ib1);\n\n        for (let j = 0; j < cb.length; j += 2) {\n            const j2 = j + 1;\n\n            ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2];\n            ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j];\n        }\n        this._f.inverseTransform(ob3, ib2);\n\n        for (let j = 0; j < ob3.length; j += 2) {\n            const a_real = ob3[j + a];\n            const a_imag = ob3[j + a + 1];\n            const b_real = sb[j];\n            const b_imag = sb[j + 1];\n\n            output[j] = a_real * b_real - a_imag * b_imag;\n            output[j + 1] = a_real * b_imag + a_imag * b_real;\n        }\n    }\n\n    transform(output, input) {\n        this._transform(output, input, false);\n    }\n\n    realTransform(output, input) {\n        this._transform(output, input, true);\n    }\n}\n\nexport class FFT {\n    constructor(fft_length) {\n        this.fft_length = fft_length;\n        this.isPowerOfTwo = isPowerOfTwo(fft_length);\n        if (this.isPowerOfTwo) {\n            this.fft = new P2FFT(fft_length);\n            this.outputBufferSize = 2 * fft_length;\n        } else {\n            this.fft = new NP2FFT(fft_length);\n            this.outputBufferSize = this.fft.bufferSize;\n        }\n    }\n\n    realTransform(out, input) {\n        this.fft.realTransform(out, input);\n    }\n\n    transform(out, input) {\n        this.fft.transform(out, input);\n    }\n}\n\n\n/**\n * Performs median filter on the provided data. Padding is done by mirroring the data.\n * @param {AnyTypedArray} data The input array\n * @param {number} windowSize The window size\n */\nexport function medianFilter(data, windowSize) {\n\n    if (windowSize % 2 === 0 || windowSize <= 0) {\n        throw new Error('Window size must be a positive odd number');\n    }\n\n    // @ts-ignore\n    const outputArray = new data.constructor(data.length);\n\n    // @ts-ignore\n    const buffer = new data.constructor(windowSize); // Reusable array for storing values\n\n    const halfWindowSize = Math.floor(windowSize / 2);\n\n    for (let i = 0; i < data.length; ++i) {\n        let valuesIndex = 0;\n\n        for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {\n            let index = i + j;\n            if (index < 0) {\n                index = Math.abs(index);\n            } else if (index >= data.length) {\n                index = 2 * (data.length - 1) - index;\n            }\n\n            buffer[valuesIndex++] = data[index];\n        }\n\n        buffer.sort();\n        outputArray[i] = buffer[halfWindowSize];\n    }\n\n    return outputArray;\n}\n\n/**\n * Helper function to round a number to a given number of decimals\n * @param {number} num The number to round\n * @param {number} decimals The number of decimals\n * @returns {number} The rounded number\n */\nexport function round(num, decimals) {\n    const pow = Math.pow(10, decimals);\n    return Math.round(num * pow) / pow;\n}\n\n/**\n * Helper function to round a number to the nearest integer, with ties rounded to the nearest even number.\n * Also known as \"bankers' rounding\". This is the default rounding mode in python. For example:\n * 1.5 rounds to 2 and 2.5 rounds to 2.\n * \n * @param {number} x The number to round\n * @returns {number} The rounded number\n */\nexport function bankers_round(x) {\n    const r = Math.round(x);\n    const br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r - 1) : r;\n    return br;\n}\n\n\n/**\n * Measures similarity between two temporal sequences (e.g., input audio and output tokens\n * to generate token-level timestamps).\n * @param {number[][]} matrix \n * @returns {number[][]}\n */\nexport function dynamic_time_warping(matrix) {\n    const output_length = matrix.length;\n    const input_length = matrix[0].length;\n\n    const outputShape = [output_length + 1, input_length + 1];\n\n    const cost = Array.from(\n        { length: outputShape[0] },\n        () => Array(outputShape[1]).fill(Infinity)\n    );\n    cost[0][0] = 0;\n\n    const trace = Array.from(\n        { length: outputShape[0] },\n        () => Array(outputShape[1]).fill(-1)\n    );\n\n    for (let j = 1; j < outputShape[1]; ++j) {\n        for (let i = 1; i < outputShape[0]; ++i) {\n            const c0 = cost[i - 1][j - 1];\n            const c1 = cost[i - 1][j];\n            const c2 = cost[i][j - 1];\n\n            let c, t;\n            if (c0 < c1 && c0 < c2) {\n                c = c0;\n                t = 0;\n            } else if (c1 < c0 && c1 < c2) {\n                c = c1;\n                t = 1;\n            } else {\n                c = c2;\n                t = 2;\n            }\n            cost[i][j] = matrix[i - 1][j - 1] + c;\n            trace[i][j] = t;\n        }\n    }\n\n    for (let i = 0; i < outputShape[1]; ++i) { // trace[0, :] = 2\n        trace[0][i] = 2;\n    }\n    for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1\n        trace[i][0] = 1;\n    }\n\n    // backtrace\n    let i = output_length;\n    let j = input_length;\n    let text_indices = [];\n    let time_indices = [];\n    while (i > 0 || j > 0) {\n        text_indices.push(i - 1);\n        time_indices.push(j - 1);\n\n        switch (trace[i][j]) {\n            case 0:\n                --i; --j;\n                break;\n            case 1:\n                --i;\n                break;\n            case 2:\n                --j;\n                break;\n            default:\n                throw new Error(\n                    `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`\n                )\n        }\n    }\n\n    text_indices.reverse();\n    time_indices.reverse();\n\n    return [text_indices, time_indices];\n\n}\n", "export default new Proxy({}, {\n  // Return a dummy function for everything to satisfy instanceof checks\n  get: () => () => {}\n});\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/**\n * # ONNX Runtime JavaScript API\n *\n * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages:\n *\n * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node)\n * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web)\n * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native)\n *\n * See also:\n * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript/)\n * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js)\n *\n * @packageDocumentation\n */\n\nexport * from './backend.js';\nexport * from './env.js';\nexport * from './inference-session.js';\nexport * from './tensor.js';\nexport * from './tensor-conversion.js';\nexport * from './tensor-factory.js';\nexport * from './trace.js';\nexport * from './onnx-model.js';\nexport * from './onnx-value.js';\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Backend } from './backend.js';\nimport { InferenceSession } from './inference-session.js';\n\ninterface BackendInfo {\n  backend: Backend;\n  priority: number;\n\n  initPromise?: Promise<void>;\n  initialized?: boolean;\n  aborted?: boolean;\n  error?: string;\n}\n\nconst backends: Map<string, BackendInfo> = new Map();\nconst backendsSortedByPriority: string[] = [];\n\n/**\n * Register a backend.\n *\n * @param name - the name as a key to lookup as an execution provider.\n * @param backend - the backend object.\n * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority\n * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.\n *\n * @ignore\n */\nexport const registerBackend = (name: string, backend: Backend, priority: number): void => {\n  if (backend && typeof backend.init === 'function' && typeof backend.createInferenceSessionHandler === 'function') {\n    const currentBackend = backends.get(name);\n    if (currentBackend === undefined) {\n      backends.set(name, { backend, priority });\n    } else if (currentBackend.priority > priority) {\n      // same name is already registered with a higher priority. skip registeration.\n      return;\n    } else if (currentBackend.priority === priority) {\n      if (currentBackend.backend !== backend) {\n        throw new Error(`cannot register backend \"${name}\" using priority ${priority}`);\n      }\n    }\n\n    if (priority >= 0) {\n      const i = backendsSortedByPriority.indexOf(name);\n      if (i !== -1) {\n        backendsSortedByPriority.splice(i, 1);\n      }\n\n      for (let i = 0; i < backendsSortedByPriority.length; i++) {\n        if (backends.get(backendsSortedByPriority[i])!.priority <= priority) {\n          backendsSortedByPriority.splice(i, 0, name);\n          return;\n        }\n      }\n      backendsSortedByPriority.push(name);\n    }\n    return;\n  }\n\n  throw new TypeError('not a valid backend');\n};\n\n/**\n * Try to resolve and initialize a backend.\n *\n * @param backendName - the name of the backend.\n * @returns the backend instance if resolved and initialized successfully, or an error message if failed.\n */\nconst tryResolveAndInitializeBackend = async (backendName: string): Promise<Backend | string> => {\n  const backendInfo = backends.get(backendName);\n  if (!backendInfo) {\n    return 'backend not found.';\n  }\n\n  if (backendInfo.initialized) {\n    return backendInfo.backend;\n  } else if (backendInfo.aborted) {\n    return backendInfo.error!;\n  } else {\n    const isInitializing = !!backendInfo.initPromise;\n    try {\n      if (!isInitializing) {\n        backendInfo.initPromise = backendInfo.backend.init(backendName);\n      }\n      await backendInfo.initPromise;\n      backendInfo.initialized = true;\n      return backendInfo.backend;\n    } catch (e) {\n      if (!isInitializing) {\n        backendInfo.error = `${e}`;\n        backendInfo.aborted = true;\n      }\n      return backendInfo.error!;\n    } finally {\n      delete backendInfo.initPromise;\n    }\n  }\n};\n\n/**\n * Resolve execution providers from the specific session options.\n *\n * @param options - the session options object.\n * @returns a promise that resolves to a tuple of an initialized backend instance and a session options object with\n * filtered EP list.\n *\n * @ignore\n */\nexport const resolveBackendAndExecutionProviders = async (\n  options: InferenceSession.SessionOptions,\n): Promise<[backend: Backend, options: InferenceSession.SessionOptions]> => {\n  // extract backend hints from session options\n  const eps = options.executionProviders || [];\n  const backendHints = eps.map((i) => (typeof i === 'string' ? i : i.name));\n  const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;\n\n  // try to resolve and initialize all requested backends\n  let backend: Backend | undefined;\n  const errors = [];\n  const availableBackendNames = new Set<string>();\n  for (const backendName of backendNames) {\n    const resolveResult = await tryResolveAndInitializeBackend(backendName);\n    if (typeof resolveResult === 'string') {\n      errors.push({ name: backendName, err: resolveResult });\n    } else {\n      if (!backend) {\n        backend = resolveResult;\n      }\n      if (backend === resolveResult) {\n        availableBackendNames.add(backendName);\n      }\n    }\n  }\n\n  // if no backend is available, throw error.\n  if (!backend) {\n    throw new Error(`no available backend found. ERR: ${errors.map((e) => `[${e.name}] ${e.err}`).join(', ')}`);\n  }\n\n  // for each explicitly requested backend, if it's not available, output warning message.\n  for (const { name, err } of errors) {\n    if (backendHints.includes(name)) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `removing requested execution provider \"${name}\" from session options because it is not available: ${err}`,\n      );\n    }\n  }\n\n  const filteredEps = eps.filter((i) => availableBackendNames.has(typeof i === 'string' ? i : i.name));\n\n  return [\n    backend,\n    new Proxy(options, {\n      get: (target, prop) => {\n        if (prop === 'executionProviders') {\n          return filteredEps;\n        }\n        return Reflect.get(target, prop);\n      },\n    }),\n  ];\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\n\nexport const version = '1.22.0-dev.20250409-89f8206ba4';\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Env } from './env.js';\nimport { version } from './version.js';\n\ntype LogLevelType = Env['logLevel'];\n\nlet logLevelValue: Required<LogLevelType> = 'warning';\n\nexport const env: Env = {\n  wasm: {} as Env.WebAssemblyFlags,\n  webgl: {} as Env.WebGLFlags,\n  webgpu: {} as Env.WebGpuFlags,\n  versions: { common: version },\n\n  set logLevel(value: LogLevelType) {\n    if (value === undefined) {\n      return;\n    }\n    if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {\n      throw new Error(`Unsupported logging level: ${value}`);\n    }\n    logLevelValue = value;\n  },\n  get logLevel(): Required<LogLevelType> {\n    return logLevelValue;\n  },\n};\n\n// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`.\nObject.defineProperty(env, 'logLevel', { enumerable: true });\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { env as envImpl } from './env-impl.js';\nimport { TryGetGlobalType } from './type-helper.js';\n\nexport declare namespace Env {\n  export type WasmPathPrefix = string;\n  export interface WasmFilePaths {\n    /**\n     * Specify the override path for the main .wasm file.\n     *\n     * This path should be an absolute path.\n     *\n     * If not modified, the filename of the .wasm file is:\n     * - `ort-wasm-simd-threaded.wasm` for default build\n     * - `ort-wasm-simd-threaded.jsep.wasm` for JSEP build (with WebGPU and WebNN)\n     */\n    wasm?: URL | string;\n    /**\n     * Specify the override path for the main .mjs file.\n     *\n     * This path should be an absolute path.\n     *\n     * If not modified, the filename of the .mjs file is:\n     * - `ort-wasm-simd-threaded.mjs` for default build\n     * - `ort-wasm-simd-threaded.jsep.mjs` for JSEP build (with WebGPU and WebNN)\n     */\n    mjs?: URL | string;\n  }\n  export type WasmPrefixOrFilePaths = WasmPathPrefix | WasmFilePaths;\n  export interface WebAssemblyFlags {\n    /**\n     * set or get number of thread(s). If omitted or set to 0, number of thread(s) will be determined by system. If set\n     * to 1, no worker thread will be spawned.\n     *\n     * This setting is available only when WebAssembly multithread feature is available in current context.\n     *\n     * @defaultValue `0`\n     */\n    numThreads?: number;\n\n    /**\n     * set a value indicating whether to enable SIMD.\n     *\n     * ONNX Runtime will perform feature detection based on the value of this property. Specifically, when the value is\n     * set to:\n     * - `undefined`, `true` or `\"fixed\"`: will check availability of Fixed-width SIMD.\n     * - `\"relaxed\"`: will check availability of Relaxed SIMD.\n     * - `false`: will not perform SIMD feature checking.\n     *\n     * Setting this property does not make ONNX Runtime to switch to the corresponding runtime automatically. User need\n     * to set `wasmPaths` or `wasmBinary` property to load the corresponding runtime.\n     *\n     * This setting is available only when WebAssembly SIMD feature is available in current context.\n     *\n     * @defaultValue `true`\n     */\n    simd?: boolean | 'fixed' | 'relaxed';\n\n    /**\n     * set or get a boolean value indicating whether to enable trace.\n     *\n     * @defaultValue `false`\n     *\n     * @deprecated Use `env.trace` instead. If `env.trace` is set, this property will be ignored.\n     */\n    trace?: boolean;\n\n    /**\n     * Set or get a number specifying the timeout for initialization of WebAssembly backend, in milliseconds. A zero\n     * value indicates no timeout is set.\n     *\n     * @defaultValue `0`\n     */\n    initTimeout?: number;\n\n    /**\n     * Set a custom URL prefix to the .wasm/.mjs files, or an object of overrides for both .wasm/.mjs file. The override\n     * path should be an absolute path.\n     */\n    wasmPaths?: WasmPrefixOrFilePaths;\n\n    /**\n     * Set a custom buffer which contains the WebAssembly binary. If this property is set, the `wasmPaths` property will\n     * be ignored.\n     */\n    wasmBinary?: ArrayBufferLike | Uint8Array;\n\n    /**\n     * Set or get a boolean value indicating whether to proxy the execution of main thread to a worker thread.\n     *\n     * @defaultValue `false`\n     */\n    proxy?: boolean;\n  }\n\n  export interface WebGLFlags {\n    /**\n     * Set or get the WebGL Context ID (webgl or webgl2).\n     *\n     * @defaultValue `'webgl2'`\n     */\n    contextId?: 'webgl' | 'webgl2';\n    /**\n     * Get the WebGL rendering context.\n     */\n    readonly context: WebGLRenderingContext;\n    /**\n     * Set or get the maximum batch size for matmul. 0 means to disable batching.\n     *\n     * @deprecated\n     */\n    matmulMaxBatchSize?: number;\n    /**\n     * Set or get the texture cache mode.\n     *\n     * @defaultValue `'full'`\n     */\n    textureCacheMode?: 'initializerOnly' | 'full';\n    /**\n     * Set or get the packed texture mode\n     *\n     * @defaultValue `false`\n     */\n    pack?: boolean;\n    /**\n     * Set or get whether enable async download.\n     *\n     * @defaultValue `false`\n     */\n    async?: boolean;\n  }\n\n  export interface WebGpuProfilingDataV1TensorMetadata {\n    dims: readonly number[];\n    dataType: string;\n  }\n  export interface WebGpuProfilingDataV1 {\n    version: 1;\n    inputsMetadata: readonly WebGpuProfilingDataV1TensorMetadata[];\n    outputsMetadata: readonly WebGpuProfilingDataV1TensorMetadata[];\n    kernelId: number;\n    kernelType: string;\n    kernelName: string;\n    programName: string;\n    startTime: number;\n    endTime: number;\n  }\n\n  export type WebGpuProfilingData = WebGpuProfilingDataV1;\n\n  export interface WebGpuFlags {\n    /**\n     * Set or get the profiling mode.\n     *\n     * @deprecated Use `env.webgpu.profiling.mode` instead. If `env.webgpu.profiling.mode` is set, this property will be\n     * ignored.\n     */\n    profilingMode?: 'off' | 'default';\n    /**\n     * Set or get the profiling configuration.\n     */\n    profiling: {\n      /**\n       * Set or get the profiling mode.\n       *\n       * @defaultValue `'off'`\n       */\n      mode?: 'off' | 'default';\n\n      /**\n       * Set or get a callback function when a profiling data is received. If not set, the profiling data will be\n       * printed to console.\n       */\n      ondata?: (data: WebGpuProfilingData) => void;\n    };\n    /**\n     * Set or get the power preference.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as options for `navigator.gpu.requestAdapter()`.\n     *\n     * See {@link https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions} for more details.\n     *\n     * @defaultValue `undefined`\n     *\n     * @deprecated Create your own GPUAdapter, use it to create a GPUDevice instance and set {@link device} property if\n     * you want to use a specific power preference.\n     */\n    powerPreference?: 'low-power' | 'high-performance';\n    /**\n     * Set or get the force fallback adapter flag.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as options for `navigator.gpu.requestAdapter()`.\n     *\n     * See {@link https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions} for more details.\n     *\n     * @defaultValue `undefined`\n     *\n     * @deprecated Create your own GPUAdapter, use it to create a GPUDevice instance and set {@link device} property if\n     * you want to use a specific fallback option.\n     */\n    forceFallbackAdapter?: boolean;\n    /**\n     * Set or get the adapter for WebGPU.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as the GPU adapter for the underlying WebGPU backend to create GPU device.\n     *\n     * If this property is not set, it will be available to get after the first WebGPU inference session is created. The\n     * value will be the GPU adapter that created by the underlying WebGPU backend.\n     *\n     * When use with TypeScript, the type of this property is `GPUAdapter` defined in \"@webgpu/types\".\n     *\n     * @deprecated It is no longer recommended to use this property. The latest WebGPU spec adds `GPUDevice.adapterInfo`\n     * (https://www.w3.org/TR/webgpu/#dom-gpudevice-adapterinfo), which allows to get the adapter information from the\n     * device. When it's available, there is no need to set/get the {@link adapter} property.\n     */\n    adapter: TryGetGlobalType<'GPUAdapter'>;\n    /**\n     * Set or get the GPU device for WebGPU.\n     *\n     * There are 3 valid scenarios of accessing this property:\n     * - Set a value before the first WebGPU inference session is created. The value will be used by the WebGPU backend\n     * to perform calculations. If the value is not a `GPUDevice` object, an error will be thrown.\n     * - Get the value before the first WebGPU inference session is created. This will try to create a new GPUDevice\n     * instance. Returns a `Promise` that resolves to a `GPUDevice` object.\n     * - Get the value after the first WebGPU inference session is created. Returns a resolved `Promise` to the\n     * `GPUDevice` object used by the WebGPU backend.\n     */\n    get device(): Promise<TryGetGlobalType<'GPUDevice'>>;\n    set device(value: TryGetGlobalType<'GPUDevice'>);\n    /**\n     * Set or get whether validate input content.\n     *\n     * @defaultValue `false`\n     */\n    validateInputContent?: boolean;\n  }\n}\n\nexport interface Env {\n  /**\n   * set the severity level for logging.\n   *\n   * @defaultValue `'warning'`\n   */\n  logLevel?: 'verbose' | 'info' | 'warning' | 'error' | 'fatal';\n\n  /**\n   * Indicate whether run in debug mode.\n   *\n   * @defaultValue `false`\n   */\n  debug?: boolean;\n\n  /**\n   * set or get a boolean value indicating whether to enable trace.\n   *\n   * @defaultValue `false`\n   */\n  trace?: boolean;\n\n  /**\n   * Get version of the current package.\n   */\n  readonly versions: {\n    readonly common: string;\n    readonly web?: string;\n    readonly node?: string;\n    // eslint-disable-next-line @typescript-eslint/naming-convention\n    readonly 'react-native'?: string;\n  };\n\n  /**\n   * Represent a set of flags for WebAssembly\n   */\n  readonly wasm: Env.WebAssemblyFlags;\n\n  /**\n   * Represent a set of flags for WebGL\n   */\n  readonly webgl: Env.WebGLFlags;\n\n  /**\n   * Represent a set of flags for WebGPU\n   */\n  readonly webgpu: Env.WebGpuFlags;\n\n  [name: string]: unknown;\n}\n\n/**\n * Represent a set of flags as a global singleton.\n */\nexport const env: Env = envImpl;\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { TensorToDataUrlOptions, TensorToImageDataOptions } from './tensor-conversion.js';\nimport { Tensor } from './tensor.js';\n\n/**\n * implementation of Tensor.toDataURL()\n */\nexport const tensorToDataURL = (tensor: Tensor, options?: TensorToDataUrlOptions): string => {\n  const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : new OffscreenCanvas(1, 1);\n  canvas.width = tensor.dims[3];\n  canvas.height = tensor.dims[2];\n  const pixels2DContext = canvas.getContext('2d') as\n    | CanvasRenderingContext2D\n    | OffscreenCanvasRenderingContext2D\n    | null;\n\n  if (pixels2DContext != null) {\n    // Default values for height and width & format\n    let width: number;\n    let height: number;\n    if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n      width = tensor.dims[2];\n      height = tensor.dims[3];\n    } else {\n      // Default layout is NCWH\n      width = tensor.dims[3];\n      height = tensor.dims[2];\n    }\n\n    const inputformat = options?.format !== undefined ? options.format : 'RGB';\n\n    const norm = options?.norm;\n    let normMean: [number, number, number, number];\n    let normBias: [number, number, number, number];\n    if (norm === undefined || norm.mean === undefined) {\n      normMean = [255, 255, 255, 255];\n    } else {\n      if (typeof norm.mean === 'number') {\n        normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n      } else {\n        normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];\n        if (norm.mean[3] !== undefined) {\n          normMean[3] = norm.mean[3];\n        }\n      }\n    }\n    if (norm === undefined || norm.bias === undefined) {\n      normBias = [0, 0, 0, 0];\n    } else {\n      if (typeof norm.bias === 'number') {\n        normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n      } else {\n        normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n        if (norm.bias[3] !== undefined) {\n          normBias[3] = norm.bias[3];\n        }\n      }\n    }\n\n    const stride = height * width;\n    // Default pointer assignments\n    let rTensorPointer = 0,\n      gTensorPointer = stride,\n      bTensorPointer = stride * 2,\n      aTensorPointer = -1;\n\n    // Updating the pointer assignments based on the input image format\n    if (inputformat === 'RGBA') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n      aTensorPointer = stride * 3;\n    } else if (inputformat === 'RGB') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n    } else if (inputformat === 'RBG') {\n      rTensorPointer = 0;\n      bTensorPointer = stride;\n      gTensorPointer = stride * 2;\n    }\n\n    for (let i = 0; i < height; i++) {\n      for (let j = 0; j < width; j++) {\n        const R = ((tensor.data[rTensorPointer++] as number) - normBias[0]) * normMean[0]; // R value\n        const G = ((tensor.data[gTensorPointer++] as number) - normBias[1]) * normMean[1]; // G value\n        const B = ((tensor.data[bTensorPointer++] as number) - normBias[2]) * normMean[2]; // B value\n        const A = aTensorPointer === -1 ? 255 : ((tensor.data[aTensorPointer++] as number) - normBias[3]) * normMean[3]; // A value\n        // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n        pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')';\n        pixels2DContext.fillRect(j, i, 1, 1);\n      }\n    }\n    if ('toDataURL' in canvas) {\n      return canvas.toDataURL();\n    } else {\n      throw new Error('toDataURL is not supported');\n    }\n  } else {\n    throw new Error('Can not access image data');\n  }\n};\n\n/**\n * implementation of Tensor.toImageData()\n */\nexport const tensorToImageData = (tensor: Tensor, options?: TensorToImageDataOptions): ImageData => {\n  const pixels2DContext =\n    typeof document !== 'undefined'\n      ? document.createElement('canvas').getContext('2d')\n      : (new OffscreenCanvas(1, 1).getContext('2d') as OffscreenCanvasRenderingContext2D);\n  let image: ImageData;\n  if (pixels2DContext != null) {\n    // Default values for height and width & format\n    let width: number;\n    let height: number;\n    let channels: number;\n    if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n      width = tensor.dims[2];\n      height = tensor.dims[1];\n      channels = tensor.dims[3];\n    } else {\n      // Default layout is NCWH\n      width = tensor.dims[3];\n      height = tensor.dims[2];\n      channels = tensor.dims[1];\n    }\n    const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';\n\n    const norm = options?.norm;\n    let normMean: [number, number, number, number];\n    let normBias: [number, number, number, number];\n    if (norm === undefined || norm.mean === undefined) {\n      normMean = [255, 255, 255, 255];\n    } else {\n      if (typeof norm.mean === 'number') {\n        normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n      } else {\n        normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];\n        if (norm.mean[3] !== undefined) {\n          normMean[3] = norm.mean[3];\n        }\n      }\n    }\n    if (norm === undefined || norm.bias === undefined) {\n      normBias = [0, 0, 0, 0];\n    } else {\n      if (typeof norm.bias === 'number') {\n        normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n      } else {\n        normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n        if (norm.bias[3] !== undefined) {\n          normBias[3] = norm.bias[3];\n        }\n      }\n    }\n\n    const stride = height * width;\n    if (options !== undefined) {\n      if (\n        (options.format !== undefined && channels === 4 && options.format !== 'RGBA') ||\n        (channels === 3 && options.format !== 'RGB' && options.format !== 'BGR')\n      ) {\n        throw new Error(\"Tensor format doesn't match input tensor dims\");\n      }\n    }\n\n    // Default pointer assignments\n    const step = 4;\n    let rImagePointer = 0,\n      gImagePointer = 1,\n      bImagePointer = 2,\n      aImagePointer = 3;\n    let rTensorPointer = 0,\n      gTensorPointer = stride,\n      bTensorPointer = stride * 2,\n      aTensorPointer = -1;\n\n    // Updating the pointer assignments based on the input image format\n    if (inputformat === 'RGBA') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n      aTensorPointer = stride * 3;\n    } else if (inputformat === 'RGB') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n    } else if (inputformat === 'RBG') {\n      rTensorPointer = 0;\n      bTensorPointer = stride;\n      gTensorPointer = stride * 2;\n    }\n\n    image = pixels2DContext.createImageData(width, height);\n\n    for (\n      let i = 0;\n      i < height * width;\n      rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++\n    ) {\n      image.data[rImagePointer] = ((tensor.data[rTensorPointer++] as number) - normBias[0]) * normMean[0]; // R value\n      image.data[gImagePointer] = ((tensor.data[gTensorPointer++] as number) - normBias[1]) * normMean[1]; // G value\n      image.data[bImagePointer] = ((tensor.data[bTensorPointer++] as number) - normBias[2]) * normMean[2]; // B value\n      image.data[aImagePointer] =\n        aTensorPointer === -1 ? 255 : ((tensor.data[aTensorPointer++] as number) - normBias[3]) * normMean[3]; // A value\n    }\n  } else {\n    throw new Error('Can not access image data');\n  }\n  return image;\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  OptionsDimensions,\n  OptionsFormat,\n  OptionsNormalizationParameters,\n  OptionsTensorFormat,\n  OptionsTensorLayout,\n  TensorFromGpuBufferOptions,\n  TensorFromImageBitmapOptions,\n  TensorFromImageDataOptions,\n  TensorFromImageElementOptions,\n  TensorFromMLTensorOptions,\n  TensorFromTextureOptions,\n  TensorFromUrlOptions,\n} from './tensor-factory.js';\nimport { Tensor } from './tensor-impl.js';\nimport { Tensor as TensorInterface } from './tensor.js';\n\ninterface BufferToTensorOptions\n  extends OptionsDimensions,\n    OptionsTensorLayout,\n    OptionsNormalizationParameters,\n    OptionsFormat,\n    OptionsTensorFormat {}\n\n/**\n * Create a new tensor object from image object\n *\n * @param buffer - Extracted image buffer data - assuming RGBA format\n * @param imageFormat - input image configuration - required configurations height, width, format\n * @param tensorFormat - output tensor configuration - Default is RGB format\n */\nexport const bufferToTensor = (buffer: Uint8ClampedArray | undefined, options: BufferToTensorOptions): Tensor => {\n  if (buffer === undefined) {\n    throw new Error('Image buffer must be defined');\n  }\n  if (options.height === undefined || options.width === undefined) {\n    throw new Error('Image height and width must be defined');\n  }\n  if (options.tensorLayout === 'NHWC') {\n    throw new Error('NHWC Tensor layout is not supported yet');\n  }\n\n  const { height, width } = options;\n\n  const norm = options.norm ?? { mean: 255, bias: 0 };\n  let normMean: [number, number, number, number];\n  let normBias: [number, number, number, number];\n\n  if (typeof norm.mean === 'number') {\n    normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n  } else {\n    normMean = [norm.mean![0], norm.mean![1], norm.mean![2], norm.mean![3] ?? 255];\n  }\n\n  if (typeof norm.bias === 'number') {\n    normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n  } else {\n    normBias = [norm.bias![0], norm.bias![1], norm.bias![2], norm.bias![3] ?? 0];\n  }\n\n  const inputformat = options.format !== undefined ? options.format : 'RGBA';\n  // default value is RGBA since imagedata and HTMLImageElement uses it\n\n  const outputformat =\n    options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB';\n  const stride = height * width;\n  const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3);\n\n  // Default pointer assignments\n  let step = 4,\n    rImagePointer = 0,\n    gImagePointer = 1,\n    bImagePointer = 2,\n    aImagePointer = 3;\n  let rTensorPointer = 0,\n    gTensorPointer = stride,\n    bTensorPointer = stride * 2,\n    aTensorPointer = -1;\n\n  // Updating the pointer assignments based on the input image format\n  if (inputformat === 'RGB') {\n    step = 3;\n    rImagePointer = 0;\n    gImagePointer = 1;\n    bImagePointer = 2;\n    aImagePointer = -1;\n  }\n\n  // Updating the pointer assignments based on the output tensor format\n  if (outputformat === 'RGBA') {\n    aTensorPointer = stride * 3;\n  } else if (outputformat === 'RBG') {\n    rTensorPointer = 0;\n    bTensorPointer = stride;\n    gTensorPointer = stride * 2;\n  } else if (outputformat === 'BGR') {\n    bTensorPointer = 0;\n    gTensorPointer = stride;\n    rTensorPointer = stride * 2;\n  }\n\n  for (\n    let i = 0;\n    i < stride;\n    i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step\n  ) {\n    float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];\n    float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];\n    float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];\n    if (aTensorPointer !== -1 && aImagePointer !== -1) {\n      float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];\n    }\n  }\n\n  // Float32Array -> ort.Tensor\n  const outputTensor =\n    outputformat === 'RGBA'\n      ? new Tensor('float32', float32Data, [1, 4, height, width])\n      : new Tensor('float32', float32Data, [1, 3, height, width]);\n  return outputTensor;\n};\n\n/**\n * implementation of Tensor.fromImage().\n */\nexport const tensorFromImage = async (\n  image: ImageData | HTMLImageElement | ImageBitmap | string,\n  options?:\n    | TensorFromImageDataOptions\n    | TensorFromImageElementOptions\n    | TensorFromImageBitmapOptions\n    | TensorFromUrlOptions,\n): Promise<Tensor> => {\n  // checking the type of image object\n  const isHTMLImageEle = typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement;\n  const isImageDataEle = typeof ImageData !== 'undefined' && image instanceof ImageData;\n  const isImageBitmap = typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap;\n  const isString = typeof image === 'string';\n\n  let data: Uint8ClampedArray | undefined;\n  let bufferToTensorOptions: BufferToTensorOptions = options ?? {};\n\n  const createCanvas = () => {\n    if (typeof document !== 'undefined') {\n      return document.createElement('canvas');\n    } else if (typeof OffscreenCanvas !== 'undefined') {\n      return new OffscreenCanvas(1, 1);\n    } else {\n      throw new Error('Canvas is not supported');\n    }\n  };\n  const createCanvasContext = (canvas: HTMLCanvasElement | OffscreenCanvas) => {\n    if (typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement) {\n      return canvas.getContext('2d');\n    } else if (canvas instanceof OffscreenCanvas) {\n      return canvas.getContext('2d') as OffscreenCanvasRenderingContext2D;\n    } else {\n      return null;\n    }\n  };\n  // filling and checking image configuration options\n  if (isHTMLImageEle) {\n    // HTMLImageElement - image object - format is RGBA by default\n    const canvas = createCanvas();\n    canvas.width = image.width;\n    canvas.height = image.height;\n    const pixels2DContext = createCanvasContext(canvas);\n\n    if (pixels2DContext != null) {\n      let height = image.height;\n      let width = image.width;\n      if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {\n        height = options.resizedHeight;\n        width = options.resizedWidth;\n      }\n\n      if (options !== undefined) {\n        bufferToTensorOptions = options;\n        if (options.tensorFormat !== undefined) {\n          throw new Error('Image input config format must be RGBA for HTMLImageElement');\n        } else {\n          bufferToTensorOptions.tensorFormat = 'RGBA';\n        }\n        bufferToTensorOptions.height = height;\n        bufferToTensorOptions.width = width;\n      } else {\n        bufferToTensorOptions.tensorFormat = 'RGBA';\n        bufferToTensorOptions.height = height;\n        bufferToTensorOptions.width = width;\n      }\n\n      pixels2DContext.drawImage(image, 0, 0);\n      data = pixels2DContext.getImageData(0, 0, width, height).data;\n    } else {\n      throw new Error('Can not access image data');\n    }\n  } else if (isImageDataEle) {\n    let height: number;\n    let width: number;\n\n    if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {\n      height = options.resizedHeight;\n      width = options.resizedWidth;\n    } else {\n      height = image.height;\n      width = image.width;\n    }\n\n    if (options !== undefined) {\n      bufferToTensorOptions = options;\n    }\n    bufferToTensorOptions.format = 'RGBA';\n    bufferToTensorOptions.height = height;\n    bufferToTensorOptions.width = width;\n\n    if (options !== undefined) {\n      const tempCanvas = createCanvas();\n\n      tempCanvas.width = width;\n      tempCanvas.height = height;\n\n      const pixels2DContext = createCanvasContext(tempCanvas);\n\n      if (pixels2DContext != null) {\n        pixels2DContext.putImageData(image, 0, 0);\n        data = pixels2DContext.getImageData(0, 0, width, height).data;\n      } else {\n        throw new Error('Can not access image data');\n      }\n    } else {\n      data = image.data;\n    }\n  } else if (isImageBitmap) {\n    // ImageBitmap - image object - format must be provided by user\n    if (options === undefined) {\n      throw new Error('Please provide image config with format for Imagebitmap');\n    }\n\n    const canvas = createCanvas();\n    canvas.width = image.width;\n    canvas.height = image.height;\n    const pixels2DContext = createCanvasContext(canvas);\n\n    if (pixels2DContext != null) {\n      const height = image.height;\n      const width = image.width;\n      pixels2DContext.drawImage(image, 0, 0, width, height);\n      data = pixels2DContext.getImageData(0, 0, width, height).data;\n      bufferToTensorOptions.height = height;\n      bufferToTensorOptions.width = width;\n      return bufferToTensor(data, bufferToTensorOptions);\n    } else {\n      throw new Error('Can not access image data');\n    }\n  } else if (isString) {\n    return new Promise((resolve, reject) => {\n      const canvas = createCanvas();\n      const context = createCanvasContext(canvas);\n      if (!image || !context) {\n        return reject();\n      }\n      const newImage = new Image();\n      newImage.crossOrigin = 'Anonymous';\n      newImage.src = image;\n      newImage.onload = () => {\n        canvas.width = newImage.width;\n        canvas.height = newImage.height;\n        context.drawImage(newImage, 0, 0, canvas.width, canvas.height);\n        const img = context.getImageData(0, 0, canvas.width, canvas.height);\n\n        bufferToTensorOptions.height = canvas.height;\n        bufferToTensorOptions.width = canvas.width;\n        resolve(bufferToTensor(img.data, bufferToTensorOptions));\n      };\n    });\n  } else {\n    throw new Error('Input data provided is not supported - aborted tensor creation');\n  }\n\n  if (data !== undefined) {\n    return bufferToTensor(data, bufferToTensorOptions);\n  } else {\n    throw new Error('Input data provided is not supported - aborted tensor creation');\n  }\n};\n\n/**\n * implementation of Tensor.fromTexture().\n */\nexport const tensorFromTexture = <T extends TensorInterface.TextureDataTypes>(\n  texture: TensorInterface.TextureType,\n  options: TensorFromTextureOptions<T>,\n): Tensor => {\n  const { width, height, download, dispose } = options;\n  // Always assume RGBAF32. TODO: support different texture format\n  const dims = [1, height, width, 4];\n  return new Tensor({ location: 'texture', type: 'float32', texture, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromGpuBuffer().\n */\nexport const tensorFromGpuBuffer = <T extends TensorInterface.GpuBufferDataTypes>(\n  gpuBuffer: TensorInterface.GpuBufferType,\n  options: TensorFromGpuBufferOptions<T>,\n): Tensor => {\n  const { dataType, dims, download, dispose } = options;\n  return new Tensor({ location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromMLTensor().\n */\nexport const tensorFromMLTensor = <T extends TensorInterface.MLTensorDataTypes>(\n  mlTensor: TensorInterface.MLTensorType,\n  options: TensorFromMLTensorOptions<T>,\n): Tensor => {\n  const { dataType, dims, download, dispose } = options;\n  return new Tensor({ location: 'ml-tensor', type: dataType ?? 'float32', mlTensor, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromPinnedBuffer().\n */\nexport const tensorFromPinnedBuffer = <T extends TensorInterface.CpuPinnedDataTypes>(\n  type: T,\n  buffer: TensorInterface.DataTypeMap[T],\n  dims?: readonly number[],\n): Tensor => new Tensor({ location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length] });\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Tensor } from './tensor.js';\n\nexport type SupportedTypedArrayConstructors =\n  | Float32ArrayConstructor\n  | Uint8ArrayConstructor\n  | Int8ArrayConstructor\n  | Uint16ArrayConstructor\n  | Int16ArrayConstructor\n  | Int32ArrayConstructor\n  | BigInt64ArrayConstructor\n  | Uint8ArrayConstructor\n  | Float64ArrayConstructor\n  | Uint32ArrayConstructor\n  | BigUint64ArrayConstructor;\nexport type SupportedTypedArray = InstanceType<SupportedTypedArrayConstructors>;\n\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map<string, SupportedTypedArrayConstructors>([\n  ['float32', Float32Array],\n  ['uint8', Uint8Array],\n  ['int8', Int8Array],\n  ['uint16', Uint16Array],\n  ['int16', Int16Array],\n  ['int32', Int32Array],\n  ['bool', Uint8Array],\n  ['float64', Float64Array],\n  ['uint32', Uint32Array],\n  ['int4', Uint8Array],\n  ['uint4', Uint8Array],\n]);\n\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map<SupportedTypedArrayConstructors, Tensor.Type>([\n  [Float32Array, 'float32'],\n  [Uint8Array, 'uint8'],\n  [Int8Array, 'int8'],\n  [Uint16Array, 'uint16'],\n  [Int16Array, 'int16'],\n  [Int32Array, 'int32'],\n  [Float64Array, 'float64'],\n  [Uint32Array, 'uint32'],\n]);\n\n// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for\n// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array\n// polyfill if available.\nlet isTypedArrayChecked = false;\nexport const checkTypedArray = () => {\n  if (!isTypedArrayChecked) {\n    isTypedArrayChecked = true;\n    const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from;\n    const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from;\n\n    // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any\n    const Float16Array = (globalThis as any).Float16Array;\n    const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from;\n\n    if (isBigInt64ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');\n    }\n    if (isBigUint64ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');\n    }\n    if (isFloat16ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16');\n    } else {\n      // if Float16Array is not available, use 'Uint16Array' to store the data.\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array);\n    }\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  CpuPinnedConstructorParameters,\n  GpuBufferConstructorParameters,\n  MLTensorConstructorParameters,\n  TextureConstructorParameters,\n} from './tensor-factory.js';\nimport { Tensor } from './tensor-impl.js';\n\n/**\n * calculate size from dims.\n *\n * @param dims the dims array. May be an illegal input.\n */\nexport const calculateSize = (dims: readonly unknown[]): number => {\n  let size = 1;\n  for (let i = 0; i < dims.length; i++) {\n    const dim = dims[i];\n    if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {\n      throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);\n    }\n    if (dim < 0) {\n      throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);\n    }\n    size *= dim;\n  }\n  return size;\n};\n\n/**\n * implementation of Tensor.reshape()\n */\nexport const tensorReshape = (tensor: Tensor, dims: readonly number[]): Tensor => {\n  switch (tensor.location) {\n    case 'cpu':\n      return new Tensor(tensor.type, tensor.data, dims);\n    case 'cpu-pinned':\n      return new Tensor({\n        location: 'cpu-pinned',\n        data: tensor.data as CpuPinnedConstructorParameters['data'],\n        type: tensor.type as CpuPinnedConstructorParameters['type'],\n        dims,\n      });\n    case 'texture':\n      return new Tensor({\n        location: 'texture',\n        texture: tensor.texture,\n        type: tensor.type as TextureConstructorParameters['type'],\n        dims,\n      });\n    case 'gpu-buffer':\n      return new Tensor({\n        location: 'gpu-buffer',\n        gpuBuffer: tensor.gpuBuffer,\n        type: tensor.type as GpuBufferConstructorParameters['type'],\n        dims,\n      });\n    case 'ml-tensor':\n      return new Tensor({\n        location: 'ml-tensor',\n        mlTensor: tensor.mlTensor,\n        type: tensor.type as MLTensorConstructorParameters['type'],\n        dims,\n      });\n    default:\n      throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { tensorToDataURL, tensorToImageData } from './tensor-conversion-impl.js';\nimport { TensorToDataUrlOptions, TensorToImageDataOptions } from './tensor-conversion.js';\nimport {\n  tensorFromGpuBuffer,\n  tensorFromImage,\n  tensorFromMLTensor,\n  tensorFromPinnedBuffer,\n  tensorFromTexture,\n} from './tensor-factory-impl.js';\nimport {\n  CpuPinnedConstructorParameters,\n  GpuBufferConstructorParameters,\n  MLTensorConstructorParameters,\n  TensorFromGpuBufferOptions,\n  TensorFromImageBitmapOptions,\n  TensorFromImageDataOptions,\n  TensorFromImageElementOptions,\n  TensorFromMLTensorOptions,\n  TensorFromTextureOptions,\n  TensorFromUrlOptions,\n  TextureConstructorParameters,\n} from './tensor-factory.js';\nimport {\n  checkTypedArray,\n  NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP,\n  NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP,\n  SupportedTypedArray,\n  SupportedTypedArrayConstructors,\n} from './tensor-impl-type-mapping.js';\nimport { calculateSize, tensorReshape } from './tensor-utils-impl.js';\nimport { Tensor as TensorInterface } from './tensor.js';\n\n// type aliases for those exported from Tensor interface\n\ntype TensorType = TensorInterface.Type;\ntype TensorDataType = TensorInterface.DataType;\ntype TensorDataLocation = TensorInterface.DataLocation;\ntype TensorTextureType = TensorInterface.TextureType;\ntype TensorGpuBufferType = TensorInterface.GpuBufferType;\ntype TensorMLTensorType = TensorInterface.MLTensorType;\n\n/**\n * the implementation of Tensor interface.\n *\n * @ignore\n */\nexport class Tensor implements TensorInterface {\n  // #region constructors\n\n  /**\n   * Construct a new CPU tensor object from the given type, data and dims.\n   */\n  constructor(\n    type: TensorType,\n    data: TensorDataType | Uint8ClampedArray | readonly string[] | readonly number[] | readonly boolean[],\n    dims?: readonly number[],\n  );\n  /**\n   * Construct a new CPU tensor object from the given data and dims. Type is inferred from data.\n   */\n  constructor(\n    data: TensorDataType | Uint8ClampedArray | readonly string[] | readonly boolean[],\n    dims?: readonly number[],\n  );\n  /**\n   * Construct a new tensor object from the pinned CPU data with the given type and dims.\n   *\n   * Tensor's location will be set to 'cpu-pinned'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: CpuPinnedConstructorParameters);\n  /**\n   * Construct a new tensor object from the WebGL texture with the given type and dims.\n   *\n   * Tensor's location will be set to 'texture'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: TextureConstructorParameters);\n  /**\n   * Construct a new tensor object from the WebGPU buffer with the given type and dims.\n   *\n   * Tensor's location will be set to 'gpu-buffer'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: GpuBufferConstructorParameters);\n\n  /**\n   * Construct a new tensor object from the WebNN MLTensor with the given type and dims.\n   *\n   * Tensor's location will be set to 'ml-tensor'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: MLTensorConstructorParameters);\n\n  /**\n   * implementation.\n   */\n  constructor(\n    arg0:\n      | TensorType\n      | TensorDataType\n      | Uint8ClampedArray\n      | readonly string[]\n      | readonly boolean[]\n      | CpuPinnedConstructorParameters\n      | TextureConstructorParameters\n      | GpuBufferConstructorParameters\n      | MLTensorConstructorParameters,\n    arg1?: TensorDataType | Uint8ClampedArray | readonly number[] | readonly string[] | readonly boolean[],\n    arg2?: readonly number[],\n  ) {\n    // perform one-time check for BigInt/Float16Array support\n    checkTypedArray();\n\n    let type: TensorType;\n    let dims: readonly number[];\n\n    if (typeof arg0 === 'object' && 'location' in arg0) {\n      //\n      // constructing tensor from specific location\n      //\n      this.dataLocation = arg0.location;\n      type = arg0.type;\n      dims = arg0.dims;\n      switch (arg0.location) {\n        case 'cpu-pinned': {\n          const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);\n          if (!expectedTypedArrayConstructor) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from pinned buffer`);\n          }\n          if (!(arg0.data instanceof expectedTypedArrayConstructor)) {\n            throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);\n          }\n          this.cpuData = arg0.data;\n          break;\n        }\n        case 'texture': {\n          if (type !== 'float32') {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from texture`);\n          }\n          this.gpuTextureData = arg0.texture;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        case 'gpu-buffer': {\n          if (\n            type !== 'float32' &&\n            type !== 'float16' &&\n            type !== 'int32' &&\n            type !== 'int64' &&\n            type !== 'uint32' &&\n            type !== 'uint8' &&\n            type !== 'bool' &&\n            type !== 'uint4' &&\n            type !== 'int4'\n          ) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from gpu buffer`);\n          }\n          this.gpuBufferData = arg0.gpuBuffer;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        case 'ml-tensor': {\n          if (\n            type !== 'float32' &&\n            type !== 'float16' &&\n            type !== 'int32' &&\n            type !== 'int64' &&\n            type !== 'uint32' &&\n            type !== 'uint64' &&\n            type !== 'int8' &&\n            type !== 'uint8' &&\n            type !== 'bool' &&\n            type !== 'uint4' &&\n            type !== 'int4'\n          ) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from MLTensor`);\n          }\n          this.mlTensorData = arg0.mlTensor;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        default:\n          throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);\n      }\n    } else {\n      //\n      // constructing tensor of location 'cpu'\n      //\n      let data: TensorDataType;\n      let maybeDims: typeof arg1 | typeof arg2;\n      // check whether arg0 is type or data\n      if (typeof arg0 === 'string') {\n        //\n        // Override: constructor(type, data, ...)\n        //\n        type = arg0;\n        maybeDims = arg2;\n        if (arg0 === 'string') {\n          // string tensor\n          if (!Array.isArray(arg1)) {\n            throw new TypeError(\"A string tensor's data must be a string array.\");\n          }\n          // we don't check whether every element in the array is string; this is too slow. we assume it's correct and\n          // error will be populated at inference\n          data = arg1;\n        } else {\n          // numeric tensor\n          const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);\n          if (typedArrayConstructor === undefined) {\n            throw new TypeError(`Unsupported tensor type: ${arg0}.`);\n          }\n          if (Array.isArray(arg1)) {\n            if ((arg0 === 'float16' && typedArrayConstructor === Uint16Array) || arg0 === 'uint4' || arg0 === 'int4') {\n              // - 'float16':\n              //   When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array.\n              //\n              //   Throw error here because when user try to use number array as data,\n              //   e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call\n              //   Uint16Array.from(arg1) which generates wrong data.\n              //\n              // - 'uint4' and 'int4':\n              //   Uint8Array.from(arg1) will generate wrong data for 'uint4' and 'int4' tensor.\n              //\n              throw new TypeError(\n                `Creating a ${arg0} tensor from number array is not supported. Please use ${typedArrayConstructor.name} as data.`,\n              );\n            } else if (arg0 === 'uint64' || arg0 === 'int64') {\n              // use 'as any' here because:\n              // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays.\n              // see https://github.com/microsoft/TypeScript/issues/17002\n              // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()'\n              // does not accept parameter mapFn.\n              // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union\n              // type.\n\n              // assume 'arg1' is of type \"readonly number[]|readonly bigint[]\" here.\n\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              data = (typedArrayConstructor as any).from(arg1, BigInt);\n            } else {\n              // assume 'arg1' is of type \"readonly number[]\" here.\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              data = (typedArrayConstructor as any).from(arg1);\n            }\n          } else if (arg1 instanceof typedArrayConstructor) {\n            data = arg1;\n          } else if (arg1 instanceof Uint8ClampedArray) {\n            if (arg0 === 'uint8') {\n              data = Uint8Array.from(arg1);\n            } else {\n              throw new TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);\n            }\n          } else if (arg0 === 'float16' && arg1 instanceof Uint16Array && typedArrayConstructor !== Uint16Array) {\n            // when Float16Array is available and data is of type Uint16Array.\n            // We allow Uint16Array to be passed in as data for 'float16' tensor until Float16Array is generally\n            // supported in JavaScript environment.\n\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            data = new (globalThis as any).Float16Array(arg1.buffer, arg1.byteOffset, arg1.length);\n          } else {\n            throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);\n          }\n        }\n      } else {\n        //\n        // Override: constructor(data, ...)\n        //\n        maybeDims = arg1;\n        if (Array.isArray(arg0)) {\n          // only boolean[] and string[] is supported\n          if (arg0.length === 0) {\n            throw new TypeError('Tensor type cannot be inferred from an empty array.');\n          }\n          const firstElementType = typeof arg0[0];\n          if (firstElementType === 'string') {\n            type = 'string';\n            data = arg0;\n          } else if (firstElementType === 'boolean') {\n            type = 'bool';\n            // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is\n            // wrong type. We use 'as any' to make it happy.\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            data = Uint8Array.from(arg0 as any[]);\n          } else {\n            throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);\n          }\n        } else if (arg0 instanceof Uint8ClampedArray) {\n          type = 'uint8';\n          data = Uint8Array.from(arg0);\n        } else {\n          // get tensor type from TypedArray\n          const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(\n            arg0.constructor as SupportedTypedArrayConstructors,\n          );\n          if (mappedType === undefined) {\n            throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);\n          }\n          type = mappedType;\n          data = arg0 as SupportedTypedArray;\n        }\n      }\n\n      // type and data is processed, now processing dims\n      if (maybeDims === undefined) {\n        // assume 1-D tensor if dims omitted\n        maybeDims = [data.length];\n      } else if (!Array.isArray(maybeDims)) {\n        throw new TypeError(\"A tensor's dims must be a number array\");\n      }\n      dims = maybeDims as readonly number[];\n\n      this.cpuData = data;\n      this.dataLocation = 'cpu';\n    }\n\n    // perform check on dims\n    const size = calculateSize(dims);\n    // if data is on CPU, check whether data length matches tensor size\n    if (this.cpuData && size !== this.cpuData.length) {\n      if ((type === 'uint4' || type === 'int4') && Math.ceil(size / 2) === this.cpuData.length) {\n        // for (u)int4, the data length is half of the tensor size. So we check this special case when size is odd.\n      } else {\n        throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);\n      }\n    }\n\n    this.type = type;\n    this.dims = dims;\n    this.size = size;\n  }\n  // #endregion\n\n  // #region factory\n  static async fromImage(\n    image: ImageData | HTMLImageElement | ImageBitmap | string,\n    options?:\n      | TensorFromImageDataOptions\n      | TensorFromImageElementOptions\n      | TensorFromImageBitmapOptions\n      | TensorFromUrlOptions,\n  ): Promise<TensorInterface> {\n    return tensorFromImage(image, options);\n  }\n\n  static fromTexture<T extends TensorInterface.TextureDataTypes>(\n    texture: TensorTextureType,\n    options: TensorFromTextureOptions<T>,\n  ): TensorInterface {\n    return tensorFromTexture(texture, options);\n  }\n\n  static fromGpuBuffer<T extends TensorInterface.GpuBufferDataTypes>(\n    gpuBuffer: TensorGpuBufferType,\n    options: TensorFromGpuBufferOptions<T>,\n  ): TensorInterface {\n    return tensorFromGpuBuffer(gpuBuffer, options);\n  }\n\n  static fromMLTensor<T extends TensorInterface.MLTensorDataTypes>(\n    mlTensor: TensorMLTensorType,\n    options: TensorFromMLTensorOptions<T>,\n  ): TensorInterface {\n    return tensorFromMLTensor(mlTensor, options);\n  }\n\n  static fromPinnedBuffer<T extends TensorInterface.CpuPinnedDataTypes>(\n    type: T,\n    buffer: TensorInterface.DataTypeMap[T],\n    dims?: readonly number[],\n  ): Tensor {\n    return tensorFromPinnedBuffer(type, buffer, dims);\n  }\n\n  // #endregion\n\n  // #region conversions\n  toDataURL(options?: TensorToDataUrlOptions): string {\n    return tensorToDataURL(this, options);\n  }\n\n  toImageData(options?: TensorToImageDataOptions): ImageData {\n    return tensorToImageData(this, options);\n  }\n  // #endregion\n\n  // #region public fields\n  readonly dims: readonly number[];\n  readonly type: TensorType;\n  readonly size: number;\n  // #endregion\n\n  // #region private fields\n\n  /**\n   * stores the location of the data.\n   */\n  private dataLocation: TensorDataLocation;\n\n  /**\n   * stores the data on CPU, if location is 'cpu' or 'cpu-pinned'. otherwise empty.\n   */\n  private cpuData?: TensorDataType;\n\n  /**\n   * stores the underlying texture when location is 'texture'. otherwise empty.\n   */\n  private gpuTextureData?: TensorTextureType;\n\n  /**\n   * stores the underlying GPU buffer when location is 'gpu-buffer'. otherwise empty.\n   */\n  private gpuBufferData?: TensorGpuBufferType;\n\n  /**\n   * stores the underlying WebNN MLTensor when location is 'ml-tensor'. otherwise empty.\n   */\n  private mlTensorData?: TensorMLTensorType;\n\n  /**\n   * stores an optional downloader function to download data from GPU to CPU.\n   */\n  private downloader?(): Promise<TensorDataType>;\n\n  /**\n   * a flag indicating whether the data is being downloaded from GPU to CPU.\n   */\n  private isDownloading?: boolean;\n\n  /**\n   * stores an optional disposer function to dispose the underlying data.\n   */\n  private disposer?(): void;\n  // #endregion\n\n  // #region properties\n  get data(): TensorDataType {\n    this.ensureValid();\n    if (!this.cpuData) {\n      throw new Error(\n        'The data is not on CPU. Use `getData()` to download GPU data to CPU, ' +\n          'or use `texture` or `gpuBuffer` property to access the GPU data directly.',\n      );\n    }\n    return this.cpuData;\n  }\n\n  get location(): TensorDataLocation {\n    return this.dataLocation;\n  }\n\n  get texture(): TensorTextureType {\n    this.ensureValid();\n    if (!this.gpuTextureData) {\n      throw new Error('The data is not stored as a WebGL texture.');\n    }\n    return this.gpuTextureData;\n  }\n\n  get gpuBuffer(): TensorGpuBufferType {\n    this.ensureValid();\n    if (!this.gpuBufferData) {\n      throw new Error('The data is not stored as a WebGPU buffer.');\n    }\n    return this.gpuBufferData;\n  }\n\n  get mlTensor(): TensorMLTensorType {\n    this.ensureValid();\n    if (!this.mlTensorData) {\n      throw new Error('The data is not stored as a WebNN MLTensor.');\n    }\n    return this.mlTensorData;\n  }\n  // #endregion\n\n  // #region methods\n\n  async getData(releaseData?: boolean): Promise<TensorDataType> {\n    this.ensureValid();\n    switch (this.dataLocation) {\n      case 'cpu':\n      case 'cpu-pinned':\n        return this.data;\n      case 'texture':\n      case 'gpu-buffer':\n      case 'ml-tensor': {\n        if (!this.downloader) {\n          throw new Error('The current tensor is not created with a specified data downloader.');\n        }\n        if (this.isDownloading) {\n          throw new Error('The current tensor is being downloaded.');\n        }\n        try {\n          this.isDownloading = true;\n          const data = await this.downloader();\n          this.downloader = undefined;\n          this.dataLocation = 'cpu';\n          this.cpuData = data;\n\n          if (releaseData && this.disposer) {\n            this.disposer();\n            this.disposer = undefined;\n          }\n\n          return data;\n        } finally {\n          this.isDownloading = false;\n        }\n      }\n      default:\n        throw new Error(`cannot get data from location: ${this.dataLocation}`);\n    }\n  }\n\n  dispose(): void {\n    if (this.isDownloading) {\n      throw new Error('The current tensor is being downloaded.');\n    }\n\n    if (this.disposer) {\n      this.disposer();\n      this.disposer = undefined;\n    }\n    this.cpuData = undefined;\n    this.gpuTextureData = undefined;\n    this.gpuBufferData = undefined;\n    this.mlTensorData = undefined;\n    this.downloader = undefined;\n    this.isDownloading = undefined;\n\n    this.dataLocation = 'none';\n  }\n\n  // #endregion\n\n  // #region tensor utilities\n  private ensureValid(): void {\n    if (this.dataLocation === 'none') {\n      throw new Error('The tensor is disposed.');\n    }\n  }\n\n  reshape(dims: readonly number[]): TensorInterface {\n    this.ensureValid();\n    if (this.downloader || this.disposer) {\n      throw new Error('Cannot reshape a tensor that owns GPU resource.');\n    }\n    return tensorReshape(this, dims);\n  }\n  // #endregion\n}\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { TensorFactory } from './tensor-factory.js';\nimport { Tensor as TensorImpl } from './tensor-impl.js';\nimport { TypedTensorUtils } from './tensor-utils.js';\nimport { TryGetGlobalType } from './type-helper.js';\n\n/* eslint-disable @typescript-eslint/no-redeclare */\n\n/**\n * represent a basic tensor with specified dimensions and data type.\n */\ninterface TypedTensorBase<T extends Tensor.Type> {\n  /**\n   * Get the dimensions of the tensor.\n   */\n  readonly dims: readonly number[];\n  /**\n   * Get the data type of the tensor.\n   */\n  readonly type: T;\n  /**\n   * Get the buffer data of the tensor.\n   *\n   * If the data is not on CPU (eg. it's in the form of WebGL texture or WebGPU buffer), throw error.\n   */\n  readonly data: Tensor.DataTypeMap[T];\n  /**\n   * Get the location of the data.\n   */\n  readonly location: Tensor.DataLocation;\n  /**\n   * Get the WebGL texture that holds the tensor data.\n   *\n   * If the data is not on GPU as WebGL texture, throw error.\n   */\n  readonly texture: Tensor.TextureType;\n  /**\n   * Get the WebGPU buffer that holds the tensor data.\n   *\n   * If the data is not on GPU as WebGPU buffer, throw error.\n   */\n  readonly gpuBuffer: Tensor.GpuBufferType;\n\n  /**\n   * Get the WebNN MLTensor that holds the tensor data.\n   *\n   * If the data is not in a WebNN MLTensor, throw error.\n   */\n  readonly mlTensor: Tensor.MLTensorType;\n\n  /**\n   * Get the buffer data of the tensor.\n   *\n   * If the data is on CPU, returns the data immediately.\n   * If the data is on GPU, downloads the data and returns the promise.\n   *\n   * @param releaseData - whether release the data on GPU. Ignore if data is already on CPU.\n   */\n  getData(releaseData?: boolean): Promise<Tensor.DataTypeMap[T]>;\n\n  /**\n   * Dispose the tensor data.\n   *\n   * If the data is on CPU, remove its internal reference to the underlying data.\n   * If the data is on GPU, release the data on GPU.\n   *\n   * After calling this function, the tensor is considered no longer valid. Its location will be set to 'none'.\n   */\n  dispose(): void;\n}\n\nexport declare namespace Tensor {\n  interface DataTypeMap {\n    float32: Float32Array;\n    uint8: Uint8Array;\n    int8: Int8Array;\n    uint16: Uint16Array;\n    int16: Int16Array;\n    int32: Int32Array;\n    int64: BigInt64Array;\n    string: string[];\n    bool: Uint8Array;\n    float16: Uint16Array; // Keep using Uint16Array until we have a concrete solution for float 16.\n    float64: Float64Array;\n    uint32: Uint32Array;\n    uint64: BigUint64Array;\n    // complex64: never;\n    // complex128: never;\n    // bfloat16: never;\n    uint4: Uint8Array;\n    int4: Int8Array;\n  }\n\n  interface ElementTypeMap {\n    float32: number;\n    uint8: number;\n    int8: number;\n    uint16: number;\n    int16: number;\n    int32: number;\n    int64: bigint;\n    string: string;\n    bool: boolean;\n    float16: number; // Keep using Uint16Array until we have a concrete solution for float 16.\n    float64: number;\n    uint32: number;\n    uint64: bigint;\n    // complex64: never;\n    // complex128: never;\n    // bfloat16: never;\n    uint4: number;\n    int4: number;\n  }\n\n  type DataType = DataTypeMap[Type];\n  type ElementType = ElementTypeMap[Type];\n\n  /**\n   * supported data types for constructing a tensor from a pinned CPU buffer\n   */\n  export type CpuPinnedDataTypes = Exclude<Tensor.Type, 'string'>;\n\n  /**\n   * type alias for WebGL texture\n   */\n  export type TextureType = WebGLTexture;\n\n  /**\n   * supported data types for constructing a tensor from a WebGL texture\n   */\n  export type TextureDataTypes = 'float32';\n\n  type GpuBufferTypeFallback = { size: number; mapState: 'unmapped' | 'pending' | 'mapped' };\n  /**\n   * type alias for WebGPU buffer\n   */\n  export type GpuBufferType = TryGetGlobalType<'GPUBuffer', GpuBufferTypeFallback>;\n\n  type MLTensorTypeFallback = { destroy(): void };\n  /**\n   * type alias for WebNN MLTensor\n   *\n   * The specification for WebNN's MLTensor is currently in flux.\n   */\n  export type MLTensorType = TryGetGlobalType<'MLTensor', MLTensorTypeFallback>;\n\n  /**\n   * supported data types for constructing a tensor from a WebGPU buffer\n   */\n  export type GpuBufferDataTypes = 'float32' | 'float16' | 'int32' | 'int64' | 'uint32' | 'uint8' | 'bool';\n\n  /**\n   * supported data types for constructing a tensor from a WebNN MLTensor\n   */\n  export type MLTensorDataTypes =\n    | 'float32'\n    | 'float16'\n    | 'int8'\n    | 'uint8'\n    | 'int32'\n    | 'uint32'\n    | 'int64'\n    | 'uint64'\n    | 'bool'\n    | 'uint4'\n    | 'int4';\n\n  /**\n   * represent where the tensor data is stored\n   */\n  export type DataLocation = 'none' | 'cpu' | 'cpu-pinned' | 'texture' | 'gpu-buffer' | 'ml-tensor';\n\n  /**\n   * represent the data type of a tensor\n   */\n  export type Type = keyof DataTypeMap;\n}\n\n/**\n * Represent multi-dimensional arrays to feed to or fetch from model inferencing.\n */\nexport interface TypedTensor<T extends Tensor.Type> extends TypedTensorBase<T>, TypedTensorUtils<T> {}\n/**\n * Represent multi-dimensional arrays to feed to or fetch from model inferencing.\n */\nexport interface Tensor extends TypedTensorBase<Tensor.Type>, TypedTensorUtils<Tensor.Type> {}\n\n/**\n * type TensorConstructor defines the constructors of 'Tensor' to create CPU tensor instances.\n */\nexport interface TensorConstructor extends TensorFactory {\n  // #region CPU tensor - specify element type\n  /**\n   * Construct a new string tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: 'string',\n    data: Tensor.DataTypeMap['string'] | readonly string[],\n    dims?: readonly number[],\n  ): TypedTensor<'string'>;\n\n  /**\n   * Construct a new bool tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: 'bool',\n    data: Tensor.DataTypeMap['bool'] | readonly boolean[],\n    dims?: readonly number[],\n  ): TypedTensor<'bool'>;\n\n  /**\n   * Construct a new uint8 tensor object from a Uint8ClampedArray, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (type: 'uint8', data: Uint8ClampedArray, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new 64-bit integer typed tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new <T extends 'uint64' | 'int64'>(\n    type: T,\n    data: Tensor.DataTypeMap[T] | readonly bigint[] | readonly number[],\n    dims?: readonly number[],\n  ): TypedTensor<T>;\n\n  /**\n   * Construct a new numeric tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new <T extends Exclude<Tensor.Type, 'string' | 'bool' | 'uint64' | 'int64'>>(\n    type: T,\n    data: Tensor.DataTypeMap[T] | readonly number[],\n    dims?: readonly number[],\n  ): TypedTensor<T>;\n  // #endregion\n\n  // #region CPU tensor - infer element types\n\n  /**\n   * Construct a new float32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Float32Array, dims?: readonly number[]): TypedTensor<'float32'>;\n\n  /**\n   * Construct a new int8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int8Array, dims?: readonly number[]): TypedTensor<'int8'>;\n\n  /**\n   * Construct a new uint8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint8Array, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new uint8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint8ClampedArray, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new uint16 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint16Array, dims?: readonly number[]): TypedTensor<'uint16'>;\n\n  /**\n   * Construct a new int16 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int16Array, dims?: readonly number[]): TypedTensor<'int16'>;\n\n  /**\n   * Construct a new int32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int32Array, dims?: readonly number[]): TypedTensor<'int32'>;\n\n  /**\n   * Construct a new int64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: BigInt64Array, dims?: readonly number[]): TypedTensor<'int64'>;\n\n  /**\n   * Construct a new string tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: readonly string[], dims?: readonly number[]): TypedTensor<'string'>;\n\n  /**\n   * Construct a new bool tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: readonly boolean[], dims?: readonly number[]): TypedTensor<'bool'>;\n\n  /**\n   * Construct a new float64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Float64Array, dims?: readonly number[]): TypedTensor<'float64'>;\n\n  /**\n   * Construct a new uint32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint32Array, dims?: readonly number[]): TypedTensor<'uint32'>;\n\n  /**\n   * Construct a new uint64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: BigUint64Array, dims?: readonly number[]): TypedTensor<'uint64'>;\n\n  // #endregion\n\n  // #region CPU tensor - fall back to non-generic tensor type declaration\n\n  /**\n   * Construct a new tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: Tensor.Type,\n    data: Tensor.DataType | readonly number[] | readonly string[] | readonly bigint[] | readonly boolean[],\n    dims?: readonly number[],\n  ): Tensor;\n\n  /**\n   * Construct a new tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Tensor.DataType, dims?: readonly number[]): Tensor;\n  // #endregion\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const Tensor = TensorImpl as TensorConstructor;\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { env } from './env-impl.js';\n\n/**\n * @ignore\n */\nexport const TRACE = (deviceType: string, label: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  // eslint-disable-next-line no-console\n  console.timeStamp(`${deviceType}::ORT::${label}`);\n};\n\nconst TRACE_FUNC = (msg: string, extraMsg?: string) => {\n  const stack = new Error().stack?.split(/\\r\\n|\\r|\\n/g) || [];\n  let hasTraceFunc = false;\n  for (let i = 0; i < stack.length; i++) {\n    if (hasTraceFunc && !stack[i].includes('TRACE_FUNC')) {\n      let label = `FUNC_${msg}::${stack[i].trim().split(' ')[1]}`;\n      if (extraMsg) {\n        label += `::${extraMsg}`;\n      }\n      TRACE('CPU', label);\n      return;\n    }\n    if (stack[i].includes('TRACE_FUNC')) {\n      hasTraceFunc = true;\n    }\n  }\n};\n\n/**\n * @ignore\n */\nexport const TRACE_FUNC_BEGIN = (extraMsg?: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  TRACE_FUNC('BEGIN', extraMsg);\n};\n\n/**\n * @ignore\n */\nexport const TRACE_FUNC_END = (extraMsg?: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  TRACE_FUNC('END', extraMsg);\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { InferenceSessionHandler } from './backend.js';\nimport { InferenceSession as InferenceSessionInterface } from './inference-session.js';\nimport { OnnxValue } from './onnx-value.js';\nimport { Tensor } from './tensor.js';\nimport { TRACE_FUNC_BEGIN, TRACE_FUNC_END } from './trace.js';\n\ntype SessionOptions = InferenceSessionInterface.SessionOptions;\ntype RunOptions = InferenceSessionInterface.RunOptions;\ntype FeedsType = InferenceSessionInterface.FeedsType;\ntype FetchesType = InferenceSessionInterface.FetchesType;\ntype ReturnType = InferenceSessionInterface.ReturnType;\n\nexport class InferenceSession implements InferenceSessionInterface {\n  private constructor(handler: InferenceSessionHandler) {\n    this.handler = handler;\n  }\n  run(feeds: FeedsType, options?: RunOptions): Promise<ReturnType>;\n  run(feeds: FeedsType, fetches: FetchesType, options?: RunOptions): Promise<ReturnType>;\n  async run(feeds: FeedsType, arg1?: FetchesType | RunOptions, arg2?: RunOptions): Promise<ReturnType> {\n    TRACE_FUNC_BEGIN();\n    const fetches: { [name: string]: OnnxValue | null } = {};\n    let options: RunOptions = {};\n    // check inputs\n    if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n      throw new TypeError(\n        \"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\",\n      );\n    }\n\n    let isFetchesEmpty = true;\n    // determine which override is being used\n    if (typeof arg1 === 'object') {\n      if (arg1 === null) {\n        throw new TypeError('Unexpected argument[1]: cannot be null.');\n      }\n      if (arg1 instanceof Tensor) {\n        throw new TypeError(\"'fetches' cannot be a Tensor\");\n      }\n\n      if (Array.isArray(arg1)) {\n        if (arg1.length === 0) {\n          throw new TypeError(\"'fetches' cannot be an empty array.\");\n        }\n        isFetchesEmpty = false;\n        // output names\n        for (const name of arg1) {\n          if (typeof name !== 'string') {\n            throw new TypeError(\"'fetches' must be a string array or an object.\");\n          }\n          if (this.outputNames.indexOf(name) === -1) {\n            throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n          }\n          fetches[name] = null;\n        }\n\n        if (typeof arg2 === 'object' && arg2 !== null) {\n          options = arg2;\n        } else if (typeof arg2 !== 'undefined') {\n          throw new TypeError(\"'options' must be an object.\");\n        }\n      } else {\n        // decide whether arg1 is fetches or options\n        // if any output name is present and its value is valid OnnxValue, we consider it fetches\n        let isFetches = false;\n        const arg1Keys = Object.getOwnPropertyNames(arg1);\n        for (const name of this.outputNames) {\n          if (arg1Keys.indexOf(name) !== -1) {\n            const v = (arg1 as InferenceSessionInterface.NullableOnnxValueMapType)[name];\n            if (v === null || v instanceof Tensor) {\n              isFetches = true;\n              isFetchesEmpty = false;\n              fetches[name] = v;\n            }\n          }\n        }\n\n        if (isFetches) {\n          if (typeof arg2 === 'object' && arg2 !== null) {\n            options = arg2;\n          } else if (typeof arg2 !== 'undefined') {\n            throw new TypeError(\"'options' must be an object.\");\n          }\n        } else {\n          options = arg1 as RunOptions;\n        }\n      }\n    } else if (typeof arg1 !== 'undefined') {\n      throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");\n    }\n\n    // check if all inputs are in feed\n    for (const name of this.inputNames) {\n      if (typeof feeds[name] === 'undefined') {\n        throw new Error(`input '${name}' is missing in 'feeds'.`);\n      }\n    }\n\n    // if no fetches is specified, we use the full output names list\n    if (isFetchesEmpty) {\n      for (const name of this.outputNames) {\n        fetches[name] = null;\n      }\n    }\n\n    // feeds, fetches and options are prepared\n\n    const results = await this.handler.run(feeds, fetches, options);\n    const returnValue: { [name: string]: OnnxValue } = {};\n    for (const key in results) {\n      if (Object.hasOwnProperty.call(results, key)) {\n        const result = results[key];\n        if (result instanceof Tensor) {\n          returnValue[key] = result;\n        } else {\n          returnValue[key] = new Tensor(result.type, result.data, result.dims);\n        }\n      }\n    }\n    TRACE_FUNC_END();\n    return returnValue;\n  }\n\n  async release(): Promise<void> {\n    return this.handler.dispose();\n  }\n\n  static create(path: string, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static create(buffer: ArrayBufferLike, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static create(\n    buffer: ArrayBufferLike,\n    byteOffset: number,\n    byteLength?: number,\n    options?: SessionOptions,\n  ): Promise<InferenceSessionInterface>;\n  static create(buffer: Uint8Array, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static async create(\n    arg0: string | ArrayBufferLike | Uint8Array,\n    arg1?: SessionOptions | number,\n    arg2?: number,\n    arg3?: SessionOptions,\n  ): Promise<InferenceSessionInterface> {\n    TRACE_FUNC_BEGIN();\n    // either load from a file or buffer\n    let filePathOrUint8Array: string | Uint8Array;\n    let options: SessionOptions = {};\n\n    if (typeof arg0 === 'string') {\n      filePathOrUint8Array = arg0;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError(\"'options' must be an object.\");\n      }\n    } else if (arg0 instanceof Uint8Array) {\n      filePathOrUint8Array = arg0;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError(\"'options' must be an object.\");\n      }\n    } else if (\n      arg0 instanceof ArrayBuffer ||\n      (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)\n    ) {\n      const buffer = arg0;\n      let byteOffset = 0;\n      let byteLength = arg0.byteLength;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 === 'number') {\n        byteOffset = arg1;\n        if (!Number.isSafeInteger(byteOffset)) {\n          throw new RangeError(\"'byteOffset' must be an integer.\");\n        }\n        if (byteOffset < 0 || byteOffset >= buffer.byteLength) {\n          throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);\n        }\n        byteLength = arg0.byteLength - byteOffset;\n        if (typeof arg2 === 'number') {\n          byteLength = arg2;\n          if (!Number.isSafeInteger(byteLength)) {\n            throw new RangeError(\"'byteLength' must be an integer.\");\n          }\n          if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {\n            throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);\n          }\n          if (typeof arg3 === 'object' && arg3 !== null) {\n            options = arg3;\n          } else if (typeof arg3 !== 'undefined') {\n            throw new TypeError(\"'options' must be an object.\");\n          }\n        } else if (typeof arg2 !== 'undefined') {\n          throw new TypeError(\"'byteLength' must be a number.\");\n        }\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError(\"'options' must be an object.\");\n      }\n      filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);\n    } else {\n      throw new TypeError(\"Unexpected argument[0]: must be 'path' or 'buffer'.\");\n    }\n\n    // resolve backend, update session options with validated EPs, and create session handler\n    const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n    const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);\n    TRACE_FUNC_END();\n    return new InferenceSession(handler);\n  }\n\n  startProfiling(): void {\n    this.handler.startProfiling();\n  }\n  endProfiling(): void {\n    this.handler.endProfiling();\n  }\n\n  get inputNames(): readonly string[] {\n    return this.handler.inputNames;\n  }\n  get outputNames(): readonly string[] {\n    return this.handler.outputNames;\n  }\n\n  get inputMetadata(): readonly InferenceSessionInterface.ValueMetadata[] {\n    return this.handler.inputMetadata;\n  }\n\n  get outputMetadata(): readonly InferenceSessionInterface.ValueMetadata[] {\n    return this.handler.outputMetadata;\n  }\n\n  private handler: InferenceSessionHandler;\n}\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { InferenceSession as InferenceSessionImpl } from './inference-session-impl.js';\nimport { OnnxModelOptions } from './onnx-model.js';\nimport { OnnxValue, OnnxValueDataLocation } from './onnx-value.js';\nimport type { Tensor } from './tensor.js';\nimport { TryGetGlobalType } from './type-helper.js';\n\n/* eslint-disable @typescript-eslint/no-redeclare */\n\nexport declare namespace InferenceSession {\n  // #region input/output types\n\n  type OnnxValueMapType = { readonly [name: string]: OnnxValue };\n  type NullableOnnxValueMapType = { readonly [name: string]: OnnxValue | null };\n\n  /**\n   * A feeds (model inputs) is an object that uses input names as keys and OnnxValue as corresponding values.\n   */\n  type FeedsType = OnnxValueMapType;\n\n  /**\n   * A fetches (model outputs) could be one of the following:\n   *\n   * - Omitted. Use model's output names definition.\n   * - An array of string indicating the output names.\n   * - An object that use output names as keys and OnnxValue or null as corresponding values.\n   *\n   * @remark\n   * different from input argument, in output, OnnxValue is optional. If an OnnxValue is present it will be\n   * used as a pre-allocated value by the inference engine; if omitted, inference engine will allocate buffer\n   * internally.\n   */\n  type FetchesType = readonly string[] | NullableOnnxValueMapType;\n\n  /**\n   * A inferencing return type is an object that uses output names as keys and OnnxValue as corresponding values.\n   */\n  type ReturnType = OnnxValueMapType;\n\n  // #endregion\n\n  // #region session options\n\n  /**\n   * A set of configurations for session behavior.\n   */\n  export interface SessionOptions extends OnnxModelOptions {\n    /**\n     * An array of execution provider options.\n     *\n     * An execution provider option can be a string indicating the name of the execution provider,\n     * or an object of corresponding type.\n     */\n    executionProviders?: readonly ExecutionProviderConfig[];\n\n    /**\n     * The intra OP threads number.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native).\n     */\n    intraOpNumThreads?: number;\n\n    /**\n     * The inter OP threads number.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native).\n     */\n    interOpNumThreads?: number;\n\n    /**\n     * The free dimension override.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    freeDimensionOverrides?: { readonly [dimensionName: string]: number };\n\n    /**\n     * The optimization level.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    graphOptimizationLevel?: 'disabled' | 'basic' | 'extended' | 'all';\n\n    /**\n     * Whether enable CPU memory arena.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    enableCpuMemArena?: boolean;\n\n    /**\n     * Whether enable memory pattern.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    enableMemPattern?: boolean;\n\n    /**\n     * Execution mode.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    executionMode?: 'sequential' | 'parallel';\n\n    /**\n     * Optimized model file path.\n     *\n     * If this setting is specified, the optimized model will be dumped. In browser, a blob will be created\n     * with a pop-up window.\n     */\n    optimizedModelFilePath?: string;\n\n    /**\n     * Whether enable profiling.\n     *\n     * This setting is a placeholder for a future use.\n     */\n    enableProfiling?: boolean;\n\n    /**\n     * File prefix for profiling.\n     *\n     * This setting is a placeholder for a future use.\n     */\n    profileFilePrefix?: string;\n\n    /**\n     * Log ID.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logId?: string;\n\n    /**\n     * Log severity level. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/common/logging/severity.h\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logSeverityLevel?: 0 | 1 | 2 | 3 | 4;\n\n    /**\n     * Log verbosity level.\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    logVerbosityLevel?: number;\n\n    /**\n     * Specify string as a preferred data location for all outputs, or an object that use output names as keys and a\n     * preferred data location as corresponding values.\n     *\n     * This setting is available only in ONNXRuntime Web for WebGL and WebGPU EP.\n     */\n    preferredOutputLocation?: OnnxValueDataLocation | { readonly [outputName: string]: OnnxValueDataLocation };\n\n    /**\n     * Whether enable graph capture.\n     * This setting is available only in ONNXRuntime Web for WebGPU EP.\n     */\n    enableGraphCapture?: boolean;\n\n    /**\n     * Store configurations for a session. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/session/\n     * onnxruntime_session_options_config_keys.h\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     *\n     * @example\n     * ```js\n     * extra: {\n     *   session: {\n     *     set_denormal_as_zero: \"1\",\n     *     disable_prepacking: \"1\"\n     *   },\n     *   optimization: {\n     *     enable_gelu_approximation: \"1\"\n     *   }\n     * }\n     * ```\n     */\n    extra?: Record<string, unknown>;\n  }\n\n  // #region execution providers\n\n  // Currently, we have the following backends to support execution providers:\n  // Backend Node.js binding: supports 'cpu', 'dml' (win32), 'coreml' (macOS) and 'cuda' (linux).\n  // Backend WebAssembly: supports 'cpu', 'wasm', 'webgpu' and 'webnn'.\n  // Backend ONNX.js: supports 'webgl'.\n  // Backend React Native: supports 'cpu', 'xnnpack', 'coreml' (iOS), 'nnapi' (Android).\n  interface ExecutionProviderOptionMap {\n    coreml: CoreMLExecutionProviderOption;\n    cpu: CpuExecutionProviderOption;\n    cuda: CudaExecutionProviderOption;\n    dml: DmlExecutionProviderOption;\n    nnapi: NnapiExecutionProviderOption;\n    tensorrt: TensorRtExecutionProviderOption;\n    wasm: WebAssemblyExecutionProviderOption;\n    webgl: WebGLExecutionProviderOption;\n    webgpu: WebGpuExecutionProviderOption;\n    webnn: WebNNExecutionProviderOption;\n    qnn: QnnExecutionProviderOption;\n    xnnpack: XnnpackExecutionProviderOption;\n  }\n\n  type ExecutionProviderName = keyof ExecutionProviderOptionMap;\n  type ExecutionProviderConfig =\n    | ExecutionProviderOptionMap[ExecutionProviderName]\n    | ExecutionProviderOption\n    | ExecutionProviderName\n    | string;\n\n  export interface ExecutionProviderOption {\n    readonly name: string;\n  }\n  export interface CpuExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'cpu';\n    useArena?: boolean;\n  }\n  export interface CudaExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'cuda';\n    deviceId?: number;\n  }\n  export interface DmlExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'dml';\n    deviceId?: number;\n  }\n  export interface TensorRtExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'tensorrt';\n    deviceId?: number;\n  }\n  export interface WebAssemblyExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'wasm';\n  }\n  export interface WebGLExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'webgl';\n    // TODO: add flags\n  }\n  export interface XnnpackExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'xnnpack';\n  }\n  export interface WebGpuExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'webgpu';\n    preferredLayout?: 'NCHW' | 'NHWC';\n  }\n\n  // #region WebNN options\n\n  interface WebNNExecutionProviderName extends ExecutionProviderOption {\n    readonly name: 'webnn';\n  }\n\n  /**\n   * Represents a set of options for creating a WebNN MLContext.\n   *\n   * @see https://www.w3.org/TR/webnn/#dictdef-mlcontextoptions\n   */\n  export interface WebNNContextOptions {\n    deviceType?: 'cpu' | 'gpu' | 'npu';\n    numThreads?: number;\n    powerPreference?: 'default' | 'low-power' | 'high-performance';\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider without MLContext.\n   */\n  export interface WebNNOptionsWithoutMLContext extends WebNNExecutionProviderName, WebNNContextOptions {\n    context?: never;\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider with MLContext.\n   *\n   * When MLContext is provided, the deviceType is also required so that the WebNN EP can determine the preferred\n   * channel layout.\n   *\n   * @see https://www.w3.org/TR/webnn/#dom-ml-createcontext\n   */\n  export interface WebNNOptionsWithMLContext\n    extends WebNNExecutionProviderName,\n      Omit<WebNNContextOptions, 'deviceType'>,\n      Required<Pick<WebNNContextOptions, 'deviceType'>> {\n    context: TryGetGlobalType<'MLContext'>;\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider with MLContext which is created from GPUDevice.\n   *\n   * @see https://www.w3.org/TR/webnn/#dom-ml-createcontext-gpudevice\n   */\n  export interface WebNNOptionsWebGpu extends WebNNExecutionProviderName {\n    context: TryGetGlobalType<'MLContext'>;\n    gpuDevice: TryGetGlobalType<'GPUDevice'>;\n  }\n\n  /**\n   * Options for WebNN execution provider.\n   */\n  export type WebNNExecutionProviderOption =\n    | WebNNOptionsWithoutMLContext\n    | WebNNOptionsWithMLContext\n    | WebNNOptionsWebGpu;\n\n  // #endregion\n\n  export interface QnnExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'qnn';\n    /**\n     * Specify the QNN backend type. E.g., 'cpu' or 'htp'.\n     * Mutually exclusive with `backendPath`.\n     *\n     * @default 'htp'\n     */\n    backendType?: string;\n    /**\n     * Specify a path to the QNN backend library.\n     * Mutually exclusive with `backendType`.\n     */\n    backendPath?: string;\n    /**\n     * Specify whether to enable HTP FP16 precision.\n     *\n     * @default true\n     */\n    enableFp16Precision?: boolean;\n  }\n  export interface CoreMLExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'coreml';\n    /**\n     * The bit flags for CoreML execution provider.\n     *\n     * ```\n     * COREML_FLAG_USE_CPU_ONLY = 0x001\n     * COREML_FLAG_ENABLE_ON_SUBGRAPH = 0x002\n     * COREML_FLAG_ONLY_ENABLE_DEVICE_WITH_ANE = 0x004\n     * COREML_FLAG_ONLY_ALLOW_STATIC_INPUT_SHAPES = 0x008\n     * COREML_FLAG_CREATE_MLPROGRAM = 0x010\n     * COREML_FLAG_USE_CPU_AND_GPU = 0x020\n     * ```\n     *\n     * See include/onnxruntime/core/providers/coreml/coreml_provider_factory.h for more details.\n     *\n     * This flag is available only in ONNXRuntime (Node.js binding).\n     */\n    coreMlFlags?: number;\n    /**\n     * Specify whether to use CPU only in CoreML EP.\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    useCPUOnly?: boolean;\n    useCPUAndGPU?: boolean;\n    /**\n     * Specify whether to enable CoreML EP on subgraph.\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    enableOnSubgraph?: boolean;\n    /**\n     * Specify whether to only enable CoreML EP for Apple devices with ANE (Apple Neural Engine).\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    onlyEnableDeviceWithANE?: boolean;\n  }\n  export interface NnapiExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'nnapi';\n    useFP16?: boolean;\n    useNCHW?: boolean;\n    cpuDisabled?: boolean;\n    cpuOnly?: boolean;\n  }\n  // #endregion\n\n  // #endregion\n\n  // #region run options\n\n  /**\n   * A set of configurations for inference run behavior\n   */\n  export interface RunOptions {\n    /**\n     * Log severity level. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/common/logging/severity.h\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logSeverityLevel?: 0 | 1 | 2 | 3 | 4;\n\n    /**\n     * Log verbosity level.\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    logVerbosityLevel?: number;\n\n    /**\n     * Terminate all incomplete OrtRun calls as soon as possible if true\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    terminate?: boolean;\n\n    /**\n     * A tag for the Run() calls using this\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    tag?: string;\n\n    /**\n     * Set a single run configuration entry. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/session/\n     * onnxruntime_run_options_config_keys.h\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     *\n     * @example\n     *\n     * ```js\n     * extra: {\n     *   memory: {\n     *     enable_memory_arena_shrinkage: \"1\",\n     *   }\n     * }\n     * ```\n     */\n    extra?: Record<string, unknown>;\n  }\n\n  // #endregion\n\n  // #region value metadata\n\n  /**\n   * The common part of the value metadata type for both tensor and non-tensor values.\n   */\n  export interface ValueMetadataBase {\n    /**\n     * The name of the specified input or output.\n     */\n    readonly name: string;\n  }\n\n  /**\n   * Represents the metadata of a non-tensor value.\n   */\n  export interface NonTensorValueMetadata extends ValueMetadataBase {\n    /**\n     * Get a value indicating whether the value is a tensor.\n     */\n    readonly isTensor: false;\n  }\n\n  /**\n   * Represents the metadata of a tensor value.\n   */\n  export interface TensorValueMetadata extends ValueMetadataBase {\n    /**\n     * Get a value indicating whether the value is a tensor.\n     */\n    readonly isTensor: true;\n    /**\n     * Get the data type of the tensor.\n     */\n    readonly type: Tensor.Type;\n    /**\n     * Get the shape of the tensor.\n     *\n     * If the shape is not defined, the value will an empty array. Otherwise, it will be an array representing the shape\n     * of the tensor. Each element in the array can be a number or a string. If the element is a number, it represents\n     * the corresponding dimension size. If the element is a string, it represents a symbolic dimension.\n     */\n    readonly shape: ReadonlyArray<number | string>;\n  }\n\n  /**\n   * Represents the metadata of a value.\n   */\n  export type ValueMetadata = NonTensorValueMetadata | TensorValueMetadata;\n\n  // #endregion\n}\n\n/**\n * Represent a runtime instance of an ONNX model.\n */\nexport interface InferenceSession {\n  // #region run()\n\n  /**\n   * Execute the model asynchronously with the given feeds and options.\n   *\n   * @param feeds - Representation of the model input. See type description of `InferenceSession.InputType` for detail.\n   * @param options - Optional. A set of options that controls the behavior of model inference.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding values.\n   */\n  run(feeds: InferenceSession.FeedsType, options?: InferenceSession.RunOptions): Promise<InferenceSession.ReturnType>;\n\n  /**\n   * Execute the model asynchronously with the given feeds, fetches and options.\n   *\n   * @param feeds - Representation of the model input. See type description of `InferenceSession.InputType` for detail.\n   * @param fetches - Representation of the model output. See type description of `InferenceSession.OutputType` for\n   * detail.\n   * @param options - Optional. A set of options that controls the behavior of model inference.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding values.\n   */\n  run(\n    feeds: InferenceSession.FeedsType,\n    fetches: InferenceSession.FetchesType,\n    options?: InferenceSession.RunOptions,\n  ): Promise<InferenceSession.ReturnType>;\n\n  // #endregion\n\n  // #region release()\n\n  /**\n   * Release the inference session and the underlying resources.\n   */\n  release(): Promise<void>;\n\n  // #endregion\n\n  // #region profiling\n\n  /**\n   * Start profiling.\n   */\n  startProfiling(): void;\n\n  /**\n   * End profiling.\n   */\n  endProfiling(): void;\n\n  // #endregion\n\n  // #region metadata\n\n  /**\n   * Get input names of the loaded model.\n   */\n  readonly inputNames: readonly string[];\n\n  /**\n   * Get output names of the loaded model.\n   */\n  readonly outputNames: readonly string[];\n\n  /**\n   * Get input metadata of the loaded model.\n   */\n  readonly inputMetadata: readonly InferenceSession.ValueMetadata[];\n\n  /**\n   * Get output metadata of the loaded model.\n   */\n  readonly outputMetadata: readonly InferenceSession.ValueMetadata[];\n\n  // #endregion\n}\n\nexport interface InferenceSessionFactory {\n  // #region create()\n\n  /**\n   * Create a new inference session and load model asynchronously from an ONNX model file.\n   *\n   * @param uri - The URI or file path of the model to load.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(uri: string, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from an array bufer.\n   *\n   * @param buffer - An ArrayBuffer representation of an ONNX model.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(buffer: ArrayBufferLike, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from segment of an array bufer.\n   *\n   * @param buffer - An ArrayBuffer representation of an ONNX model.\n   * @param byteOffset - The beginning of the specified portion of the array buffer.\n   * @param byteLength - The length in bytes of the array buffer.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(\n    buffer: ArrayBufferLike,\n    byteOffset: number,\n    byteLength?: number,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from a Uint8Array.\n   *\n   * @param buffer - A Uint8Array representation of an ONNX model.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(buffer: Uint8Array, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  // #endregion\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const InferenceSession: InferenceSessionFactory = InferenceSessionImpl;\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nexport const isNode = !!(typeof process !== 'undefined' && process.versions && process.versions.node);\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport type { OrtWasmModule } from './wasm-types';\nimport { isNode } from './wasm-utils-env';\n\n/**\n * The origin of the current location.\n *\n * In Node.js, this is undefined.\n */\nconst origin = isNode || typeof location === 'undefined' ? undefined : location.origin;\n\n/**\n * Some bundlers (eg. Webpack) will rewrite `import.meta.url` to a file URL at compile time.\n *\n * This function checks if `import.meta.url` starts with `file:`, but using the `>` and `<` operators instead of\n * `startsWith` function so that code minimizers can remove the dead code correctly.\n *\n * For example, if we use terser to minify the following code:\n * ```js\n * if (\"file://hard-coded-filename\".startsWith(\"file:\")) {\n *   console.log(1)\n * } else {\n *   console.log(2)\n * }\n *\n * if (\"file://hard-coded-filename\" > \"file:\" && \"file://hard-coded-filename\" < \"file;\") {\n *   console.log(3)\n * } else {\n *   console.log(4)\n * }\n * ```\n *\n * The minified code will be:\n * ```js\n * \"file://hard-coded-filename\".startsWith(\"file:\")?console.log(1):console.log(2),console.log(3);\n * ```\n *\n * (use Terser 5.39.0 with default options, https://try.terser.org/)\n *\n * @returns true if the import.meta.url is hardcoded as a file URI.\n */\nexport const isEsmImportMetaUrlHardcodedAsFileUri =\n  BUILD_DEFS.IS_ESM && BUILD_DEFS.ESM_IMPORT_META_URL! > 'file:' && BUILD_DEFS.ESM_IMPORT_META_URL! < 'file;';\n\nconst getScriptSrc = (): string | undefined => {\n  // if Nodejs, return undefined\n  if (isNode) {\n    return undefined;\n  }\n  // if It's ESM, use import.meta.url\n  if (BUILD_DEFS.IS_ESM) {\n    // For ESM, if the import.meta.url is a file URL, this usually means the bundler rewrites `import.meta.url` to\n    // the file path at compile time. In this case, this file path cannot be used to determine the runtime URL.\n    //\n    // We need to use the URL constructor like this:\n    // ```js\n    // new URL('actual-bundle-name.js', import.meta.url).href\n    // ```\n    // So that bundler can preprocess the URL correctly.\n    if (isEsmImportMetaUrlHardcodedAsFileUri) {\n      // if the rewritten URL is a relative path, we need to use the origin to resolve the URL.\n\n      // The following is a workaround for Vite.\n      //\n      // Vite uses a bundler(rollup/rolldown) that does not rewrite `import.meta.url` to a file URL. So in theory, this\n      // code path should not be executed in Vite. However, the bundler does not know it and it still try to load the\n      // following pattern:\n      // - `return new URL('filename', import.meta.url).href`\n      //\n      // By replacing the pattern above with the following code, we can skip the resource loading behavior:\n      // - `const URL2 = URL; return new URL2('filename', import.meta.url).href;`\n      //\n      // And it still works in Webpack.\n      const URL2 = URL;\n      return new URL(new URL2(BUILD_DEFS.BUNDLE_FILENAME, BUILD_DEFS.ESM_IMPORT_META_URL).href, origin).href;\n    }\n\n    return BUILD_DEFS.ESM_IMPORT_META_URL;\n  }\n\n  return typeof document !== 'undefined'\n    ? (document.currentScript as HTMLScriptElement)?.src\n    : // use `self.location.href` if available\n      typeof self !== 'undefined'\n      ? self.location?.href\n      : undefined;\n};\n\n/**\n * The classic script source URL. This is not always available in non ESModule environments.\n *\n * In Node.js, this is undefined.\n */\nexport const scriptSrc = getScriptSrc();\n\n/**\n * Infer the wasm path prefix from the script source URL.\n *\n * @returns The inferred wasm path prefix, or undefined if the script source URL is not available or is a blob URL.\n */\nexport const inferWasmPathPrefixFromScriptSrc = (): string | undefined => {\n  if (scriptSrc && !scriptSrc.startsWith('blob:')) {\n    return scriptSrc.substring(0, scriptSrc.lastIndexOf('/') + 1);\n  }\n  return undefined;\n};\n\n/**\n * Check if the given filename with prefix is from the same origin.\n */\nconst isSameOrigin = (filename: string, prefixOverride?: string) => {\n  try {\n    const baseUrl = prefixOverride ?? scriptSrc;\n    const url = baseUrl ? new URL(filename, baseUrl) : new URL(filename);\n    return url.origin === origin;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Normalize the inputs to an absolute URL with the given prefix override. If failed, return undefined.\n */\nconst normalizeUrl = (filename: string, prefixOverride?: string) => {\n  const baseUrl = prefixOverride ?? scriptSrc;\n  try {\n    const url = baseUrl ? new URL(filename, baseUrl) : new URL(filename);\n    return url.href;\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Create a fallback URL if an absolute URL cannot be created by the normalizeUrl function.\n */\nconst fallbackUrl = (filename: string, prefixOverride?: string) => `${prefixOverride ?? './'}${filename}`;\n\n/**\n * This helper function is used to preload a module from a URL.\n *\n * If the origin of the worker URL is different from the current origin, the worker cannot be loaded directly.\n * See discussions in https://github.com/webpack-contrib/worker-loader/issues/154\n *\n * In this case, we will fetch the worker URL and create a new Blob URL with the same origin as a workaround.\n *\n * @param absoluteUrl - The absolute URL to preload.\n *\n * @returns - A promise that resolves to a new Blob URL\n */\nconst preload = async (absoluteUrl: string): Promise<string> => {\n  const response = await fetch(absoluteUrl, { credentials: 'same-origin' });\n  const blob = await response.blob();\n  return URL.createObjectURL(blob);\n};\n\n/**\n * This helper function is used to dynamically import a module from a URL.\n *\n * The build script has special handling for this function to ensure that the URL is not bundled into the final output.\n *\n * @param url - The URL to import.\n *\n * @returns - A promise that resolves to the default export of the module.\n */\nconst dynamicImportDefault = async <T>(url: string): Promise<T> =>\n  (await import(/* webpackIgnore: true */ url)).default;\n\n/**\n * The proxy worker factory imported from the proxy worker module.\n *\n * This is only available when the WebAssembly proxy is not disabled.\n */\nconst createProxyWorker: ((urlOverride?: string) => Worker) | undefined =\n  // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n  BUILD_DEFS.DISABLE_WASM_PROXY ? undefined : require('./proxy-worker/main').default;\n\n/**\n * Import the proxy worker.\n *\n * This function will perform the following steps:\n * 1. If a preload is needed, it will preload the module and return the object URL.\n * 2. Use the proxy worker factory to create the proxy worker.\n *\n * @returns - A promise that resolves to a tuple of 2 elements:\n *            - The object URL of the preloaded module, or undefined if no preload is needed.\n *            - The proxy worker.\n */\nexport const importProxyWorker = async (): Promise<[undefined | string, Worker]> => {\n  if (!scriptSrc) {\n    throw new Error('Failed to load proxy worker: cannot determine the script source URL.');\n  }\n\n  // If the script source is from the same origin, we can use the embedded proxy module directly.\n  if (isSameOrigin(scriptSrc)) {\n    return [undefined, createProxyWorker!()];\n  }\n\n  // Otherwise, need to preload\n  const url = await preload(scriptSrc);\n  return [url, createProxyWorker!(url)];\n};\n\n/**\n * The embedded WebAssembly module.\n *\n * This is only available in ESM and when embedding is not disabled.\n */\nconst embeddedWasmModule: EmscriptenModuleFactory<OrtWasmModule> | undefined =\n  BUILD_DEFS.IS_ESM && BUILD_DEFS.ENABLE_BUNDLE_WASM_JS\n    ? // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n      require(\n        !BUILD_DEFS.DISABLE_JSEP\n          ? '../../dist/ort-wasm-simd-threaded.jsep.mjs'\n          : '../../dist/ort-wasm-simd-threaded.mjs',\n      ).default\n    : undefined;\n\n/**\n * Import the WebAssembly module.\n *\n * This function will perform the following steps:\n * 1. If the embedded module exists and no custom URL is specified, use the embedded module.\n * 2. If a preload is needed, it will preload the module and return the object URL.\n * 3. Otherwise, it will perform a dynamic import of the module.\n *\n * @returns - A promise that resolves to a tuple of 2 elements:\n *            - The object URL of the preloaded module, or undefined if no preload is needed.\n *            - The default export of the module, which is a factory function to create the WebAssembly module.\n */\nexport const importWasmModule = async (\n  urlOverride: string | undefined,\n  prefixOverride: string | undefined,\n  isMultiThreaded: boolean,\n): Promise<[undefined | string, EmscriptenModuleFactory<OrtWasmModule>]> => {\n  if (!urlOverride && !prefixOverride && embeddedWasmModule && scriptSrc && isSameOrigin(scriptSrc)) {\n    return [undefined, embeddedWasmModule];\n  } else {\n    const wasmModuleFilename = !BUILD_DEFS.DISABLE_JSEP\n      ? 'ort-wasm-simd-threaded.jsep.mjs'\n      : 'ort-wasm-simd-threaded.mjs';\n    const wasmModuleUrl = urlOverride ?? normalizeUrl(wasmModuleFilename, prefixOverride);\n    // need to preload if all of the following conditions are met:\n    // 1. not in Node.js.\n    //    - Node.js does not have the same origin policy for creating workers.\n    // 2. multi-threaded is enabled.\n    //    - If multi-threaded is disabled, no worker will be created. So we don't need to preload the module.\n    // 3. the absolute URL is available.\n    //    - If the absolute URL is failed to be created, the origin cannot be determined. In this case, we will not\n    //    preload the module.\n    // 4. the worker URL is not from the same origin.\n    //    - If the worker URL is from the same origin, we can create the worker directly.\n    const needPreload = !isNode && isMultiThreaded && wasmModuleUrl && !isSameOrigin(wasmModuleUrl, prefixOverride);\n    const url = needPreload\n      ? await preload(wasmModuleUrl)\n      : (wasmModuleUrl ?? fallbackUrl(wasmModuleFilename, prefixOverride));\n    return [needPreload ? url : undefined, await dynamicImportDefault<EmscriptenModuleFactory<OrtWasmModule>>(url)];\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Env } from 'onnxruntime-common';\n\nimport type { OrtWasmModule } from './wasm-types';\nimport { importWasmModule, inferWasmPathPrefixFromScriptSrc } from './wasm-utils-import';\n\nlet wasm: OrtWasmModule | undefined;\nlet initialized = false;\nlet initializing = false;\nlet aborted = false;\n\nconst isMultiThreadSupported = (): boolean => {\n  // If 'SharedArrayBuffer' is not available, WebAssembly threads will not work.\n  if (typeof SharedArrayBuffer === 'undefined') {\n    return false;\n  }\n\n  try {\n    // Test for transferability of SABs (for browsers. needed for Firefox)\n    // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ\n    if (typeof MessageChannel !== 'undefined') {\n      new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));\n    }\n\n    // Test for WebAssembly threads capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing threaded instructions.\n    return WebAssembly.validate(\n      new Uint8Array([\n        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,\n        2, 0, 26, 11,\n      ]),\n    );\n  } catch (e) {\n    return false;\n  }\n};\n\nconst isSimdSupported = (): boolean => {\n  try {\n    // Test for WebAssembly SIMD capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing SIMD instructions.\n\n    // The binary data is generated from the following code by wat2wasm:\n    //\n    // (module\n    //   (type $t0 (func))\n    //   (func $f0 (type $t0)\n    //     (drop\n    //       (i32x4.dot_i16x8_s\n    //         (i8x16.splat\n    //           (i32.const 0))\n    //         (v128.const i32x4 0x00000000 0x00000000 0x00000000 0x00000000)))))\n\n    return WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11,\n      ]),\n    );\n  } catch (e) {\n    return false;\n  }\n};\n\nconst isRelaxedSimdSupported = (): boolean => {\n  try {\n    // Test for WebAssembly Relaxed SIMD capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing Relaxed SIMD instructions.\n\n    // The binary data is generated from the following code by wat2wasm:\n    // (module\n    //   (func (result v128)\n    //      i32.const 1\n    //      i8x16.splat\n    //      i32.const 2\n    //      i8x16.splat\n    //      i32.const 3\n    //      i8x16.splat\n    //      i32x4.relaxed_dot_i8x16_i7x16_add_s\n    //   )\n    //  )\n    return WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 19, 1, 17, 0, 65, 1, 253, 15, 65, 2, 253,\n        15, 65, 3, 253, 15, 253, 147, 2, 11,\n      ]),\n    );\n  } catch (e) {\n    return false;\n  }\n};\n\nexport const initializeWebAssembly = async (flags: Env.WebAssemblyFlags): Promise<void> => {\n  if (initialized) {\n    return Promise.resolve();\n  }\n  if (initializing) {\n    throw new Error(\"multiple calls to 'initializeWebAssembly()' detected.\");\n  }\n  if (aborted) {\n    throw new Error(\"previous call to 'initializeWebAssembly()' failed.\");\n  }\n\n  initializing = true;\n\n  // wasm flags are already initialized\n  const timeout = flags.initTimeout!;\n  let numThreads = flags.numThreads!;\n\n  // ensure SIMD is supported\n  if (flags.simd === false) {\n    // skip SIMD feature checking as it is disabled explicitly by user\n  } else if (flags.simd === 'relaxed') {\n    // check if relaxed SIMD is supported\n    if (!isRelaxedSimdSupported()) {\n      throw new Error('Relaxed WebAssembly SIMD is not supported in the current environment.');\n    }\n  } else if (!isSimdSupported()) {\n    throw new Error('WebAssembly SIMD is not supported in the current environment.');\n  }\n\n  // check if multi-threading is supported\n  const multiThreadSupported = isMultiThreadSupported();\n  if (numThreads > 1 && !multiThreadSupported) {\n    if (typeof self !== 'undefined' && !self.crossOriginIsolated) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        'env.wasm.numThreads is set to ' +\n          numThreads +\n          ', but this will not work unless you enable crossOriginIsolated mode. ' +\n          'See https://web.dev/cross-origin-isolation-guide/ for more info.',\n      );\n    }\n\n    // eslint-disable-next-line no-console\n    console.warn(\n      'WebAssembly multi-threading is not supported in the current environment. ' + 'Falling back to single-threading.',\n    );\n\n    // set flags.numThreads to 1 so that OrtInit() will not create a global thread pool.\n    flags.numThreads = numThreads = 1;\n  }\n\n  const wasmPaths = flags.wasmPaths;\n  const wasmPrefixOverride = typeof wasmPaths === 'string' ? wasmPaths : undefined;\n  const mjsPathOverrideFlag = (wasmPaths as Env.WasmFilePaths)?.mjs;\n  const mjsPathOverride = (mjsPathOverrideFlag as URL)?.href ?? mjsPathOverrideFlag;\n  const wasmPathOverrideFlag = (wasmPaths as Env.WasmFilePaths)?.wasm;\n  const wasmPathOverride = (wasmPathOverrideFlag as URL)?.href ?? wasmPathOverrideFlag;\n  const wasmBinaryOverride = flags.wasmBinary;\n\n  const [objectUrl, ortWasmFactory] = await importWasmModule(mjsPathOverride, wasmPrefixOverride, numThreads > 1);\n\n  let isTimeout = false;\n\n  const tasks: Array<Promise<void>> = [];\n\n  // promise for timeout\n  if (timeout > 0) {\n    tasks.push(\n      new Promise((resolve) => {\n        setTimeout(() => {\n          isTimeout = true;\n          resolve();\n        }, timeout);\n      }),\n    );\n  }\n\n  // promise for module initialization\n  tasks.push(\n    new Promise((resolve, reject) => {\n      const config: Partial<OrtWasmModule> = {\n        /**\n         * The number of threads. WebAssembly will create (Module.numThreads - 1) workers. If it is 1, no worker will be\n         * created.\n         */\n        numThreads,\n      };\n\n      if (wasmBinaryOverride) {\n        // Set a custom buffer which contains the WebAssembly binary. This will skip the wasm file fetching.\n        config.wasmBinary = wasmBinaryOverride;\n      } else if (wasmPathOverride || wasmPrefixOverride) {\n        // A callback function to locate the WebAssembly file. The function should return the full path of the file.\n        //\n        // Since Emscripten 3.1.58, this function is only called for the .wasm file.\n        config.locateFile = (fileName) => wasmPathOverride ?? wasmPrefixOverride + fileName;\n      } else if (mjsPathOverride && mjsPathOverride.indexOf('blob:') !== 0) {\n        // if mjs path is specified, use it as the base path for the .wasm file.\n        config.locateFile = (fileName) => new URL(fileName, mjsPathOverride).href;\n      } else if (objectUrl) {\n        const inferredWasmPathPrefix = inferWasmPathPrefixFromScriptSrc();\n        if (inferredWasmPathPrefix) {\n          // if the wasm module is preloaded, use the inferred wasm path as the base path for the .wasm file.\n          config.locateFile = (fileName) => inferredWasmPathPrefix + fileName;\n        }\n      }\n\n      ortWasmFactory(config).then(\n        // wasm module initialized successfully\n        (module) => {\n          initializing = false;\n          initialized = true;\n          wasm = module;\n          resolve();\n          if (objectUrl) {\n            URL.revokeObjectURL(objectUrl);\n          }\n        },\n        // wasm module failed to initialize\n        (what) => {\n          initializing = false;\n          aborted = true;\n          reject(what);\n        },\n      );\n    }),\n  );\n\n  await Promise.race(tasks);\n\n  if (isTimeout) {\n    throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);\n  }\n};\n\nexport const getInstance = (): OrtWasmModule => {\n  if (initialized && wasm) {\n    return wasm;\n  }\n\n  throw new Error('WebAssembly is not initialized yet.');\n};\n\nexport const dispose = (): void => {\n  if (initialized && !initializing && !aborted) {\n    // TODO: currently \"PThread.terminateAllThreads()\" is not exposed in the wasm module.\n    //       And this function is not yet called by any code.\n    //       If it is needed in the future, we should expose it in the wasm module and uncomment the following line.\n\n    // wasm?.PThread?.terminateAllThreads();\n    wasm = undefined;\n\n    initializing = false;\n    initialized = false;\n    aborted = true;\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { getInstance } from './wasm-factory';\n\nexport const allocWasmString = (data: string, allocs: number[]): number => {\n  const wasm = getInstance();\n\n  const dataLength = wasm.lengthBytesUTF8(data) + 1;\n  const dataOffset = wasm._malloc(dataLength);\n  wasm.stringToUTF8(data, dataOffset, dataLength);\n  allocs.push(dataOffset);\n\n  return dataOffset;\n};\n\ninterface ExtraOptionsHandler {\n  (name: string, value: string): void;\n}\n\nexport const iterateExtraOptions = (\n  options: Record<string, unknown>,\n  prefix: string,\n  seen: WeakSet<Record<string, unknown>>,\n  handler: ExtraOptionsHandler,\n): void => {\n  if (typeof options == 'object' && options !== null) {\n    if (seen.has(options)) {\n      throw new Error('Circular reference in options');\n    } else {\n      seen.add(options);\n    }\n  }\n\n  Object.entries(options).forEach(([key, value]) => {\n    const name = prefix ? prefix + key : key;\n    if (typeof value === 'object') {\n      iterateExtraOptions(value as Record<string, unknown>, name + '.', seen, handler);\n    } else if (typeof value === 'string' || typeof value === 'number') {\n      handler(name, value.toString());\n    } else if (typeof value === 'boolean') {\n      handler(name, value ? '1' : '0');\n    } else {\n      throw new Error(`Can't handle extra config type: ${typeof value}`);\n    }\n  });\n};\n\n/**\n * check web assembly API's last error and throw error if any error occurred.\n * @param message a message used when an error occurred.\n */\nexport const checkLastError = (message: string): void => {\n  const wasm = getInstance();\n\n  const stack = wasm.stackSave();\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const paramsOffset = wasm.stackAlloc(2 * ptrSize);\n    wasm._OrtGetLastError(paramsOffset, paramsOffset + ptrSize);\n    const errorCode = Number(wasm.getValue(paramsOffset, ptrSize === 4 ? 'i32' : 'i64'));\n    const errorMessagePointer = wasm.getValue(paramsOffset + ptrSize, '*');\n    const errorMessage = errorMessagePointer ? wasm.UTF8ToString(errorMessagePointer) : '';\n    throw new Error(`${message} ERROR_CODE: ${errorCode}, ERROR_MESSAGE: ${errorMessage}`);\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { InferenceSession } from 'onnxruntime-common';\n\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError, iterateExtraOptions } from './wasm-utils';\n\nexport const setRunOptions = (options: InferenceSession.RunOptions): [number, number[]] => {\n  const wasm = getInstance();\n  let runOptionsHandle = 0;\n  const allocs: number[] = [];\n\n  const runOptions: InferenceSession.RunOptions = options || {};\n\n  try {\n    if (options?.logSeverityLevel === undefined) {\n      runOptions.logSeverityLevel = 2; // Default to warning\n    } else if (\n      typeof options.logSeverityLevel !== 'number' ||\n      !Number.isInteger(options.logSeverityLevel) ||\n      options.logSeverityLevel < 0 ||\n      options.logSeverityLevel > 4\n    ) {\n      throw new Error(`log serverity level is not valid: ${options.logSeverityLevel}`);\n    }\n\n    if (options?.logVerbosityLevel === undefined) {\n      runOptions.logVerbosityLevel = 0; // Default to 0\n    } else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {\n      throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);\n    }\n\n    if (options?.terminate === undefined) {\n      runOptions.terminate = false;\n    }\n\n    let tagDataOffset = 0;\n    if (options?.tag !== undefined) {\n      tagDataOffset = allocWasmString(options.tag, allocs);\n    }\n\n    runOptionsHandle = wasm._OrtCreateRunOptions(\n      runOptions.logSeverityLevel!,\n      runOptions.logVerbosityLevel!,\n      !!runOptions.terminate!,\n      tagDataOffset,\n    );\n    if (runOptionsHandle === 0) {\n      checkLastError(\"Can't create run options.\");\n    }\n\n    if (options?.extra !== undefined) {\n      iterateExtraOptions(options.extra, '', new WeakSet<Record<string, unknown>>(), (key, value) => {\n        const keyDataOffset = allocWasmString(key, allocs);\n        const valueDataOffset = allocWasmString(value, allocs);\n\n        if (wasm._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n          checkLastError(`Can't set a run config entry: ${key} - ${value}.`);\n        }\n      });\n    }\n\n    return [runOptionsHandle, allocs];\n  } catch (e) {\n    if (runOptionsHandle !== 0) {\n      wasm._OrtReleaseRunOptions(runOptionsHandle);\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n    throw e;\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport type { InferenceSession } from 'onnxruntime-common';\n\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError, iterateExtraOptions } from './wasm-utils';\n\nconst getGraphOptimzationLevel = (graphOptimizationLevel: string | unknown): number => {\n  switch (graphOptimizationLevel) {\n    case 'disabled':\n      return 0;\n    case 'basic':\n      return 1;\n    case 'extended':\n      return 2;\n    case 'all':\n      return 99;\n    default:\n      throw new Error(`unsupported graph optimization level: ${graphOptimizationLevel}`);\n  }\n};\n\nconst getExecutionMode = (executionMode: 'sequential' | 'parallel'): number => {\n  switch (executionMode) {\n    case 'sequential':\n      return 0;\n    case 'parallel':\n      return 1;\n    default:\n      throw new Error(`unsupported execution mode: ${executionMode}`);\n  }\n};\n\nconst appendDefaultOptions = (options: InferenceSession.SessionOptions): void => {\n  if (!options.extra) {\n    options.extra = {};\n  }\n  if (!options.extra.session) {\n    options.extra.session = {};\n  }\n  const session = options.extra.session as Record<string, string>;\n  if (!session.use_ort_model_bytes_directly) {\n    // eslint-disable-next-line camelcase\n    session.use_ort_model_bytes_directly = '1';\n  }\n\n  // if using JSEP with WebGPU, always disable memory pattern\n  if (\n    options.executionProviders &&\n    options.executionProviders.some((ep) => (typeof ep === 'string' ? ep : ep.name) === 'webgpu')\n  ) {\n    options.enableMemPattern = false;\n  }\n};\n\nconst appendSessionConfig = (sessionOptionsHandle: number, key: string, value: string, allocs: number[]): void => {\n  const keyDataOffset = allocWasmString(key, allocs);\n  const valueDataOffset = allocWasmString(value, allocs);\n  if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n    checkLastError(`Can't set a session config entry: ${key} - ${value}.`);\n  }\n};\n\nconst appendEpOption = (epOptions: Array<[number, number]>, key: string, value: string, allocs: number[]): void => {\n  const keyDataOffset = allocWasmString(key, allocs);\n  const valueDataOffset = allocWasmString(value, allocs);\n  epOptions.push([keyDataOffset, valueDataOffset]);\n};\n\nconst setExecutionProviders = async (\n  sessionOptionsHandle: number,\n  executionProviders: readonly InferenceSession.ExecutionProviderConfig[],\n  allocs: number[],\n): Promise<void> => {\n  for (const ep of executionProviders) {\n    let epName = typeof ep === 'string' ? ep : ep.name;\n    const epOptions: Array<[number, number]> = [];\n\n    // check EP name\n    switch (epName) {\n      case 'webnn':\n        epName = 'WEBNN';\n        if (typeof ep !== 'string') {\n          const webnnOptions = ep as InferenceSession.WebNNExecutionProviderOption;\n          // const context = (webnnOptions as InferenceSession.WebNNOptionsWithMLContext)?.context;\n          const deviceType = (webnnOptions as InferenceSession.WebNNContextOptions)?.deviceType;\n          if (deviceType) {\n            appendSessionConfig(sessionOptionsHandle, 'deviceType', deviceType, allocs);\n          }\n        }\n        break;\n      case 'webgpu':\n        if (BUILD_DEFS.USE_WEBGPU_EP) {\n          epName = 'WebGPU';\n          let customDevice: GPUDevice | undefined;\n\n          if (typeof ep !== 'string') {\n            const customOptions = ep as unknown as { device: GPUDevice };\n            if (customOptions.device) {\n              if (typeof GPUDevice !== 'undefined' && customOptions.device instanceof GPUDevice) {\n                customDevice = customOptions.device;\n              } else {\n                throw new Error('Invalid GPU device set in WebGPU EP options.');\n              }\n            }\n\n            // TODO: handle more options\n          }\n\n          const info = getInstance().webgpuRegisterDevice!(customDevice);\n          if (info) {\n            const [deviceId, instanceHandle, deviceHandle] = info;\n            appendEpOption(epOptions, 'deviceId', deviceId.toString(), allocs);\n            appendEpOption(epOptions, 'webgpuInstance', instanceHandle.toString(), allocs);\n            appendEpOption(epOptions, 'webgpuDevice', deviceHandle.toString(), allocs);\n          }\n        } else {\n          epName = 'JS';\n          if (typeof ep !== 'string') {\n            const webgpuOptions = ep as InferenceSession.WebGpuExecutionProviderOption;\n            if (webgpuOptions?.preferredLayout) {\n              if (webgpuOptions.preferredLayout !== 'NCHW' && webgpuOptions.preferredLayout !== 'NHWC') {\n                throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${webgpuOptions.preferredLayout}`);\n              }\n              appendSessionConfig(sessionOptionsHandle, 'preferredLayout', webgpuOptions.preferredLayout, allocs);\n            }\n          }\n        }\n        break;\n      case 'wasm':\n      case 'cpu':\n        continue;\n      default:\n        throw new Error(`not supported execution provider: ${epName}`);\n    }\n\n    const epNameDataOffset = allocWasmString(epName, allocs);\n    const epOptionsCount = epOptions.length;\n    let keysOffset = 0;\n    let valuesOffset = 0;\n    if (epOptionsCount > 0) {\n      keysOffset = getInstance()._malloc(epOptionsCount * getInstance().PTR_SIZE);\n      allocs.push(keysOffset);\n      valuesOffset = getInstance()._malloc(epOptionsCount * getInstance().PTR_SIZE);\n      allocs.push(valuesOffset);\n      for (let i = 0; i < epOptionsCount; i++) {\n        getInstance().setValue(keysOffset + i * getInstance().PTR_SIZE, epOptions[i][0], '*');\n        getInstance().setValue(valuesOffset + i * getInstance().PTR_SIZE, epOptions[i][1], '*');\n      }\n    }\n    if (\n      (await getInstance()._OrtAppendExecutionProvider(\n        sessionOptionsHandle,\n        epNameDataOffset,\n        keysOffset,\n        valuesOffset,\n        epOptionsCount,\n      )) !== 0\n    ) {\n      checkLastError(`Can't append execution provider: ${epName}.`);\n    }\n  }\n};\n\nexport const setSessionOptions = async (options?: InferenceSession.SessionOptions): Promise<[number, number[]]> => {\n  const wasm = getInstance();\n  let sessionOptionsHandle = 0;\n  const allocs: number[] = [];\n\n  const sessionOptions: InferenceSession.SessionOptions = options || {};\n  appendDefaultOptions(sessionOptions);\n\n  try {\n    const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel ?? 'all');\n    const executionMode = getExecutionMode(sessionOptions.executionMode ?? 'sequential');\n    const logIdDataOffset =\n      typeof sessionOptions.logId === 'string' ? allocWasmString(sessionOptions.logId, allocs) : 0;\n\n    const logSeverityLevel = sessionOptions.logSeverityLevel ?? 2; // Default to 2 - warning\n    if (!Number.isInteger(logSeverityLevel) || logSeverityLevel < 0 || logSeverityLevel > 4) {\n      throw new Error(`log serverity level is not valid: ${logSeverityLevel}`);\n    }\n\n    const logVerbosityLevel = sessionOptions.logVerbosityLevel ?? 0; // Default to 0 - verbose\n    if (!Number.isInteger(logVerbosityLevel) || logVerbosityLevel < 0 || logVerbosityLevel > 4) {\n      throw new Error(`log verbosity level is not valid: ${logVerbosityLevel}`);\n    }\n\n    const optimizedModelFilePathOffset =\n      typeof sessionOptions.optimizedModelFilePath === 'string'\n        ? allocWasmString(sessionOptions.optimizedModelFilePath, allocs)\n        : 0;\n\n    sessionOptionsHandle = wasm._OrtCreateSessionOptions(\n      graphOptimizationLevel,\n      !!sessionOptions.enableCpuMemArena,\n      !!sessionOptions.enableMemPattern,\n      executionMode,\n      !!sessionOptions.enableProfiling,\n      0,\n      logIdDataOffset,\n      logSeverityLevel,\n      logVerbosityLevel,\n      optimizedModelFilePathOffset,\n    );\n    if (sessionOptionsHandle === 0) {\n      checkLastError(\"Can't create session options.\");\n    }\n\n    if (sessionOptions.executionProviders) {\n      await setExecutionProviders(sessionOptionsHandle, sessionOptions.executionProviders, allocs);\n    }\n\n    if (sessionOptions.enableGraphCapture !== undefined) {\n      if (typeof sessionOptions.enableGraphCapture !== 'boolean') {\n        throw new Error(`enableGraphCapture must be a boolean value: ${sessionOptions.enableGraphCapture}`);\n      }\n      appendSessionConfig(\n        sessionOptionsHandle,\n        'enableGraphCapture',\n        sessionOptions.enableGraphCapture.toString(),\n        allocs,\n      );\n    }\n\n    if (sessionOptions.freeDimensionOverrides) {\n      for (const [name, value] of Object.entries(sessionOptions.freeDimensionOverrides)) {\n        if (typeof name !== 'string') {\n          throw new Error(`free dimension override name must be a string: ${name}`);\n        }\n        if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n          throw new Error(`free dimension override value must be a non-negative integer: ${value}`);\n        }\n        const nameOffset = allocWasmString(name, allocs);\n        if (wasm._OrtAddFreeDimensionOverride(sessionOptionsHandle, nameOffset, value) !== 0) {\n          checkLastError(`Can't set a free dimension override: ${name} - ${value}.`);\n        }\n      }\n    }\n\n    if (sessionOptions.extra !== undefined) {\n      iterateExtraOptions(sessionOptions.extra, '', new WeakSet<Record<string, unknown>>(), (key, value) => {\n        appendSessionConfig(sessionOptionsHandle, key, value, allocs);\n      });\n    }\n\n    return [sessionOptionsHandle, allocs];\n  } catch (e) {\n    if (sessionOptionsHandle !== 0) {\n      if (wasm._OrtReleaseSessionOptions(sessionOptionsHandle) !== 0) {\n        checkLastError(\"Can't release session options.\");\n      }\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n    throw e;\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Tensor } from 'onnxruntime-common';\n\n// a dummy type declaration for Float16Array in case any polyfill is available.\ndeclare global {\n  // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any\n  const Float16Array: any;\n}\n\n// This file includes common definitions. They do NOT have dependency on the WebAssembly instance.\n\n/**\n * Copied from ONNX definition. Use this to drop dependency 'onnx_proto' to decrease compiled .js file size.\n */\nexport const enum DataType {\n  undefined = 0,\n  float = 1,\n  uint8 = 2,\n  int8 = 3,\n  uint16 = 4,\n  int16 = 5,\n  int32 = 6,\n  int64 = 7,\n  string = 8,\n  bool = 9,\n  float16 = 10,\n  double = 11,\n  uint32 = 12,\n  uint64 = 13,\n  complex64 = 14,\n  complex128 = 15,\n  bfloat16 = 16,\n\n  // 4-bit data-types\n  uint4 = 21,\n  int4 = 22,\n}\n\n/**\n * Map string tensor data to enum value\n */\nexport const tensorDataTypeStringToEnum = (type: string): DataType => {\n  switch (type) {\n    case 'int8':\n      return DataType.int8;\n    case 'uint8':\n      return DataType.uint8;\n    case 'bool':\n      return DataType.bool;\n    case 'int16':\n      return DataType.int16;\n    case 'uint16':\n      return DataType.uint16;\n    case 'int32':\n      return DataType.int32;\n    case 'uint32':\n      return DataType.uint32;\n    case 'float16':\n      return DataType.float16;\n    case 'float32':\n      return DataType.float;\n    case 'float64':\n      return DataType.double;\n    case 'string':\n      return DataType.string;\n    case 'int64':\n      return DataType.int64;\n    case 'uint64':\n      return DataType.uint64;\n    case 'int4':\n      return DataType.int4;\n    case 'uint4':\n      return DataType.uint4;\n\n    default:\n      throw new Error(`unsupported data type: ${type}`);\n  }\n};\n\n/**\n * Map enum value to string tensor data\n */\nexport const tensorDataTypeEnumToString = (typeProto: DataType): Tensor.Type => {\n  switch (typeProto) {\n    case DataType.int8:\n      return 'int8';\n    case DataType.uint8:\n      return 'uint8';\n    case DataType.bool:\n      return 'bool';\n    case DataType.int16:\n      return 'int16';\n    case DataType.uint16:\n      return 'uint16';\n    case DataType.int32:\n      return 'int32';\n    case DataType.uint32:\n      return 'uint32';\n    case DataType.float16:\n      return 'float16';\n    case DataType.float:\n      return 'float32';\n    case DataType.double:\n      return 'float64';\n    case DataType.string:\n      return 'string';\n    case DataType.int64:\n      return 'int64';\n    case DataType.uint64:\n      return 'uint64';\n    case DataType.int4:\n      return 'int4';\n    case DataType.uint4:\n      return 'uint4';\n\n    default:\n      throw new Error(`unsupported data type: ${typeProto}`);\n  }\n};\n\n/**\n * get tensor size in bytes by the given data type and dimensions\n * @returns size in integer or undefined if the data type is not supported\n */\nexport const calculateTensorSizeInBytes = (\n  dateType: number,\n  dimsOrSize: readonly number[] | number,\n): number | undefined => {\n  const elementSize = [\n    -1, // undefined = 0\n    4, // float = 1\n    1, // uint8 = 2\n    1, // int8 = 3\n    2, // uint16 = 4\n    2, // int16 = 5\n    4, // int32 = 6\n    8, // int64 = 7\n    -1, // string = 8\n    1, // bool = 9\n    2, // float16 = 10\n    8, // double = 11\n    4, // uint32 = 12\n    8, // uint64 = 13\n    -1, // complex64 = 14\n    -1, // complex128 = 15\n    -1, // bfloat16 = 16\n    -1, // FLOAT8E4M3FN = 17\n    -1, // FLOAT8E4M3FNUZ = 18\n    -1, // FLOAT8E5M2 = 19\n    -1, // FLOAT8E5M2FNUZ = 20\n    0.5, // uint4 = 21\n    0.5, // int4 = 22\n  ][dateType];\n\n  const size = typeof dimsOrSize === 'number' ? dimsOrSize : dimsOrSize.reduce((a, b) => a * b, 1);\n  return elementSize > 0 ? Math.ceil(size * elementSize) : undefined;\n};\n\n/**\n * get typed array constructor by the given tensor type\n */\nexport const tensorTypeToTypedArrayConstructor = (\n  type: Tensor.Type,\n):\n  | Float32ArrayConstructor\n  | Uint8ArrayConstructor\n  | Int8ArrayConstructor\n  | Uint16ArrayConstructor\n  | Int16ArrayConstructor\n  | Int32ArrayConstructor\n  | BigInt64ArrayConstructor\n  | Uint8ArrayConstructor\n  | Float64ArrayConstructor\n  | Uint32ArrayConstructor\n  | BigUint64ArrayConstructor => {\n  switch (type) {\n    case 'float16':\n      // allow Float16Array polyfill.\n      return typeof Float16Array !== 'undefined' && Float16Array.from ? Float16Array : Uint16Array;\n    case 'float32':\n      return Float32Array;\n    case 'uint8':\n      return Uint8Array;\n    case 'int8':\n      return Int8Array;\n    case 'uint16':\n      return Uint16Array;\n    case 'int16':\n      return Int16Array;\n    case 'int32':\n      return Int32Array;\n    case 'bool':\n      return Uint8Array;\n    case 'float64':\n      return Float64Array;\n    case 'uint32':\n      return Uint32Array;\n    case 'int64':\n      return BigInt64Array;\n    case 'uint64':\n      return BigUint64Array;\n    default:\n      throw new Error(`unsupported type: ${type}`);\n  }\n};\n\n/**\n * Map string log level to integer value\n */\nexport const logLevelStringToEnum = (logLevel?: 'verbose' | 'info' | 'warning' | 'error' | 'fatal'): number => {\n  switch (logLevel) {\n    case 'verbose':\n      return 0;\n    case 'info':\n      return 1;\n    case 'warning':\n      return 2;\n    case 'error':\n      return 3;\n    case 'fatal':\n      return 4;\n    default:\n      throw new Error(`unsupported logging level: ${logLevel}`);\n  }\n};\n\n/**\n * Check whether the given tensor type is supported by GPU buffer\n */\nexport const isGpuBufferSupportedType = (type: Tensor.Type): type is Tensor.GpuBufferDataTypes =>\n  type === 'float32' ||\n  type === 'float16' ||\n  type === 'int32' ||\n  type === 'int64' ||\n  type === 'uint32' ||\n  type === 'uint8' ||\n  type === 'bool' ||\n  type === 'uint4' ||\n  type === 'int4';\n\n/**\n * Check whether the given tensor type is supported by WebNN MLTensor\n */\nexport const isMLTensorSupportedType = (type: Tensor.Type): type is Tensor.MLTensorDataTypes =>\n  type === 'float32' ||\n  type === 'float16' ||\n  type === 'int32' ||\n  type === 'int64' ||\n  type === 'uint32' ||\n  type === 'uint64' ||\n  type === 'int8' ||\n  type === 'uint8' ||\n  type === 'bool' ||\n  type === 'uint4' ||\n  type === 'int4';\n\n/**\n * Map string data location to integer value\n */\nexport const dataLocationStringToEnum = (location: Tensor.DataLocation): number => {\n  switch (location) {\n    case 'none':\n      return 0;\n    case 'cpu':\n      return 1;\n    case 'cpu-pinned':\n      return 2;\n    case 'texture':\n      return 3;\n    case 'gpu-buffer':\n      return 4;\n    case 'ml-tensor':\n      return 5;\n    default:\n      throw new Error(`unsupported data location: ${location}`);\n  }\n};\n\n/**\n * Map integer data location to string value\n */\nexport const dataLocationEnumToString = (location: number): Tensor.DataLocation | undefined =>\n  (['none', 'cpu', 'cpu-pinned', 'texture', 'gpu-buffer', 'ml-tensor'] as const)[location];\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { isNode } from './wasm-utils-env';\n\n/**\n * Load a file into a Uint8Array.\n *\n * @param file - the file to load. Can be a URL/path, a Blob, an ArrayBuffer, or a Uint8Array.\n * @returns a Uint8Array containing the file data.\n */\nexport const loadFile = async (file: string | Blob | ArrayBufferLike | Uint8Array): Promise<Uint8Array> => {\n  if (typeof file === 'string') {\n    if (isNode) {\n      // load file into ArrayBuffer in Node.js\n      try {\n        const { readFile } = require('node:fs/promises');\n        return new Uint8Array(await readFile(file));\n      } catch (e) {\n        if (e.code === 'ERR_FS_FILE_TOO_LARGE') {\n          // file is too large, use fs.createReadStream instead\n          const { createReadStream } = require('node:fs');\n          const stream = createReadStream(file);\n          const chunks: Uint8Array[] = [];\n          for await (const chunk of stream) {\n            chunks.push(chunk);\n          }\n          return new Uint8Array(Buffer.concat(chunks));\n        }\n        throw e;\n      }\n    } else {\n      // load file into ArrayBuffer in browsers\n      const response = await fetch(file);\n      if (!response.ok) {\n        throw new Error(`failed to load external data file: ${file}`);\n      }\n      const contentLengthHeader = response.headers.get('Content-Length');\n      const fileSize = contentLengthHeader ? parseInt(contentLengthHeader, 10) : 0;\n      if (fileSize < 1073741824 /* 1GB */) {\n        // when Content-Length header is not set, we cannot determine the file size. We assume it is small enough to\n        // load into memory.\n        return new Uint8Array(await response.arrayBuffer());\n      } else {\n        // file is too large, use stream instead\n        if (!response.body) {\n          throw new Error(`failed to load external data file: ${file}, no response body.`);\n        }\n        const reader = response.body.getReader();\n\n        let buffer;\n        try {\n          // try to create ArrayBuffer directly\n          buffer = new ArrayBuffer(fileSize);\n        } catch (e) {\n          if (e instanceof RangeError) {\n            // use WebAssembly Memory to allocate larger ArrayBuffer\n            const pages = Math.ceil(fileSize / 65536);\n            buffer = new WebAssembly.Memory({ initial: pages, maximum: pages }).buffer;\n          } else {\n            throw e;\n          }\n        }\n\n        let offset = 0;\n        // eslint-disable-next-line no-constant-condition\n        while (true) {\n          const { done, value } = await reader.read();\n          if (done) {\n            break;\n          }\n          const chunkSize = value.byteLength;\n          const chunk = new Uint8Array(buffer, offset, chunkSize);\n          chunk.set(value);\n          offset += chunkSize;\n        }\n        return new Uint8Array(buffer, 0, fileSize);\n      }\n    }\n  } else if (file instanceof Blob) {\n    return new Uint8Array(await file.arrayBuffer());\n  } else if (file instanceof Uint8Array) {\n    return file;\n  } else {\n    return new Uint8Array(file);\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// WebNN API currently does not have a TypeScript definition file. This file is a workaround with types generated from\n// WebNN API specification.\n// https://github.com/webmachinelearning/webnn/issues/677\n/// <reference path=\"jsep/webnn/webnn.d.ts\" />\n\nimport { Env, InferenceSession, Tensor } from 'onnxruntime-common';\n\nimport {\n  SerializableInternalBuffer,\n  SerializableSessionMetadata,\n  SerializableTensorMetadata,\n  TensorMetadata,\n} from './proxy-messages';\nimport { setRunOptions } from './run-options';\nimport { setSessionOptions } from './session-options';\nimport {\n  calculateTensorSizeInBytes,\n  dataLocationStringToEnum,\n  isGpuBufferSupportedType,\n  isMLTensorSupportedType,\n  logLevelStringToEnum,\n  tensorDataTypeEnumToString,\n  tensorDataTypeStringToEnum,\n  tensorTypeToTypedArrayConstructor,\n} from './wasm-common';\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError } from './wasm-utils';\nimport { loadFile } from './wasm-utils-load-file';\n\n// #region Initializations\n\n/**\n * There are 4 different \"initialization\" steps for ORT. They happen in different places and different time.\n *\n * 1. JavaScript initialization for onnxruntime-common and onnxruntime-web.\n *    This is the first initialization step. In this step, onnxruntime-web calls onnxruntime-common's registerBackend()\n * function multiple times to register all the available backends. The backend registration is very fast. It only\n * registers the backend name with the uninitialized backend object. No heavy initialization is done in this step.\n *    Refer to web/lib/index.ts for the backend registration.\n *\n * 2. WebAssembly artifact initialization.\n *    This happens when any registered wasm backend is used for the first time (ie. `ort.InferenceSession.create()` is\n * called). In this step, onnxruntime-web does the followings:\n *     - create a proxy worker and make sure the proxy worker is ready to receive messages, if proxy is enabled.\n *     - perform feature detection, locate correct WebAssembly artifact path and call the Emscripten generated\n * JavaScript code to initialize the WebAssembly runtime.\n *         - if proxy is enabled, this step happens in the proxy worker using message 'init-wasm'.\n *         - downloading the 'ort-wasm{...}.wasm' file is done in this step.\n *         - if multi-thread is enabled, one or more webworker will be created to initialize the PThread threadpool.\n *\n * 3. ORT environment initialization.\n *    This happens after step 2. In this step, onnxruntime-web performs ONNX Runtime environment initialization.\n * Function `_OrtInit()` is called in this step.\n *     - if proxy is enabled, this step happens in the proxy worker using message 'init-ort'.\n *     - logging level (ort.env.logLevel) and thread number (ort.env.wasm.numThreads) are set in this step.\n *\n * 4. Session initialization.\n *    This happens when `ort.InferenceSession.create()` is called. Unlike the first 3 steps (they only called once),\n * this step will be done for each session. In this step, onnxruntime-web does the followings:\n *    If the parameter is a URL:\n *    - download the model data from the URL.\n *    - copy the model data to the WASM heap. (proxy: 'copy-from')\n *    - dereference the model buffer. This step allows the original ArrayBuffer to be garbage collected.\n *    - call `_OrtCreateSession()` to create the session. (proxy: 'create')\n *\n *    If the parameter is a Uint8Array object:\n *    - copy the model data to the WASM heap. (proxy: 'copy-from')\n *    - call `_OrtCreateSession()` to create the session. (proxy: 'create')\n *\n *\n */\n\n/**\n * initialize ORT environment.\n *\n * @param numThreads SetGlobalIntraOpNumThreads(numThreads)\n * @param loggingLevel CreateEnv(static_cast<OrtLoggingLevel>(logging_level))\n */\nconst initOrt = (numThreads: number, loggingLevel: number): void => {\n  const errorCode = getInstance()._OrtInit(numThreads, loggingLevel);\n  if (errorCode !== 0) {\n    checkLastError(\"Can't initialize onnxruntime.\");\n  }\n};\n\n/**\n * initialize runtime environment.\n * @param env passed in the environment config object.\n */\nexport const initRuntime = async (env: Env): Promise<void> => {\n  // init ORT\n  initOrt(env.wasm.numThreads!, logLevelStringToEnum(env.logLevel));\n};\n\n/**\n * perform EP specific initialization.\n *\n * @param env\n * @param epName\n */\nexport const initEp = async (env: Env, epName: string): Promise<void> => {\n  // initialize ASYNCIFY support\n  getInstance().asyncInit?.();\n\n  if (epName === 'webgpu' && BUILD_DEFS.USE_WEBGPU_EP) {\n    getInstance().webgpuInit!((device) => {\n      env.webgpu.device = device;\n    });\n  }\n\n  if (!BUILD_DEFS.DISABLE_JSEP) {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n    const initJsep = require('./jsep/init').init;\n\n    if (epName === 'webgpu' && !BUILD_DEFS.USE_WEBGPU_EP) {\n      // perform WebGPU availability check\n      if (typeof navigator === 'undefined' || !navigator.gpu) {\n        throw new Error('WebGPU is not supported in current environment');\n      }\n\n      let adapter = env.webgpu.adapter as GPUAdapter | null;\n      if (!adapter) {\n        // if adapter is not set, request a new adapter.\n        const powerPreference = env.webgpu.powerPreference;\n        if (\n          powerPreference !== undefined &&\n          powerPreference !== 'low-power' &&\n          powerPreference !== 'high-performance'\n        ) {\n          throw new Error(`Invalid powerPreference setting: \"${powerPreference}\"`);\n        }\n        const forceFallbackAdapter = env.webgpu.forceFallbackAdapter;\n        if (forceFallbackAdapter !== undefined && typeof forceFallbackAdapter !== 'boolean') {\n          throw new Error(`Invalid forceFallbackAdapter setting: \"${forceFallbackAdapter}\"`);\n        }\n        adapter = await navigator.gpu.requestAdapter({ powerPreference, forceFallbackAdapter });\n        if (!adapter) {\n          throw new Error(\n            'Failed to get GPU adapter. ' +\n              'You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.',\n          );\n        }\n      } else {\n        // if adapter is set, validate it.\n        if (\n          typeof adapter.limits !== 'object' ||\n          typeof adapter.features !== 'object' ||\n          typeof adapter.requestDevice !== 'function'\n        ) {\n          throw new Error('Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.');\n        }\n      }\n\n      await initJsep('webgpu', getInstance(), env, adapter);\n    }\n    if (epName === 'webnn') {\n      // perform WebNN availability check\n      if (typeof navigator === 'undefined' || !(navigator as unknown as { ml: unknown }).ml) {\n        throw new Error('WebNN is not supported in current environment');\n      }\n\n      await initJsep('webnn', getInstance(), env);\n    }\n  }\n};\n\n// #endregion Initializations\n\n/**\n * valid data locations for input/output tensors.\n */\ntype SupportedTensorDataLocationForInputOutput = 'cpu' | 'cpu-pinned' | 'gpu-buffer' | 'ml-tensor';\n\ntype IOBindingState = {\n  /**\n   * the handle of IO binding.\n   */\n  readonly handle: number;\n\n  /**\n   * the preferred location for each output tensor.\n   *\n   * value is one of 'cpu', 'cpu-pinned', 'gpu-buffer', 'ml-tensor'.\n   */\n  readonly outputPreferredLocations: readonly SupportedTensorDataLocationForInputOutput[];\n\n  /**\n   * enum value of the preferred location for each output tensor.\n   */\n  readonly outputPreferredLocationsEncoded: readonly number[];\n};\n\n/**\n *  tuple elements are: InferenceSession ID; inputNamesUTF8Encoded; outputNamesUTF8Encoded; bindingState\n */\ntype SessionMetadata = [\n  inferenceSessionId: number,\n  inputNamesUTF8Encoded: number[],\n  outputNamesUTF8Encoded: number[],\n  bindingState: IOBindingState | null,\n  enableGraphCapture: boolean,\n  inputOutputBound: boolean,\n];\n\nconst activeSessions = new Map<number, SessionMetadata>();\n\n/**\n * get the input/output count of the session.\n * @param sessionHandle the handle representing the session. should be non-zero.\n * @returns a tuple including 2 numbers, representing the input count and output count.\n */\nconst getSessionInputOutputCount = (sessionHandle: number): [number, number] => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const dataOffset = wasm.stackAlloc(2 * ptrSize);\n    const errorCode = wasm._OrtGetInputOutputCount(sessionHandle, dataOffset, dataOffset + ptrSize);\n    if (errorCode !== 0) {\n      checkLastError(\"Can't get session input/output count.\");\n    }\n    const type = ptrSize === 4 ? 'i32' : 'i64';\n    return [Number(wasm.getValue(dataOffset, type)), Number(wasm.getValue(dataOffset + ptrSize, type))];\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\nconst getSessionInputOutputMetadata = (\n  sessionHandle: number,\n  index: number,\n): [nameOffset: number, elementType: number, dims?: Array<number | string>] => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n  let metadataOffset = 0;\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const dataOffset = wasm.stackAlloc(2 * ptrSize);\n    const errorCode = wasm._OrtGetInputOutputMetadata(sessionHandle, index, dataOffset, dataOffset + ptrSize);\n    if (errorCode !== 0) {\n      checkLastError(\"Can't get session input/output metadata.\");\n    }\n    const nameOffset = Number(wasm.getValue(dataOffset, '*'));\n    metadataOffset = Number(wasm.getValue(dataOffset + ptrSize, '*'));\n    // get element type\n    const elementType = wasm.HEAP32[metadataOffset / 4];\n    if (elementType === 0) {\n      return [nameOffset, 0]; // non-tensor\n    }\n\n    // get dims count\n    const dimsCount = wasm.HEAPU32[metadataOffset / 4 + 1];\n    // get dims\n    const dims: Array<number | string> = [];\n    for (let i = 0; i < dimsCount; i++) {\n      const symbolicDimNameOffset = Number(wasm.getValue(metadataOffset + 8 + i * ptrSize, '*'));\n      dims.push(\n        symbolicDimNameOffset !== 0\n          ? wasm.UTF8ToString(symbolicDimNameOffset)\n          : Number(wasm.getValue(metadataOffset + 8 + (i + dimsCount) * ptrSize, '*')),\n      );\n    }\n    return [nameOffset, elementType, dims];\n  } finally {\n    wasm.stackRestore(stack);\n    if (metadataOffset !== 0) {\n      wasm._OrtFree(metadataOffset);\n    }\n  }\n};\n\n/**\n * allocate the memory and memcpy the external buffer.\n *\n * @param model - the external buffer containing the model data. Must not be the same buffer as the WASM heap.\n * @returns a 2-elements tuple - the pointer and size of the allocated buffer\n */\nexport const copyFromExternalBuffer = (model: Uint8Array): [number, number] => {\n  const wasm = getInstance();\n  const modelDataOffset = wasm._malloc(model.byteLength);\n  if (modelDataOffset === 0) {\n    throw new Error(`Can't create a session. failed to allocate a buffer of size ${model.byteLength}.`);\n  }\n  wasm.HEAPU8.set(model, modelDataOffset);\n  return [modelDataOffset, model.byteLength];\n};\n\n/**\n * create an inference session from a model data buffer.\n *\n * @param modelData - either a Uint8Array object representing the model data, or a 2-elements tuple containing the\n *     pointer and size of the model data buffer.\n * @param options an optional session options object.\n * @returns a 3-elements tuple containing [session handle, input names, output names]\n */\nexport const createSession = async (\n  modelData: Uint8Array | SerializableInternalBuffer,\n  options?: InferenceSession.SessionOptions,\n): Promise<SerializableSessionMetadata> => {\n  let modelDataOffset: number, modelDataLength: number;\n  const wasm = getInstance();\n\n  if (Array.isArray(modelData)) {\n    // if model data is an array, it must be a 2-elements tuple containing the pointer and size of the model data\n    [modelDataOffset, modelDataLength] = modelData;\n  } else if (modelData.buffer === wasm.HEAPU8.buffer) {\n    // if model data uses the same buffer as the WASM heap, we don't need to copy it.\n    [modelDataOffset, modelDataLength] = [modelData.byteOffset, modelData.byteLength];\n  } else {\n    // otherwise, copy the model data to the WASM heap.\n    [modelDataOffset, modelDataLength] = copyFromExternalBuffer(modelData);\n  }\n\n  let sessionHandle = 0;\n  let sessionOptionsHandle = 0;\n  let ioBindingHandle = 0;\n  let allocs: number[] = [];\n  const inputNamesUTF8Encoded = [];\n  const outputNamesUTF8Encoded = [];\n\n  try {\n    [sessionOptionsHandle, allocs] = await setSessionOptions(options);\n\n    if (options?.externalData && wasm.mountExternalData) {\n      const loadingPromises = [];\n      for (const file of options.externalData) {\n        const path = typeof file === 'string' ? file : file.path;\n        loadingPromises.push(\n          loadFile(typeof file === 'string' ? file : file.data).then((data) => {\n            wasm.mountExternalData(path, data);\n          }),\n        );\n      }\n\n      // wait for all external data files to be loaded\n      await Promise.all(loadingPromises);\n    }\n\n    for (const provider of options?.executionProviders ?? []) {\n      const providerName = typeof provider === 'string' ? provider : provider.name;\n      if (providerName === 'webnn') {\n        wasm.shouldTransferToMLTensor = false;\n        if (typeof provider !== 'string') {\n          const webnnOptions = provider as InferenceSession.WebNNExecutionProviderOption;\n          const context = (webnnOptions as InferenceSession.WebNNOptionsWithMLContext)?.context;\n          const gpuDevice = (webnnOptions as InferenceSession.WebNNOptionsWebGpu)?.gpuDevice;\n          const deviceType = (webnnOptions as InferenceSession.WebNNContextOptions)?.deviceType;\n          const powerPreference = (webnnOptions as InferenceSession.WebNNContextOptions)?.powerPreference;\n          if (context) {\n            wasm.currentContext = context as MLContext;\n          } else if (gpuDevice) {\n            wasm.currentContext = await wasm.webnnCreateMLContext!(gpuDevice);\n          } else {\n            wasm.currentContext = await wasm.webnnCreateMLContext!({ deviceType, powerPreference });\n          }\n        } else {\n          wasm.currentContext = await wasm.webnnCreateMLContext!();\n        }\n        break;\n      }\n    }\n\n    sessionHandle = await wasm._OrtCreateSession(modelDataOffset, modelDataLength, sessionOptionsHandle);\n    wasm.webgpuOnCreateSession?.(sessionHandle);\n    if (sessionHandle === 0) {\n      checkLastError(\"Can't create a session.\");\n    }\n\n    wasm.jsepOnCreateSession?.();\n\n    // clear current MLContext after session creation\n    if (wasm.currentContext) {\n      wasm.webnnRegisterMLContext!(sessionHandle, wasm.currentContext);\n      wasm.currentContext = undefined;\n      wasm.shouldTransferToMLTensor = true;\n    }\n\n    const [inputCount, outputCount] = getSessionInputOutputCount(sessionHandle);\n\n    const enableGraphCapture = !!options?.enableGraphCapture;\n\n    const inputNames = [];\n    const outputNames = [];\n    const inputMetadata: InferenceSession.ValueMetadata[] = [];\n    const outputMetadata: InferenceSession.ValueMetadata[] = [];\n    const outputPreferredLocations: SupportedTensorDataLocationForInputOutput[] = [];\n    for (let i = 0; i < inputCount; i++) {\n      const [nameOffset, elementType, shape] = getSessionInputOutputMetadata(sessionHandle, i);\n      if (nameOffset === 0) {\n        checkLastError(\"Can't get an input name.\");\n      }\n      inputNamesUTF8Encoded.push(nameOffset);\n      const name = wasm.UTF8ToString(nameOffset);\n      inputNames.push(name);\n      inputMetadata.push(\n        elementType === 0\n          ? { name, isTensor: false }\n          : { name, isTensor: true, type: tensorDataTypeEnumToString(elementType), shape: shape! },\n      );\n    }\n    for (let i = 0; i < outputCount; i++) {\n      const [nameOffset, elementType, shape] = getSessionInputOutputMetadata(sessionHandle, i + inputCount);\n      if (nameOffset === 0) {\n        checkLastError(\"Can't get an output name.\");\n      }\n      outputNamesUTF8Encoded.push(nameOffset);\n      const nameString = wasm.UTF8ToString(nameOffset);\n      outputNames.push(nameString);\n      outputMetadata.push(\n        elementType === 0\n          ? { name: nameString, isTensor: false }\n          : { name: nameString, isTensor: true, type: tensorDataTypeEnumToString(elementType), shape: shape! },\n      );\n\n      if (!BUILD_DEFS.DISABLE_JSEP) {\n        if (enableGraphCapture && options?.preferredOutputLocation === undefined) {\n          outputPreferredLocations.push('gpu-buffer');\n          continue;\n        }\n        const location =\n          typeof options?.preferredOutputLocation === 'string'\n            ? options.preferredOutputLocation\n            : (options?.preferredOutputLocation?.[nameString] ?? 'cpu');\n        if (location !== 'cpu' && location !== 'cpu-pinned' && location !== 'gpu-buffer' && location !== 'ml-tensor') {\n          throw new Error(`Not supported preferred output location: ${location}.`);\n        }\n        if (enableGraphCapture && location !== 'gpu-buffer') {\n          throw new Error(\n            `Not supported preferred output location: ${location}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`,\n          );\n        }\n        outputPreferredLocations.push(location);\n      }\n    }\n\n    // use IO binding only when at least one output is preferred to be on GPU.\n    let bindingState: IOBindingState | null = null;\n    if (!BUILD_DEFS.DISABLE_JSEP && outputPreferredLocations.some((l) => l === 'gpu-buffer' || l === 'ml-tensor')) {\n      ioBindingHandle = wasm._OrtCreateBinding(sessionHandle);\n      if (ioBindingHandle === 0) {\n        checkLastError(\"Can't create IO binding.\");\n      }\n\n      bindingState = {\n        handle: ioBindingHandle,\n        outputPreferredLocations,\n        outputPreferredLocationsEncoded: outputPreferredLocations.map((l) => dataLocationStringToEnum(l)),\n      };\n    }\n\n    activeSessions.set(sessionHandle, [\n      sessionHandle,\n      inputNamesUTF8Encoded,\n      outputNamesUTF8Encoded,\n      bindingState,\n      enableGraphCapture,\n      false,\n    ]);\n    return [sessionHandle, inputNames, outputNames, inputMetadata, outputMetadata];\n  } catch (e) {\n    inputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n    outputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n\n    if (ioBindingHandle !== 0) {\n      if (wasm._OrtReleaseBinding(ioBindingHandle) !== 0) {\n        checkLastError(\"Can't release IO binding.\");\n      }\n    }\n\n    if (sessionHandle !== 0) {\n      if (wasm._OrtReleaseSession(sessionHandle) !== 0) {\n        checkLastError(\"Can't release session.\");\n      }\n    }\n    throw e;\n  } finally {\n    wasm._free(modelDataOffset);\n    if (sessionOptionsHandle !== 0) {\n      if (wasm._OrtReleaseSessionOptions(sessionOptionsHandle) !== 0) {\n        checkLastError(\"Can't release session options.\");\n      }\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n\n    // unmount external data if necessary\n    wasm.unmountExternalData?.();\n  }\n};\n\nexport const releaseSession = (sessionId: number): void => {\n  const wasm = getInstance();\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error(`cannot release session. invalid session id: ${sessionId}`);\n  }\n  const [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture] = session;\n\n  if (ioBindingState) {\n    if (enableGraphCapture) {\n      if (wasm._OrtClearBoundOutputs(ioBindingState.handle) !== 0) {\n        checkLastError(\"Can't clear bound outputs.\");\n      }\n    }\n    if (wasm._OrtReleaseBinding(ioBindingState.handle) !== 0) {\n      checkLastError(\"Can't release IO binding.\");\n    }\n  }\n\n  wasm.jsepOnReleaseSession?.(sessionId);\n  wasm.webnnOnReleaseSession?.(sessionId);\n  wasm.webgpuOnReleaseSession?.(sessionId);\n\n  inputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n  outputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n  if (wasm._OrtReleaseSession(sessionHandle) !== 0) {\n    checkLastError(\"Can't release session.\");\n  }\n  activeSessions.delete(sessionId);\n};\n\nexport const prepareInputOutputTensor = async (\n  tensor: TensorMetadata | null,\n  tensorHandles: number[],\n  allocs: number[],\n  sessionId: number,\n  tensorNameUTF8Encoded: number,\n  index: number,\n  enableGraphCapture = false,\n): Promise<void> => {\n  if (!tensor) {\n    tensorHandles.push(0);\n    return;\n  }\n\n  const wasm = getInstance();\n  const ptrSize = wasm.PTR_SIZE;\n\n  const dataType = tensor[0];\n  const dims = tensor[1];\n  const location = tensor[3];\n  let actualLocation = location;\n\n  let rawData: number;\n  let dataByteLength: number;\n\n  if (dataType === 'string' && (location === 'gpu-buffer' || location === 'ml-tensor')) {\n    throw new Error('String tensor is not supported on GPU.');\n  }\n\n  if (enableGraphCapture && location !== 'gpu-buffer') {\n    throw new Error(\n      `External buffer must be provided for input/output index ${index} when enableGraphCapture is true.`,\n    );\n  }\n\n  if (location === 'gpu-buffer') {\n    const gpuBuffer = tensor[2].gpuBuffer;\n    dataByteLength = calculateTensorSizeInBytes(tensorDataTypeStringToEnum(dataType), dims)!;\n\n    if (BUILD_DEFS.USE_WEBGPU_EP) {\n      const registerBuffer = wasm.webgpuRegisterBuffer;\n      if (!registerBuffer) {\n        throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');\n      }\n\n      rawData = registerBuffer(gpuBuffer, sessionId);\n    } else {\n      const registerBuffer = wasm.jsepRegisterBuffer;\n      if (!registerBuffer) {\n        throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');\n      }\n      rawData = registerBuffer(sessionId, index, gpuBuffer, dataByteLength);\n    }\n  } else if (location === 'ml-tensor') {\n    const mlTensor = tensor[2].mlTensor as MLTensor;\n    dataByteLength = calculateTensorSizeInBytes(tensorDataTypeStringToEnum(dataType), dims)!;\n\n    const registerMLTensor = wasm.webnnRegisterMLTensor;\n    if (!registerMLTensor) {\n      throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');\n    }\n    rawData = registerMLTensor(sessionId, mlTensor, tensorDataTypeStringToEnum(dataType), dims);\n  } else {\n    const data = tensor[2];\n\n    if (Array.isArray(data)) {\n      // string tensor\n      dataByteLength = ptrSize * data.length;\n      rawData = wasm._malloc(dataByteLength);\n      allocs.push(rawData);\n      for (let i = 0; i < data.length; i++) {\n        if (typeof data[i] !== 'string') {\n          throw new TypeError(`tensor data at index ${i} is not a string`);\n        }\n        wasm.setValue(rawData + i * ptrSize, allocWasmString(data[i], allocs), '*');\n      }\n    } else {\n      const isGraphInput = wasm.webnnIsGraphInput;\n      if (dataType !== 'string' && isGraphInput) {\n        const tensorName = wasm.UTF8ToString(tensorNameUTF8Encoded);\n        // Promote the tensor to 'ml-tensor' if it is a graph input.\n        if (isGraphInput(sessionId, tensorName)) {\n          const dataTypeEnum = tensorDataTypeStringToEnum(dataType);\n          dataByteLength = calculateTensorSizeInBytes(dataTypeEnum, dims)!;\n          actualLocation = 'ml-tensor';\n          const createTemporaryTensor = wasm.webnnCreateTemporaryTensor;\n          const uploadTensor = wasm.webnnUploadTensor;\n          if (!createTemporaryTensor || !uploadTensor) {\n            throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');\n          }\n          const tensorId = await createTemporaryTensor(sessionId, dataTypeEnum, dims as number[]);\n          uploadTensor(tensorId, new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n          rawData = tensorId;\n        } else {\n          dataByteLength = data.byteLength;\n          rawData = wasm._malloc(dataByteLength);\n          allocs.push(rawData);\n          wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), rawData);\n        }\n      } else {\n        dataByteLength = data.byteLength;\n        rawData = wasm._malloc(dataByteLength);\n        allocs.push(rawData);\n        wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), rawData);\n      }\n    }\n  }\n\n  const stack = wasm.stackSave();\n  const dimsOffset = wasm.stackAlloc(4 * dims.length);\n  try {\n    dims.forEach((d, index) => wasm.setValue(dimsOffset + index * ptrSize, d, ptrSize === 4 ? 'i32' : 'i64'));\n    const tensor = wasm._OrtCreateTensor(\n      tensorDataTypeStringToEnum(dataType),\n      rawData,\n      dataByteLength,\n      dimsOffset,\n      dims.length,\n      dataLocationStringToEnum(actualLocation),\n    );\n    if (tensor === 0) {\n      checkLastError(`Can't create tensor for input/output. session=${sessionId}, index=${index}.`);\n    }\n    tensorHandles.push(tensor);\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\n/**\n * perform inference run\n */\nexport const run = async (\n  sessionId: number,\n  inputIndices: number[],\n  inputTensors: TensorMetadata[],\n  outputIndices: number[],\n  outputTensors: Array<TensorMetadata | null>,\n  options: InferenceSession.RunOptions,\n): Promise<TensorMetadata[]> => {\n  const wasm = getInstance();\n  const ptrSize = wasm.PTR_SIZE;\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error(`cannot run inference. invalid session id: ${sessionId}`);\n  }\n  const sessionHandle = session[0];\n  const inputNamesUTF8Encoded = session[1];\n  const outputNamesUTF8Encoded = session[2];\n  const ioBindingState = session[3];\n  const enableGraphCapture = session[4];\n  const inputOutputBound = session[5];\n\n  const inputCount = inputIndices.length;\n  const outputCount = outputIndices.length;\n\n  let runOptionsHandle = 0;\n  let runOptionsAllocs: number[] = [];\n\n  const inputTensorHandles: number[] = [];\n  const outputTensorHandles: number[] = [];\n  const inputOutputAllocs: number[] = [];\n\n  const beforeRunStack = wasm.stackSave();\n  const inputValuesOffset = wasm.stackAlloc(inputCount * ptrSize);\n  const inputNamesOffset = wasm.stackAlloc(inputCount * ptrSize);\n  const outputValuesOffset = wasm.stackAlloc(outputCount * ptrSize);\n  const outputNamesOffset = wasm.stackAlloc(outputCount * ptrSize);\n\n  try {\n    [runOptionsHandle, runOptionsAllocs] = setRunOptions(options);\n\n    // create input tensors\n    for (let i = 0; i < inputCount; i++) {\n      await prepareInputOutputTensor(\n        inputTensors[i],\n        inputTensorHandles,\n        inputOutputAllocs,\n        sessionId,\n        inputNamesUTF8Encoded[inputIndices[i]],\n        inputIndices[i],\n        enableGraphCapture,\n      );\n    }\n\n    // create output tensors\n    for (let i = 0; i < outputCount; i++) {\n      await prepareInputOutputTensor(\n        outputTensors[i],\n        outputTensorHandles,\n        inputOutputAllocs,\n        sessionId,\n        outputNamesUTF8Encoded[outputIndices[i]],\n        inputCount + outputIndices[i],\n        enableGraphCapture,\n      );\n    }\n\n    for (let i = 0; i < inputCount; i++) {\n      wasm.setValue(inputValuesOffset + i * ptrSize, inputTensorHandles[i], '*');\n      wasm.setValue(inputNamesOffset + i * ptrSize, inputNamesUTF8Encoded[inputIndices[i]], '*');\n    }\n    for (let i = 0; i < outputCount; i++) {\n      wasm.setValue(outputValuesOffset + i * ptrSize, outputTensorHandles[i], '*');\n      wasm.setValue(outputNamesOffset + i * ptrSize, outputNamesUTF8Encoded[outputIndices[i]], '*');\n    }\n\n    if (!BUILD_DEFS.DISABLE_JSEP && ioBindingState && !inputOutputBound) {\n      const { handle, outputPreferredLocations, outputPreferredLocationsEncoded } = ioBindingState;\n\n      if (inputNamesUTF8Encoded.length !== inputCount) {\n        throw new Error(\n          `input count from feeds (${inputCount}) is expected to be always equal to model's input count (${inputNamesUTF8Encoded.length}).`,\n        );\n      }\n\n      // process inputs\n      for (let i = 0; i < inputCount; i++) {\n        const index = inputIndices[i];\n        const errorCode = await wasm._OrtBindInput(handle, inputNamesUTF8Encoded[index], inputTensorHandles[i]);\n        if (errorCode !== 0) {\n          checkLastError(`Can't bind input[${i}] for session=${sessionId}.`);\n        }\n      }\n\n      // process pre-allocated outputs\n      for (let i = 0; i < outputCount; i++) {\n        const index = outputIndices[i];\n        const location = outputTensors[i]?.[3]; // undefined means output is not pre-allocated.\n\n        if (location) {\n          // output is pre-allocated. bind the tensor.\n          const errorCode = wasm._OrtBindOutput(handle, outputNamesUTF8Encoded[index], outputTensorHandles[i], 0);\n          if (errorCode !== 0) {\n            checkLastError(`Can't bind pre-allocated output[${i}] for session=${sessionId}.`);\n          }\n        } else {\n          // output is not pre-allocated. reset preferred location.\n          const errorCode = wasm._OrtBindOutput(\n            handle,\n            outputNamesUTF8Encoded[index],\n            0,\n            outputPreferredLocationsEncoded[index],\n          );\n          if (errorCode !== 0) {\n            checkLastError(`Can't bind output[${i}] to ${outputPreferredLocations[i]} for session=${sessionId}.`);\n          }\n        }\n      }\n      activeSessions.set(sessionId, [\n        sessionHandle,\n        inputNamesUTF8Encoded,\n        outputNamesUTF8Encoded,\n        ioBindingState,\n        enableGraphCapture,\n        true,\n      ]);\n    }\n\n    wasm.jsepOnRunStart?.(sessionHandle);\n    wasm.webnnOnRunStart?.(sessionHandle);\n\n    let errorCode: number;\n    if (!BUILD_DEFS.DISABLE_JSEP && ioBindingState) {\n      errorCode = await wasm._OrtRunWithBinding(\n        sessionHandle,\n        ioBindingState.handle,\n        outputCount,\n        outputValuesOffset,\n        runOptionsHandle,\n      );\n    } else {\n      errorCode = await wasm._OrtRun(\n        sessionHandle,\n        inputNamesOffset,\n        inputValuesOffset,\n        inputCount,\n        outputNamesOffset,\n        outputCount,\n        outputValuesOffset,\n        runOptionsHandle,\n      );\n    }\n\n    if (errorCode !== 0) {\n      checkLastError('failed to call OrtRun().');\n    }\n\n    const output: TensorMetadata[] = [];\n\n    for (let i = 0; i < outputCount; i++) {\n      const tensor = Number(wasm.getValue(outputValuesOffset + i * ptrSize, '*'));\n      if (tensor === outputTensorHandles[i]) {\n        // output tensor is pre-allocated. no need to copy data.\n        output.push(outputTensors[i]!);\n        continue;\n      }\n\n      const beforeGetTensorDataStack = wasm.stackSave();\n      // stack allocate 4 pointer value\n      const tensorDataOffset = wasm.stackAlloc(4 * ptrSize);\n\n      let keepOutputTensor = false;\n      let type: Tensor.Type | undefined,\n        dataOffset = 0;\n      try {\n        const errorCode = wasm._OrtGetTensorData(\n          tensor,\n          tensorDataOffset,\n          tensorDataOffset + ptrSize,\n          tensorDataOffset + 2 * ptrSize,\n\n          tensorDataOffset + 3 * ptrSize,\n        );\n        if (errorCode !== 0) {\n          checkLastError(`Can't access output tensor data on index ${i}.`);\n        }\n        const valueType = ptrSize === 4 ? 'i32' : 'i64';\n        const dataType = Number(wasm.getValue(tensorDataOffset, valueType));\n        dataOffset = wasm.getValue(tensorDataOffset + ptrSize, '*');\n        const dimsOffset = wasm.getValue(tensorDataOffset + ptrSize * 2, '*');\n        const dimsLength = Number(wasm.getValue(tensorDataOffset + ptrSize * 3, valueType));\n        const dims = [];\n        for (let i = 0; i < dimsLength; i++) {\n          dims.push(Number(wasm.getValue(dimsOffset + i * ptrSize, valueType)));\n        }\n        if (wasm._OrtFree(dimsOffset) !== 0) {\n          checkLastError(\"Can't free memory for tensor dims.\");\n        }\n        const size = dims.reduce((a, b) => a * b, 1);\n        type = tensorDataTypeEnumToString(dataType);\n\n        const preferredLocation = ioBindingState?.outputPreferredLocations[outputIndices[i]];\n\n        if (type === 'string') {\n          if (preferredLocation === 'gpu-buffer' || preferredLocation === 'ml-tensor') {\n            throw new Error('String tensor is not supported on GPU.');\n          }\n          const stringData: string[] = [];\n          for (let i = 0; i < size; i++) {\n            const offset = wasm.getValue(dataOffset + i * ptrSize, '*');\n            const nextOffset = wasm.getValue(dataOffset + (i + 1) * ptrSize, '*');\n            const maxBytesToRead = i === size - 1 ? undefined : nextOffset - offset;\n            stringData.push(wasm.UTF8ToString(offset, maxBytesToRead));\n          }\n          output.push([type, dims, stringData, 'cpu']);\n        } else {\n          // If a certain output's preferred location is GPU but the tensor is empty, we still need to create a CPU\n          // tensor for it. There is no mapping GPU buffer for an empty tensor.\n          if (preferredLocation === 'gpu-buffer' && size > 0) {\n            const getBuffer = BUILD_DEFS.USE_WEBGPU_EP ? wasm.webgpuGetBuffer : wasm.jsepGetBuffer;\n            if (!getBuffer) {\n              throw new Error('preferredLocation \"gpu-buffer\" is not supported without using WebGPU.');\n            }\n            const gpuBuffer = getBuffer(dataOffset);\n            const bufferSize = calculateTensorSizeInBytes(dataType, size);\n            if (bufferSize === undefined || !isGpuBufferSupportedType(type)) {\n              throw new Error(`Unsupported data type: ${type}`);\n            }\n\n            // do not release the tensor right now. it will be released when user calls tensor.dispose().\n            keepOutputTensor = true;\n\n            if (BUILD_DEFS.USE_WEBGPU_EP) {\n              wasm.webgpuRegisterBuffer!(gpuBuffer, sessionId, dataOffset);\n              const downloadDataFunction = wasm.webgpuCreateDownloader!(gpuBuffer, bufferSize, sessionId);\n              output.push([\n                type,\n                dims,\n                {\n                  gpuBuffer,\n                  download: async () => {\n                    const arrayBuffer = await downloadDataFunction();\n                    const data = new (tensorTypeToTypedArrayConstructor(type!))(arrayBuffer);\n                    return data as Tensor.DataTypeMap[Tensor.GpuBufferDataTypes];\n                  },\n                  dispose: () => {\n                    if (wasm._OrtReleaseTensor(tensor) !== 0) {\n                      checkLastError(\"Can't release tensor.\");\n                    }\n                  },\n                },\n                'gpu-buffer',\n              ]);\n            } else {\n              output.push([\n                type,\n                dims,\n                {\n                  gpuBuffer,\n                  download: wasm.jsepCreateDownloader!(gpuBuffer, bufferSize, type),\n                  dispose: () => {\n                    if (wasm._OrtReleaseTensor(tensor) !== 0) {\n                      checkLastError(\"Can't release tensor.\");\n                    }\n                  },\n                },\n                'gpu-buffer',\n              ]);\n            }\n          } else if (preferredLocation === 'ml-tensor' && size > 0) {\n            const ensureTensor = wasm.webnnEnsureTensor;\n            const isInt64Supported = wasm.webnnIsInt64Supported;\n            if (!ensureTensor || !isInt64Supported) {\n              throw new Error('preferredLocation \"ml-tensor\" is not supported without using WebNN.');\n            }\n            const tensorSize = calculateTensorSizeInBytes(dataType, size);\n            if (tensorSize === undefined || !isMLTensorSupportedType(type)) {\n              throw new Error(`Unsupported data type: ${type}`);\n            }\n            if (type === 'int64' && !isInt64Supported(sessionId)) {\n              throw new Error(\n                `preferredLocation \"ml-tensor\" for int64 output is not supported by current WebNN Context.`,\n              );\n            }\n\n            // If the graph has been partitioned, the output tensor may have not been created. For this reason, we use\n            // ensureTensor to get/create the MLTensor. In which case, we don't need to copy the data if a new tensor\n            // has been created.\n            const mlTensor = await ensureTensor(sessionId, dataOffset, dataType, dims, false);\n\n            // do not release the tensor right now. it will be released when user calls tensor.dispose().\n            keepOutputTensor = true;\n\n            output.push([\n              type,\n              dims,\n              {\n                mlTensor,\n                download: wasm.webnnCreateMLTensorDownloader!(dataOffset, type),\n                dispose: () => {\n                  wasm.webnnReleaseTensorId!(dataOffset);\n                  wasm._OrtReleaseTensor(tensor);\n                },\n              },\n              'ml-tensor',\n            ]);\n          } else {\n            const typedArrayConstructor = tensorTypeToTypedArrayConstructor(type);\n            const data = new typedArrayConstructor(size);\n            new Uint8Array(data.buffer, data.byteOffset, data.byteLength).set(\n              wasm.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength),\n            );\n            output.push([type, dims, data, 'cpu']);\n          }\n        }\n      } finally {\n        wasm.stackRestore(beforeGetTensorDataStack);\n        if (type === 'string' && dataOffset) {\n          wasm._free(dataOffset);\n        }\n        if (!keepOutputTensor) {\n          wasm._OrtReleaseTensor(tensor);\n        }\n        wasm.webnnOnRunEnd?.(sessionHandle);\n      }\n    }\n\n    if (ioBindingState && !enableGraphCapture) {\n      if (wasm._OrtClearBoundOutputs(ioBindingState.handle) !== 0) {\n        checkLastError(\"Can't clear bound outputs.\");\n      }\n      activeSessions.set(sessionId, [\n        sessionHandle,\n        inputNamesUTF8Encoded,\n        outputNamesUTF8Encoded,\n        ioBindingState,\n        enableGraphCapture,\n        false,\n      ]);\n    }\n    return output;\n  } finally {\n    wasm.stackRestore(beforeRunStack);\n\n    if (BUILD_DEFS.USE_WEBGPU_EP) {\n      inputTensors.forEach((t) => {\n        if (t && t[3] === 'gpu-buffer') {\n          wasm.webgpuUnregisterBuffer!(t[2].gpuBuffer);\n        }\n      });\n      outputTensors.forEach((t) => {\n        if (t && t[3] === 'gpu-buffer') {\n          wasm.webgpuUnregisterBuffer!(t[2].gpuBuffer);\n        }\n      });\n    }\n    inputTensorHandles.forEach((v) => wasm._OrtReleaseTensor(v));\n    outputTensorHandles.forEach((v) => wasm._OrtReleaseTensor(v));\n    inputOutputAllocs.forEach((p) => wasm._free(p));\n\n    if (runOptionsHandle !== 0) {\n      wasm._OrtReleaseRunOptions(runOptionsHandle);\n    }\n    runOptionsAllocs.forEach((p) => wasm._free(p));\n  }\n};\n\n/**\n * end profiling\n */\nexport const endProfiling = (sessionId: number): void => {\n  const wasm = getInstance();\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error('invalid session id');\n  }\n  const sessionHandle = session[0];\n\n  // profile file name is not used yet, but it must be freed.\n  const profileFileName = wasm._OrtEndProfiling(sessionHandle);\n  if (profileFileName === 0) {\n    checkLastError(\"Can't get an profile file name.\");\n  }\n  wasm._OrtFree(profileFileName);\n};\n\nexport const extractTransferableBuffers = (tensors: readonly SerializableTensorMetadata[]): ArrayBufferLike[] => {\n  const buffers: ArrayBufferLike[] = [];\n  for (const tensor of tensors) {\n    const data = tensor[2];\n    if (!Array.isArray(data) && 'buffer' in data) {\n      buffers.push(data.buffer);\n    }\n  }\n  return buffers;\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { env, InferenceSession } from 'onnxruntime-common';\n\nimport {\n  OrtWasmMessage,\n  SerializableInternalBuffer,\n  SerializableSessionMetadata,\n  SerializableTensorMetadata,\n  TensorMetadata,\n} from './proxy-messages';\nimport * as core from './wasm-core-impl';\nimport { initializeWebAssembly } from './wasm-factory';\nimport {\n  importProxyWorker,\n  inferWasmPathPrefixFromScriptSrc,\n  isEsmImportMetaUrlHardcodedAsFileUri,\n} from './wasm-utils-import';\n\nconst isProxy = (): boolean => !!env.wasm.proxy && typeof document !== 'undefined';\nlet proxyWorker: Worker | undefined;\nlet initializing = false;\nlet initialized = false;\nlet aborted = false;\nlet temporaryObjectUrl: string | undefined;\n\ntype PromiseCallbacks<T = void> = [resolve: (result: T) => void, reject: (reason: unknown) => void];\nlet initWasmCallbacks: PromiseCallbacks;\nconst queuedCallbacks: Map<OrtWasmMessage['type'], Array<PromiseCallbacks<unknown>>> = new Map();\n\nconst enqueueCallbacks = (type: OrtWasmMessage['type'], callbacks: PromiseCallbacks<unknown>): void => {\n  const queue = queuedCallbacks.get(type);\n  if (queue) {\n    queue.push(callbacks);\n  } else {\n    queuedCallbacks.set(type, [callbacks]);\n  }\n};\n\nconst ensureWorker = (): void => {\n  if (initializing || !initialized || aborted || !proxyWorker) {\n    throw new Error('worker not ready');\n  }\n};\n\nconst onProxyWorkerMessage = (ev: MessageEvent<OrtWasmMessage>): void => {\n  switch (ev.data.type) {\n    case 'init-wasm':\n      initializing = false;\n      if (ev.data.err) {\n        aborted = true;\n        initWasmCallbacks[1](ev.data.err);\n      } else {\n        initialized = true;\n        initWasmCallbacks[0]();\n      }\n      if (temporaryObjectUrl) {\n        URL.revokeObjectURL(temporaryObjectUrl);\n        temporaryObjectUrl = undefined;\n      }\n      break;\n    case 'init-ep':\n    case 'copy-from':\n    case 'create':\n    case 'release':\n    case 'run':\n    case 'end-profiling': {\n      const callbacks = queuedCallbacks.get(ev.data.type)!;\n      if (ev.data.err) {\n        callbacks.shift()![1](ev.data.err);\n      } else {\n        callbacks.shift()![0](ev.data.out!);\n      }\n      break;\n    }\n    default:\n  }\n};\n\nexport const initializeWebAssemblyAndOrtRuntime = async (): Promise<void> => {\n  if (initialized) {\n    return;\n  }\n  if (initializing) {\n    throw new Error(\"multiple calls to 'initWasm()' detected.\");\n  }\n  if (aborted) {\n    throw new Error(\"previous call to 'initWasm()' failed.\");\n  }\n\n  initializing = true;\n\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    return new Promise<void>((resolve, reject) => {\n      proxyWorker?.terminate();\n\n      void importProxyWorker().then(([objectUrl, worker]) => {\n        try {\n          proxyWorker = worker;\n          proxyWorker.onerror = (ev: ErrorEvent) => reject(ev);\n          proxyWorker.onmessage = onProxyWorkerMessage;\n          initWasmCallbacks = [resolve, reject];\n          const message: OrtWasmMessage = { type: 'init-wasm', in: env };\n\n          // if the proxy worker is loaded from a blob URL, we need to make sure the path information is not lost.\n          //\n          // when `env.wasm.wasmPaths` is not set, we need to pass the path information to the worker.\n          //\n          if (!BUILD_DEFS.ENABLE_BUNDLE_WASM_JS && !message.in!.wasm.wasmPaths && objectUrl) {\n            // for a build not bundled the wasm JS, we need to pass the path prefix to the worker.\n            // the path prefix will be used to resolve the path to both the wasm JS and the wasm file.\n            const inferredWasmPathPrefix = inferWasmPathPrefixFromScriptSrc();\n            if (inferredWasmPathPrefix) {\n              message.in!.wasm.wasmPaths = inferredWasmPathPrefix;\n            }\n          }\n\n          if (\n            BUILD_DEFS.IS_ESM &&\n            BUILD_DEFS.ENABLE_BUNDLE_WASM_JS &&\n            !message.in!.wasm.wasmPaths &&\n            (objectUrl || isEsmImportMetaUrlHardcodedAsFileUri)\n          ) {\n            // for a build bundled the wasm JS, if either of the following conditions is met:\n            // - the proxy worker is loaded from a blob URL\n            // - `import.meta.url` is a file URL, it means it is overwriten by the bundler.\n            //\n            // in either case, the path information is lost, we need to pass the path of the .wasm file to the worker.\n            // we need to use the bundler preferred URL format:\n            // new URL('filename', import.meta.url)\n            // so that the bundler can handle the file using corresponding loaders.\n            message.in!.wasm.wasmPaths = {\n              wasm: !BUILD_DEFS.DISABLE_JSEP\n                ? new URL('ort-wasm-simd-threaded.jsep.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href\n                : new URL('ort-wasm-simd-threaded.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href,\n            };\n          }\n          proxyWorker.postMessage(message);\n          temporaryObjectUrl = objectUrl;\n        } catch (e) {\n          reject(e);\n        }\n      }, reject);\n    });\n  } else {\n    try {\n      await initializeWebAssembly(env.wasm);\n      await core.initRuntime(env);\n      initialized = true;\n    } catch (e) {\n      aborted = true;\n      throw e;\n    } finally {\n      initializing = false;\n    }\n  }\n};\n\nexport const initializeOrtEp = async (epName: string): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('init-ep', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'init-ep', in: { epName, env } };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    await core.initEp(env, epName);\n  }\n};\n\nexport const copyFromExternalBuffer = async (buffer: Uint8Array): Promise<SerializableInternalBuffer> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<SerializableInternalBuffer>((resolve, reject) => {\n      enqueueCallbacks('copy-from', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'copy-from', in: { buffer } };\n      proxyWorker!.postMessage(message, [buffer.buffer]);\n    });\n  } else {\n    return core.copyFromExternalBuffer(buffer);\n  }\n};\n\nexport const createSession = async (\n  model: SerializableInternalBuffer | Uint8Array,\n  options?: InferenceSession.SessionOptions,\n): Promise<SerializableSessionMetadata> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    // check unsupported options\n    if (options?.preferredOutputLocation) {\n      throw new Error('session option \"preferredOutputLocation\" is not supported for proxy.');\n    }\n    ensureWorker();\n    return new Promise<SerializableSessionMetadata>((resolve, reject) => {\n      enqueueCallbacks('create', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'create', in: { model, options: { ...options } } };\n      const transferable: Transferable[] = [];\n      if (model instanceof Uint8Array) {\n        transferable.push(model.buffer);\n      }\n      proxyWorker!.postMessage(message, transferable);\n    });\n  } else {\n    return core.createSession(model, options);\n  }\n};\n\nexport const releaseSession = async (sessionId: number): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('release', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'release', in: sessionId };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    core.releaseSession(sessionId);\n  }\n};\n\nexport const run = async (\n  sessionId: number,\n  inputIndices: number[],\n  inputs: TensorMetadata[],\n  outputIndices: number[],\n  outputs: Array<TensorMetadata | null>,\n  options: InferenceSession.RunOptions,\n): Promise<TensorMetadata[]> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    // check inputs location\n    if (inputs.some((t) => t[3] !== 'cpu')) {\n      throw new Error('input tensor on GPU is not supported for proxy.');\n    }\n    // check outputs location\n    if (outputs.some((t) => t)) {\n      throw new Error('pre-allocated output tensor is not supported for proxy.');\n    }\n    ensureWorker();\n    return new Promise<SerializableTensorMetadata[]>((resolve, reject) => {\n      enqueueCallbacks('run', [resolve, reject]);\n      const serializableInputs = inputs as SerializableTensorMetadata[]; // every input is on CPU.\n      const message: OrtWasmMessage = {\n        type: 'run',\n        in: { sessionId, inputIndices, inputs: serializableInputs, outputIndices, options },\n      };\n      proxyWorker!.postMessage(message, core.extractTransferableBuffers(serializableInputs));\n    });\n  } else {\n    return core.run(sessionId, inputIndices, inputs, outputIndices, outputs, options);\n  }\n};\n\nexport const endProfiling = async (sessionId: number): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('end-profiling', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'end-profiling', in: sessionId };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    core.endProfiling(sessionId);\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  InferenceSession,\n  InferenceSessionHandler,\n  SessionHandler,\n  Tensor,\n  TRACE_FUNC_BEGIN,\n  TRACE_FUNC_END,\n} from 'onnxruntime-common';\n\nimport { SerializableInternalBuffer, TensorMetadata } from './proxy-messages';\nimport { copyFromExternalBuffer, createSession, endProfiling, releaseSession, run } from './proxy-wrapper';\nimport { isGpuBufferSupportedType, isMLTensorSupportedType } from './wasm-common';\nimport { isNode } from './wasm-utils-env';\nimport { loadFile } from './wasm-utils-load-file';\n\nexport const encodeTensorMetadata = (tensor: Tensor, getName: () => string): TensorMetadata => {\n  switch (tensor.location) {\n    case 'cpu':\n      return [tensor.type, tensor.dims, tensor.data, 'cpu'];\n    case 'gpu-buffer':\n      return [tensor.type, tensor.dims, { gpuBuffer: tensor.gpuBuffer }, 'gpu-buffer'];\n    case 'ml-tensor':\n      return [tensor.type, tensor.dims, { mlTensor: tensor.mlTensor }, 'ml-tensor'];\n    default:\n      throw new Error(`invalid data location: ${tensor.location} for ${getName()}`);\n  }\n};\n\nexport const decodeTensorMetadata = (tensor: TensorMetadata): Tensor => {\n  switch (tensor[3]) {\n    case 'cpu':\n      return new Tensor(tensor[0], tensor[2], tensor[1]);\n    case 'gpu-buffer': {\n      const dataType = tensor[0];\n      if (!isGpuBufferSupportedType(dataType)) {\n        throw new Error(`not supported data type: ${dataType} for deserializing GPU tensor`);\n      }\n      const { gpuBuffer, download, dispose } = tensor[2];\n      return Tensor.fromGpuBuffer(gpuBuffer, { dataType, dims: tensor[1], download, dispose });\n    }\n    case 'ml-tensor': {\n      const dataType = tensor[0];\n      if (!isMLTensorSupportedType(dataType)) {\n        throw new Error(`not supported data type: ${dataType} for deserializing MLTensor tensor`);\n      }\n      const { mlTensor, download, dispose } = tensor[2];\n      return Tensor.fromMLTensor(mlTensor, { dataType, dims: tensor[1], download, dispose });\n    }\n    default:\n      throw new Error(`invalid data location: ${tensor[3]}`);\n  }\n};\n\nexport class OnnxruntimeWebAssemblySessionHandler implements InferenceSessionHandler {\n  private sessionId: number;\n\n  inputNames: readonly string[];\n  outputNames: readonly string[];\n  inputMetadata: readonly InferenceSession.ValueMetadata[];\n  outputMetadata: readonly InferenceSession.ValueMetadata[];\n\n  async fetchModelAndCopyToWasmMemory(path: string): Promise<SerializableInternalBuffer> {\n    // fetch model from url and move to wasm heap.\n    return copyFromExternalBuffer(await loadFile(path));\n  }\n\n  async loadModel(pathOrBuffer: string | Uint8Array, options?: InferenceSession.SessionOptions): Promise<void> {\n    TRACE_FUNC_BEGIN();\n    let model: Parameters<typeof createSession>[0];\n\n    if (typeof pathOrBuffer === 'string') {\n      if (isNode) {\n        // node\n        model = await loadFile(pathOrBuffer);\n      } else {\n        // browser\n        // fetch model and copy to wasm heap.\n        model = await this.fetchModelAndCopyToWasmMemory(pathOrBuffer);\n      }\n    } else {\n      model = pathOrBuffer;\n    }\n\n    [this.sessionId, this.inputNames, this.outputNames, this.inputMetadata, this.outputMetadata] = await createSession(\n      model,\n      options,\n    );\n    TRACE_FUNC_END();\n  }\n\n  async dispose(): Promise<void> {\n    return releaseSession(this.sessionId);\n  }\n\n  async run(\n    feeds: SessionHandler.FeedsType,\n    fetches: SessionHandler.FetchesType,\n    options: InferenceSession.RunOptions,\n  ): Promise<SessionHandler.ReturnType> {\n    TRACE_FUNC_BEGIN();\n    const inputArray: Tensor[] = [];\n    const inputIndices: number[] = [];\n    Object.entries(feeds).forEach((kvp) => {\n      const name = kvp[0];\n      const tensor = kvp[1];\n      const index = this.inputNames.indexOf(name);\n      if (index === -1) {\n        throw new Error(`invalid input '${name}'`);\n      }\n      inputArray.push(tensor);\n      inputIndices.push(index);\n    });\n\n    const outputArray: Array<Tensor | null> = [];\n    const outputIndices: number[] = [];\n    Object.entries(fetches).forEach((kvp) => {\n      const name = kvp[0];\n      const tensor = kvp[1];\n      const index = this.outputNames.indexOf(name);\n      if (index === -1) {\n        throw new Error(`invalid output '${name}'`);\n      }\n      outputArray.push(tensor);\n      outputIndices.push(index);\n    });\n\n    const inputs = inputArray.map((t, i) =>\n      encodeTensorMetadata(t, () => `input \"${this.inputNames[inputIndices[i]]}\"`),\n    );\n    const outputs = outputArray.map((t, i) =>\n      t ? encodeTensorMetadata(t, () => `output \"${this.outputNames[outputIndices[i]]}\"`) : null,\n    );\n\n    const results = await run(this.sessionId, inputIndices, inputs, outputIndices, outputs, options);\n\n    const resultMap: SessionHandler.ReturnType = {};\n    for (let i = 0; i < results.length; i++) {\n      resultMap[this.outputNames[outputIndices[i]]] = outputArray[i] ?? decodeTensorMetadata(results[i]);\n    }\n    TRACE_FUNC_END();\n    return resultMap;\n  }\n\n  startProfiling(): void {\n    // TODO: implement profiling\n  }\n\n  endProfiling(): void {\n    void endProfiling(this.sessionId);\n  }\n}\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Backend, env, InferenceSession, InferenceSessionHandler } from 'onnxruntime-common';\n\nimport { initializeOrtEp, initializeWebAssemblyAndOrtRuntime } from './wasm/proxy-wrapper';\nimport { OnnxruntimeWebAssemblySessionHandler } from './wasm/session-handler-inference';\n\n/**\n * This function initializes all flags for WebAssembly.\n *\n * Those flags are accessible from `ort.env.wasm`. Users are allow to set those flags before the first inference session\n * being created, to override default value.\n */\nexport const initializeFlags = (): void => {\n  if (typeof env.wasm.initTimeout !== 'number' || env.wasm.initTimeout < 0) {\n    env.wasm.initTimeout = 0;\n  }\n\n  const simd = env.wasm.simd;\n  if (typeof simd !== 'boolean' && simd !== undefined && simd !== 'fixed' && simd !== 'relaxed') {\n    // eslint-disable-next-line no-console\n    console.warn(\n      `Property \"env.wasm.simd\" is set to unknown value \"${simd}\". Reset it to \\`false\\` and ignore SIMD feature checking.`,\n    );\n    env.wasm.simd = false;\n  }\n\n  if (typeof env.wasm.proxy !== 'boolean') {\n    env.wasm.proxy = false;\n  }\n\n  if (typeof env.wasm.trace !== 'boolean') {\n    env.wasm.trace = false;\n  }\n\n  if (typeof env.wasm.numThreads !== 'number' || !Number.isInteger(env.wasm.numThreads) || env.wasm.numThreads <= 0) {\n    // The following logic only applies when `ort.env.wasm.numThreads` is not set by user. We will always honor user's\n    // setting if it is provided.\n\n    // Browser: when crossOriginIsolated is false, SharedArrayBuffer is not available so WebAssembly threads will not\n    // work. In this case, we will set numThreads to 1.\n    //\n    // There is an exception: when the browser is configured to force-enable SharedArrayBuffer (e.g. Chromuim with\n    // --enable-features=SharedArrayBuffer), it is possible that `self.crossOriginIsolated` is false and\n    // SharedArrayBuffer is available at the same time. This is usually for testing. In this case,  we will still set\n    // numThreads to 1 here. If we want to enable multi-threading in test, we should set `ort.env.wasm.numThreads` to a\n    // value greater than 1.\n    if (typeof self !== 'undefined' && !self.crossOriginIsolated) {\n      env.wasm.numThreads = 1;\n    } else {\n      const numCpuLogicalCores =\n        typeof navigator === 'undefined' ? require('node:os').cpus().length : navigator.hardwareConcurrency;\n      env.wasm.numThreads = Math.min(4, Math.ceil((numCpuLogicalCores || 1) / 2));\n    }\n  }\n};\n\nexport class OnnxruntimeWebAssemblyBackend implements Backend {\n  /**\n   * This function initializes the WebAssembly backend.\n   *\n   * This function will be called only once for each backend name. It will be called the first time when\n   * `ort.InferenceSession.create()` is called with a registered backend name.\n   *\n   * @param backendName - the registered backend name.\n   */\n  async init(backendName: string): Promise<void> {\n    // populate wasm flags\n    initializeFlags();\n\n    // init wasm\n    await initializeWebAssemblyAndOrtRuntime();\n\n    // performe EP specific initialization\n    await initializeOrtEp(backendName);\n  }\n  createInferenceSessionHandler(\n    path: string,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler>;\n  createInferenceSessionHandler(\n    buffer: Uint8Array,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler>;\n  async createInferenceSessionHandler(\n    pathOrBuffer: string | Uint8Array,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler> {\n    const handler = new OnnxruntimeWebAssemblySessionHandler();\n    await handler.loadModel(pathOrBuffer, options);\n    return handler;\n  }\n}\n\nexport const wasmBackend = new OnnxruntimeWebAssemblyBackend();\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/* eslint-disable @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports */\n\n// We use \"require\" instead of \"import\" here because import statement must be put in top level. Our current code does\n// not allow bundler to tree-shaking code as expected because some codes are treated as having side effects.\n// So we import code inside the if-clause to allow bundler remove the code safely.\n\nexport * from 'onnxruntime-common';\nimport * as ort from 'onnxruntime-common';\nexport default ort;\n\nimport { registerBackend, env } from 'onnxruntime-common';\nimport { version } from './version';\n\nif (!BUILD_DEFS.DISABLE_WEBGL) {\n  const onnxjsBackend = require('./backend-onnxjs').onnxjsBackend;\n  registerBackend('webgl', onnxjsBackend, -10);\n}\n\nif (!BUILD_DEFS.DISABLE_WASM) {\n  const wasmBackend = require('./backend-wasm').wasmBackend;\n  if (!BUILD_DEFS.DISABLE_JSEP) {\n    registerBackend('webgpu', wasmBackend, 5);\n    registerBackend('webnn', wasmBackend, 5);\n  }\n  registerBackend('cpu', wasmBackend, 10);\n  registerBackend('wasm', wasmBackend, 10);\n}\n\nObject.defineProperty(env.versions, 'web', { value: version, enumerable: true });\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\n\nexport const version = '1.22.0-dev.20250409-89f8206ba4';\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\n\nexport const version = '1.25.1';\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Env } from './env.js';\nimport { version } from './version.js';\n\ntype LogLevelType = Env['logLevel'];\n\nlet logLevelValue: Required<LogLevelType> = 'warning';\n\nexport const env: Env = {\n  wasm: {} as Env.WebAssemblyFlags,\n  webgl: {} as Env.WebGLFlags,\n  webgpu: {} as Env.WebGpuFlags,\n  versions: { common: version },\n\n  set logLevel(value: LogLevelType) {\n    if (value === undefined) {\n      return;\n    }\n    if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {\n      throw new Error(`Unsupported logging level: ${value}`);\n    }\n    logLevelValue = value;\n  },\n  get logLevel(): Required<LogLevelType> {\n    return logLevelValue;\n  },\n};\n\n// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`.\nObject.defineProperty(env, 'logLevel', { enumerable: true });\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { TensorToDataUrlOptions, TensorToImageDataOptions } from './tensor-conversion.js';\nimport { Tensor } from './tensor.js';\n\n/**\n * implementation of Tensor.toDataURL()\n */\nexport const tensorToDataURL = (tensor: Tensor, options?: TensorToDataUrlOptions): string => {\n  const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : new OffscreenCanvas(1, 1);\n  canvas.width = tensor.dims[3];\n  canvas.height = tensor.dims[2];\n  const pixels2DContext = canvas.getContext('2d') as\n    | CanvasRenderingContext2D\n    | OffscreenCanvasRenderingContext2D\n    | null;\n\n  if (pixels2DContext != null) {\n    // Default values for height and width & format\n    let width: number;\n    let height: number;\n    if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n      width = tensor.dims[2];\n      height = tensor.dims[3];\n    } else {\n      // Default layout is NCWH\n      width = tensor.dims[3];\n      height = tensor.dims[2];\n    }\n\n    const inputformat = options?.format !== undefined ? options.format : 'RGB';\n\n    const norm = options?.norm;\n    let normMean: [number, number, number, number];\n    let normBias: [number, number, number, number];\n    if (norm === undefined || norm.mean === undefined) {\n      normMean = [255, 255, 255, 255];\n    } else {\n      if (typeof norm.mean === 'number') {\n        normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n      } else {\n        normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];\n        if (norm.mean[3] !== undefined) {\n          normMean[3] = norm.mean[3];\n        }\n      }\n    }\n    if (norm === undefined || norm.bias === undefined) {\n      normBias = [0, 0, 0, 0];\n    } else {\n      if (typeof norm.bias === 'number') {\n        normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n      } else {\n        normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n        if (norm.bias[3] !== undefined) {\n          normBias[3] = norm.bias[3];\n        }\n      }\n    }\n\n    const stride = height * width;\n    // Default pointer assignments\n    let rTensorPointer = 0,\n      gTensorPointer = stride,\n      bTensorPointer = stride * 2,\n      aTensorPointer = -1;\n\n    // Updating the pointer assignments based on the input image format\n    if (inputformat === 'RGBA') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n      aTensorPointer = stride * 3;\n    } else if (inputformat === 'RGB') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n    } else if (inputformat === 'RBG') {\n      rTensorPointer = 0;\n      bTensorPointer = stride;\n      gTensorPointer = stride * 2;\n    }\n\n    for (let i = 0; i < height; i++) {\n      for (let j = 0; j < width; j++) {\n        const R = ((tensor.data[rTensorPointer++] as number) - normBias[0]) * normMean[0]; // R value\n        const G = ((tensor.data[gTensorPointer++] as number) - normBias[1]) * normMean[1]; // G value\n        const B = ((tensor.data[bTensorPointer++] as number) - normBias[2]) * normMean[2]; // B value\n        const A = aTensorPointer === -1 ? 255 : ((tensor.data[aTensorPointer++] as number) - normBias[3]) * normMean[3]; // A value\n\n        pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')';\n        pixels2DContext.fillRect(j, i, 1, 1);\n      }\n    }\n    if ('toDataURL' in canvas) {\n      return canvas.toDataURL();\n    } else {\n      throw new Error('toDataURL is not supported');\n    }\n  } else {\n    throw new Error('Can not access image data');\n  }\n};\n\n/**\n * implementation of Tensor.toImageData()\n */\nexport const tensorToImageData = (tensor: Tensor, options?: TensorToImageDataOptions): ImageData => {\n  const pixels2DContext =\n    typeof document !== 'undefined'\n      ? document.createElement('canvas').getContext('2d')\n      : (new OffscreenCanvas(1, 1).getContext('2d') as OffscreenCanvasRenderingContext2D);\n  let image: ImageData;\n  if (pixels2DContext != null) {\n    // Default values for height and width & format\n    let width: number;\n    let height: number;\n    let channels: number;\n    if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n      width = tensor.dims[2];\n      height = tensor.dims[1];\n      channels = tensor.dims[3];\n    } else {\n      // Default layout is NCWH\n      width = tensor.dims[3];\n      height = tensor.dims[2];\n      channels = tensor.dims[1];\n    }\n    const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';\n\n    const norm = options?.norm;\n    let normMean: [number, number, number, number];\n    let normBias: [number, number, number, number];\n    if (norm === undefined || norm.mean === undefined) {\n      normMean = [255, 255, 255, 255];\n    } else {\n      if (typeof norm.mean === 'number') {\n        normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n      } else {\n        normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];\n        if (norm.mean[3] !== undefined) {\n          normMean[3] = norm.mean[3];\n        }\n      }\n    }\n    if (norm === undefined || norm.bias === undefined) {\n      normBias = [0, 0, 0, 0];\n    } else {\n      if (typeof norm.bias === 'number') {\n        normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n      } else {\n        normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n        if (norm.bias[3] !== undefined) {\n          normBias[3] = norm.bias[3];\n        }\n      }\n    }\n\n    const stride = height * width;\n    if (options !== undefined) {\n      if (\n        (options.format !== undefined && channels === 4 && options.format !== 'RGBA') ||\n        (channels === 3 && options.format !== 'RGB' && options.format !== 'BGR')\n      ) {\n        throw new Error(\"Tensor format doesn't match input tensor dims\");\n      }\n    }\n\n    // Default pointer assignments\n    const step = 4;\n    let rImagePointer = 0,\n      gImagePointer = 1,\n      bImagePointer = 2,\n      aImagePointer = 3;\n    let rTensorPointer = 0,\n      gTensorPointer = stride,\n      bTensorPointer = stride * 2,\n      aTensorPointer = -1;\n\n    // Updating the pointer assignments based on the input image format\n    if (inputformat === 'RGBA') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n      aTensorPointer = stride * 3;\n    } else if (inputformat === 'RGB') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n    } else if (inputformat === 'RBG') {\n      rTensorPointer = 0;\n      bTensorPointer = stride;\n      gTensorPointer = stride * 2;\n    }\n\n    image = pixels2DContext.createImageData(width, height);\n\n    for (\n      let i = 0;\n      i < height * width;\n      rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++\n    ) {\n      image.data[rImagePointer] = ((tensor.data[rTensorPointer++] as number) - normBias[0]) * normMean[0]; // R value\n      image.data[gImagePointer] = ((tensor.data[gTensorPointer++] as number) - normBias[1]) * normMean[1]; // G value\n      image.data[bImagePointer] = ((tensor.data[bTensorPointer++] as number) - normBias[2]) * normMean[2]; // B value\n      image.data[aImagePointer] =\n        aTensorPointer === -1 ? 255 : ((tensor.data[aTensorPointer++] as number) - normBias[3]) * normMean[3]; // A value\n    }\n  } else {\n    throw new Error('Can not access image data');\n  }\n  return image;\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  OptionsDimensions,\n  OptionsFormat,\n  OptionsNormalizationParameters,\n  OptionsTensorFormat,\n  OptionsTensorLayout,\n  TensorFromGpuBufferOptions,\n  TensorFromImageBitmapOptions,\n  TensorFromImageDataOptions,\n  TensorFromImageElementOptions,\n  TensorFromMLTensorOptions,\n  TensorFromTextureOptions,\n  TensorFromUrlOptions,\n} from './tensor-factory.js';\nimport { Tensor } from './tensor-impl.js';\nimport { Tensor as TensorInterface } from './tensor.js';\n\ninterface BufferToTensorOptions\n  extends OptionsDimensions,\n    OptionsTensorLayout,\n    OptionsNormalizationParameters,\n    OptionsFormat,\n    OptionsTensorFormat {}\n\n/**\n * Create a new tensor object from image object\n *\n * @param buffer - Extracted image buffer data - assuming RGBA format\n * @param imageFormat - input image configuration - required configurations height, width, format\n * @param tensorFormat - output tensor configuration - Default is RGB format\n */\nexport const bufferToTensor = (buffer: Uint8ClampedArray | undefined, options: BufferToTensorOptions): Tensor => {\n  if (buffer === undefined) {\n    throw new Error('Image buffer must be defined');\n  }\n  if (options.height === undefined || options.width === undefined) {\n    throw new Error('Image height and width must be defined');\n  }\n  if (options.tensorLayout === 'NHWC') {\n    throw new Error('NHWC Tensor layout is not supported yet');\n  }\n\n  const { height, width } = options;\n\n  const norm = options.norm ?? { mean: 255, bias: 0 };\n  let normMean: [number, number, number, number];\n  let normBias: [number, number, number, number];\n\n  if (typeof norm.mean === 'number') {\n    normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n  } else {\n    normMean = [norm.mean![0], norm.mean![1], norm.mean![2], norm.mean![3] ?? 255];\n  }\n\n  if (typeof norm.bias === 'number') {\n    normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n  } else {\n    normBias = [norm.bias![0], norm.bias![1], norm.bias![2], norm.bias![3] ?? 0];\n  }\n\n  const inputformat = options.format !== undefined ? options.format : 'RGBA';\n  // default value is RGBA since imagedata and HTMLImageElement uses it\n\n  const outputformat =\n    options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB';\n  const stride = height * width;\n  const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3);\n\n  // Default pointer assignments\n  let step = 4,\n    rImagePointer = 0,\n    gImagePointer = 1,\n    bImagePointer = 2,\n    aImagePointer = 3;\n  let rTensorPointer = 0,\n    gTensorPointer = stride,\n    bTensorPointer = stride * 2,\n    aTensorPointer = -1;\n\n  // Updating the pointer assignments based on the input image format\n  if (inputformat === 'RGB') {\n    step = 3;\n    rImagePointer = 0;\n    gImagePointer = 1;\n    bImagePointer = 2;\n    aImagePointer = -1;\n  }\n\n  // Updating the pointer assignments based on the output tensor format\n  if (outputformat === 'RGBA') {\n    aTensorPointer = stride * 3;\n  } else if (outputformat === 'RBG') {\n    rTensorPointer = 0;\n    bTensorPointer = stride;\n    gTensorPointer = stride * 2;\n  } else if (outputformat === 'BGR') {\n    bTensorPointer = 0;\n    gTensorPointer = stride;\n    rTensorPointer = stride * 2;\n  }\n\n  for (\n    let i = 0;\n    i < stride;\n    i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step\n  ) {\n    float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];\n    float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];\n    float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];\n    if (aTensorPointer !== -1 && aImagePointer !== -1) {\n      float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];\n    }\n  }\n\n  // Float32Array -> ort.Tensor\n  const outputTensor =\n    outputformat === 'RGBA'\n      ? new Tensor('float32', float32Data, [1, 4, height, width])\n      : new Tensor('float32', float32Data, [1, 3, height, width]);\n  return outputTensor;\n};\n\n/**\n * implementation of Tensor.fromImage().\n */\nexport const tensorFromImage = async (\n  image: ImageData | HTMLImageElement | ImageBitmap | string,\n  options?:\n    | TensorFromImageDataOptions\n    | TensorFromImageElementOptions\n    | TensorFromImageBitmapOptions\n    | TensorFromUrlOptions,\n): Promise<Tensor> => {\n  // checking the type of image object\n  const isHTMLImageEle = typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement;\n  const isImageDataEle = typeof ImageData !== 'undefined' && image instanceof ImageData;\n  const isImageBitmap = typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap;\n  const isString = typeof image === 'string';\n\n  let data: Uint8ClampedArray | undefined;\n  let bufferToTensorOptions: BufferToTensorOptions = options ?? {};\n\n  const createCanvas = () => {\n    if (typeof document !== 'undefined') {\n      return document.createElement('canvas');\n    } else if (typeof OffscreenCanvas !== 'undefined') {\n      return new OffscreenCanvas(1, 1);\n    } else {\n      throw new Error('Canvas is not supported');\n    }\n  };\n  const createCanvasContext = (canvas: HTMLCanvasElement | OffscreenCanvas) => {\n    if (typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement) {\n      return canvas.getContext('2d');\n    } else if (canvas instanceof OffscreenCanvas) {\n      return canvas.getContext('2d') as OffscreenCanvasRenderingContext2D;\n    } else {\n      return null;\n    }\n  };\n  // filling and checking image configuration options\n  if (isHTMLImageEle) {\n    // HTMLImageElement - image object - format is RGBA by default\n    const canvas = createCanvas();\n    canvas.width = image.width;\n    canvas.height = image.height;\n    const pixels2DContext = createCanvasContext(canvas);\n\n    if (pixels2DContext != null) {\n      let height = image.height;\n      let width = image.width;\n      if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {\n        height = options.resizedHeight;\n        width = options.resizedWidth;\n      }\n\n      if (options !== undefined) {\n        bufferToTensorOptions = options;\n        if (options.tensorFormat !== undefined) {\n          throw new Error('Image input config format must be RGBA for HTMLImageElement');\n        } else {\n          bufferToTensorOptions.tensorFormat = 'RGBA';\n        }\n        bufferToTensorOptions.height = height;\n        bufferToTensorOptions.width = width;\n      } else {\n        bufferToTensorOptions.tensorFormat = 'RGBA';\n        bufferToTensorOptions.height = height;\n        bufferToTensorOptions.width = width;\n      }\n\n      pixels2DContext.drawImage(image, 0, 0);\n      data = pixels2DContext.getImageData(0, 0, width, height).data;\n    } else {\n      throw new Error('Can not access image data');\n    }\n  } else if (isImageDataEle) {\n    let height: number;\n    let width: number;\n\n    if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {\n      height = options.resizedHeight;\n      width = options.resizedWidth;\n    } else {\n      height = image.height;\n      width = image.width;\n    }\n\n    if (options !== undefined) {\n      bufferToTensorOptions = options;\n    }\n    bufferToTensorOptions.format = 'RGBA';\n    bufferToTensorOptions.height = height;\n    bufferToTensorOptions.width = width;\n\n    if (options !== undefined) {\n      const tempCanvas = createCanvas();\n\n      tempCanvas.width = width;\n      tempCanvas.height = height;\n\n      const pixels2DContext = createCanvasContext(tempCanvas);\n\n      if (pixels2DContext != null) {\n        pixels2DContext.putImageData(image, 0, 0);\n        data = pixels2DContext.getImageData(0, 0, width, height).data;\n      } else {\n        throw new Error('Can not access image data');\n      }\n    } else {\n      data = image.data;\n    }\n  } else if (isImageBitmap) {\n    // ImageBitmap - image object - format must be provided by user\n    if (options === undefined) {\n      throw new Error('Please provide image config with format for Imagebitmap');\n    }\n\n    const canvas = createCanvas();\n    canvas.width = image.width;\n    canvas.height = image.height;\n    const pixels2DContext = createCanvasContext(canvas);\n\n    if (pixels2DContext != null) {\n      const height = image.height;\n      const width = image.width;\n      pixels2DContext.drawImage(image, 0, 0, width, height);\n      data = pixels2DContext.getImageData(0, 0, width, height).data;\n      bufferToTensorOptions.height = height;\n      bufferToTensorOptions.width = width;\n      return bufferToTensor(data, bufferToTensorOptions);\n    } else {\n      throw new Error('Can not access image data');\n    }\n  } else if (isString) {\n    return new Promise((resolve, reject) => {\n      const canvas = createCanvas();\n      const context = createCanvasContext(canvas);\n      if (!image || !context) {\n        return reject();\n      }\n      const newImage = new Image();\n      newImage.crossOrigin = 'Anonymous';\n      newImage.src = image;\n      newImage.onload = () => {\n        canvas.width = newImage.width;\n        canvas.height = newImage.height;\n        context.drawImage(newImage, 0, 0, canvas.width, canvas.height);\n        const img = context.getImageData(0, 0, canvas.width, canvas.height);\n\n        bufferToTensorOptions.height = canvas.height;\n        bufferToTensorOptions.width = canvas.width;\n        resolve(bufferToTensor(img.data, bufferToTensorOptions));\n      };\n    });\n  } else {\n    throw new Error('Input data provided is not supported - aborted tensor creation');\n  }\n\n  if (data !== undefined) {\n    return bufferToTensor(data, bufferToTensorOptions);\n  } else {\n    throw new Error('Input data provided is not supported - aborted tensor creation');\n  }\n};\n\n/**\n * implementation of Tensor.fromTexture().\n */\nexport const tensorFromTexture = <T extends TensorInterface.TextureDataTypes>(\n  texture: TensorInterface.TextureType,\n  options: TensorFromTextureOptions<T>,\n): Tensor => {\n  const { width, height, download, dispose } = options;\n  // Always assume RGBAF32. TODO: support different texture format\n  const dims = [1, height, width, 4];\n  return new Tensor({ location: 'texture', type: 'float32', texture, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromGpuBuffer().\n */\nexport const tensorFromGpuBuffer = <T extends TensorInterface.GpuBufferDataTypes>(\n  gpuBuffer: TensorInterface.GpuBufferType,\n  options: TensorFromGpuBufferOptions<T>,\n): Tensor => {\n  const { dataType, dims, download, dispose } = options;\n  return new Tensor({ location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromMLTensor().\n */\nexport const tensorFromMLTensor = <T extends TensorInterface.MLTensorDataTypes>(\n  mlTensor: TensorInterface.MLTensorType,\n  options: TensorFromMLTensorOptions<T>,\n): Tensor => {\n  const { dataType, dims, download, dispose } = options;\n  return new Tensor({ location: 'ml-tensor', type: dataType ?? 'float32', mlTensor, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromPinnedBuffer().\n */\nexport const tensorFromPinnedBuffer = <T extends TensorInterface.CpuPinnedDataTypes>(\n  type: T,\n  buffer: TensorInterface.DataTypeMap[T],\n  dims?: readonly number[],\n): Tensor => new Tensor({ location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length] });\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Tensor } from './tensor.js';\n\nexport type SupportedTypedArrayConstructors =\n  | Float32ArrayConstructor\n  | Uint8ArrayConstructor\n  | Int8ArrayConstructor\n  | Uint16ArrayConstructor\n  | Int16ArrayConstructor\n  | Int32ArrayConstructor\n  | BigInt64ArrayConstructor\n  | Uint8ArrayConstructor\n  | Float64ArrayConstructor\n  | Uint32ArrayConstructor\n  | BigUint64ArrayConstructor;\nexport type SupportedTypedArray = InstanceType<SupportedTypedArrayConstructors>;\n\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map<string, SupportedTypedArrayConstructors>([\n  ['float32', Float32Array],\n  ['uint8', Uint8Array],\n  ['int8', Int8Array],\n  ['uint16', Uint16Array],\n  ['int16', Int16Array],\n  ['int32', Int32Array],\n  ['bool', Uint8Array],\n  ['float64', Float64Array],\n  ['uint32', Uint32Array],\n  ['int4', Uint8Array],\n  ['uint4', Uint8Array],\n]);\n\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map<SupportedTypedArrayConstructors, Tensor.Type>([\n  [Float32Array, 'float32'],\n  [Uint8Array, 'uint8'],\n  [Int8Array, 'int8'],\n  [Uint16Array, 'uint16'],\n  [Int16Array, 'int16'],\n  [Int32Array, 'int32'],\n  [Float64Array, 'float64'],\n  [Uint32Array, 'uint32'],\n]);\n\n// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for\n// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array\n// polyfill if available.\nlet isTypedArrayChecked = false;\nexport const checkTypedArray = () => {\n  if (!isTypedArrayChecked) {\n    isTypedArrayChecked = true;\n    const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from;\n    const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from;\n\n    // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any\n    const Float16Array = (globalThis as any).Float16Array;\n    const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from;\n\n    if (isBigInt64ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');\n    }\n    if (isBigUint64ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');\n    }\n    if (isFloat16ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16');\n    } else {\n      // if Float16Array is not available, use 'Uint16Array' to store the data.\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array);\n    }\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  CpuPinnedConstructorParameters,\n  GpuBufferConstructorParameters,\n  MLTensorConstructorParameters,\n  TextureConstructorParameters,\n} from './tensor-factory.js';\nimport { Tensor } from './tensor-impl.js';\n\n/**\n * calculate size from dims.\n *\n * @param dims the dims array. May be an illegal input.\n */\nexport const calculateSize = (dims: readonly unknown[]): number => {\n  let size = 1;\n  for (let i = 0; i < dims.length; i++) {\n    const dim = dims[i];\n    if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {\n      throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);\n    }\n    if (dim < 0) {\n      throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);\n    }\n    size *= dim;\n  }\n  return size;\n};\n\n/**\n * implementation of Tensor.reshape()\n */\nexport const tensorReshape = (tensor: Tensor, dims: readonly number[]): Tensor => {\n  switch (tensor.location) {\n    case 'cpu':\n      return new Tensor(tensor.type, tensor.data, dims);\n    case 'cpu-pinned':\n      return new Tensor({\n        location: 'cpu-pinned',\n        data: tensor.data as CpuPinnedConstructorParameters['data'],\n        type: tensor.type as CpuPinnedConstructorParameters['type'],\n        dims,\n      });\n    case 'texture':\n      return new Tensor({\n        location: 'texture',\n        texture: tensor.texture,\n        type: tensor.type as TextureConstructorParameters['type'],\n        dims,\n      });\n    case 'gpu-buffer':\n      return new Tensor({\n        location: 'gpu-buffer',\n        gpuBuffer: tensor.gpuBuffer,\n        type: tensor.type as GpuBufferConstructorParameters['type'],\n        dims,\n      });\n    case 'ml-tensor':\n      return new Tensor({\n        location: 'ml-tensor',\n        mlTensor: tensor.mlTensor,\n        type: tensor.type as MLTensorConstructorParameters['type'],\n        dims,\n      });\n    default:\n      throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);\n  }\n};\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { tensorToDataURL, tensorToImageData } from './tensor-conversion-impl.js';\nimport { TensorToDataUrlOptions, TensorToImageDataOptions } from './tensor-conversion.js';\nimport {\n  tensorFromGpuBuffer,\n  tensorFromImage,\n  tensorFromMLTensor,\n  tensorFromPinnedBuffer,\n  tensorFromTexture,\n} from './tensor-factory-impl.js';\nimport {\n  CpuPinnedConstructorParameters,\n  GpuBufferConstructorParameters,\n  MLTensorConstructorParameters,\n  TensorFromGpuBufferOptions,\n  TensorFromImageBitmapOptions,\n  TensorFromImageDataOptions,\n  TensorFromImageElementOptions,\n  TensorFromMLTensorOptions,\n  TensorFromTextureOptions,\n  TensorFromUrlOptions,\n  TextureConstructorParameters,\n} from './tensor-factory.js';\nimport {\n  checkTypedArray,\n  NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP,\n  NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP,\n  SupportedTypedArray,\n  SupportedTypedArrayConstructors,\n} from './tensor-impl-type-mapping.js';\nimport { calculateSize, tensorReshape } from './tensor-utils-impl.js';\nimport { Tensor as TensorInterface } from './tensor.js';\n\n// type aliases for those exported from Tensor interface\n\ntype TensorType = TensorInterface.Type;\ntype TensorDataType = TensorInterface.DataType;\ntype TensorDataLocation = TensorInterface.DataLocation;\ntype TensorTextureType = TensorInterface.TextureType;\ntype TensorGpuBufferType = TensorInterface.GpuBufferType;\ntype TensorMLTensorType = TensorInterface.MLTensorType;\n\n/**\n * the implementation of Tensor interface.\n *\n * @ignore\n */\nexport class Tensor implements TensorInterface {\n  // #region constructors\n\n  /**\n   * Construct a new CPU tensor object from the given type, data and dims.\n   */\n  constructor(\n    type: TensorType,\n    data: TensorDataType | Uint8ClampedArray | readonly string[] | readonly number[] | readonly boolean[],\n    dims?: readonly number[],\n  );\n  /**\n   * Construct a new CPU tensor object from the given data and dims. Type is inferred from data.\n   */\n  constructor(\n    data: TensorDataType | Uint8ClampedArray | readonly string[] | readonly boolean[],\n    dims?: readonly number[],\n  );\n  /**\n   * Construct a new tensor object from the pinned CPU data with the given type and dims.\n   *\n   * Tensor's location will be set to 'cpu-pinned'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: CpuPinnedConstructorParameters);\n  /**\n   * Construct a new tensor object from the WebGL texture with the given type and dims.\n   *\n   * Tensor's location will be set to 'texture'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: TextureConstructorParameters);\n  /**\n   * Construct a new tensor object from the WebGPU buffer with the given type and dims.\n   *\n   * Tensor's location will be set to 'gpu-buffer'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: GpuBufferConstructorParameters);\n\n  /**\n   * Construct a new tensor object from the WebNN MLTensor with the given type and dims.\n   *\n   * Tensor's location will be set to 'ml-tensor'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: MLTensorConstructorParameters);\n\n  /**\n   * implementation.\n   */\n  constructor(\n    arg0:\n      | TensorType\n      | TensorDataType\n      | Uint8ClampedArray\n      | readonly string[]\n      | readonly boolean[]\n      | CpuPinnedConstructorParameters\n      | TextureConstructorParameters\n      | GpuBufferConstructorParameters\n      | MLTensorConstructorParameters,\n    arg1?: TensorDataType | Uint8ClampedArray | readonly number[] | readonly string[] | readonly boolean[],\n    arg2?: readonly number[],\n  ) {\n    // perform one-time check for BigInt/Float16Array support\n    checkTypedArray();\n\n    let type: TensorType;\n    let dims: readonly number[];\n\n    if (typeof arg0 === 'object' && 'location' in arg0) {\n      //\n      // constructing tensor from specific location\n      //\n      this.dataLocation = arg0.location;\n      type = arg0.type;\n      dims = arg0.dims;\n      switch (arg0.location) {\n        case 'cpu-pinned': {\n          const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);\n          if (!expectedTypedArrayConstructor) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from pinned buffer`);\n          }\n          if (!(arg0.data instanceof expectedTypedArrayConstructor)) {\n            throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);\n          }\n          this.cpuData = arg0.data;\n          break;\n        }\n        case 'texture': {\n          if (type !== 'float32') {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from texture`);\n          }\n          this.gpuTextureData = arg0.texture;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        case 'gpu-buffer': {\n          if (\n            type !== 'float32' &&\n            type !== 'float16' &&\n            type !== 'int32' &&\n            type !== 'int64' &&\n            type !== 'uint32' &&\n            type !== 'uint8' &&\n            type !== 'bool' &&\n            type !== 'uint4' &&\n            type !== 'int4'\n          ) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from gpu buffer`);\n          }\n          this.gpuBufferData = arg0.gpuBuffer;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        case 'ml-tensor': {\n          if (\n            type !== 'float32' &&\n            type !== 'float16' &&\n            type !== 'int32' &&\n            type !== 'int64' &&\n            type !== 'uint32' &&\n            type !== 'uint64' &&\n            type !== 'int8' &&\n            type !== 'uint8' &&\n            type !== 'bool' &&\n            type !== 'uint4' &&\n            type !== 'int4'\n          ) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from MLTensor`);\n          }\n          this.mlTensorData = arg0.mlTensor;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        default:\n          throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);\n      }\n    } else {\n      //\n      // constructing tensor of location 'cpu'\n      //\n      let data: TensorDataType;\n      let maybeDims: typeof arg1 | typeof arg2;\n      // check whether arg0 is type or data\n      if (typeof arg0 === 'string') {\n        //\n        // Override: constructor(type, data, ...)\n        //\n        type = arg0;\n        maybeDims = arg2;\n        if (arg0 === 'string') {\n          // string tensor\n          if (!Array.isArray(arg1)) {\n            throw new TypeError(\"A string tensor's data must be a string array.\");\n          }\n          // we don't check whether every element in the array is string; this is too slow. we assume it's correct and\n          // error will be populated at inference\n          data = arg1;\n        } else {\n          // numeric tensor\n          const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);\n          if (typedArrayConstructor === undefined) {\n            throw new TypeError(`Unsupported tensor type: ${arg0}.`);\n          }\n          if (Array.isArray(arg1)) {\n            if ((arg0 === 'float16' && typedArrayConstructor === Uint16Array) || arg0 === 'uint4' || arg0 === 'int4') {\n              // - 'float16':\n              //   When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array.\n              //\n              //   Throw error here because when user try to use number array as data,\n              //   e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call\n              //   Uint16Array.from(arg1) which generates wrong data.\n              //\n              // - 'uint4' and 'int4':\n              //   Uint8Array.from(arg1) will generate wrong data for 'uint4' and 'int4' tensor.\n              //\n              throw new TypeError(\n                `Creating a ${arg0} tensor from number array is not supported. Please use ${typedArrayConstructor.name} as data.`,\n              );\n            } else if (arg0 === 'uint64' || arg0 === 'int64') {\n              // use 'as any' here because:\n              // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays.\n              // see https://github.com/microsoft/TypeScript/issues/17002\n              // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()'\n              // does not accept parameter mapFn.\n              // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union\n              // type.\n\n              // assume 'arg1' is of type \"readonly number[]|readonly bigint[]\" here.\n\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              data = (typedArrayConstructor as any).from(arg1, BigInt);\n            } else {\n              // assume 'arg1' is of type \"readonly number[]\" here.\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              data = (typedArrayConstructor as any).from(arg1);\n            }\n          } else if (arg1 instanceof typedArrayConstructor) {\n            data = arg1;\n          } else if (arg1 instanceof Uint8ClampedArray) {\n            if (arg0 === 'uint8') {\n              data = Uint8Array.from(arg1);\n            } else {\n              throw new TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);\n            }\n          } else if (arg0 === 'float16' && arg1 instanceof Uint16Array && typedArrayConstructor !== Uint16Array) {\n            // when Float16Array is available and data is of type Uint16Array.\n            // We allow Uint16Array to be passed in as data for 'float16' tensor until Float16Array is generally\n            // supported in JavaScript environment.\n\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            data = new (globalThis as any).Float16Array(arg1.buffer, arg1.byteOffset, arg1.length);\n          } else {\n            throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);\n          }\n        }\n      } else {\n        //\n        // Override: constructor(data, ...)\n        //\n        maybeDims = arg1;\n        if (Array.isArray(arg0)) {\n          // only boolean[] and string[] is supported\n          if (arg0.length === 0) {\n            throw new TypeError('Tensor type cannot be inferred from an empty array.');\n          }\n          const firstElementType = typeof arg0[0];\n          if (firstElementType === 'string') {\n            type = 'string';\n            data = arg0;\n          } else if (firstElementType === 'boolean') {\n            type = 'bool';\n            // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is\n            // wrong type. We use 'as any' to make it happy.\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            data = Uint8Array.from(arg0 as any[]);\n          } else {\n            throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);\n          }\n        } else if (arg0 instanceof Uint8ClampedArray) {\n          type = 'uint8';\n          data = Uint8Array.from(arg0);\n        } else {\n          // get tensor type from TypedArray\n          const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(\n            arg0.constructor as SupportedTypedArrayConstructors,\n          );\n          if (mappedType === undefined) {\n            throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);\n          }\n          type = mappedType;\n          data = arg0 as SupportedTypedArray;\n        }\n      }\n\n      // type and data is processed, now processing dims\n      if (maybeDims === undefined) {\n        // assume 1-D tensor if dims omitted\n        maybeDims = [data.length];\n      } else if (!Array.isArray(maybeDims)) {\n        throw new TypeError(\"A tensor's dims must be a number array\");\n      }\n      dims = maybeDims as readonly number[];\n\n      this.cpuData = data;\n      this.dataLocation = 'cpu';\n    }\n\n    // perform check on dims\n    const size = calculateSize(dims);\n    // if data is on CPU, check whether data length matches tensor size\n    if (this.cpuData && size !== this.cpuData.length) {\n      if ((type === 'uint4' || type === 'int4') && Math.ceil(size / 2) === this.cpuData.length) {\n        // for (u)int4, the data length is half of the tensor size. So we check this special case when size is odd.\n      } else {\n        throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);\n      }\n    }\n\n    this.type = type;\n    this.dims = dims;\n    this.size = size;\n  }\n  // #endregion\n\n  // #region factory\n  static async fromImage(\n    image: ImageData | HTMLImageElement | ImageBitmap | string,\n    options?:\n      | TensorFromImageDataOptions\n      | TensorFromImageElementOptions\n      | TensorFromImageBitmapOptions\n      | TensorFromUrlOptions,\n  ): Promise<TensorInterface> {\n    return tensorFromImage(image, options);\n  }\n\n  static fromTexture<T extends TensorInterface.TextureDataTypes>(\n    texture: TensorTextureType,\n    options: TensorFromTextureOptions<T>,\n  ): TensorInterface {\n    return tensorFromTexture(texture, options);\n  }\n\n  static fromGpuBuffer<T extends TensorInterface.GpuBufferDataTypes>(\n    gpuBuffer: TensorGpuBufferType,\n    options: TensorFromGpuBufferOptions<T>,\n  ): TensorInterface {\n    return tensorFromGpuBuffer(gpuBuffer, options);\n  }\n\n  static fromMLTensor<T extends TensorInterface.MLTensorDataTypes>(\n    mlTensor: TensorMLTensorType,\n    options: TensorFromMLTensorOptions<T>,\n  ): TensorInterface {\n    return tensorFromMLTensor(mlTensor, options);\n  }\n\n  static fromPinnedBuffer<T extends TensorInterface.CpuPinnedDataTypes>(\n    type: T,\n    buffer: TensorInterface.DataTypeMap[T],\n    dims?: readonly number[],\n  ): Tensor {\n    return tensorFromPinnedBuffer(type, buffer, dims);\n  }\n\n  // #endregion\n\n  // #region conversions\n  toDataURL(options?: TensorToDataUrlOptions): string {\n    return tensorToDataURL(this, options);\n  }\n\n  toImageData(options?: TensorToImageDataOptions): ImageData {\n    return tensorToImageData(this, options);\n  }\n  // #endregion\n\n  // #region public fields\n  readonly dims: readonly number[];\n  readonly type: TensorType;\n  readonly size: number;\n  // #endregion\n\n  // #region private fields\n\n  /**\n   * stores the location of the data.\n   */\n  private dataLocation: TensorDataLocation;\n\n  /**\n   * stores the data on CPU, if location is 'cpu' or 'cpu-pinned'. otherwise empty.\n   */\n  private cpuData?: TensorDataType;\n\n  /**\n   * stores the underlying texture when location is 'texture'. otherwise empty.\n   */\n  private gpuTextureData?: TensorTextureType;\n\n  /**\n   * stores the underlying GPU buffer when location is 'gpu-buffer'. otherwise empty.\n   */\n  private gpuBufferData?: TensorGpuBufferType;\n\n  /**\n   * stores the underlying WebNN MLTensor when location is 'ml-tensor'. otherwise empty.\n   */\n  private mlTensorData?: TensorMLTensorType;\n\n  /**\n   * stores an optional downloader function to download data from GPU to CPU.\n   */\n  private downloader?(): Promise<TensorDataType>;\n\n  /**\n   * a flag indicating whether the data is being downloaded from GPU to CPU.\n   */\n  private isDownloading?: boolean;\n\n  /**\n   * stores an optional disposer function to dispose the underlying data.\n   */\n  private disposer?(): void;\n  // #endregion\n\n  // #region properties\n  get data(): TensorDataType {\n    this.ensureValid();\n    if (!this.cpuData) {\n      throw new Error(\n        'The data is not on CPU. Use `getData()` to download GPU data to CPU, ' +\n          'or use `texture` or `gpuBuffer` property to access the GPU data directly.',\n      );\n    }\n    return this.cpuData;\n  }\n\n  get location(): TensorDataLocation {\n    return this.dataLocation;\n  }\n\n  get texture(): TensorTextureType {\n    this.ensureValid();\n    if (!this.gpuTextureData) {\n      throw new Error('The data is not stored as a WebGL texture.');\n    }\n    return this.gpuTextureData;\n  }\n\n  get gpuBuffer(): TensorGpuBufferType {\n    this.ensureValid();\n    if (!this.gpuBufferData) {\n      throw new Error('The data is not stored as a WebGPU buffer.');\n    }\n    return this.gpuBufferData;\n  }\n\n  get mlTensor(): TensorMLTensorType {\n    this.ensureValid();\n    if (!this.mlTensorData) {\n      throw new Error('The data is not stored as a WebNN MLTensor.');\n    }\n    return this.mlTensorData;\n  }\n  // #endregion\n\n  // #region methods\n\n  async getData(releaseData?: boolean): Promise<TensorDataType> {\n    this.ensureValid();\n    switch (this.dataLocation) {\n      case 'cpu':\n      case 'cpu-pinned':\n        return this.data;\n      case 'texture':\n      case 'gpu-buffer':\n      case 'ml-tensor': {\n        if (!this.downloader) {\n          throw new Error('The current tensor is not created with a specified data downloader.');\n        }\n        if (this.isDownloading) {\n          throw new Error('The current tensor is being downloaded.');\n        }\n        try {\n          this.isDownloading = true;\n          const data = await this.downloader();\n          this.downloader = undefined;\n          this.dataLocation = 'cpu';\n          this.cpuData = data;\n\n          if (releaseData && this.disposer) {\n            this.disposer();\n            this.disposer = undefined;\n          }\n\n          return data;\n        } finally {\n          this.isDownloading = false;\n        }\n      }\n      default:\n        throw new Error(`cannot get data from location: ${this.dataLocation}`);\n    }\n  }\n\n  dispose(): void {\n    if (this.isDownloading) {\n      throw new Error('The current tensor is being downloaded.');\n    }\n\n    if (this.disposer) {\n      this.disposer();\n      this.disposer = undefined;\n    }\n    this.cpuData = undefined;\n    this.gpuTextureData = undefined;\n    this.gpuBufferData = undefined;\n    this.mlTensorData = undefined;\n    this.downloader = undefined;\n    this.isDownloading = undefined;\n\n    this.dataLocation = 'none';\n  }\n\n  // #endregion\n\n  // #region tensor utilities\n  private ensureValid(): void {\n    if (this.dataLocation === 'none') {\n      throw new Error('The tensor is disposed.');\n    }\n  }\n\n  reshape(dims: readonly number[]): TensorInterface {\n    this.ensureValid();\n    if (this.downloader || this.disposer) {\n      throw new Error('Cannot reshape a tensor that owns GPU resource.');\n    }\n    return tensorReshape(this, dims);\n  }\n  // #endregion\n}\n", "// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { TensorFactory } from './tensor-factory.js';\nimport { Tensor as TensorImpl } from './tensor-impl.js';\nimport { TypedTensorUtils } from './tensor-utils.js';\nimport { TryGetGlobalType } from './type-helper.js';\n\n/* eslint-disable @typescript-eslint/no-redeclare */\n\n/**\n * represent a basic tensor with specified dimensions and data type.\n */\ninterface TypedTensorBase<T extends Tensor.Type> {\n  /**\n   * Get the dimensions of the tensor.\n   */\n  readonly dims: readonly number[];\n  /**\n   * Get the data type of the tensor.\n   */\n  readonly type: T;\n  /**\n   * Get the buffer data of the tensor.\n   *\n   * If the data is not on CPU (eg. it's in the form of WebGL texture or WebGPU buffer), throw error.\n   */\n  readonly data: Tensor.DataTypeMap[T];\n  /**\n   * Get the location of the data.\n   */\n  readonly location: Tensor.DataLocation;\n  /**\n   * Get the WebGL texture that holds the tensor data.\n   *\n   * If the data is not on GPU as WebGL texture, throw error.\n   */\n  readonly texture: Tensor.TextureType;\n  /**\n   * Get the WebGPU buffer that holds the tensor data.\n   *\n   * If the data is not on GPU as WebGPU buffer, throw error.\n   */\n  readonly gpuBuffer: Tensor.GpuBufferType;\n\n  /**\n   * Get the WebNN MLTensor that holds the tensor data.\n   *\n   * If the data is not in a WebNN MLTensor, throw error.\n   */\n  readonly mlTensor: Tensor.MLTensorType;\n\n  /**\n   * Get the buffer data of the tensor.\n   *\n   * If the data is on CPU, returns the data immediately.\n   * If the data is on GPU, downloads the data and returns the promise.\n   *\n   * @param releaseData - whether release the data on GPU. Ignore if data is already on CPU.\n   */\n  getData(releaseData?: boolean): Promise<Tensor.DataTypeMap[T]>;\n\n  /**\n   * Dispose the tensor data.\n   *\n   * If the data is on CPU, remove its internal reference to the underlying data.\n   * If the data is on GPU, release the data on GPU.\n   *\n   * After calling this function, the tensor is considered no longer valid. Its location will be set to 'none'.\n   */\n  dispose(): void;\n}\n\nexport declare namespace Tensor {\n  interface DataTypeMap {\n    float32: Float32Array;\n    uint8: Uint8Array;\n    int8: Int8Array;\n    uint16: Uint16Array;\n    int16: Int16Array;\n    int32: Int32Array;\n    int64: BigInt64Array;\n    string: string[];\n    bool: Uint8Array;\n    float16: Uint16Array; // Keep using Uint16Array until we have a concrete solution for float 16.\n    float64: Float64Array;\n    uint32: Uint32Array;\n    uint64: BigUint64Array;\n    // complex64: never;\n    // complex128: never;\n    // bfloat16: never;\n    uint4: Uint8Array;\n    int4: Int8Array;\n  }\n\n  interface ElementTypeMap {\n    float32: number;\n    uint8: number;\n    int8: number;\n    uint16: number;\n    int16: number;\n    int32: number;\n    int64: bigint;\n    string: string;\n    bool: boolean;\n    float16: number; // Keep using Uint16Array until we have a concrete solution for float 16.\n    float64: number;\n    uint32: number;\n    uint64: bigint;\n    // complex64: never;\n    // complex128: never;\n    // bfloat16: never;\n    uint4: number;\n    int4: number;\n  }\n\n  type DataType = DataTypeMap[Type];\n  type ElementType = ElementTypeMap[Type];\n\n  /**\n   * supported data types for constructing a tensor from a pinned CPU buffer\n   */\n  export type CpuPinnedDataTypes = Exclude<Tensor.Type, 'string'>;\n\n  /**\n   * type alias for WebGL texture\n   */\n  export type TextureType = WebGLTexture;\n\n  /**\n   * supported data types for constructing a tensor from a WebGL texture\n   */\n  export type TextureDataTypes = 'float32';\n\n  type GpuBufferTypeFallback = { size: number; mapState: 'unmapped' | 'pending' | 'mapped' };\n  /**\n   * type alias for WebGPU buffer\n   */\n  export type GpuBufferType = TryGetGlobalType<'GPUBuffer', GpuBufferTypeFallback>;\n\n  type MLTensorTypeFallback = { destroy(): void };\n  /**\n   * type alias for WebNN MLTensor\n   *\n   * The specification for WebNN's MLTensor is currently in flux.\n   */\n  export type MLTensorType = TryGetGlobalType<'MLTensor', MLTensorTypeFallback>;\n\n  /**\n   * supported data types for constructing a tensor from a WebGPU buffer\n   */\n  export type GpuBufferDataTypes = 'float32' | 'float16' | 'int32' | 'int64' | 'uint32' | 'uint8' | 'bool';\n\n  /**\n   * supported data types for constructing a tensor from a WebNN MLTensor\n   */\n  export type MLTensorDataTypes =\n    | 'float32'\n    | 'float16'\n    | 'int8'\n    | 'uint8'\n    | 'int32'\n    | 'uint32'\n    | 'int64'\n    | 'uint64'\n    | 'bool'\n    | 'uint4'\n    | 'int4';\n\n  /**\n   * represent where the tensor data is stored\n   */\n  export type DataLocation = 'none' | 'cpu' | 'cpu-pinned' | 'texture' | 'gpu-buffer' | 'ml-tensor';\n\n  /**\n   * represent the data type of a tensor\n   */\n  export type Type = keyof DataTypeMap;\n}\n\n/**\n * Represent multi-dimensional arrays to feed to or fetch from model inferencing.\n */\nexport interface TypedTensor<T extends Tensor.Type> extends TypedTensorBase<T>, TypedTensorUtils<T> {}\n/**\n * Represent multi-dimensional arrays to feed to or fetch from model inferencing.\n */\nexport interface Tensor extends TypedTensorBase<Tensor.Type>, TypedTensorUtils<Tensor.Type> {}\n\n/**\n * type TensorConstructor defines the constructors of 'Tensor' to create CPU tensor instances.\n */\nexport interface TensorConstructor extends TensorFactory {\n  // #region CPU tensor - specify element type\n  /**\n   * Construct a new string tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: 'string',\n    data: Tensor.DataTypeMap['string'] | readonly string[],\n    dims?: readonly number[],\n  ): TypedTensor<'string'>;\n\n  /**\n   * Construct a new bool tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: 'bool',\n    data: Tensor.DataTypeMap['bool'] | readonly boolean[],\n    dims?: readonly number[],\n  ): TypedTensor<'bool'>;\n\n  /**\n   * Construct a new uint8 tensor object from a Uint8ClampedArray, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (type: 'uint8', data: Uint8ClampedArray, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new 64-bit integer typed tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new <T extends 'uint64' | 'int64'>(\n    type: T,\n    data: Tensor.DataTypeMap[T] | readonly bigint[] | readonly number[],\n    dims?: readonly number[],\n  ): TypedTensor<T>;\n\n  /**\n   * Construct a new numeric tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new <T extends Exclude<Tensor.Type, 'string' | 'bool' | 'uint64' | 'int64'>>(\n    type: T,\n    data: Tensor.DataTypeMap[T] | readonly number[],\n    dims?: readonly number[],\n  ): TypedTensor<T>;\n  // #endregion\n\n  // #region CPU tensor - infer element types\n\n  /**\n   * Construct a new float32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Float32Array, dims?: readonly number[]): TypedTensor<'float32'>;\n\n  /**\n   * Construct a new int8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int8Array, dims?: readonly number[]): TypedTensor<'int8'>;\n\n  /**\n   * Construct a new uint8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint8Array, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new uint8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint8ClampedArray, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new uint16 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint16Array, dims?: readonly number[]): TypedTensor<'uint16'>;\n\n  /**\n   * Construct a new int16 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int16Array, dims?: readonly number[]): TypedTensor<'int16'>;\n\n  /**\n   * Construct a new int32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int32Array, dims?: readonly number[]): TypedTensor<'int32'>;\n\n  /**\n   * Construct a new int64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: BigInt64Array, dims?: readonly number[]): TypedTensor<'int64'>;\n\n  /**\n   * Construct a new string tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: readonly string[], dims?: readonly number[]): TypedTensor<'string'>;\n\n  /**\n   * Construct a new bool tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: readonly boolean[], dims?: readonly number[]): TypedTensor<'bool'>;\n\n  /**\n   * Construct a new float64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Float64Array, dims?: readonly number[]): TypedTensor<'float64'>;\n\n  /**\n   * Construct a new uint32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint32Array, dims?: readonly number[]): TypedTensor<'uint32'>;\n\n  /**\n   * Construct a new uint64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: BigUint64Array, dims?: readonly number[]): TypedTensor<'uint64'>;\n\n  // #endregion\n\n  // #region CPU tensor - fall back to non-generic tensor type declaration\n\n  /**\n   * Construct a new tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: Tensor.Type,\n    data: Tensor.DataType | readonly number[] | readonly string[] | readonly bigint[] | readonly boolean[],\n    dims?: readonly number[],\n  ): Tensor;\n\n  /**\n   * Construct a new tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Tensor.DataType, dims?: readonly number[]): Tensor;\n  // #endregion\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const Tensor = TensorImpl as TensorConstructor;\n", "/**\n * @file Handler file for choosing the correct version of ONNX Runtime, based on the environment.\n * Ideally, we could import the `onnxruntime-web` and `onnxruntime-node` packages only when needed,\n * but dynamic imports don't seem to work with the current webpack version and/or configuration.\n * This is possibly due to the experimental nature of top-level await statements.\n * So, we just import both packages, and use the appropriate one based on the environment:\n *   - When running in node, we use `onnxruntime-node`.\n *   - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).\n * \n * This module is not directly exported, but can be accessed through the environment variables:\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * console.log(env.backends.onnx);\n * ```\n * \n * @module backends/onnx\n */\n\nimport { env, apis } from '../env.js';\n\n// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.\n// In either case, we select the default export if it exists, otherwise we use the named export.\nimport * as ONNX_NODE from 'onnxruntime-node';\nimport * as ONNX_WEB from 'onnxruntime-web';\n\nexport { Tensor } from 'onnxruntime-common';\n\n/**\n * @typedef {import('onnxruntime-common').InferenceSession.ExecutionProviderConfig} ONNXExecutionProviders\n */\n\n/** @type {Record<import(\"../utils/devices.js\").DeviceType, ONNXExecutionProviders>} */\nconst DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({\n    auto: null, // Auto-detect based on device and environment\n    gpu: null, // Auto-detect GPU\n    cpu: 'cpu', // CPU\n    wasm: 'wasm', // WebAssembly\n    webgpu: 'webgpu', // WebGPU\n    cuda: 'cuda', // CUDA\n    dml: 'dml', // DirectML\n\n    webnn: { name: 'webnn', deviceType: 'cpu' }, // WebNN (default)\n    'webnn-npu': { name: 'webnn', deviceType: 'npu' }, // WebNN NPU\n    'webnn-gpu': { name: 'webnn', deviceType: 'gpu' }, // WebNN GPU\n    'webnn-cpu': { name: 'webnn', deviceType: 'cpu' }, // WebNN CPU\n});\n\n/** \n * The list of supported devices, sorted by priority/performance.\n * @type {import(\"../utils/devices.js\").DeviceType[]}\n */\nconst supportedDevices = [];\n\n/** @type {ONNXExecutionProviders[]} */\nlet defaultDevices;\nlet ONNX;\nconst ORT_SYMBOL = Symbol.for('onnxruntime');\n\nif (ORT_SYMBOL in globalThis) {\n    // If the JS runtime exposes their own ONNX runtime, use it\n    ONNX = globalThis[ORT_SYMBOL];\n\n} else if (apis.IS_NODE_ENV) {\n    ONNX = ONNX_NODE.default ?? ONNX_NODE;\n\n    // Updated as of ONNX Runtime 1.20.1\n    // The following table lists the supported versions of ONNX Runtime Node.js binding provided with pre-built binaries.\n    // | EPs/Platforms | Windows x64 | Windows arm64 | Linux x64         | Linux arm64 | MacOS x64 | MacOS arm64 |\n    // | ------------- | ----------- | ------------- | ----------------- | ----------- | --------- | ----------- |\n    // | CPU           | \u2714\uFE0F          | \u2714\uFE0F            | \u2714\uFE0F                | \u2714\uFE0F          | \u2714\uFE0F        | \u2714\uFE0F          |\n    // | DirectML      | \u2714\uFE0F          | \u2714\uFE0F            | \u274C                | \u274C          | \u274C        | \u274C          |\n    // | CUDA          | \u274C          | \u274C            | \u2714\uFE0F (CUDA v11.8)   | \u274C          | \u274C        | \u274C          |\n    switch (process.platform) {\n        case 'win32': // Windows x64 and Windows arm64\n            supportedDevices.push('dml');\n            break;\n        case 'linux': // Linux x64 and Linux arm64\n            if (process.arch === 'x64') {\n                supportedDevices.push('cuda');\n            }\n            break;\n        case 'darwin': // MacOS x64 and MacOS arm64\n            break;\n    }\n\n    supportedDevices.push('cpu');\n    defaultDevices = ['cpu'];\n} else {\n    ONNX = ONNX_WEB;\n\n    if (apis.IS_WEBNN_AVAILABLE) {\n        // TODO: Only push supported providers (depending on available hardware)\n        supportedDevices.push('webnn-npu', 'webnn-gpu', 'webnn-cpu', 'webnn');\n    }\n\n    if (apis.IS_WEBGPU_AVAILABLE) {\n        supportedDevices.push('webgpu');\n    }\n\n    supportedDevices.push('wasm');\n    defaultDevices = ['wasm'];\n}\n\n// @ts-ignore\nconst InferenceSession = ONNX.InferenceSession;\n\n/**\n * Map a device to the execution providers to use for the given device.\n * @param {import(\"../utils/devices.js\").DeviceType|\"auto\"|null} [device=null] (Optional) The device to run the inference on.\n * @returns {ONNXExecutionProviders[]} The execution providers to use for the given device.\n */\nexport function deviceToExecutionProviders(device = null) {\n    // Use the default execution providers if the user hasn't specified anything\n    if (!device) return defaultDevices;\n\n    // Handle overloaded cases\n    switch (device) {\n        case \"auto\":\n            return supportedDevices;\n        case \"gpu\":\n            return supportedDevices.filter(x =>\n                [\"webgpu\", \"cuda\", \"dml\", \"webnn-gpu\"].includes(x),\n            );\n    }\n\n    if (supportedDevices.includes(device)) {\n        return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device];\n    }\n\n    throw new Error(`Unsupported device: \"${device}\". Should be one of: ${supportedDevices.join(', ')}.`)\n}\n\n\n/**\n * To prevent multiple calls to `initWasm()`, we store the first call in a Promise\n * that is resolved when the first InferenceSession is created. Subsequent calls\n * will wait for this Promise to resolve before creating their own InferenceSession.\n * @type {Promise<any>|null}\n */\nlet wasmInitPromise = null;\n\n/**\n * Create an ONNX inference session.\n * @param {Uint8Array|string} buffer_or_path The ONNX model buffer or path.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options ONNX inference session options.\n * @param {Object} session_config ONNX inference session configuration.\n * @returns {Promise<import('onnxruntime-common').InferenceSession & { config: Object}>} The ONNX inference session.\n */\nexport async function createInferenceSession(buffer_or_path, session_options, session_config) {\n    if (wasmInitPromise) {\n        // A previous session has already initialized the WASM runtime\n        // so we wait for it to resolve before creating this new session.\n        await wasmInitPromise;\n    }\n\n    const sessionPromise = InferenceSession.create(buffer_or_path, session_options);\n    wasmInitPromise ??= sessionPromise;\n    const session = await sessionPromise;\n    session.config = session_config;\n    return session;\n}\n\n\n/**\n * Currently, Transformers.js doesn't support simultaneous execution of sessions in WASM/WebGPU.\n * For this reason, we need to chain the inference calls (otherwise we get \"Error: Session already started\").\n * @type {Promise<any>}\n */\nlet webInferenceChain = Promise.resolve();\n\nconst IS_WEB_ENV = apis.IS_BROWSER_ENV || apis.IS_WEBWORKER_ENV;\n\n/**\n * Run an inference session.\n * @param {import('onnxruntime-common').InferenceSession} session The ONNX inference session.\n * @param {Record<string, import('onnxruntime-common').Tensor>} ortFeed The input tensors.\n * @returns {Promise<Record<string, import('onnxruntime-common').Tensor>>} The output tensors.\n */\nexport async function runInferenceSession(session, ortFeed) {\n    const run = () => session.run(ortFeed);\n    const output = await (IS_WEB_ENV\n        ? (webInferenceChain = webInferenceChain.then(run))\n        : run()\n    );\n    return output;\n}\n\n\n/**\n * Check if an object is an ONNX tensor.\n * @param {any} x The object to check\n * @returns {boolean} Whether the object is an ONNX tensor.\n */\nexport function isONNXTensor(x) {\n    return x instanceof ONNX.Tensor;\n}\n\n/** @type {import('onnxruntime-common').Env} */\n// @ts-ignore\nconst ONNX_ENV = ONNX?.env;\nif (ONNX_ENV?.wasm) {\n    // Initialize wasm backend with suitable default settings.\n\n    // (Optional) Set path to wasm files. This will override the default path search behavior of onnxruntime-web.\n    // By default, we only do this if we are not in a service worker and the wasmPaths are not already set.\n    if (\n        // @ts-ignore Cannot find name 'ServiceWorkerGlobalScope'.ts(2304)\n        !(typeof ServiceWorkerGlobalScope !== 'undefined' && self instanceof ServiceWorkerGlobalScope)\n        && !ONNX_ENV.wasm.wasmPaths\n    ) {\n        ONNX_ENV.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${env.version}/dist/`;\n    }\n\n    // TODO: Add support for loading WASM files from cached buffer when we upgrade to onnxruntime-web@1.19.0\n    // https://github.com/microsoft/onnxruntime/pull/21534\n\n    // Users may wish to proxy the WASM backend to prevent the UI from freezing,\n    // However, this is not necessary when using WebGPU, so we default to false.\n    ONNX_ENV.wasm.proxy = false;\n}\n\nif (ONNX_ENV?.webgpu) {\n    ONNX_ENV.webgpu.powerPreference = 'high-performance';\n}\n\n/**\n * Check if ONNX's WASM backend is being proxied.\n * @returns {boolean} Whether ONNX's WASM backend is being proxied.\n */\nexport function isONNXProxy() {\n    // TODO: Update this when allowing non-WASM backends.\n    return ONNX_ENV?.wasm?.proxy;\n}\n\n// Expose ONNX environment variables to `env.backends.onnx`\nenv.backends.onnx = ONNX_ENV;\n", "/**\n * @file Helper module for `Tensor` processing.\n *\n * These functions and classes are only used internally,\n * meaning an end-user shouldn't need to access anything here.\n *\n * @module utils/tensor\n */\n\nimport {\n    interpolate_data,\n    max,\n    min,\n    permute_data\n} from './maths.js';\n\nimport {\n    Tensor as ONNXTensor, isONNXTensor,\n} from '../backends/onnx.js';\n\nimport { TensorOpRegistry } from '../ops/registry.js';\n\nexport const DataTypeMap = Object.freeze({\n    float32: Float32Array,\n    // @ts-ignore ts(2552) Limited availability of Float16Array across browsers:\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array\n    float16: typeof Float16Array !== \"undefined\" ? Float16Array: Uint16Array,\n    float64: Float64Array,\n    string: Array, // string[]\n    int8: Int8Array,\n    uint8: Uint8Array,\n    int16: Int16Array,\n    uint16: Uint16Array,\n    int32: Int32Array,\n    uint32: Uint32Array,\n    int64: BigInt64Array,\n    uint64: BigUint64Array,\n    bool: Uint8Array,\n    uint4: Uint8Array,\n    int4: Int8Array,\n});\n\n/**\n * @typedef {keyof typeof DataTypeMap} DataType\n * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray\n */\n\n\nexport class Tensor {\n    /** @type {number[]} Dimensions of the tensor. */\n    get dims() {\n        // @ts-ignore\n        return this.ort_tensor.dims;\n    }\n    set dims(value) {\n        // FIXME: ONNXTensor declares dims as readonly so one needs to use the constructor() if dims change.\n        // @ts-ignore\n        this.ort_tensor.dims = value;\n    }\n\n    /** @type {DataType} Type of the tensor. */\n    get type() {\n        return this.ort_tensor.type;\n    };\n\n    /** @type {DataArray} The data stored in the tensor. */\n    get data() {\n        return this.ort_tensor.data;\n    }\n\n    /** @type {number} The number of elements in the tensor. */\n    get size() {\n        return this.ort_tensor.size;\n    };\n\n    /** @type {string} The location of the tensor data. */\n    get location() {\n        return this.ort_tensor.location;\n    };\n\n    ort_tensor;\n\n    /**\n     * Create a new Tensor or copy an existing Tensor.\n     * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args\n     */\n    constructor(...args) {\n        if (isONNXTensor(args[0])) {\n            this.ort_tensor = /** @type {ONNXTensor} */ (args[0]);\n        } else {\n            // Create new tensor\n            this.ort_tensor = new ONNXTensor(\n                /** @type {DataType} */(args[0]),\n                // @ts-expect-error ts(2769) Type 'number' is not assignable to type 'bigint'.\n                /** @type {Exclude<import('./maths.js').AnyTypedArray, Uint8ClampedArray>} */(args[1]),\n                args[2],\n            );\n        }\n\n        return new Proxy(this, {\n            get: (obj, key) => {\n                if (typeof key === 'string') {\n                    let index = Number(key);\n                    if (Number.isInteger(index)) {\n                        // key is an integer (i.e., index)\n                        return obj._getitem(index);\n                    }\n                }\n                // @ts-ignore\n                return obj[key];\n            },\n            set: (obj, key, value) => {\n                // TODO allow setting of data\n\n                // @ts-ignore\n                return obj[key] = value;\n            }\n        });\n    }\n\n    dispose() {\n        this.ort_tensor.dispose();\n        // this.ort_tensor = undefined;\n    }\n\n    /**\n     * Returns an iterator object for iterating over the tensor data in row-major order.\n     * If the tensor has more than one dimension, the iterator will yield subarrays.\n     * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.\n     */\n    *[Symbol.iterator]() {\n        const [iterLength, ...iterDims] = this.dims;\n\n        if (iterDims.length > 0) {\n            const iterSize = iterDims.reduce((a, b) => a * b);\n            for (let i = 0; i < iterLength; ++i) {\n                yield this._subarray(i, iterSize, iterDims);\n            }\n        } else {\n            yield* this.data\n        }\n\n    }\n\n    /**\n     * Index into a Tensor object.\n     * @param {number} index The index to access.\n     * @returns {Tensor} The data at the specified index.\n     */\n    _getitem(index) {\n        const [iterLength, ...iterDims] = this.dims;\n\n        index = safeIndex(index, iterLength);\n\n        if (iterDims.length > 0) {\n            const iterSize = iterDims.reduce((a, b) => a * b);\n            return this._subarray(index, iterSize, iterDims);\n        } else {\n            return new Tensor(this.type, [this.data[index]], iterDims);\n        }\n    }\n\n    /**\n     * @param {number|bigint} item The item to search for in the tensor\n     * @returns {number} The index of the first occurrence of item in the tensor data.\n     */\n    indexOf(item) {\n        const this_data = this.data;\n        for (let index = 0; index < this_data.length; ++index) {\n            // Note: == instead of === so we can match Ints with BigInts\n            if (this_data[index] == item) {\n                return index;\n            }\n        }\n        return -1;\n    }\n\n    /**\n     * @param {number} index\n     * @param {number} iterSize\n     * @param {any} iterDims\n     * @returns {Tensor}\n     */\n    _subarray(index, iterSize, iterDims) {\n        const o1 = index * iterSize;\n        const o2 = (index + 1) * iterSize;\n\n        // We use subarray if available (typed array), otherwise we use slice (normal array)\n        const data =\n            ('subarray' in this.data)\n                ? this.data.subarray(o1, o2)\n                : this.data.slice(o1, o2);\n        return new Tensor(this.type, data, iterDims);\n    }\n\n    /**\n     * Returns the value of this tensor as a standard JavaScript Number. This only works\n     * for tensors with one element. For other cases, see `Tensor.tolist()`.\n     * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.\n     * @throws {Error} If the tensor has more than one element.\n     */\n    item() {\n        const this_data = this.data;\n        if (this_data.length !== 1) {\n            throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`);\n        }\n        return this_data[0];\n    }\n\n    /**\n     * Convert tensor data to a n-dimensional JS list\n     * @returns {Array}\n     */\n    tolist() {\n        return reshape(this.data, this.dims)\n    }\n\n    /**\n     * Return a new Tensor with the sigmoid function applied to each element.\n     * @returns {Tensor} The tensor with the sigmoid function applied.\n     */\n    sigmoid() {\n        return this.clone().sigmoid_();\n    }\n\n    /**\n     * Applies the sigmoid function to the tensor in place.\n     * @returns {Tensor} Returns `this`.\n     */\n    sigmoid_() {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] = 1 / (1 + Math.exp(-this_data[i]));\n        }\n        return this;\n    }\n\n    /**\n     * Return a new Tensor with a callback function applied to each element.\n     * @param {Function} callback - The function to apply to each element. It should take three arguments:\n     *                              the current element, its index, and the tensor's data array.\n     * @returns {Tensor} A new Tensor with the callback function applied to each element.\n     */\n    map(callback) {\n        return this.clone().map_(callback);\n    }\n\n    /**\n     * Apply a callback function to each element of the tensor in place.\n     * @param {Function} callback - The function to apply to each element. It should take three arguments:\n     *                              the current element, its index, and the tensor's data array.\n     * @returns {Tensor} Returns `this`.\n     */\n    map_(callback) {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] = callback(this_data[i], i, this_data);\n        }\n        return this;\n    }\n\n    /**\n     * Return a new Tensor with every element multiplied by a constant.\n     * @param {number} val The value to multiply by.\n     * @returns {Tensor} The new tensor.\n     */\n    mul(val) {\n        return this.clone().mul_(val);\n    }\n\n    /**\n     * Multiply the tensor by a constant in place.\n     * @param {number} val The value to multiply by.\n     * @returns {Tensor} Returns `this`.\n     */\n    mul_(val) {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] *= val;\n        }\n        return this;\n    }\n\n    /**\n     * Return a new Tensor with every element divided by a constant.\n     * @param {number} val The value to divide by.\n     * @returns {Tensor} The new tensor.\n     */\n    div(val) {\n        return this.clone().div_(val);\n    }\n\n    /**\n     * Divide the tensor by a constant in place.\n     * @param {number} val The value to divide by.\n     * @returns {Tensor} Returns `this`.\n     */\n    div_(val) {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] /= val;\n        }\n        return this;\n    }\n\n    /**\n     * Return a new Tensor with every element added by a constant.\n     * @param {number} val The value to add by.\n     * @returns {Tensor} The new tensor.\n     */\n    add(val) {\n        return this.clone().add_(val);\n    }\n\n    /**\n     * Add the tensor by a constant in place.\n     * @param {number} val The value to add by.\n     * @returns {Tensor} Returns `this`.\n     */\n    add_(val) {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] += val;\n        }\n        return this;\n    }\n\n    /**\n     * Return a new Tensor with every element subtracted by a constant.\n     * @param {number} val The value to subtract by.\n     * @returns {Tensor} The new tensor.\n     */\n    sub(val) {\n        return this.clone().sub_(val);\n    }\n\n    /**\n     * Subtract the tensor by a constant in place.\n     * @param {number} val The value to subtract by.\n     * @returns {Tensor} Returns `this`.\n     */\n    sub_(val) {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] -= val;\n        }\n        return this;\n    }\n\n    /**\n     * Creates a deep copy of the current Tensor.\n     * @returns {Tensor} A new Tensor with the same type, data, and dimensions as the original.\n     */\n    clone() {\n        return new Tensor(this.type, this.data.slice(), this.dims.slice());\n    }\n\n    /**\n     * Performs a slice operation on the Tensor along specified dimensions.\n     *\n     * Consider a Tensor that has a dimension of [4, 7]:\n     * ```\n     * [ 1,  2,  3,  4,  5,  6,  7]\n     * [ 8,  9, 10, 11, 12, 13, 14]\n     * [15, 16, 17, 18, 19, 20, 21]\n     * [22, 23, 24, 25, 26, 27, 28]\n     * ```\n     * We can slice against the two dims of row and column, for instance in this\n     * case we can start at the second element, and return to the second last,\n     * like this:\n     * ```\n     * tensor.slice([1, -1], [1, -1]);\n     * ```\n     * which would return:\n     * ```\n     * [  9, 10, 11, 12, 13 ]\n     * [ 16, 17, 18, 19, 20 ]\n     * ```\n     *\n     * @param {...(number|number[]|null)} slices The slice specifications for each dimension.\n     * - If a number is given, then a single element is selected.\n     * - If an array of two numbers is given, then a range of elements [start, end (exclusive)] is selected.\n     * - If null is given, then the entire dimension is selected.\n     * @returns {Tensor} A new Tensor containing the selected elements.\n     * @throws {Error} If the slice input is invalid.\n     */\n    slice(...slices) {\n        // This allows for slicing with ranges and numbers\n        const newTensorDims = [];\n        const newOffsets = [];\n\n        // slices is an array of numbers or arrays of numbers\n        // e.g., slices = [0, [1, 3], null, [0, 3]]\n        for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {\n            let slice = slices[sliceIndex];\n\n            if (slice === null || slice === undefined) {\n                // null or undefined means take the whole dimension\n                newOffsets.push([0, this.dims[sliceIndex]]);\n                newTensorDims.push(this.dims[sliceIndex]);\n\n            } else if (typeof slice === 'number') {\n                slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);\n\n                // A number means take a single element\n                newOffsets.push([slice, slice + 1]);\n\n            } else if (Array.isArray(slice) && slice.length === 2) {\n                // An array of length 2 means take a range of elements\n                let [start, end] = slice;\n                start = start === null\n                    ? 0\n                    : safeIndex(start, this.dims[sliceIndex], sliceIndex, false);\n                end = end === null\n                    ? this.dims[sliceIndex]\n                    : safeIndex(end, this.dims[sliceIndex], sliceIndex, false);\n\n                if (start > end) {\n                    throw new Error(`Invalid slice: ${slice}`);\n                }\n\n                const offsets = [\n                    Math.max(start, 0),\n                    Math.min(end, this.dims[sliceIndex])\n                ];\n\n                newOffsets.push(offsets);\n                newTensorDims.push(offsets[1] - offsets[0]);\n\n            } else {\n                throw new Error(`Invalid slice: ${slice}`);\n            }\n        }\n\n        const newDims = newOffsets.map(([start, end]) => end - start);\n        const newBufferSize = newDims.reduce((a, b) => a * b);\n\n        const this_data = this.data;\n        // Allocate memory\n        // @ts-ignore\n        const data = new this_data.constructor(newBufferSize);\n\n        // Precompute strides\n        const stride = this.stride();\n\n        // Detect if the slice is contiguous\n        let isContiguous = true;\n        for (let i = 1; i < newDims.length; ++i) {\n            if (newOffsets[i][0] !== 0 || newOffsets[i][1] !== this.dims[i]) {\n                isContiguous = false;\n                break;\n            }\n        }\n\n        if (isContiguous) {\n            // Perform bulk copy for contiguous slices to improve performance\n            const start = newOffsets[0][0] * stride[0];\n            const end = newOffsets[0][1] * stride[0];\n\n            if (ArrayBuffer.isView(this_data)) {\n                // If this.data is a TypedArray, use subarray\n                // @ts-ignore\n                data.set(this_data.subarray(start, end));\n            } else if (Array.isArray(this_data)) {\n                // If this.data is a plain array, use slice\n                const slicedData = this_data.slice(start, end);\n                for (let i = 0; i < slicedData.length; ++i) {\n                    data[i] = slicedData[i];\n                }\n            } else {\n                throw new Error(\"Unsupported data type for slicing\");\n            }\n        } else {\n            // Fallback to manual copying for non-contiguous slices\n            for (let i = 0; i < newBufferSize; ++i) {\n                let originalIndex = 0;\n                for (let j = newDims.length - 1, num = i; j >= 0; --j) {\n                    const size = newDims[j];\n                    originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];\n                    num = Math.floor(num / size);\n                }\n                data[i] = this_data[originalIndex];\n            }\n        }\n\n        return new Tensor(this.type, data, newTensorDims);\n    }\n\n    /**\n     * Return a permuted version of this Tensor, according to the provided dimensions.\n     * @param  {...number} dims Dimensions to permute.\n     * @returns {Tensor} The permuted tensor.\n     */\n    permute(...dims) {\n        return permute(this, dims);\n    }\n\n    // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()\n    transpose(...dims) {\n        return this.permute(...dims);\n    }\n\n    /**\n     * Returns the sum of each row of the input tensor in the given dimension dim.\n     *\n     * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.\n     * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.\n     * @returns The summed tensor\n     */\n    sum(dim = null, keepdim = false) {\n        return this.norm(1, dim, keepdim);\n    }\n\n    /**\n     * Returns the matrix norm or vector norm of a given tensor.\n     * @param {number|string} [p='fro'] The order of norm\n     * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.\n     * If dim is None, the norm will be calculated across all dimensions of input.\n     * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.\n     * @returns {Tensor} The norm of the tensor.\n     */\n    norm(p = 'fro', dim = null, keepdim = false) {\n        if (p === 'fro') {\n            // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.\n            p = 2;\n        } else if (typeof p === 'string') {\n            throw Error(`Unsupported norm: ${p}`);\n        }\n\n        const this_data = this.data;\n        const fn = (a, b) => a + (b ** p);\n\n        if (dim === null) {\n            // @ts-ignore\n            const val = this_data.reduce(fn, 0) ** (1 / p);\n            return new Tensor(this.type, [val], []);\n        }\n\n        const [type, result, resultDims] = reduce_helper(fn, this, dim, keepdim);\n\n        if (p !== 1) {\n            for (let i = 0; i < result.length; ++i) {\n                result[i] = result[i] ** (1 / p);\n            }\n        }\n        return new Tensor(type, result, resultDims);\n    }\n\n    /**\n     * Performs `L_p` normalization of inputs over specified dimension. Operates in place.\n     * @param {number} [p=2] The exponent value in the norm formulation\n     * @param {number} [dim=1] The dimension to reduce\n     * @returns {Tensor} `this` for operation chaining.\n     */\n    normalize_(p = 2.0, dim = 1) {\n        dim = safeIndex(dim, this.dims.length);\n\n        const norm = this.norm(p, dim, true);\n\n        const this_data = this.data;\n        const norm_data = norm.data;\n        for (let i = 0; i < this_data.length; ++i) {\n\n            // Calculate the index in the resulting array\n            let resultIndex = 0;\n\n            for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n                const size = this.dims[j];\n                if (j !== dim) {\n                    const index = num % size;\n                    resultIndex += index * resultMultiplier;\n                    resultMultiplier *= this.dims[j];\n                }\n                num = Math.floor(num / size);\n            }\n\n            // Divide by normalized value\n            this_data[i] /= norm_data[resultIndex];\n        }\n\n        return this;\n    }\n\n    /**\n     * Performs `L_p` normalization of inputs over specified dimension.\n     * @param {number} [p=2] The exponent value in the norm formulation\n     * @param {number} [dim=1] The dimension to reduce\n     * @returns {Tensor} The normalized tensor.\n     */\n    normalize(p = 2.0, dim = 1) {\n        return this.clone().normalize_(p, dim);\n    }\n\n    /**\n     * Compute and return the stride of this tensor.\n     * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.\n     * @returns {number[]} The stride of this tensor.\n     */\n    stride() {\n        return dimsToStride(this.dims);\n    }\n\n    /**\n     * Returns a tensor with all specified dimensions of input of size 1 removed.\n     *\n     * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.\n     * If you would like a copy, use `tensor.clone()` before squeezing.\n     *\n     * @param {number|number[]} [dim=null] If given, the input will be squeezed only in the specified dimensions.\n     * @returns {Tensor} The squeezed tensor\n     */\n    squeeze(dim = null) {\n        return new Tensor(\n            this.type,\n            this.data,\n            calc_squeeze_dims(this.dims, dim)\n        )\n    }\n\n    /**\n     * In-place version of @see {@link Tensor.squeeze}\n     */\n    squeeze_(dim = null) {\n        this.dims = calc_squeeze_dims(this.dims, dim);\n        return this;\n    }\n\n    /**\n     * Returns a new tensor with a dimension of size one inserted at the specified position.\n     *\n     * NOTE: The returned tensor shares the same underlying data with this tensor.\n     *\n     * @param {number} dim The index at which to insert the singleton dimension\n     * @returns {Tensor} The unsqueezed tensor\n     */\n    unsqueeze(dim = null) {\n        return new Tensor(\n            this.type,\n            this.data,\n            calc_unsqueeze_dims(this.dims, dim)\n        );\n    }\n\n    /**\n     * In-place version of @see {@link Tensor.unsqueeze}\n     */\n    unsqueeze_(dim = null) {\n        this.dims = calc_unsqueeze_dims(this.dims, dim);\n        return this;\n    }\n\n    /**\n     * In-place version of @see {@link Tensor.flatten}\n     */\n    flatten_(start_dim = 0, end_dim = -1) {\n        // TODO validate inputs\n        end_dim = (end_dim + this.dims.length) % this.dims.length;\n\n        let dimsToKeepBefore = this.dims.slice(0, start_dim);\n        let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);\n        let dimsToKeepAfter = this.dims.slice(end_dim + 1);\n\n        this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]\n        return this;\n    }\n\n    /**\n     * Flattens input by reshaping it into a one-dimensional tensor.\n     * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`\n     * and ending with `end_dim` are flattened. The order of elements in input is unchanged.\n     * @param {number} start_dim the first dim to flatten\n     * @param {number} end_dim the last dim to flatten\n     * @returns {Tensor} The flattened tensor.\n     */\n    flatten(start_dim = 0, end_dim = -1) {\n        return this.clone().flatten_(start_dim, end_dim);\n    }\n\n    /**\n     * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.\n     * @param  {...number} dims the desired size\n     * @returns {Tensor} The tensor with the same data but different shape\n     */\n    view(...dims) {\n        // TODO: validate dims\n        let inferredIndex = -1;\n        for (let i = 0; i < dims.length; ++i) {\n            if (dims[i] === -1) {\n                if (inferredIndex !== -1) {\n                    throw new Error(\"Only one dimension can be inferred\");\n                }\n                inferredIndex = i;\n            }\n        }\n\n        const this_data = this.data;\n        if (inferredIndex !== -1) {\n            // Some dimension must be inferred\n            const productOther = dims.reduce((product, curr, index) => {\n                return index !== inferredIndex ? product * curr : product\n            }, 1);\n\n            dims[inferredIndex] = this_data.length / productOther;\n        }\n        return new Tensor(this.type, this_data, dims); // NOTE: uses same underlying storage\n    }\n\n    neg_() {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] = -this_data[i];\n        }\n        return this;\n    }\n    neg() {\n        return this.clone().neg_();\n    }\n\n    /**\n     * Computes input > val element-wise.\n     * @param {number} val The value to compare with.\n     * @returns {Tensor} A boolean tensor that is `true` where input is greater than other and `false` elsewhere.\n     */\n    gt(val) {\n        const mask = new Uint8Array(this.data.length);\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            mask[i] = this_data[i] > val ? 1 : 0;\n        }\n        return new Tensor('bool', mask, this.dims);\n    }\n\n    /**\n     * Computes input < val element-wise.\n     * @param {number} val The value to compare with.\n     * @returns {Tensor} A boolean tensor that is `true` where input is less than other and `false` elsewhere.\n     */\n    lt(val) {\n        const mask = new Uint8Array(this.data.length);\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            mask[i] = this_data[i] < val ? 1 : 0;\n        }\n        return new Tensor('bool', mask, this.dims);\n    }\n\n    /**\n     * In-place version of @see {@link Tensor.clamp}\n     */\n    clamp_(min, max) {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] = Math.min(Math.max(this_data[i], min), max);\n        }\n        return this;\n    }\n\n    /**\n     * Clamps all elements in input into the range [ min, max ]\n     * @param {number} min lower-bound of the range to be clamped to\n     * @param {number} max upper-bound of the range to be clamped to\n     * @returns {Tensor} the output tensor.\n     */\n    clamp(min, max) {\n        return this.clone().clamp_(min, max);\n    }\n\n    /**\n     * In-place version of @see {@link Tensor.round}\n     */\n    round_() {\n        const this_data = this.data;\n        for (let i = 0; i < this_data.length; ++i) {\n            this_data[i] = Math.round(this_data[i]);\n        }\n        return this;\n    }\n\n    /**\n     * Rounds elements of input to the nearest integer.\n     * @returns {Tensor} the output tensor.\n     */\n    round() {\n        return this.clone().round_();\n    }\n\n    mean(dim = null, keepdim = false) {\n        return mean(this, dim, keepdim);\n    }\n\n    min(dim = null, keepdim = false) {\n        if (dim === null) {\n            // None to reduce over all dimensions.\n            const val = min(this.data)[0];\n            return new Tensor(this.type, [val], [/* scalar */]);\n        }\n        const [type, result, resultDims] = reduce_helper((a, b) => Math.min(a, b), this, dim, keepdim, Infinity);\n        return new Tensor(type, result, resultDims);\n    }\n\n    max(dim = null, keepdim = false) {\n        if (dim === null) {\n            // None to reduce over all dimensions.\n            const val = max(this.data)[0];\n            return new Tensor(this.type, [val], [/* scalar */]);\n        }\n        const [type, result, resultDims] = reduce_helper((a, b) => Math.max(a, b), this, dim, keepdim, -Infinity);\n        return new Tensor(type, result, resultDims);\n    }\n\n    argmin(dim = null, keepdim = false) {\n        if (dim !== null) {\n            throw new Error(\"`dim !== null` not yet implemented.\");\n        }\n        const index = min(this.data)[1];\n        return new Tensor('int64', [BigInt(index)], []);\n    }\n    argmax(dim = null, keepdim = false) {\n        if (dim !== null) {\n            throw new Error(\"`dim !== null` not yet implemented.\");\n        }\n        const index = max(this.data)[1];\n        return new Tensor('int64', [BigInt(index)], []);\n    }\n\n    /**\n     * Performs Tensor dtype conversion.\n     * @param {DataType} type The desired data type.\n     * @returns {Tensor} The converted tensor.\n     */\n    to(type) {\n        // If the self Tensor already has the correct dtype, then self is returned.\n        if (this.type === type) return this;\n\n        // Otherwise, the returned tensor is a copy of self with the desired dtype.\n        if (!DataTypeMap.hasOwnProperty(type)) {\n            throw new Error(`Unsupported type: ${type}`);\n        }\n\n        // Handle special cases where a mapping function is needed (e.g., where one type is a bigint and the other is a number)\n        let map_fn;\n        const is_source_bigint = ['int64', 'uint64'].includes(this.type);\n        const is_dest_bigint = ['int64', 'uint64'].includes(type);\n        if (is_source_bigint && !is_dest_bigint) {\n            // TypeError: Cannot convert a BigInt value to a number\n            map_fn = Number;\n        } else if (!is_source_bigint && is_dest_bigint) {\n            // TypeError: Cannot convert [x] to a BigInt\n            if (['float16', 'float32', 'float64'].includes(this.type)) {\n                map_fn = (x) => BigInt(Math.floor(x));\n            } else {\n                map_fn = BigInt;\n            }\n        }\n\n        // @ts-ignore\n        return new Tensor(type, DataTypeMap[type].from(this.data, map_fn), this.dims);\n    }\n}\n\n/**\n * This creates a nested array of a given type and depth (see examples).\n *\n * @example\n *   NestArray<string, 1>; // string[]\n * @example\n *   NestArray<number, 2>; // number[][]\n * @example\n *   NestArray<string, 3>; // string[][][] etc.\n * @template T\n * @template {number} Depth\n * @template {never[]} [Acc=[]]\n * @typedef {Acc['length'] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>} NestArray\n */\n\n/**\n * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.\n *\n * @example\n *   reshape([10                    ], [1      ]); // Type: number[]      Value: [10]\n *   reshape([1, 2, 3, 4            ], [2, 2   ]); // Type: number[][]    Value: [[1, 2], [3, 4]]\n *   reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][]  Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n *   reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2   ]); // Type: number[][]    Value: [[1, 2], [3, 4], [5, 6], [7, 8]]\n * @param {T[]|DataArray} data The input array to reshape.\n * @param {DIM} dimensions The target shape/dimensions.\n * @template T\n * @template {[number]|number[]} DIM\n * @returns {NestArray<T, DIM[\"length\"]>} The reshaped array.\n */\nfunction reshape(data, dimensions) {\n\n    const totalElements = data.length;\n    const dimensionSize = dimensions.reduce((a, b) => a * b);\n\n    if (totalElements !== dimensionSize) {\n        throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);\n    }\n\n    /** @type {any} */\n    let reshapedArray = data;\n\n    for (let i = dimensions.length - 1; i >= 0; i--) {\n        reshapedArray = reshapedArray.reduce((acc, val) => {\n            let lastArray = acc[acc.length - 1];\n\n            if (lastArray.length < dimensions[i]) {\n                lastArray.push(val);\n            } else {\n                acc.push([val]);\n            }\n\n            return acc;\n        }, [[]]);\n    }\n\n    return reshapedArray[0];\n}\n\n/**\n * Permutes a tensor according to the provided axes.\n * @param {any} tensor The input tensor to permute.\n * @param {Array} axes The axes to permute the tensor along.\n * @returns {Tensor} The permuted tensor.\n */\nexport function permute(tensor, axes) {\n    const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);\n    return new Tensor(tensor.type, permutedData, shape);\n}\n\n\n/**\n * Interpolates an Tensor to the given size.\n * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])\n * @param {number[]} size The output size of the image\n * @param {string} mode The interpolation mode\n * @param {boolean} align_corners Whether to align corners.\n * @returns {Tensor} The interpolated tensor.\n */\nexport function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {\n\n    // Input image dimensions\n    const in_channels = input.dims.at(-3) ?? 1;\n    const in_height = input.dims.at(-2);\n    const in_width = input.dims.at(-1);\n\n    let output = interpolate_data(\n        /** @type {import('./maths.js').TypedArray}*/(input.data),\n        [in_channels, in_height, in_width],\n        [out_height, out_width],\n        mode,\n        align_corners\n    );\n    return new Tensor(input.type, output, [in_channels, out_height, out_width]);\n}\n\n\n/**\n * Down/up samples the input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html.\n * @param {Tensor} input the input tensor\n * @param {Object} options the options for the interpolation\n * @param {[number, number]|[number, number, number]|[number, number, number, number]} [options.size=null] output spatial size.\n * @param {\"nearest\"|\"bilinear\"|\"bicubic\"} [options.mode='bilinear'] algorithm used for upsampling\n * @returns {Promise<Tensor>} The interpolated tensor.\n */\nexport async function interpolate_4d(input, {\n    size = null,\n    mode = 'bilinear',\n} = {}) {\n\n    // Error checking\n    if (input.dims.length !== 4) {\n        throw new Error('`interpolate_4d` currently only supports 4D input.');\n    }\n    if (!size) {\n        // TODO: support scale_factor\n        throw new Error('`interpolate_4d` requires a `size` argument.');\n    }\n\n    // Fill in missing dimensions\n    let targetDims;\n    if (size.length === 2) {\n        targetDims = [...input.dims.slice(0, 2), ...size];\n    } else if (size.length === 3) {\n        targetDims = [input.dims[0], ...size];\n    } else if (size.length === 4) {\n        targetDims = size;\n    } else {\n        throw new Error('`size` must be of length 2, 3, or 4.');\n    }\n\n    let op;\n    if (mode === 'nearest') {\n        op = await TensorOpRegistry.nearest_interpolate_4d;\n    } else if (mode === 'bilinear') {\n        op = await TensorOpRegistry.bilinear_interpolate_4d;\n    } else if (mode === 'bicubic') {\n        op = await TensorOpRegistry.bicubic_interpolate_4d;\n    } else {\n        throw new Error(`Unsupported mode: ${mode}`);\n    }\n\n    const sizeTensor = new Tensor('int64', new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]);\n    return await op({ x: input, s: sizeTensor });\n}\n\n/**\n * Matrix product of two tensors.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.matmul.html\n * @param {Tensor} a the first tensor to be multiplied\n * @param {Tensor} b the second tensor to be multiplied\n * @returns {Promise<Tensor>} The matrix product of the two tensors.\n */\nexport async function matmul(a, b) {\n    const op = await TensorOpRegistry.matmul;\n    return await op({ a, b });\n}\n\n/**\n * Computes the one dimensional Fourier transform of real-valued input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.fft.rfft.html\n * @param {Tensor} x the real input tensor\n * @param {Tensor} a The dimension along which to take the one dimensional real FFT.\n * @returns {Promise<Tensor>} the output tensor.\n */\nexport async function rfft(x, a) {\n    const op = await TensorOpRegistry.rfft;\n    return await op({ x, a });\n}\n\n\n/**\n * Returns the k largest elements of the given input tensor.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.topk.html\n * @param {Tensor} x the input tensor\n * @param {number} [k] the k in \"top-k\"\n * @returns {Promise<[Tensor, Tensor]>} the output tuple of (Tensor, LongTensor) of top-k elements and their indices.\n */\nexport async function topk(x, k) {\n    const op = await TensorOpRegistry.top_k;\n\n    if (k == null) {\n        k = x.dims.at(-1);\n    } else {\n        k = Math.min(k, x.dims.at(-1));\n    }\n    return await op({\n        x,\n        k: new Tensor(\n            'int64',\n            [BigInt(k)],\n            [1]\n        )\n    });\n}\n\n\nconst arrayToIndexTensor = (array) => new Tensor('int64', array, [array.length]);\n/**\n * Slice a multidimensional float32 tensor.\n * @param {Tensor} data: Tensor of data to extract slices from\n * @param {number[]} starts: 1-D array of starting indices of corresponding axis in axes\n * @param {number[]} ends: 1-D array of ending indices (exclusive) of corresponding axis in axes\n * @param {number[]} axes: 1-D array of axes that starts and ends apply to\n * @param {number[]} [steps]: 1-D array of slice step of corresponding axis in axes.\n * @returns {Promise<Tensor>} Sliced data tensor.\n */\nexport async function slice(data, starts, ends, axes, steps) {\n    const op = await TensorOpRegistry.slice;\n    return await op({\n        x: data,\n        s: arrayToIndexTensor(starts),\n        e: arrayToIndexTensor(ends),\n        a: arrayToIndexTensor(axes),\n        t: arrayToIndexTensor(steps ?? new Array(axes.length).fill(1)),\n    });\n}\n\n\n/**\n * Perform mean pooling of the last hidden state followed by a normalization step.\n * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]\n * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]\n * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].\n */\nexport function mean_pooling(last_hidden_state, attention_mask) {\n    // last_hidden_state: [batchSize, seqLength, embedDim]\n    // attention_mask:    [batchSize, seqLength]\n    const lastHiddenStateData = last_hidden_state.data;\n    const attentionMaskData = attention_mask.data;\n\n    const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];\n\n    // @ts-ignore\n    const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]);\n    const [batchSize, seqLength, embedDim] = last_hidden_state.dims;\n\n    let outIndex = 0;\n    for (let i = 0; i < batchSize; ++i) {\n        const offset = i * embedDim * seqLength;\n\n        for (let k = 0; k < embedDim; ++k) {\n            let sum = 0;\n            let count = 0;\n\n            const attnMaskOffset = i * seqLength;\n            const offset2 = offset + k;\n            // Pool over all words in sequence\n            for (let j = 0; j < seqLength; ++j) {\n                // index into attention mask\n                const attn = Number(attentionMaskData[attnMaskOffset + j]);\n\n                count += attn;\n                sum += lastHiddenStateData[offset2 + j * embedDim] * attn;\n            }\n\n            const avg = sum / count;\n            returnedData[outIndex++] = avg;\n        }\n    }\n\n    return new Tensor(\n        last_hidden_state.type,\n        returnedData,\n        shape\n    )\n}\n\n/**\n * Apply Layer Normalization for last certain number of dimensions.\n * @param {Tensor} input The input tensor\n * @param {number[]} normalized_shape input shape from an expected input of size\n * @param {Object} options The options for the layer normalization\n * @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability.\n * @returns {Tensor} The normalized tensor.\n */\nexport function layer_norm(input, normalized_shape, {\n    eps = 1e-5,\n} = {}) {\n    if (input.dims.length !== 2) {\n        throw new Error('`layer_norm` currently only supports 2D input.');\n    }\n\n    const [batchSize, featureDim] = input.dims;\n\n    if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) {\n        throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.');\n    }\n\n    const [std, mean] = std_mean(input, 1, 0, true);\n    const stdData = /** @type {Float32Array} */(std.data);\n    const meanData = /** @type {Float32Array} */(mean.data);\n\n    const inputData = /** @type {Float32Array} */(input.data);\n\n    // @ts-ignore\n    const returnedData = new inputData.constructor(inputData.length);\n\n    for (let i = 0; i < batchSize; ++i) {\n        const offset = i * featureDim;\n        for (let j = 0; j < featureDim; ++j) {\n            const offset2 = offset + j;\n            returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps);\n        }\n    }\n    return new Tensor(input.type, returnedData, input.dims);\n}\n\n/**\n * Helper function to calculate new dimensions when performing a squeeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number|number[]|null} dim The dimension(s) to squeeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_squeeze_dims(dims, dim) {\n    dims = dims.slice();\n    if (dim === null) {\n        dims = dims.filter((d) => d !== 1);\n    } else if (typeof dim === 'number') {\n        if (dims[dim] === 1) {\n            dims.splice(dim, 1);\n        }\n    } else if (Array.isArray(dim)) {\n        dims = dims.filter((x, i) => {\n            return x !== 1 || !dim.includes(i);\n        });\n    }\n    return dims;\n}\n\n/**\n * Helper function to calculate new dimensions when performing an unsqueeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number} dim The dimension to unsqueeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_unsqueeze_dims(dims, dim) {\n    // Dimension out of range (e.g., \"expected to be in range of [-4, 3], but got 4\")\n    // + 1 since we allow inserting at the end (i.e. dim = -1)\n    dim = safeIndex(dim, dims.length + 1);\n    dims = dims.slice();\n    // Insert 1 into specified dimension\n    dims.splice(dim, 0, 1);\n    return dims;\n}\n\n/**\n * Safely calculate the index for an array of a given size, allowing negative indexing.\n * @param {number} index The index that will be used.\n * @param {number} size The size of the array.\n * @param {number} [dimension=null] The dimension that the index is for (optional).\n * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.\n *\n * @throws {Error} If the index is out of range.\n * @private\n */\nfunction safeIndex(index, size, dimension = null, boundsCheck = true) {\n    if (index < -size || index >= size) {\n        if (boundsCheck) {\n            throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);\n        } else {\n            return index < -size ? 0 : size;\n        }\n    }\n\n    if (index < 0) {\n        // Negative indexing, ensuring positive index\n        index = ((index % size) + size) % size;\n    }\n    return index;\n}\n\n/**\n * Concatenates an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to concatenate.\n * @param {number} dim The dimension to concatenate along.\n * @returns {Tensor} The concatenated tensor.\n */\nexport function cat(tensors, dim = 0) {\n    dim = safeIndex(dim, tensors[0].dims.length);\n\n    // TODO do validation of shapes\n\n    const resultDims = tensors[0].dims.slice();\n    resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);\n\n    // Create a new array to store the accumulated values\n    const resultSize = resultDims.reduce((a, b) => a * b, 1);\n    // @ts-ignore\n    const result = new tensors[0].data.constructor(resultSize);\n\n    // Create output tensor of same type as first\n    const resultType = tensors[0].type;\n\n    if (dim === 0) {\n        // Handle special case for performance reasons\n\n        let offset = 0;\n        for (const tensor of tensors) {\n            const tensorData = tensor.data;\n            result.set(tensorData, offset);\n            offset += tensorData.length;\n        }\n\n    } else {\n\n        let currentDim = 0;\n\n        for (let t = 0; t < tensors.length; ++t) {\n            const { data, dims } = tensors[t];\n\n            // Iterate over the data array\n            for (let i = 0; i < data.length; ++i) {\n                // Calculate the index in the resulting array\n                let resultIndex = 0;\n\n                for (let j = dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n                    const size = dims[j];\n                    let index = num % size;\n                    if (j === dim) {\n                        index += currentDim;\n                    }\n                    resultIndex += index * resultMultiplier;\n                    resultMultiplier *= resultDims[j];\n                    num = Math.floor(num / size);\n                }\n                // Accumulate the value at the current index\n                result[resultIndex] = data[i];\n            }\n\n            currentDim += dims[dim];\n        }\n    }\n    return new Tensor(resultType, result, resultDims);\n}\n\n/**\n * Stack an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to stack.\n * @param {number} dim The dimension to stack along.\n * @returns {Tensor} The stacked tensor.\n */\nexport function stack(tensors, dim = 0) {\n    // TODO do validation of shapes\n    // NOTE: stack expects each tensor to be equal size\n    return cat(tensors.map(t => t.unsqueeze(dim)), dim);\n}\n\n\n/**\n * @param {(previousValue: any, currentValue: any, currentIndex?: number, resultIndex?: number) => any} callbackfn\n * @param {Tensor} input the input tensor.\n * @param {number|null} dim the dimension to reduce.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {[DataType, any, number[]]} The reduced tensor data.\n */\nfunction reduce_helper(callbackfn, input, dim = null, keepdim = false, initialValue = null) {\n    const inputData = input.data;\n    const inputDims = input.dims;\n\n    // Negative indexing\n    dim = safeIndex(dim, inputDims.length);\n\n    // Calculate the shape of the resulting array after summation\n    const resultDims = inputDims.slice(); // Copy the original dimensions\n    resultDims[dim] = 1; // Remove the specified axis\n\n    // Create a new array to store the accumulated values\n    // @ts-ignore\n    const result = new inputData.constructor(inputData.length / inputDims[dim]);\n    if (initialValue !== null) {\n        result.fill(initialValue);\n    }\n\n    // Iterate over the data array\n    for (let i = 0; i < inputData.length; ++i) {\n\n        // Calculate the index in the resulting array\n        let resultIndex = 0;\n\n        for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n            const size = inputDims[j];\n            if (j !== dim) {\n                const index = num % size;\n                resultIndex += index * resultMultiplier;\n                resultMultiplier *= resultDims[j];\n            }\n            num = Math.floor(num / size);\n        }\n\n        // Accumulate the value at the current index\n        result[resultIndex] = callbackfn(result[resultIndex], inputData[i], i, resultIndex);\n    }\n\n    if (!keepdim) resultDims.splice(dim, 1);\n\n    return [input.type, result, resultDims];\n}\n\n\n/**\n * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.\n * @param {Tensor} input the input tenso\n * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced.\n * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor[]} A tuple of (std, mean) tensors.\n */\nexport function std_mean(input, dim = null, correction = 1, keepdim = false) {\n    const inputData = /** @type {Float32Array} */(input.data);\n    const inputDims = input.dims;\n\n    if (dim === null) {\n        // None to reduce over all dimensions.\n        const sum = inputData.reduce((a, b) => a + b, 0);\n        const mean = sum / inputData.length;\n        const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean) ** 2, 0) / (inputData.length - correction));\n\n        const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);\n        const stdTensor = new Tensor(input.type, [std], [/* scalar */]);\n\n        return [stdTensor, meanTensor];\n    }\n    dim = safeIndex(dim, inputDims.length);\n    const meanTensor = mean(input, dim, keepdim);\n    const meanTensorData = meanTensor.data;\n\n    // Compute squared sum\n    const [type, result, resultDims] = reduce_helper((a, b, i, j) => a + (b - meanTensorData[j]) ** 2, input, dim, keepdim);\n\n    // Square root of the squared sum\n    for (let i = 0; i < result.length; ++i) {\n        result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction));\n    }\n\n    const stdTensor = new Tensor(type, result, resultDims);\n\n    return [stdTensor, meanTensor];\n}\n\n/**\n * Returns the mean value of each row of the input tensor in the given dimension dim.\n * @param {Tensor} input the input tensor.\n * @param {number|null} dim the dimension to reduce.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor} A new tensor with means taken along the specified dimension.\n */\nexport function mean(input, dim = null, keepdim = false) {\n    const inputDims = input.dims;\n    const inputData = /** @type {Float32Array} */(input.data);\n\n    if (dim === null) {\n        // None to reduce over all dimensions.\n        const val = inputData.reduce((a, b) => a + b, 0);\n        return new Tensor(input.type, [val / inputData.length], [/* scalar */]);\n    }\n    dim = safeIndex(dim, inputDims.length);\n\n    // Compute sum\n    const [type, result, resultDims] = reduce_helper((a, b) => a + b, input, dim, keepdim);\n\n    // Divide by number of elements in the dimension\n    if (inputDims[dim] !== 1) {\n        for (let i = 0; i < result.length; ++i) {\n            result[i] /= inputDims[dim];\n        }\n    }\n\n    return new Tensor(type, result, resultDims);\n}\n\n\nfunction dimsToStride(dims) {\n    const stride = new Array(dims.length);\n    for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {\n        stride[i] = s2;\n        s2 *= dims[i];\n    }\n    return stride;\n}\n\nfunction fullHelper(size, fill_value, dtype, cls) {\n    const numElements = size.reduce((a, b) => a * b, 1);\n    return new Tensor(\n        dtype,\n        new cls(numElements).fill(fill_value),\n        size\n    )\n}\n\n/**\n * Creates a tensor of size size filled with fill_value. The tensor's dtype is inferred from fill_value.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @param {number|bigint|boolean} fill_value The value to fill the output tensor with.\n * @returns {Tensor} The filled tensor.\n */\nexport function full(size, fill_value) {\n    let dtype;\n    let typedArrayCls;\n    if (typeof fill_value === 'number') {\n        dtype = 'float32';\n        typedArrayCls = Float32Array;\n    } else if (typeof fill_value === 'bigint') {\n        dtype = 'int64';\n        typedArrayCls = BigInt64Array;\n    } else if (typeof fill_value === 'boolean') {\n        dtype = 'bool';\n        typedArrayCls = Uint8Array;\n    } else {\n        // TODO: support other dtypes\n        throw new Error(`Unsupported data type: ${typeof fill_value}`);\n    }\n    return fullHelper(size, fill_value, dtype, typedArrayCls);\n}\n\nexport function full_like(tensor, fill_value) {\n    return full(tensor.dims, fill_value);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones(size) {\n    return fullHelper(size, 1n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones_like(tensor) {\n    return ones(tensor.dims);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros(size) {\n    return fullHelper(size, 0n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros_like(tensor) {\n    return zeros(tensor.dims);\n}\n\n/**\n * Returns a tensor filled with random numbers from a uniform distribution on the interval [0, 1)\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The random tensor.\n */\nexport function rand(size) {\n    const length = size.reduce((a, b) => a * b, 1);\n    return new Tensor(\n        \"float32\",\n        Float32Array.from({ length }, () => Math.random()),\n        size,\n    )\n}\n\n/**\n * Returns a tensor filled with random numbers from a normal distribution with mean 0 and variance 1 (also called the standard normal distribution).\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The random tensor.\n */\nexport function randn(size) {\n    const length = size.reduce((a, b) => a * b, 1);\n\n    // Box-Muller transform\n    function boxMullerRandom() {\n        // NOTE: 1 - Math.random() is used to avoid log(0)\n        const u = 1 - Math.random();\n        const v = 1 - Math.random();\n        return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);\n    }\n\n    return new Tensor(\n        \"float32\",\n        Float32Array.from({ length }, () => boxMullerRandom()),\n        size,\n    )\n}\n\n/**\n * Quantizes the embeddings tensor to binary or unsigned binary precision.\n * @param {Tensor} tensor The tensor to quantize.\n * @param {'binary'|'ubinary'} precision The precision to use for quantization.\n * @returns {Tensor} The quantized tensor.\n */\nexport function quantize_embeddings(tensor, precision) {\n    if (tensor.dims.length !== 2) {\n        throw new Error(\"The tensor must have 2 dimensions\");\n    }\n    if (tensor.dims.at(-1) % 8 !== 0) {\n        throw new Error(\"The last dimension of the tensor must be a multiple of 8\");\n    }\n    if (!['binary', 'ubinary'].includes(precision)) {\n        throw new Error(\"The precision must be either 'binary' or 'ubinary'\");\n    }\n\n    const signed = precision === 'binary';\n    const dtype = signed ? 'int8' : 'uint8';\n\n    // Create a typed array to store the packed bits\n    const cls = signed ? Int8Array : Uint8Array;\n    const inputData = tensor.data;\n    const outputData = new cls(inputData.length / 8);\n\n    // Iterate over each number in the array\n    for (let i = 0; i < inputData.length; ++i) {\n        // Determine if the number is greater than 0\n        const bit = inputData[i] > 0 ? 1 : 0;\n\n        // Calculate the index in the typed array and the position within the byte\n        const arrayIndex = Math.floor(i / 8);\n        const bitPosition = i % 8;\n\n        // Pack the bit into the typed array\n        outputData[arrayIndex] |= bit << (7 - bitPosition);\n        if (signed && bitPosition === 0) {\n            outputData[arrayIndex] -= 128;\n        }\n    };\n\n    return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);\n}\n", "\n/**\n * @file Custom data structures.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/data-structures\n */\n\n\n/**\n * Efficient Heap-based Implementation of a Priority Queue.\n * It uses an array-based binary heap, where the root is at index `0`, and the\n * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.\n * \n * Adapted from the following sources:\n * - https://stackoverflow.com/a/42919752/13989043 (original)\n * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)\n */\nexport class PriorityQueue {\n\n    /**\n     * Create a new PriorityQueue.\n     * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap.\n     */\n    constructor(comparator = (a, b) => a > b, maxSize = Infinity) {\n        this._heap = [];\n        this._comparator = comparator;\n        this._maxSize = maxSize;\n    }\n\n    /**\n     * The size of the queue\n     */\n    get size() {\n        return this._heap.length;\n    }\n\n    /**\n     * Check if the queue is empty.\n     * @returns {boolean} `true` if the queue is empty, `false` otherwise.\n     */\n    isEmpty() {\n        return this.size === 0;\n    }\n\n    /**\n     * Return the element with the highest priority in the queue.\n     * @returns {any} The highest priority element in the queue.\n     */\n    peek() {\n        return this._heap[0];\n    }\n\n    /**\n     * Add one or more elements to the queue.\n     * @param  {...any} values The values to push into the queue.\n     * @returns {number} The new size of the queue.\n     */\n    push(...values) {\n        return this.extend(values);\n    }\n\n    /**\n     * Add multiple elements to the queue.\n     * @param {any[]} values The values to push into the queue.\n     * @returns {number} The new size of the queue.\n     */\n    extend(values) {\n        for (const value of values) {\n            if (this.size < this._maxSize) {\n                this._heap.push(value);\n                this._siftUp();\n            } else {\n                // Get index of value with the lowest priority\n                const smallest = this._smallest();\n\n                // If the new value has higher priority than the smallest value in the heap\n                // then replace the smallest value with the new value and update the heap\n                if (this._comparator(value, this._heap[smallest])) {\n                    this._heap[smallest] = value;\n                    this._siftUpFrom(smallest);\n                }\n            }\n        }\n        return this.size;\n    }\n\n    /**\n     * Remove and return the element with the highest priority in the queue.\n     * @returns {any} The element with the highest priority in the queue.\n     */\n    pop() {\n        const poppedValue = this.peek();\n        const bottom = this.size - 1;\n        if (bottom > 0) {\n            this._swap(0, bottom);\n        }\n        this._heap.pop();\n        this._siftDown();\n        return poppedValue;\n    }\n\n    /**\n     * Replace the element with the highest priority in the queue with a new value.\n     * @param {*} value The new value.\n     * @returns {*} The replaced value.\n     */\n    replace(value) {\n        const replacedValue = this.peek();\n        this._heap[0] = value;\n        this._siftDown();\n        return replacedValue;\n    }\n\n    /**\n     * Compute the index for the parent of the node at index `i`.\n     * @param {number} i The index of the node to get the parent of.\n     * @returns {number} The index of the parent node.\n     * @private\n     */\n    _parent(i) {\n        return ((i + 1) >>> 1) - 1;\n    }\n\n    /**\n     * Compute the index for the left child of the node at index `i`.\n     * @param {number} i The index of the node to get the left child of.\n     * @returns {number} The index of the left child.\n     * @private\n     */\n    _left(i) {\n        return (i << 1) + 1;\n    }\n\n    /**\n     * Compute the index for the right child of the node at index `i`.\n     * @param {number} i The index of the node to get the right child of.\n     * @returns {number} The index of the right child.\n     * @private\n     */\n    _right(i) {\n        return (i + 1) << 1;\n    }\n\n    /**\n     * Check if the element at index `i` is greater than the element at index `j`.\n     * @param {number} i The index of the first element to compare.\n     * @param {number} j The index of the second element to compare.\n     * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.\n     * @private\n     */\n    _greater(i, j) {\n        return this._comparator(this._heap[i], this._heap[j]);\n    }\n\n    /**\n     * Swap the elements at indices `i` and `j`.\n     * @param {number} i The index of the first element to swap.\n     * @param {number} j The index of the second element to swap.\n     * @private\n     */\n    _swap(i, j) {\n        const temp = this._heap[i];\n        this._heap[i] = this._heap[j];\n        this._heap[j] = temp;\n    }\n\n    /**\n     * Maintain the heap property by updating positions in the heap,\n     * starting at the last element and moving up the heap.\n     * @private\n     */\n    _siftUp() {\n        this._siftUpFrom(this.size - 1);\n    }\n\n    /**\n     * Helper function to sift up from a given node.\n     * @param {number} node The index of the node to start sifting up from.\n     */\n    _siftUpFrom(node) {\n        while (node > 0 && this._greater(node, this._parent(node))) {\n            this._swap(node, this._parent(node));\n            node = this._parent(node);\n        }\n    }\n\n    /**\n     * Maintain the heap property by updating positions in the heap,\n     * starting at the first element and moving down the heap.\n     * @private\n     */\n    _siftDown() {\n        let node = 0;\n        while (\n            (this._left(node) < this.size && this._greater(this._left(node), node)) ||\n            (this._right(node) < this.size && this._greater(this._right(node), node))\n        ) {\n            const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))\n                ? this._right(node)\n                : this._left(node);\n            this._swap(node, maxChild);\n            node = maxChild;\n        }\n    }\n\n    /**\n     * Get the index of the smallest element in the heap. Since we use an array-based heap,\n     * the index can be computed without needing to traverse the heap.\n     * @private\n     */\n    _smallest() {\n        return (2 ** (Math.floor(Math.log2(this.size))) - 1);\n    }\n}\n\n/**\n * A trie structure to efficiently store and search for strings.\n */\nexport class CharTrie {\n    constructor() {\n        this.root = CharTrieNode.default();\n    }\n\n    /**\n     * Adds one or more `texts` to the trie.\n     * @param {string[]} texts The strings to add to the trie.\n     */\n    extend(texts) {\n        for (const text of texts) {\n            this.push(text);\n        }\n    }\n\n    /**\n     * Adds text to the trie.\n     * @param {string} text The string to add to the trie.\n     */\n    push(text) {\n        let node = this.root;\n        for (const ch of text) {\n            let child = node.children.get(ch);\n            if (child === undefined) {\n                child = CharTrieNode.default();\n                node.children.set(ch, child);\n            }\n            node = child;\n        }\n        node.isLeaf = true;\n    }\n\n    /**\n     * Searches the trie for all strings with a common prefix of `text`.\n     * @param {string} text The common prefix to search for.\n     * @yields {string} Each string in the trie that has `text` as a prefix.\n     */\n    *commonPrefixSearch(text) {\n        let node = this.root;\n        if (node === undefined) return;\n\n        let prefix = \"\";\n        for (const ch of text) {\n            prefix += ch;\n            node = node.children.get(ch);\n            if (node === undefined) return;\n            if (node.isLeaf) {\n                yield prefix;\n            }\n        }\n    }\n}\n\n/**\n * Represents a node in a character trie.\n */\nclass CharTrieNode {\n    /**\n     * Create a new CharTrieNode.\n     * @param {boolean} isLeaf Whether the node is a leaf node or not.\n     * @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.\n     */\n    constructor(isLeaf, children) {\n        this.isLeaf = isLeaf;\n        this.children = children;\n    }\n\n    /**\n     * Returns a new `CharTrieNode` instance with default values.\n     * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.\n     */\n    static default() {\n        return new CharTrieNode(false, new Map());\n    }\n}\n\n/**\n * A lattice data structure to be used for tokenization.\n */\nexport class TokenLattice {\n    /**\n     * Creates a new TokenLattice instance.\n     *\n     * @param {string} sentence The input sentence to be tokenized.\n     * @param {number} bosTokenId The beginning-of-sequence token ID.\n     * @param {number} eosTokenId The end-of-sequence token ID.\n     */\n    constructor(sentence, bosTokenId, eosTokenId) {\n        this.chars = Array.from(sentence);\n        this.len = this.chars.length;\n        this.bosTokenId = bosTokenId;\n        this.eosTokenId = eosTokenId;\n        this.nodes = [];\n        this.beginNodes = Array.from({ length: this.len + 1 }, () => []);\n        this.endNodes = Array.from({ length: this.len + 1 }, () => []);\n\n        const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);\n        const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);\n        this.nodes.push(bos.clone());\n        this.nodes.push(eos.clone());\n        this.beginNodes[this.len].push(eos);\n        this.endNodes[0].push(bos);\n    }\n\n    /**\n     * Inserts a new token node into the token lattice.\n     *\n     * @param {number} pos The starting position of the token.\n     * @param {number} length The length of the token.\n     * @param {number} score The score of the token.\n     * @param {number} tokenId The token ID of the token.\n     */\n    insert(pos, length, score, tokenId) {\n        const nodeId = this.nodes.length;\n        const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);\n        this.beginNodes[pos].push(node);\n        this.endNodes[pos + length].push(node);\n        this.nodes.push(node);\n    }\n\n    /**\n     * Implements the Viterbi algorithm to compute the most likely sequence of tokens.\n     *\n     * @returns {TokenLatticeNode[]} The most likely sequence of tokens.\n     */\n    viterbi() {\n        const len = this.len;\n        let pos = 0;\n        while (pos <= len) {\n            if (this.beginNodes[pos].length == 0) {\n                return [];\n            }\n            for (let rnode of this.beginNodes[pos]) {\n                rnode.prev = null;\n                let bestScore = 0.0;\n                let bestNode = null;\n                for (let lnode of this.endNodes[pos]) {\n                    const score = lnode.backtraceScore + rnode.score;\n                    if (bestNode === null || score > bestScore) {\n                        bestNode = lnode.clone();\n                        bestScore = score;\n                    }\n                }\n\n                if (bestNode !== null) {\n                    rnode.prev = bestNode;\n                    rnode.backtraceScore = bestScore;\n                } else {\n                    return [];\n                }\n            }\n            ++pos;\n        }\n\n        const results = [];\n        const root = this.beginNodes[len][0];\n        const prev = root.prev;\n        if (prev === null) {\n            return [];\n        }\n\n        let node = prev.clone();\n        while (node.prev !== null) {\n            results.push(node.clone());\n            const n = node.clone();\n            node = n.prev.clone();\n        }\n\n        results.reverse();\n        return results;\n    }\n\n    /**\n     * @param {TokenLatticeNode} node\n     * @returns {string} The array of nodes representing the most likely sequence of tokens.\n     */\n    piece(node) {\n        return this.chars.slice(node.pos, node.pos + node.length).join('');\n    }\n\n    /**\n     * @returns {string[]} The most likely sequence of tokens.\n     */\n    tokens() {\n        const nodes = this.viterbi();\n        return nodes.map(x => this.piece(x));\n    }\n\n    /**\n     * @returns {number[]} The most likely sequence of token ids.\n     */\n    tokenIds() {\n        const nodes = this.viterbi();\n        return nodes.map(x => x.tokenId);\n    }\n}\nclass TokenLatticeNode {\n    /**\n     * Represents a node in a token lattice for a given sentence.\n     * @param {number} tokenId The ID of the token associated with this node.\n     * @param {number} nodeId The ID of this node.\n     * @param {number} pos The starting position of the token in the sentence.\n     * @param {number} length The length of the token.\n     * @param {number} score The score associated with the token.\n     */\n    constructor(tokenId, nodeId, pos, length, score) {\n        this.tokenId = tokenId;\n        this.nodeId = nodeId;\n        this.pos = pos;\n        this.length = length;\n        this.score = score;\n        this.prev = null;\n        this.backtraceScore = 0.0;\n    }\n\n    /**\n     * Returns a clone of this node.\n     * @returns {TokenLatticeNode} A clone of this node.\n     */\n    clone() {\n        const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);\n        n.prev = this.prev;\n        n.backtraceScore = this.backtraceScore;\n        return n;\n    }\n}\n\n/**\n * A data structure which uses a trie to split a string into tokens based on a dictionary.\n * It can also use a regular expression to preprocess the input text before splitting.\n * \n * NOTE: To ensure multi-byte characters are handled correctly, we operate at byte-level instead of character-level.\n */\nexport class DictionarySplitter {\n    /**\n     * @param {string[]} dictionary The dictionary of words to use for splitting.\n     */\n    constructor(dictionary) {\n        this.trie = this._buildTrie(dictionary);\n    }\n\n    /**\n     * Builds a trie from the given dictionary.\n     * @param {string[]} dictionary The dictionary of words to build the trie from.\n     * @returns {Object} The root node of the trie.\n     * @private\n     */\n    _buildTrie(dictionary) {\n        const trie = Object.create(null);\n        for (const word of dictionary) {\n            let node = trie;\n            for (let i = 0; i < word.length; ++i) {\n                node = (node[word[i]] ??= Object.create(null));\n            }\n            node.end = word;\n        }\n        return trie;\n    }\n\n    /**\n     * Splits the input text into tokens based on the dictionary.\n     * @param {string} text The input text to split.\n     * @returns {string[]} An array of tokens.\n     */\n    split(text) {\n        const result = [];\n        const n = text.length;\n        let start = 0;\n        let i = 0;\n\n        while (i < n) {\n            let node = this.trie;\n            let match = null;\n            let j = i;\n\n            while (j < n && (node = node[text[j]])) {\n                if (node.end) {\n                    // Always keep the last (i.e., longest) match.\n                    match = node.end;\n                }\n                ++j;\n            }\n\n            if (match) {\n                if (i > start) {\n                    result.push(text.slice(start, i));\n                }\n                result.push(match);\n                i += match.length;\n                start = i;\n            } else {\n                ++i;\n            }\n        }\n        if (start < n) {\n            result.push(text.slice(start));\n        }\n        return result;\n    }\n}\n\n/**\n* A simple Least Recently Used (LRU) cache implementation in JavaScript.\n* This cache stores key-value pairs and evicts the least recently used item\n* when the capacity is exceeded.\n*/\nexport class LRUCache {\n    /**\n     * Creates an LRUCache instance.\n     * @param {number} capacity The maximum number of items the cache can hold.\n     */\n    constructor(capacity) {\n        this.capacity = capacity;\n        this.cache = new Map();\n    }\n\n    /**\n     * Retrieves the value associated with the given key and marks the key as recently used.\n     * @param {any} key The key to retrieve.\n     * @returns {any} The value associated with the key, or undefined if the key does not exist.\n     */\n    get(key) {\n        if (!this.cache.has(key)) return undefined;\n        const value = this.cache.get(key);\n        this.cache.delete(key);\n        this.cache.set(key, value);\n        return value;\n    }\n\n    /**\n     * Inserts or updates the key-value pair in the cache.\n     * If the key already exists, it is updated and marked as recently used.\n     * If the cache exceeds its capacity, the least recently used item is evicted.\n     * @param {any} key The key to add or update.\n     * @param {any} value The value to associate with the key.\n     */\n    put(key, value) {\n        if (this.cache.has(key)) {\n            this.cache.delete(key);\n        }\n        this.cache.set(key, value);\n        if (this.cache.size > this.capacity) {\n            this.cache.delete(this.cache.keys().next().value);\n        }\n    }\n\n    /**\n     * Clears the cache.\n     */\n    clear() {\n        this.cache.clear();\n    }\n}\n", "// src/lexer.ts\nvar TOKEN_TYPES = Object.freeze({\n  Text: \"Text\",\n  // The text between Jinja statements or expressions\n  NumericLiteral: \"NumericLiteral\",\n  // e.g., 123, 1.0\n  StringLiteral: \"StringLiteral\",\n  // 'string'\n  Identifier: \"Identifier\",\n  // Variables, functions, statements, booleans, etc.\n  Equals: \"Equals\",\n  // =\n  OpenParen: \"OpenParen\",\n  // (\n  CloseParen: \"CloseParen\",\n  // )\n  OpenStatement: \"OpenStatement\",\n  // {%\n  CloseStatement: \"CloseStatement\",\n  // %}\n  OpenExpression: \"OpenExpression\",\n  // {{\n  CloseExpression: \"CloseExpression\",\n  // }}\n  OpenSquareBracket: \"OpenSquareBracket\",\n  // [\n  CloseSquareBracket: \"CloseSquareBracket\",\n  // ]\n  OpenCurlyBracket: \"OpenCurlyBracket\",\n  // {\n  CloseCurlyBracket: \"CloseCurlyBracket\",\n  // }\n  Comma: \"Comma\",\n  // ,\n  Dot: \"Dot\",\n  // .\n  Colon: \"Colon\",\n  // :\n  Pipe: \"Pipe\",\n  // |\n  CallOperator: \"CallOperator\",\n  // ()\n  AdditiveBinaryOperator: \"AdditiveBinaryOperator\",\n  // + - ~\n  MultiplicativeBinaryOperator: \"MultiplicativeBinaryOperator\",\n  // * / %\n  ComparisonBinaryOperator: \"ComparisonBinaryOperator\",\n  // < > <= >= == !=\n  UnaryOperator: \"UnaryOperator\",\n  // ! - +\n  Comment: \"Comment\"\n  // {# ... #}\n});\nvar Token = class {\n  /**\n   * Constructs a new Token.\n   * @param {string} value The raw value as seen inside the source code.\n   * @param {TokenType} type The type of token.\n   */\n  constructor(value, type) {\n    this.value = value;\n    this.type = type;\n  }\n};\nfunction isWord(char) {\n  return /\\w/.test(char);\n}\nfunction isInteger(char) {\n  return /[0-9]/.test(char);\n}\nfunction isWhitespace(char) {\n  return /\\s/.test(char);\n}\nvar ORDERED_MAPPING_TABLE = [\n  // Control sequences\n  [\"{%\", TOKEN_TYPES.OpenStatement],\n  [\"%}\", TOKEN_TYPES.CloseStatement],\n  [\"{{\", TOKEN_TYPES.OpenExpression],\n  [\"}}\", TOKEN_TYPES.CloseExpression],\n  // Single character tokens\n  [\"(\", TOKEN_TYPES.OpenParen],\n  [\")\", TOKEN_TYPES.CloseParen],\n  [\"{\", TOKEN_TYPES.OpenCurlyBracket],\n  [\"}\", TOKEN_TYPES.CloseCurlyBracket],\n  [\"[\", TOKEN_TYPES.OpenSquareBracket],\n  [\"]\", TOKEN_TYPES.CloseSquareBracket],\n  [\",\", TOKEN_TYPES.Comma],\n  [\".\", TOKEN_TYPES.Dot],\n  [\":\", TOKEN_TYPES.Colon],\n  [\"|\", TOKEN_TYPES.Pipe],\n  // Comparison operators\n  [\"<=\", TOKEN_TYPES.ComparisonBinaryOperator],\n  [\">=\", TOKEN_TYPES.ComparisonBinaryOperator],\n  [\"==\", TOKEN_TYPES.ComparisonBinaryOperator],\n  [\"!=\", TOKEN_TYPES.ComparisonBinaryOperator],\n  [\"<\", TOKEN_TYPES.ComparisonBinaryOperator],\n  [\">\", TOKEN_TYPES.ComparisonBinaryOperator],\n  // Arithmetic operators\n  [\"+\", TOKEN_TYPES.AdditiveBinaryOperator],\n  [\"-\", TOKEN_TYPES.AdditiveBinaryOperator],\n  [\"~\", TOKEN_TYPES.AdditiveBinaryOperator],\n  [\"*\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n  [\"/\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n  [\"%\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n  // Assignment operator\n  [\"=\", TOKEN_TYPES.Equals]\n];\nvar ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([\n  [\"n\", \"\\n\"],\n  // New line\n  [\"t\", \"\t\"],\n  // Horizontal tab\n  [\"r\", \"\\r\"],\n  // Carriage return\n  [\"b\", \"\\b\"],\n  // Backspace\n  [\"f\", \"\\f\"],\n  // Form feed\n  [\"v\", \"\\v\"],\n  // Vertical tab\n  [\"'\", \"'\"],\n  // Single quote\n  ['\"', '\"'],\n  // Double quote\n  [\"\\\\\", \"\\\\\"]\n  // Backslash\n]);\nfunction preprocess(template, options = {}) {\n  if (template.endsWith(\"\\n\")) {\n    template = template.slice(0, -1);\n  }\n  if (options.lstrip_blocks) {\n    template = template.replace(/^[ \\t]*({[#%-])/gm, \"$1\");\n  }\n  if (options.trim_blocks) {\n    template = template.replace(/([#%-]})\\n/g, \"$1\");\n  }\n  return template.replace(/{%\\s*(end)?generation\\s*%}/gs, \"\");\n}\nfunction tokenize(source, options = {}) {\n  const tokens = [];\n  const src = preprocess(source, options);\n  let cursorPosition = 0;\n  let curlyBracketDepth = 0;\n  const consumeWhile = (predicate) => {\n    let str = \"\";\n    while (predicate(src[cursorPosition])) {\n      if (src[cursorPosition] === \"\\\\\") {\n        ++cursorPosition;\n        if (cursorPosition >= src.length)\n          throw new SyntaxError(\"Unexpected end of input\");\n        const escaped = src[cursorPosition++];\n        const unescaped = ESCAPE_CHARACTERS.get(escaped);\n        if (unescaped === void 0) {\n          throw new SyntaxError(`Unexpected escaped character: ${escaped}`);\n        }\n        str += unescaped;\n        continue;\n      }\n      str += src[cursorPosition++];\n      if (cursorPosition >= src.length)\n        throw new SyntaxError(\"Unexpected end of input\");\n    }\n    return str;\n  };\n  const stripTrailingWhitespace = () => {\n    const lastToken = tokens.at(-1);\n    if (lastToken && lastToken.type === TOKEN_TYPES.Text) {\n      lastToken.value = lastToken.value.trimEnd();\n      if (lastToken.value === \"\") {\n        tokens.pop();\n      }\n    }\n  };\n  const skipLeadingWhitespace = () => {\n    while (cursorPosition < src.length && isWhitespace(src[cursorPosition])) {\n      ++cursorPosition;\n    }\n  };\n  main:\n    while (cursorPosition < src.length) {\n      const lastTokenType = tokens.at(-1)?.type;\n      if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression || lastTokenType === TOKEN_TYPES.Comment) {\n        let text = \"\";\n        while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression\n        !(src[cursorPosition] === \"{\" && (src[cursorPosition + 1] === \"%\" || src[cursorPosition + 1] === \"{\" || src[cursorPosition + 1] === \"#\"))) {\n          text += src[cursorPosition++];\n        }\n        if (text.length > 0) {\n          tokens.push(new Token(text, TOKEN_TYPES.Text));\n          continue;\n        }\n      }\n      if (src[cursorPosition] === \"{\" && src[cursorPosition + 1] === \"#\") {\n        cursorPosition += 2;\n        const stripBefore = src[cursorPosition] === \"-\";\n        if (stripBefore) {\n          ++cursorPosition;\n        }\n        let comment = \"\";\n        while (src[cursorPosition] !== \"#\" || src[cursorPosition + 1] !== \"}\") {\n          if (cursorPosition + 2 >= src.length) {\n            throw new SyntaxError(\"Missing end of comment tag\");\n          }\n          comment += src[cursorPosition++];\n        }\n        const stripAfter = comment.endsWith(\"-\");\n        if (stripAfter) {\n          comment = comment.slice(0, -1);\n        }\n        if (stripBefore) {\n          stripTrailingWhitespace();\n        }\n        tokens.push(new Token(comment, TOKEN_TYPES.Comment));\n        cursorPosition += 2;\n        if (stripAfter) {\n          skipLeadingWhitespace();\n        }\n        continue;\n      }\n      if (src.slice(cursorPosition, cursorPosition + 3) === \"{%-\") {\n        stripTrailingWhitespace();\n        tokens.push(new Token(\"{%\", TOKEN_TYPES.OpenStatement));\n        cursorPosition += 3;\n        continue;\n      }\n      if (src.slice(cursorPosition, cursorPosition + 3) === \"{{-\") {\n        stripTrailingWhitespace();\n        tokens.push(new Token(\"{{\", TOKEN_TYPES.OpenExpression));\n        curlyBracketDepth = 0;\n        cursorPosition += 3;\n        continue;\n      }\n      consumeWhile(isWhitespace);\n      if (src.slice(cursorPosition, cursorPosition + 3) === \"-%}\") {\n        tokens.push(new Token(\"%}\", TOKEN_TYPES.CloseStatement));\n        cursorPosition += 3;\n        skipLeadingWhitespace();\n        continue;\n      }\n      if (src.slice(cursorPosition, cursorPosition + 3) === \"-}}\") {\n        tokens.push(new Token(\"}}\", TOKEN_TYPES.CloseExpression));\n        cursorPosition += 3;\n        skipLeadingWhitespace();\n        continue;\n      }\n      const char = src[cursorPosition];\n      if (char === \"-\" || char === \"+\") {\n        const lastTokenType2 = tokens.at(-1)?.type;\n        if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) {\n          throw new SyntaxError(`Unexpected character: ${char}`);\n        }\n        switch (lastTokenType2) {\n          case TOKEN_TYPES.Identifier:\n          case TOKEN_TYPES.NumericLiteral:\n          case TOKEN_TYPES.StringLiteral:\n          case TOKEN_TYPES.CloseParen:\n          case TOKEN_TYPES.CloseSquareBracket:\n            break;\n          default: {\n            ++cursorPosition;\n            const num = consumeWhile(isInteger);\n            tokens.push(\n              new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator)\n            );\n            continue;\n          }\n        }\n      }\n      for (const [seq, type] of ORDERED_MAPPING_TABLE) {\n        if (seq === \"}}\" && curlyBracketDepth > 0) {\n          continue;\n        }\n        const slice2 = src.slice(cursorPosition, cursorPosition + seq.length);\n        if (slice2 === seq) {\n          tokens.push(new Token(seq, type));\n          if (type === TOKEN_TYPES.OpenExpression) {\n            curlyBracketDepth = 0;\n          } else if (type === TOKEN_TYPES.OpenCurlyBracket) {\n            ++curlyBracketDepth;\n          } else if (type === TOKEN_TYPES.CloseCurlyBracket) {\n            --curlyBracketDepth;\n          }\n          cursorPosition += seq.length;\n          continue main;\n        }\n      }\n      if (char === \"'\" || char === '\"') {\n        ++cursorPosition;\n        const str = consumeWhile((c) => c !== char);\n        tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));\n        ++cursorPosition;\n        continue;\n      }\n      if (isInteger(char)) {\n        let num = consumeWhile(isInteger);\n        if (src[cursorPosition] === \".\" && isInteger(src[cursorPosition + 1])) {\n          ++cursorPosition;\n          const frac = consumeWhile(isInteger);\n          num = `${num}.${frac}`;\n        }\n        tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));\n        continue;\n      }\n      if (isWord(char)) {\n        const word = consumeWhile(isWord);\n        tokens.push(new Token(word, TOKEN_TYPES.Identifier));\n        continue;\n      }\n      throw new SyntaxError(`Unexpected character: ${char}`);\n    }\n  return tokens;\n}\n\n// src/ast.ts\nvar Statement = class {\n  type = \"Statement\";\n};\nvar Program = class extends Statement {\n  constructor(body) {\n    super();\n    this.body = body;\n  }\n  type = \"Program\";\n};\nvar If = class extends Statement {\n  constructor(test, body, alternate) {\n    super();\n    this.test = test;\n    this.body = body;\n    this.alternate = alternate;\n  }\n  type = \"If\";\n};\nvar For = class extends Statement {\n  constructor(loopvar, iterable, body, defaultBlock) {\n    super();\n    this.loopvar = loopvar;\n    this.iterable = iterable;\n    this.body = body;\n    this.defaultBlock = defaultBlock;\n  }\n  type = \"For\";\n};\nvar Break = class extends Statement {\n  type = \"Break\";\n};\nvar Continue = class extends Statement {\n  type = \"Continue\";\n};\nvar SetStatement = class extends Statement {\n  constructor(assignee, value, body) {\n    super();\n    this.assignee = assignee;\n    this.value = value;\n    this.body = body;\n  }\n  type = \"Set\";\n};\nvar Macro = class extends Statement {\n  constructor(name, args, body) {\n    super();\n    this.name = name;\n    this.args = args;\n    this.body = body;\n  }\n  type = \"Macro\";\n};\nvar Comment = class extends Statement {\n  constructor(value) {\n    super();\n    this.value = value;\n  }\n  type = \"Comment\";\n};\nvar Expression = class extends Statement {\n  type = \"Expression\";\n};\nvar MemberExpression = class extends Expression {\n  constructor(object, property, computed) {\n    super();\n    this.object = object;\n    this.property = property;\n    this.computed = computed;\n  }\n  type = \"MemberExpression\";\n};\nvar CallExpression = class extends Expression {\n  constructor(callee, args) {\n    super();\n    this.callee = callee;\n    this.args = args;\n  }\n  type = \"CallExpression\";\n};\nvar Identifier = class extends Expression {\n  /**\n   * @param {string} value The name of the identifier\n   */\n  constructor(value) {\n    super();\n    this.value = value;\n  }\n  type = \"Identifier\";\n};\nvar Literal = class extends Expression {\n  constructor(value) {\n    super();\n    this.value = value;\n  }\n  type = \"Literal\";\n};\nvar IntegerLiteral = class extends Literal {\n  type = \"IntegerLiteral\";\n};\nvar FloatLiteral = class extends Literal {\n  type = \"FloatLiteral\";\n};\nvar StringLiteral = class extends Literal {\n  type = \"StringLiteral\";\n};\nvar ArrayLiteral = class extends Literal {\n  type = \"ArrayLiteral\";\n};\nvar TupleLiteral = class extends Literal {\n  type = \"TupleLiteral\";\n};\nvar ObjectLiteral = class extends Literal {\n  type = \"ObjectLiteral\";\n};\nvar BinaryExpression = class extends Expression {\n  constructor(operator, left, right) {\n    super();\n    this.operator = operator;\n    this.left = left;\n    this.right = right;\n  }\n  type = \"BinaryExpression\";\n};\nvar FilterExpression = class extends Expression {\n  constructor(operand, filter) {\n    super();\n    this.operand = operand;\n    this.filter = filter;\n  }\n  type = \"FilterExpression\";\n};\nvar FilterStatement = class extends Statement {\n  constructor(filter, body) {\n    super();\n    this.filter = filter;\n    this.body = body;\n  }\n  type = \"FilterStatement\";\n};\nvar SelectExpression = class extends Expression {\n  constructor(lhs, test) {\n    super();\n    this.lhs = lhs;\n    this.test = test;\n  }\n  type = \"SelectExpression\";\n};\nvar TestExpression = class extends Expression {\n  constructor(operand, negate, test) {\n    super();\n    this.operand = operand;\n    this.negate = negate;\n    this.test = test;\n  }\n  type = \"TestExpression\";\n};\nvar UnaryExpression = class extends Expression {\n  constructor(operator, argument) {\n    super();\n    this.operator = operator;\n    this.argument = argument;\n  }\n  type = \"UnaryExpression\";\n};\nvar SliceExpression = class extends Expression {\n  constructor(start = void 0, stop = void 0, step = void 0) {\n    super();\n    this.start = start;\n    this.stop = stop;\n    this.step = step;\n  }\n  type = \"SliceExpression\";\n};\nvar KeywordArgumentExpression = class extends Expression {\n  constructor(key, value) {\n    super();\n    this.key = key;\n    this.value = value;\n  }\n  type = \"KeywordArgumentExpression\";\n};\nvar SpreadExpression = class extends Expression {\n  constructor(argument) {\n    super();\n    this.argument = argument;\n  }\n  type = \"SpreadExpression\";\n};\nvar CallStatement = class extends Statement {\n  constructor(call, callerArgs, body) {\n    super();\n    this.call = call;\n    this.callerArgs = callerArgs;\n    this.body = body;\n  }\n  type = \"CallStatement\";\n};\nvar Ternary = class extends Expression {\n  constructor(condition, trueExpr, falseExpr) {\n    super();\n    this.condition = condition;\n    this.trueExpr = trueExpr;\n    this.falseExpr = falseExpr;\n  }\n  type = \"Ternary\";\n};\n\n// src/parser.ts\nfunction parse(tokens) {\n  const program = new Program([]);\n  let current = 0;\n  function expect(type, error) {\n    const prev = tokens[current++];\n    if (!prev || prev.type !== type) {\n      throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`);\n    }\n    return prev;\n  }\n  function expectIdentifier(name) {\n    if (!isIdentifier(name)) {\n      throw new SyntaxError(`Expected ${name}`);\n    }\n    ++current;\n  }\n  function parseAny() {\n    switch (tokens[current].type) {\n      case TOKEN_TYPES.Comment:\n        return new Comment(tokens[current++].value);\n      case TOKEN_TYPES.Text:\n        return parseText();\n      case TOKEN_TYPES.OpenStatement:\n        return parseJinjaStatement();\n      case TOKEN_TYPES.OpenExpression:\n        return parseJinjaExpression();\n      default:\n        throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`);\n    }\n  }\n  function is(...types) {\n    return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type);\n  }\n  function isStatement(...names) {\n    return tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.Identifier && names.includes(tokens[current + 1]?.value);\n  }\n  function isIdentifier(...names) {\n    return current + names.length <= tokens.length && names.every((name, i) => tokens[current + i].type === \"Identifier\" && name === tokens[current + i].value);\n  }\n  function parseText() {\n    return new StringLiteral(expect(TOKEN_TYPES.Text, \"Expected text token\").value);\n  }\n  function parseJinjaStatement() {\n    expect(TOKEN_TYPES.OpenStatement, \"Expected opening statement token\");\n    if (tokens[current].type !== TOKEN_TYPES.Identifier) {\n      throw new SyntaxError(`Unknown statement, got ${tokens[current].type}`);\n    }\n    const name = tokens[current].value;\n    let result;\n    switch (name) {\n      case \"set\":\n        ++current;\n        result = parseSetStatement();\n        break;\n      case \"if\":\n        ++current;\n        result = parseIfStatement();\n        expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n        expectIdentifier(\"endif\");\n        expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n        break;\n      case \"macro\":\n        ++current;\n        result = parseMacroStatement();\n        expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n        expectIdentifier(\"endmacro\");\n        expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n        break;\n      case \"for\":\n        ++current;\n        result = parseForStatement();\n        expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n        expectIdentifier(\"endfor\");\n        expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n        break;\n      case \"call\": {\n        ++current;\n        let callerArgs = null;\n        if (is(TOKEN_TYPES.OpenParen)) {\n          callerArgs = parseArgs();\n        }\n        const callee = parsePrimaryExpression();\n        if (callee.type !== \"Identifier\") {\n          throw new SyntaxError(`Expected identifier following call statement`);\n        }\n        const callArgs = parseArgs();\n        expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n        const body = [];\n        while (!isStatement(\"endcall\")) {\n          body.push(parseAny());\n        }\n        expect(TOKEN_TYPES.OpenStatement, \"Expected '{%'\");\n        expectIdentifier(\"endcall\");\n        expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n        const callExpr = new CallExpression(callee, callArgs);\n        result = new CallStatement(callExpr, callerArgs, body);\n        break;\n      }\n      case \"break\":\n        ++current;\n        expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n        result = new Break();\n        break;\n      case \"continue\":\n        ++current;\n        expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n        result = new Continue();\n        break;\n      case \"filter\": {\n        ++current;\n        let filterNode = parsePrimaryExpression();\n        if (filterNode instanceof Identifier && is(TOKEN_TYPES.OpenParen)) {\n          filterNode = parseCallExpression(filterNode);\n        }\n        expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n        const filterBody = [];\n        while (!isStatement(\"endfilter\")) {\n          filterBody.push(parseAny());\n        }\n        expect(TOKEN_TYPES.OpenStatement, \"Expected '{%'\");\n        expectIdentifier(\"endfilter\");\n        expect(TOKEN_TYPES.CloseStatement, \"Expected '%}'\");\n        result = new FilterStatement(filterNode, filterBody);\n        break;\n      }\n      default:\n        throw new SyntaxError(`Unknown statement type: ${name}`);\n    }\n    return result;\n  }\n  function parseJinjaExpression() {\n    expect(TOKEN_TYPES.OpenExpression, \"Expected opening expression token\");\n    const result = parseExpression();\n    expect(TOKEN_TYPES.CloseExpression, \"Expected closing expression token\");\n    return result;\n  }\n  function parseSetStatement() {\n    const left = parseExpressionSequence();\n    let value = null;\n    const body = [];\n    if (is(TOKEN_TYPES.Equals)) {\n      ++current;\n      value = parseExpressionSequence();\n    } else {\n      expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n      while (!isStatement(\"endset\")) {\n        body.push(parseAny());\n      }\n      expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n      expectIdentifier(\"endset\");\n    }\n    expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n    return new SetStatement(left, value, body);\n  }\n  function parseIfStatement() {\n    const test = parseExpression();\n    expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n    const body = [];\n    const alternate = [];\n    while (!isStatement(\"elif\", \"else\", \"endif\")) {\n      body.push(parseAny());\n    }\n    if (isStatement(\"elif\")) {\n      ++current;\n      ++current;\n      const result = parseIfStatement();\n      alternate.push(result);\n    } else if (isStatement(\"else\")) {\n      ++current;\n      ++current;\n      expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n      while (!isStatement(\"endif\")) {\n        alternate.push(parseAny());\n      }\n    }\n    return new If(test, body, alternate);\n  }\n  function parseMacroStatement() {\n    const name = parsePrimaryExpression();\n    if (name.type !== \"Identifier\") {\n      throw new SyntaxError(`Expected identifier following macro statement`);\n    }\n    const args = parseArgs();\n    expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n    const body = [];\n    while (!isStatement(\"endmacro\")) {\n      body.push(parseAny());\n    }\n    return new Macro(name, args, body);\n  }\n  function parseExpressionSequence(primary = false) {\n    const fn = primary ? parsePrimaryExpression : parseExpression;\n    const expressions = [fn()];\n    const isTuple = is(TOKEN_TYPES.Comma);\n    while (isTuple) {\n      ++current;\n      expressions.push(fn());\n      if (!is(TOKEN_TYPES.Comma)) {\n        break;\n      }\n    }\n    return isTuple ? new TupleLiteral(expressions) : expressions[0];\n  }\n  function parseForStatement() {\n    const loopVariable = parseExpressionSequence(true);\n    if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) {\n      throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`);\n    }\n    if (!isIdentifier(\"in\")) {\n      throw new SyntaxError(\"Expected `in` keyword following loop variable\");\n    }\n    ++current;\n    const iterable = parseExpression();\n    expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n    const body = [];\n    while (!isStatement(\"endfor\", \"else\")) {\n      body.push(parseAny());\n    }\n    const alternative = [];\n    if (isStatement(\"else\")) {\n      ++current;\n      ++current;\n      expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n      while (!isStatement(\"endfor\")) {\n        alternative.push(parseAny());\n      }\n    }\n    return new For(loopVariable, iterable, body, alternative);\n  }\n  function parseExpression() {\n    return parseIfExpression();\n  }\n  function parseIfExpression() {\n    const a = parseLogicalOrExpression();\n    if (isIdentifier(\"if\")) {\n      ++current;\n      const test = parseLogicalOrExpression();\n      if (isIdentifier(\"else\")) {\n        ++current;\n        const falseExpr = parseIfExpression();\n        return new Ternary(test, a, falseExpr);\n      } else {\n        return new SelectExpression(a, test);\n      }\n    }\n    return a;\n  }\n  function parseLogicalOrExpression() {\n    let left = parseLogicalAndExpression();\n    while (isIdentifier(\"or\")) {\n      const operator = tokens[current];\n      ++current;\n      const right = parseLogicalAndExpression();\n      left = new BinaryExpression(operator, left, right);\n    }\n    return left;\n  }\n  function parseLogicalAndExpression() {\n    let left = parseLogicalNegationExpression();\n    while (isIdentifier(\"and\")) {\n      const operator = tokens[current];\n      ++current;\n      const right = parseLogicalNegationExpression();\n      left = new BinaryExpression(operator, left, right);\n    }\n    return left;\n  }\n  function parseLogicalNegationExpression() {\n    let right;\n    while (isIdentifier(\"not\")) {\n      const operator = tokens[current];\n      ++current;\n      const arg = parseLogicalNegationExpression();\n      right = new UnaryExpression(operator, arg);\n    }\n    return right ?? parseComparisonExpression();\n  }\n  function parseComparisonExpression() {\n    let left = parseAdditiveExpression();\n    while (true) {\n      let operator;\n      if (isIdentifier(\"not\", \"in\")) {\n        operator = new Token(\"not in\", TOKEN_TYPES.Identifier);\n        current += 2;\n      } else if (isIdentifier(\"in\")) {\n        operator = tokens[current++];\n      } else if (is(TOKEN_TYPES.ComparisonBinaryOperator)) {\n        operator = tokens[current++];\n      } else {\n        break;\n      }\n      const right = parseAdditiveExpression();\n      left = new BinaryExpression(operator, left, right);\n    }\n    return left;\n  }\n  function parseAdditiveExpression() {\n    let left = parseMultiplicativeExpression();\n    while (is(TOKEN_TYPES.AdditiveBinaryOperator)) {\n      const operator = tokens[current];\n      ++current;\n      const right = parseMultiplicativeExpression();\n      left = new BinaryExpression(operator, left, right);\n    }\n    return left;\n  }\n  function parseCallMemberExpression() {\n    const member = parseMemberExpression(parsePrimaryExpression());\n    if (is(TOKEN_TYPES.OpenParen)) {\n      return parseCallExpression(member);\n    }\n    return member;\n  }\n  function parseCallExpression(callee) {\n    let expression = new CallExpression(callee, parseArgs());\n    expression = parseMemberExpression(expression);\n    if (is(TOKEN_TYPES.OpenParen)) {\n      expression = parseCallExpression(expression);\n    }\n    return expression;\n  }\n  function parseArgs() {\n    expect(TOKEN_TYPES.OpenParen, \"Expected opening parenthesis for arguments list\");\n    const args = parseArgumentsList();\n    expect(TOKEN_TYPES.CloseParen, \"Expected closing parenthesis for arguments list\");\n    return args;\n  }\n  function parseArgumentsList() {\n    const args = [];\n    while (!is(TOKEN_TYPES.CloseParen)) {\n      let argument;\n      if (tokens[current].type === TOKEN_TYPES.MultiplicativeBinaryOperator && tokens[current].value === \"*\") {\n        ++current;\n        const expr = parseExpression();\n        argument = new SpreadExpression(expr);\n      } else {\n        argument = parseExpression();\n        if (is(TOKEN_TYPES.Equals)) {\n          ++current;\n          if (!(argument instanceof Identifier)) {\n            throw new SyntaxError(`Expected identifier for keyword argument`);\n          }\n          const value = parseExpression();\n          argument = new KeywordArgumentExpression(argument, value);\n        }\n      }\n      args.push(argument);\n      if (is(TOKEN_TYPES.Comma)) {\n        ++current;\n      }\n    }\n    return args;\n  }\n  function parseMemberExpressionArgumentsList() {\n    const slices = [];\n    let isSlice = false;\n    while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n      if (is(TOKEN_TYPES.Colon)) {\n        slices.push(void 0);\n        ++current;\n        isSlice = true;\n      } else {\n        slices.push(parseExpression());\n        if (is(TOKEN_TYPES.Colon)) {\n          ++current;\n          isSlice = true;\n        }\n      }\n    }\n    if (slices.length === 0) {\n      throw new SyntaxError(`Expected at least one argument for member/slice expression`);\n    }\n    if (isSlice) {\n      if (slices.length > 3) {\n        throw new SyntaxError(`Expected 0-3 arguments for slice expression`);\n      }\n      return new SliceExpression(...slices);\n    }\n    return slices[0];\n  }\n  function parseMemberExpression(object) {\n    while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) {\n      const operator = tokens[current];\n      ++current;\n      let property;\n      const computed = operator.type === TOKEN_TYPES.OpenSquareBracket;\n      if (computed) {\n        property = parseMemberExpressionArgumentsList();\n        expect(TOKEN_TYPES.CloseSquareBracket, \"Expected closing square bracket\");\n      } else {\n        property = parsePrimaryExpression();\n        if (property.type !== \"Identifier\") {\n          throw new SyntaxError(`Expected identifier following dot operator`);\n        }\n      }\n      object = new MemberExpression(object, property, computed);\n    }\n    return object;\n  }\n  function parseMultiplicativeExpression() {\n    let left = parseTestExpression();\n    while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) {\n      const operator = tokens[current++];\n      const right = parseTestExpression();\n      left = new BinaryExpression(operator, left, right);\n    }\n    return left;\n  }\n  function parseTestExpression() {\n    let operand = parseFilterExpression();\n    while (isIdentifier(\"is\")) {\n      ++current;\n      const negate = isIdentifier(\"not\");\n      if (negate) {\n        ++current;\n      }\n      const filter = parsePrimaryExpression();\n      if (!(filter instanceof Identifier)) {\n        throw new SyntaxError(`Expected identifier for the test`);\n      }\n      operand = new TestExpression(operand, negate, filter);\n    }\n    return operand;\n  }\n  function parseFilterExpression() {\n    let operand = parseCallMemberExpression();\n    while (is(TOKEN_TYPES.Pipe)) {\n      ++current;\n      let filter = parsePrimaryExpression();\n      if (!(filter instanceof Identifier)) {\n        throw new SyntaxError(`Expected identifier for the filter`);\n      }\n      if (is(TOKEN_TYPES.OpenParen)) {\n        filter = parseCallExpression(filter);\n      }\n      operand = new FilterExpression(operand, filter);\n    }\n    return operand;\n  }\n  function parsePrimaryExpression() {\n    const token = tokens[current++];\n    switch (token.type) {\n      case TOKEN_TYPES.NumericLiteral: {\n        const num = token.value;\n        return num.includes(\".\") ? new FloatLiteral(Number(num)) : new IntegerLiteral(Number(num));\n      }\n      case TOKEN_TYPES.StringLiteral: {\n        let value = token.value;\n        while (is(TOKEN_TYPES.StringLiteral)) {\n          value += tokens[current++].value;\n        }\n        return new StringLiteral(value);\n      }\n      case TOKEN_TYPES.Identifier:\n        return new Identifier(token.value);\n      case TOKEN_TYPES.OpenParen: {\n        const expression = parseExpressionSequence();\n        expect(TOKEN_TYPES.CloseParen, \"Expected closing parenthesis, got ${tokens[current].type} instead.\");\n        return expression;\n      }\n      case TOKEN_TYPES.OpenSquareBracket: {\n        const values = [];\n        while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n          values.push(parseExpression());\n          if (is(TOKEN_TYPES.Comma)) {\n            ++current;\n          }\n        }\n        ++current;\n        return new ArrayLiteral(values);\n      }\n      case TOKEN_TYPES.OpenCurlyBracket: {\n        const values = /* @__PURE__ */ new Map();\n        while (!is(TOKEN_TYPES.CloseCurlyBracket)) {\n          const key = parseExpression();\n          expect(TOKEN_TYPES.Colon, \"Expected colon between key and value in object literal\");\n          const value = parseExpression();\n          values.set(key, value);\n          if (is(TOKEN_TYPES.Comma)) {\n            ++current;\n          }\n        }\n        ++current;\n        return new ObjectLiteral(values);\n      }\n      default:\n        throw new SyntaxError(`Unexpected token: ${token.type}`);\n    }\n  }\n  while (current < tokens.length) {\n    program.body.push(parseAny());\n  }\n  return program;\n}\n\n// src/utils.ts\nfunction range(start, stop, step = 1) {\n  if (stop === void 0) {\n    stop = start;\n    start = 0;\n  }\n  if (step === 0) {\n    throw new Error(\"range() step must not be zero\");\n  }\n  const result = [];\n  if (step > 0) {\n    for (let i = start; i < stop; i += step) {\n      result.push(i);\n    }\n  } else {\n    for (let i = start; i > stop; i += step) {\n      result.push(i);\n    }\n  }\n  return result;\n}\nfunction slice(array, start, stop, step = 1) {\n  const direction = Math.sign(step);\n  if (direction >= 0) {\n    start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);\n    stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);\n  } else {\n    start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);\n    stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1);\n  }\n  const result = [];\n  for (let i = start; direction * i < direction * stop; i += step) {\n    result.push(array[i]);\n  }\n  return result;\n}\nfunction titleCase(value) {\n  return value.replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\nfunction strftime_now(format2) {\n  return strftime(/* @__PURE__ */ new Date(), format2);\n}\nfunction strftime(date, format2) {\n  const monthFormatterLong = new Intl.DateTimeFormat(void 0, { month: \"long\" });\n  const monthFormatterShort = new Intl.DateTimeFormat(void 0, { month: \"short\" });\n  const pad2 = (n) => n < 10 ? \"0\" + n : n.toString();\n  return format2.replace(/%[YmdbBHM%]/g, (token) => {\n    switch (token) {\n      case \"%Y\":\n        return date.getFullYear().toString();\n      case \"%m\":\n        return pad2(date.getMonth() + 1);\n      case \"%d\":\n        return pad2(date.getDate());\n      case \"%b\":\n        return monthFormatterShort.format(date);\n      case \"%B\":\n        return monthFormatterLong.format(date);\n      case \"%H\":\n        return pad2(date.getHours());\n      case \"%M\":\n        return pad2(date.getMinutes());\n      case \"%%\":\n        return \"%\";\n      default:\n        return token;\n    }\n  });\n}\nfunction escapeRegExp(s) {\n  return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\nfunction replace(str, oldvalue, newvalue, count) {\n  if (count === 0)\n    return str;\n  let remaining = count == null || count < 0 ? Infinity : count;\n  const pattern = oldvalue.length === 0 ? new RegExp(\"(?=)\", \"gu\") : new RegExp(escapeRegExp(oldvalue), \"gu\");\n  return str.replaceAll(pattern, (match) => {\n    if (remaining > 0) {\n      --remaining;\n      return newvalue;\n    }\n    return match;\n  });\n}\n\n// src/runtime.ts\nvar BreakControl = class extends Error {\n};\nvar ContinueControl = class extends Error {\n};\nvar RuntimeValue = class {\n  type = \"RuntimeValue\";\n  value;\n  /**\n   * A collection of built-in functions for this type.\n   */\n  builtins = /* @__PURE__ */ new Map();\n  /**\n   * Creates a new RuntimeValue.\n   */\n  constructor(value = void 0) {\n    this.value = value;\n  }\n  /**\n   * Determines truthiness or falsiness of the runtime value.\n   * This function should be overridden by subclasses if it has custom truthiness criteria.\n   * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.\n   */\n  __bool__() {\n    return new BooleanValue(!!this.value);\n  }\n  toString() {\n    return String(this.value);\n  }\n};\nvar IntegerValue = class extends RuntimeValue {\n  type = \"IntegerValue\";\n};\nvar FloatValue = class extends RuntimeValue {\n  type = \"FloatValue\";\n  toString() {\n    return this.value % 1 === 0 ? this.value.toFixed(1) : this.value.toString();\n  }\n};\nvar StringValue = class extends RuntimeValue {\n  type = \"StringValue\";\n  builtins = /* @__PURE__ */ new Map([\n    [\n      \"upper\",\n      new FunctionValue(() => {\n        return new StringValue(this.value.toUpperCase());\n      })\n    ],\n    [\n      \"lower\",\n      new FunctionValue(() => {\n        return new StringValue(this.value.toLowerCase());\n      })\n    ],\n    [\n      \"strip\",\n      new FunctionValue(() => {\n        return new StringValue(this.value.trim());\n      })\n    ],\n    [\n      \"title\",\n      new FunctionValue(() => {\n        return new StringValue(titleCase(this.value));\n      })\n    ],\n    [\n      \"capitalize\",\n      new FunctionValue(() => {\n        return new StringValue(this.value.charAt(0).toUpperCase() + this.value.slice(1));\n      })\n    ],\n    [\"length\", new IntegerValue(this.value.length)],\n    [\n      \"rstrip\",\n      new FunctionValue(() => {\n        return new StringValue(this.value.trimEnd());\n      })\n    ],\n    [\n      \"lstrip\",\n      new FunctionValue(() => {\n        return new StringValue(this.value.trimStart());\n      })\n    ],\n    [\n      \"startswith\",\n      new FunctionValue((args) => {\n        if (args.length === 0) {\n          throw new Error(\"startswith() requires at least one argument\");\n        }\n        const pattern = args[0];\n        if (pattern instanceof StringValue) {\n          return new BooleanValue(this.value.startsWith(pattern.value));\n        } else if (pattern instanceof ArrayValue) {\n          for (const item of pattern.value) {\n            if (!(item instanceof StringValue)) {\n              throw new Error(\"startswith() tuple elements must be strings\");\n            }\n            if (this.value.startsWith(item.value)) {\n              return new BooleanValue(true);\n            }\n          }\n          return new BooleanValue(false);\n        }\n        throw new Error(\"startswith() argument must be a string or tuple of strings\");\n      })\n    ],\n    [\n      \"endswith\",\n      new FunctionValue((args) => {\n        if (args.length === 0) {\n          throw new Error(\"endswith() requires at least one argument\");\n        }\n        const pattern = args[0];\n        if (pattern instanceof StringValue) {\n          return new BooleanValue(this.value.endsWith(pattern.value));\n        } else if (pattern instanceof ArrayValue) {\n          for (const item of pattern.value) {\n            if (!(item instanceof StringValue)) {\n              throw new Error(\"endswith() tuple elements must be strings\");\n            }\n            if (this.value.endsWith(item.value)) {\n              return new BooleanValue(true);\n            }\n          }\n          return new BooleanValue(false);\n        }\n        throw new Error(\"endswith() argument must be a string or tuple of strings\");\n      })\n    ],\n    [\n      \"split\",\n      // follows Python's `str.split(sep=None, maxsplit=-1)` function behavior\n      // https://docs.python.org/3.13/library/stdtypes.html#str.split\n      new FunctionValue((args) => {\n        const sep = args[0] ?? new NullValue();\n        if (!(sep instanceof StringValue || sep instanceof NullValue)) {\n          throw new Error(\"sep argument must be a string or null\");\n        }\n        const maxsplit = args[1] ?? new IntegerValue(-1);\n        if (!(maxsplit instanceof IntegerValue)) {\n          throw new Error(\"maxsplit argument must be a number\");\n        }\n        let result = [];\n        if (sep instanceof NullValue) {\n          const text = this.value.trimStart();\n          for (const { 0: match, index } of text.matchAll(/\\S+/g)) {\n            if (maxsplit.value !== -1 && result.length >= maxsplit.value && index !== void 0) {\n              result.push(match + text.slice(index + match.length));\n              break;\n            }\n            result.push(match);\n          }\n        } else {\n          if (sep.value === \"\") {\n            throw new Error(\"empty separator\");\n          }\n          result = this.value.split(sep.value);\n          if (maxsplit.value !== -1 && result.length > maxsplit.value) {\n            result.push(result.splice(maxsplit.value).join(sep.value));\n          }\n        }\n        return new ArrayValue(result.map((part) => new StringValue(part)));\n      })\n    ],\n    [\n      \"replace\",\n      new FunctionValue((args) => {\n        if (args.length < 2) {\n          throw new Error(\"replace() requires at least two arguments\");\n        }\n        const oldValue = args[0];\n        const newValue = args[1];\n        if (!(oldValue instanceof StringValue && newValue instanceof StringValue)) {\n          throw new Error(\"replace() arguments must be strings\");\n        }\n        let count;\n        if (args.length > 2) {\n          if (args[2].type === \"KeywordArgumentsValue\") {\n            count = args[2].value.get(\"count\") ?? new NullValue();\n          } else {\n            count = args[2];\n          }\n        } else {\n          count = new NullValue();\n        }\n        if (!(count instanceof IntegerValue || count instanceof NullValue)) {\n          throw new Error(\"replace() count argument must be a number or null\");\n        }\n        return new StringValue(replace(this.value, oldValue.value, newValue.value, count.value));\n      })\n    ]\n  ]);\n};\nvar BooleanValue = class extends RuntimeValue {\n  type = \"BooleanValue\";\n};\nvar NON_ASCII_CHARS = /[\\x7f-\\uffff]/g;\nfunction makeAsciiSafe(str) {\n  return str.replace(NON_ASCII_CHARS, (char) => \"\\\\u\" + char.charCodeAt(0).toString(16).padStart(4, \"0\"));\n}\nfunction toJSON(input, options = {}, depth = 0, convertUndefinedToNull = true) {\n  const { indent = null, ensureAscii = false, separators = null, sortKeys = false } = options;\n  let itemSeparator;\n  let keySeparator;\n  if (separators) {\n    [itemSeparator, keySeparator] = separators;\n  } else if (indent) {\n    itemSeparator = \",\";\n    keySeparator = \": \";\n  } else {\n    itemSeparator = \", \";\n    keySeparator = \": \";\n  }\n  switch (input.type) {\n    case \"NullValue\":\n      return \"null\";\n    case \"UndefinedValue\":\n      return convertUndefinedToNull ? \"null\" : \"undefined\";\n    case \"IntegerValue\":\n    case \"FloatValue\":\n    case \"BooleanValue\":\n      return JSON.stringify(input.value);\n    case \"StringValue\": {\n      let result = JSON.stringify(input.value);\n      if (ensureAscii) {\n        result = makeAsciiSafe(result);\n      }\n      return result;\n    }\n    case \"ArrayValue\":\n    case \"ObjectValue\": {\n      const indentValue = indent ? \" \".repeat(indent) : \"\";\n      const basePadding = \"\\n\" + indentValue.repeat(depth);\n      const childrenPadding = basePadding + indentValue;\n      if (input.type === \"ArrayValue\") {\n        const core = input.value.map((x) => toJSON(x, options, depth + 1, convertUndefinedToNull));\n        return indent ? `[${childrenPadding}${core.join(`${itemSeparator}${childrenPadding}`)}${basePadding}]` : `[${core.join(itemSeparator)}]`;\n      } else {\n        let entries = Array.from(input.value.entries());\n        if (sortKeys) {\n          entries = entries.sort(([a], [b]) => a.localeCompare(b));\n        }\n        const core = entries.map(([key, value]) => {\n          let keyStr = JSON.stringify(key);\n          if (ensureAscii) {\n            keyStr = makeAsciiSafe(keyStr);\n          }\n          const v = `${keyStr}${keySeparator}${toJSON(value, options, depth + 1, convertUndefinedToNull)}`;\n          return indent ? `${childrenPadding}${v}` : v;\n        });\n        return indent ? `{${core.join(itemSeparator)}${basePadding}}` : `{${core.join(itemSeparator)}}`;\n      }\n    }\n    default:\n      throw new Error(`Cannot convert to JSON: ${input.type}`);\n  }\n}\nvar ObjectValue = class extends RuntimeValue {\n  type = \"ObjectValue\";\n  /**\n   * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n   * while only non-empty Python arrays are consider truthy.\n   *\n   * e.g.,\n   *  - JavaScript:  {} && 5 -> 5\n   *  - Python:      {} and 5 -> {}\n   */\n  __bool__() {\n    return new BooleanValue(this.value.size > 0);\n  }\n  builtins = /* @__PURE__ */ new Map([\n    [\n      \"get\",\n      new FunctionValue(([key, defaultValue]) => {\n        if (!(key instanceof StringValue)) {\n          throw new Error(`Object key must be a string: got ${key.type}`);\n        }\n        return this.value.get(key.value) ?? defaultValue ?? new NullValue();\n      })\n    ],\n    [\"items\", new FunctionValue(() => this.items())],\n    [\"keys\", new FunctionValue(() => this.keys())],\n    [\"values\", new FunctionValue(() => this.values())],\n    [\n      \"dictsort\",\n      new FunctionValue((args) => {\n        let kwargs = /* @__PURE__ */ new Map();\n        const positionalArgs = args.filter((arg) => {\n          if (arg instanceof KeywordArgumentsValue) {\n            kwargs = arg.value;\n            return false;\n          }\n          return true;\n        });\n        const caseSensitive = positionalArgs.at(0) ?? kwargs.get(\"case_sensitive\") ?? new BooleanValue(false);\n        if (!(caseSensitive instanceof BooleanValue)) {\n          throw new Error(\"case_sensitive must be a boolean\");\n        }\n        const by = positionalArgs.at(1) ?? kwargs.get(\"by\") ?? new StringValue(\"key\");\n        if (!(by instanceof StringValue)) {\n          throw new Error(\"by must be a string\");\n        }\n        if (![\"key\", \"value\"].includes(by.value)) {\n          throw new Error(\"by must be either 'key' or 'value'\");\n        }\n        const reverse = positionalArgs.at(2) ?? kwargs.get(\"reverse\") ?? new BooleanValue(false);\n        if (!(reverse instanceof BooleanValue)) {\n          throw new Error(\"reverse must be a boolean\");\n        }\n        const items = Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])).sort((a, b) => {\n          const index = by.value === \"key\" ? 0 : 1;\n          const aVal = a.value[index];\n          const bVal = b.value[index];\n          const result = compareRuntimeValues(aVal, bVal, caseSensitive.value);\n          return reverse.value ? -result : result;\n        });\n        return new ArrayValue(items);\n      })\n    ]\n  ]);\n  items() {\n    return new ArrayValue(\n      Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n    );\n  }\n  keys() {\n    return new ArrayValue(Array.from(this.value.keys()).map((key) => new StringValue(key)));\n  }\n  values() {\n    return new ArrayValue(Array.from(this.value.values()));\n  }\n  toString() {\n    return toJSON(this, {}, 0, false);\n  }\n};\nvar KeywordArgumentsValue = class extends ObjectValue {\n  type = \"KeywordArgumentsValue\";\n};\nvar ArrayValue = class extends RuntimeValue {\n  type = \"ArrayValue\";\n  builtins = /* @__PURE__ */ new Map([[\"length\", new IntegerValue(this.value.length)]]);\n  /**\n   * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n   * while only non-empty Python arrays are consider truthy.\n   *\n   * e.g.,\n   *  - JavaScript:  [] && 5 -> 5\n   *  - Python:      [] and 5 -> []\n   */\n  __bool__() {\n    return new BooleanValue(this.value.length > 0);\n  }\n  toString() {\n    return toJSON(this, {}, 0, false);\n  }\n};\nvar TupleValue = class extends ArrayValue {\n  type = \"TupleValue\";\n};\nvar FunctionValue = class extends RuntimeValue {\n  type = \"FunctionValue\";\n};\nvar NullValue = class extends RuntimeValue {\n  type = \"NullValue\";\n};\nvar UndefinedValue = class extends RuntimeValue {\n  type = \"UndefinedValue\";\n};\nvar Environment = class {\n  constructor(parent) {\n    this.parent = parent;\n  }\n  /**\n   * The variables declared in this environment.\n   */\n  variables = /* @__PURE__ */ new Map([\n    [\n      \"namespace\",\n      new FunctionValue((args) => {\n        if (args.length === 0) {\n          return new ObjectValue(/* @__PURE__ */ new Map());\n        }\n        if (args.length !== 1 || !(args[0] instanceof ObjectValue)) {\n          throw new Error(\"`namespace` expects either zero arguments or a single object argument\");\n        }\n        return args[0];\n      })\n    ]\n  ]);\n  /**\n   * The tests available in this environment.\n   */\n  tests = /* @__PURE__ */ new Map([\n    [\"boolean\", (operand) => operand.type === \"BooleanValue\"],\n    [\"callable\", (operand) => operand instanceof FunctionValue],\n    [\n      \"odd\",\n      (operand) => {\n        if (!(operand instanceof IntegerValue)) {\n          throw new Error(`cannot odd on ${operand.type}`);\n        }\n        return operand.value % 2 !== 0;\n      }\n    ],\n    [\n      \"even\",\n      (operand) => {\n        if (!(operand instanceof IntegerValue)) {\n          throw new Error(`cannot even on ${operand.type}`);\n        }\n        return operand.value % 2 === 0;\n      }\n    ],\n    [\"false\", (operand) => operand.type === \"BooleanValue\" && !operand.value],\n    [\"true\", (operand) => operand.type === \"BooleanValue\" && operand.value],\n    [\"none\", (operand) => operand.type === \"NullValue\"],\n    [\"string\", (operand) => operand.type === \"StringValue\"],\n    [\"number\", (operand) => operand instanceof IntegerValue || operand instanceof FloatValue],\n    [\"integer\", (operand) => operand instanceof IntegerValue],\n    [\"iterable\", (operand) => operand.type === \"ArrayValue\" || operand.type === \"StringValue\"],\n    [\"mapping\", (operand) => operand.type === \"ObjectValue\"],\n    [\n      \"lower\",\n      (operand) => {\n        const str = operand.value;\n        return operand.type === \"StringValue\" && str === str.toLowerCase();\n      }\n    ],\n    [\n      \"upper\",\n      (operand) => {\n        const str = operand.value;\n        return operand.type === \"StringValue\" && str === str.toUpperCase();\n      }\n    ],\n    [\"none\", (operand) => operand.type === \"NullValue\"],\n    [\"defined\", (operand) => operand.type !== \"UndefinedValue\"],\n    [\"undefined\", (operand) => operand.type === \"UndefinedValue\"],\n    [\"equalto\", (a, b) => a.value === b.value],\n    [\"eq\", (a, b) => a.value === b.value]\n  ]);\n  /**\n   * Set the value of a variable in the current environment.\n   */\n  set(name, value) {\n    return this.declareVariable(name, convertToRuntimeValues(value));\n  }\n  declareVariable(name, value) {\n    if (this.variables.has(name)) {\n      throw new SyntaxError(`Variable already declared: ${name}`);\n    }\n    this.variables.set(name, value);\n    return value;\n  }\n  // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue {\n  // \tconst env = this.resolve(name);\n  // \tenv.variables.set(name, value);\n  // \treturn value;\n  // }\n  /**\n   * Set variable in the current scope.\n   * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.\n   */\n  setVariable(name, value) {\n    this.variables.set(name, value);\n    return value;\n  }\n  /**\n   * Resolve the environment in which the variable is declared.\n   * @param {string} name The name of the variable.\n   * @returns {Environment} The environment in which the variable is declared.\n   */\n  resolve(name) {\n    if (this.variables.has(name)) {\n      return this;\n    }\n    if (this.parent) {\n      return this.parent.resolve(name);\n    }\n    throw new Error(`Unknown variable: ${name}`);\n  }\n  lookupVariable(name) {\n    try {\n      return this.resolve(name).variables.get(name) ?? new UndefinedValue();\n    } catch {\n      return new UndefinedValue();\n    }\n  }\n};\nfunction setupGlobals(env) {\n  env.set(\"false\", false);\n  env.set(\"true\", true);\n  env.set(\"none\", null);\n  env.set(\"raise_exception\", (args) => {\n    throw new Error(args);\n  });\n  env.set(\"range\", range);\n  env.set(\"strftime_now\", strftime_now);\n  env.set(\"True\", true);\n  env.set(\"False\", false);\n  env.set(\"None\", null);\n}\nfunction getAttributeValue(item, attributePath) {\n  const parts = attributePath.split(\".\");\n  let value = item;\n  for (const part of parts) {\n    if (value instanceof ObjectValue) {\n      value = value.value.get(part) ?? new UndefinedValue();\n    } else if (value instanceof ArrayValue) {\n      const index = parseInt(part, 10);\n      if (!isNaN(index) && index >= 0 && index < value.value.length) {\n        value = value.value[index];\n      } else {\n        return new UndefinedValue();\n      }\n    } else {\n      return new UndefinedValue();\n    }\n  }\n  return value;\n}\nfunction compareRuntimeValues(a, b, caseSensitive = false) {\n  if (a instanceof NullValue && b instanceof NullValue) {\n    return 0;\n  }\n  if (a instanceof NullValue || b instanceof NullValue) {\n    throw new Error(`Cannot compare ${a.type} with ${b.type}`);\n  }\n  if (a instanceof UndefinedValue && b instanceof UndefinedValue) {\n    return 0;\n  }\n  if (a instanceof UndefinedValue || b instanceof UndefinedValue) {\n    throw new Error(`Cannot compare ${a.type} with ${b.type}`);\n  }\n  const isNumericLike = (v) => v instanceof IntegerValue || v instanceof FloatValue || v instanceof BooleanValue;\n  const getNumericValue = (v) => {\n    if (v instanceof BooleanValue) {\n      return v.value ? 1 : 0;\n    }\n    return v.value;\n  };\n  if (isNumericLike(a) && isNumericLike(b)) {\n    const aNum = getNumericValue(a);\n    const bNum = getNumericValue(b);\n    return aNum < bNum ? -1 : aNum > bNum ? 1 : 0;\n  }\n  if (a.type !== b.type) {\n    throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`);\n  }\n  switch (a.type) {\n    case \"StringValue\": {\n      let aStr = a.value;\n      let bStr = b.value;\n      if (!caseSensitive) {\n        aStr = aStr.toLowerCase();\n        bStr = bStr.toLowerCase();\n      }\n      return aStr < bStr ? -1 : aStr > bStr ? 1 : 0;\n    }\n    default:\n      throw new Error(`Cannot compare type: ${a.type}`);\n  }\n}\nvar Interpreter = class {\n  global;\n  constructor(env) {\n    this.global = env ?? new Environment();\n  }\n  /**\n   * Run the program.\n   */\n  run(program) {\n    return this.evaluate(program, this.global);\n  }\n  /**\n   * Evaluates expressions following the binary operation type.\n   */\n  evaluateBinaryExpression(node, environment) {\n    const left = this.evaluate(node.left, environment);\n    switch (node.operator.value) {\n      case \"and\":\n        return left.__bool__().value ? this.evaluate(node.right, environment) : left;\n      case \"or\":\n        return left.__bool__().value ? left : this.evaluate(node.right, environment);\n    }\n    const right = this.evaluate(node.right, environment);\n    switch (node.operator.value) {\n      case \"==\":\n        return new BooleanValue(left.value == right.value);\n      case \"!=\":\n        return new BooleanValue(left.value != right.value);\n    }\n    if (left instanceof UndefinedValue || right instanceof UndefinedValue) {\n      if (right instanceof UndefinedValue && [\"in\", \"not in\"].includes(node.operator.value)) {\n        return new BooleanValue(node.operator.value === \"not in\");\n      }\n      throw new Error(`Cannot perform operation ${node.operator.value} on undefined values`);\n    } else if (left instanceof NullValue || right instanceof NullValue) {\n      throw new Error(\"Cannot perform operation on null values\");\n    } else if (node.operator.value === \"~\") {\n      return new StringValue(left.value.toString() + right.value.toString());\n    } else if ((left instanceof IntegerValue || left instanceof FloatValue) && (right instanceof IntegerValue || right instanceof FloatValue)) {\n      const a = left.value, b = right.value;\n      switch (node.operator.value) {\n        case \"+\":\n        case \"-\":\n        case \"*\": {\n          const res = node.operator.value === \"+\" ? a + b : node.operator.value === \"-\" ? a - b : a * b;\n          const isFloat = left instanceof FloatValue || right instanceof FloatValue;\n          return isFloat ? new FloatValue(res) : new IntegerValue(res);\n        }\n        case \"/\":\n          return new FloatValue(a / b);\n        case \"%\": {\n          const rem = a % b;\n          const isFloat = left instanceof FloatValue || right instanceof FloatValue;\n          return isFloat ? new FloatValue(rem) : new IntegerValue(rem);\n        }\n        case \"<\":\n          return new BooleanValue(a < b);\n        case \">\":\n          return new BooleanValue(a > b);\n        case \">=\":\n          return new BooleanValue(a >= b);\n        case \"<=\":\n          return new BooleanValue(a <= b);\n      }\n    } else if (left instanceof ArrayValue && right instanceof ArrayValue) {\n      switch (node.operator.value) {\n        case \"+\":\n          return new ArrayValue(left.value.concat(right.value));\n      }\n    } else if (right instanceof ArrayValue) {\n      const member = right.value.find((x) => x.value === left.value) !== void 0;\n      switch (node.operator.value) {\n        case \"in\":\n          return new BooleanValue(member);\n        case \"not in\":\n          return new BooleanValue(!member);\n      }\n    }\n    if (left instanceof StringValue || right instanceof StringValue) {\n      switch (node.operator.value) {\n        case \"+\":\n          return new StringValue(left.value.toString() + right.value.toString());\n      }\n    }\n    if (left instanceof StringValue && right instanceof StringValue) {\n      switch (node.operator.value) {\n        case \"in\":\n          return new BooleanValue(right.value.includes(left.value));\n        case \"not in\":\n          return new BooleanValue(!right.value.includes(left.value));\n      }\n    }\n    if (left instanceof StringValue && right instanceof ObjectValue) {\n      switch (node.operator.value) {\n        case \"in\":\n          return new BooleanValue(right.value.has(left.value));\n        case \"not in\":\n          return new BooleanValue(!right.value.has(left.value));\n      }\n    }\n    throw new SyntaxError(`Unknown operator \"${node.operator.value}\" between ${left.type} and ${right.type}`);\n  }\n  evaluateArguments(args, environment) {\n    const positionalArguments = [];\n    const keywordArguments = /* @__PURE__ */ new Map();\n    for (const argument of args) {\n      if (argument.type === \"SpreadExpression\") {\n        const spreadNode = argument;\n        const val = this.evaluate(spreadNode.argument, environment);\n        if (!(val instanceof ArrayValue)) {\n          throw new Error(`Cannot unpack non-iterable type: ${val.type}`);\n        }\n        for (const item of val.value) {\n          positionalArguments.push(item);\n        }\n      } else if (argument.type === \"KeywordArgumentExpression\") {\n        const kwarg = argument;\n        keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment));\n      } else {\n        if (keywordArguments.size > 0) {\n          throw new Error(\"Positional arguments must come before keyword arguments\");\n        }\n        positionalArguments.push(this.evaluate(argument, environment));\n      }\n    }\n    return [positionalArguments, keywordArguments];\n  }\n  applyFilter(operand, filterNode, environment) {\n    if (filterNode.type === \"Identifier\") {\n      const filter = filterNode;\n      if (filter.value === \"tojson\") {\n        return new StringValue(toJSON(operand, {}));\n      }\n      if (operand instanceof ArrayValue) {\n        switch (filter.value) {\n          case \"list\":\n            return operand;\n          case \"first\":\n            return operand.value[0];\n          case \"last\":\n            return operand.value[operand.value.length - 1];\n          case \"length\":\n            return new IntegerValue(operand.value.length);\n          case \"reverse\":\n            return new ArrayValue(operand.value.slice().reverse());\n          case \"sort\": {\n            return new ArrayValue(operand.value.slice().sort((a, b) => compareRuntimeValues(a, b, false)));\n          }\n          case \"join\":\n            return new StringValue(operand.value.map((x) => x.value).join(\"\"));\n          case \"string\":\n            return new StringValue(toJSON(operand, {}, 0, false));\n          case \"unique\": {\n            const seen = /* @__PURE__ */ new Set();\n            const output = [];\n            for (const item of operand.value) {\n              if (!seen.has(item.value)) {\n                seen.add(item.value);\n                output.push(item);\n              }\n            }\n            return new ArrayValue(output);\n          }\n          default:\n            throw new Error(`Unknown ArrayValue filter: ${filter.value}`);\n        }\n      } else if (operand instanceof StringValue) {\n        switch (filter.value) {\n          case \"length\":\n          case \"upper\":\n          case \"lower\":\n          case \"title\":\n          case \"capitalize\": {\n            const builtin = operand.builtins.get(filter.value);\n            if (builtin instanceof FunctionValue) {\n              return builtin.value(\n                /* no arguments */\n                [],\n                environment\n              );\n            } else if (builtin instanceof IntegerValue) {\n              return builtin;\n            } else {\n              throw new Error(`Unknown StringValue filter: ${filter.value}`);\n            }\n          }\n          case \"trim\":\n            return new StringValue(operand.value.trim());\n          case \"indent\":\n            return new StringValue(\n              operand.value.split(\"\\n\").map(\n                (x, i) => (\n                  // By default, don't indent the first line or empty lines\n                  i === 0 || x.length === 0 ? x : \"    \" + x\n                )\n              ).join(\"\\n\")\n            );\n          case \"join\":\n          case \"string\":\n            return operand;\n          case \"int\": {\n            const val = parseInt(operand.value, 10);\n            return new IntegerValue(isNaN(val) ? 0 : val);\n          }\n          case \"float\": {\n            const val = parseFloat(operand.value);\n            return new FloatValue(isNaN(val) ? 0 : val);\n          }\n          default:\n            throw new Error(`Unknown StringValue filter: ${filter.value}`);\n        }\n      } else if (operand instanceof IntegerValue || operand instanceof FloatValue) {\n        switch (filter.value) {\n          case \"abs\":\n            return operand instanceof IntegerValue ? new IntegerValue(Math.abs(operand.value)) : new FloatValue(Math.abs(operand.value));\n          case \"int\":\n            return new IntegerValue(Math.floor(operand.value));\n          case \"float\":\n            return new FloatValue(operand.value);\n          default:\n            throw new Error(`Unknown NumericValue filter: ${filter.value}`);\n        }\n      } else if (operand instanceof ObjectValue) {\n        switch (filter.value) {\n          case \"items\":\n            return new ArrayValue(\n              Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n            );\n          case \"length\":\n            return new IntegerValue(operand.value.size);\n          default: {\n            const builtin = operand.builtins.get(filter.value);\n            if (builtin) {\n              if (builtin instanceof FunctionValue) {\n                return builtin.value([], environment);\n              }\n              return builtin;\n            }\n            throw new Error(`Unknown ObjectValue filter: ${filter.value}`);\n          }\n        }\n      } else if (operand instanceof BooleanValue) {\n        switch (filter.value) {\n          case \"bool\":\n            return new BooleanValue(operand.value);\n          case \"int\":\n            return new IntegerValue(operand.value ? 1 : 0);\n          case \"float\":\n            return new FloatValue(operand.value ? 1 : 0);\n          case \"string\":\n            return new StringValue(operand.value ? \"true\" : \"false\");\n          default:\n            throw new Error(`Unknown BooleanValue filter: ${filter.value}`);\n        }\n      }\n      throw new Error(`Cannot apply filter \"${filter.value}\" to type: ${operand.type}`);\n    } else if (filterNode.type === \"CallExpression\") {\n      const filter = filterNode;\n      if (filter.callee.type !== \"Identifier\") {\n        throw new Error(`Unknown filter: ${filter.callee.type}`);\n      }\n      const filterName = filter.callee.value;\n      if (filterName === \"tojson\") {\n        const [, kwargs] = this.evaluateArguments(filter.args, environment);\n        const indent = kwargs.get(\"indent\") ?? new NullValue();\n        if (!(indent instanceof IntegerValue || indent instanceof NullValue)) {\n          throw new Error(\"If set, indent must be a number\");\n        }\n        const ensureAscii = kwargs.get(\"ensure_ascii\") ?? new BooleanValue(false);\n        if (!(ensureAscii instanceof BooleanValue)) {\n          throw new Error(\"If set, ensure_ascii must be a boolean\");\n        }\n        const sortKeys = kwargs.get(\"sort_keys\") ?? new BooleanValue(false);\n        if (!(sortKeys instanceof BooleanValue)) {\n          throw new Error(\"If set, sort_keys must be a boolean\");\n        }\n        const separatorsArg = kwargs.get(\"separators\") ?? new NullValue();\n        let separators = null;\n        if (separatorsArg instanceof ArrayValue || separatorsArg instanceof TupleValue) {\n          if (separatorsArg.value.length !== 2) {\n            throw new Error(\"separators must be a tuple of two strings\");\n          }\n          const [itemSep, keySep] = separatorsArg.value;\n          if (!(itemSep instanceof StringValue) || !(keySep instanceof StringValue)) {\n            throw new Error(\"separators must be a tuple of two strings\");\n          }\n          separators = [itemSep.value, keySep.value];\n        } else if (!(separatorsArg instanceof NullValue)) {\n          throw new Error(\"If set, separators must be a tuple of two strings\");\n        }\n        return new StringValue(\n          toJSON(operand, {\n            indent: indent.value,\n            ensureAscii: ensureAscii.value,\n            sortKeys: sortKeys.value,\n            separators\n          })\n        );\n      } else if (filterName === \"join\") {\n        let value;\n        if (operand instanceof StringValue) {\n          value = Array.from(operand.value);\n        } else if (operand instanceof ArrayValue) {\n          value = operand.value.map((x) => x.value);\n        } else {\n          throw new Error(`Cannot apply filter \"${filterName}\" to type: ${operand.type}`);\n        }\n        const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n        const separator = args.at(0) ?? kwargs.get(\"separator\") ?? new StringValue(\"\");\n        if (!(separator instanceof StringValue)) {\n          throw new Error(\"separator must be a string\");\n        }\n        return new StringValue(value.join(separator.value));\n      } else if (filterName === \"int\" || filterName === \"float\") {\n        const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n        const defaultValue = args.at(0) ?? kwargs.get(\"default\") ?? (filterName === \"int\" ? new IntegerValue(0) : new FloatValue(0));\n        if (operand instanceof StringValue) {\n          const val = filterName === \"int\" ? parseInt(operand.value, 10) : parseFloat(operand.value);\n          return isNaN(val) ? defaultValue : filterName === \"int\" ? new IntegerValue(val) : new FloatValue(val);\n        } else if (operand instanceof IntegerValue || operand instanceof FloatValue) {\n          return operand;\n        } else if (operand instanceof BooleanValue) {\n          return filterName === \"int\" ? new IntegerValue(operand.value ? 1 : 0) : new FloatValue(operand.value ? 1 : 0);\n        } else {\n          throw new Error(`Cannot apply filter \"${filterName}\" to type: ${operand.type}`);\n        }\n      } else if (filterName === \"default\") {\n        const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n        const defaultValue = args[0] ?? new StringValue(\"\");\n        const booleanValue = args[1] ?? kwargs.get(\"boolean\") ?? new BooleanValue(false);\n        if (!(booleanValue instanceof BooleanValue)) {\n          throw new Error(\"`default` filter flag must be a boolean\");\n        }\n        if (operand instanceof UndefinedValue || booleanValue.value && !operand.__bool__().value) {\n          return defaultValue;\n        }\n        return operand;\n      }\n      if (operand instanceof ArrayValue) {\n        switch (filterName) {\n          case \"sort\": {\n            const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n            const reverse = args.at(0) ?? kwargs.get(\"reverse\") ?? new BooleanValue(false);\n            if (!(reverse instanceof BooleanValue)) {\n              throw new Error(\"reverse must be a boolean\");\n            }\n            const caseSensitive = args.at(1) ?? kwargs.get(\"case_sensitive\") ?? new BooleanValue(false);\n            if (!(caseSensitive instanceof BooleanValue)) {\n              throw new Error(\"case_sensitive must be a boolean\");\n            }\n            const attribute = args.at(2) ?? kwargs.get(\"attribute\") ?? new NullValue();\n            if (!(attribute instanceof StringValue || attribute instanceof IntegerValue || attribute instanceof NullValue)) {\n              throw new Error(\"attribute must be a string, integer, or null\");\n            }\n            const getSortValue = (item) => {\n              if (attribute instanceof NullValue) {\n                return item;\n              }\n              const attrPath = attribute instanceof IntegerValue ? String(attribute.value) : attribute.value;\n              return getAttributeValue(item, attrPath);\n            };\n            return new ArrayValue(\n              operand.value.slice().sort((a, b) => {\n                const aVal = getSortValue(a);\n                const bVal = getSortValue(b);\n                const result = compareRuntimeValues(aVal, bVal, caseSensitive.value);\n                return reverse.value ? -result : result;\n              })\n            );\n          }\n          case \"selectattr\":\n          case \"rejectattr\": {\n            const select = filterName === \"selectattr\";\n            if (operand.value.some((x) => !(x instanceof ObjectValue))) {\n              throw new Error(`\\`${filterName}\\` can only be applied to array of objects`);\n            }\n            if (filter.args.some((x) => x.type !== \"StringLiteral\")) {\n              throw new Error(`arguments of \\`${filterName}\\` must be strings`);\n            }\n            const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));\n            let testFunction;\n            if (testName) {\n              const test = environment.tests.get(testName.value);\n              if (!test) {\n                throw new Error(`Unknown test: ${testName.value}`);\n              }\n              testFunction = test;\n            } else {\n              testFunction = (...x) => x[0].__bool__().value;\n            }\n            const filtered = operand.value.filter((item) => {\n              const a = item.value.get(attr.value);\n              const result = a ? testFunction(a, value) : false;\n              return select ? result : !result;\n            });\n            return new ArrayValue(filtered);\n          }\n          case \"map\": {\n            const [, kwargs] = this.evaluateArguments(filter.args, environment);\n            if (kwargs.has(\"attribute\")) {\n              const attr = kwargs.get(\"attribute\");\n              if (!(attr instanceof StringValue)) {\n                throw new Error(\"attribute must be a string\");\n              }\n              const defaultValue = kwargs.get(\"default\");\n              const mapped = operand.value.map((item) => {\n                if (!(item instanceof ObjectValue)) {\n                  throw new Error(\"items in map must be an object\");\n                }\n                const value = getAttributeValue(item, attr.value);\n                return value instanceof UndefinedValue ? defaultValue ?? new UndefinedValue() : value;\n              });\n              return new ArrayValue(mapped);\n            } else {\n              throw new Error(\"`map` expressions without `attribute` set are not currently supported.\");\n            }\n          }\n        }\n        throw new Error(`Unknown ArrayValue filter: ${filterName}`);\n      } else if (operand instanceof StringValue) {\n        switch (filterName) {\n          case \"indent\": {\n            const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n            const width = args.at(0) ?? kwargs.get(\"width\") ?? new IntegerValue(4);\n            if (!(width instanceof IntegerValue)) {\n              throw new Error(\"width must be a number\");\n            }\n            const first = args.at(1) ?? kwargs.get(\"first\") ?? new BooleanValue(false);\n            const blank = args.at(2) ?? kwargs.get(\"blank\") ?? new BooleanValue(false);\n            const lines = operand.value.split(\"\\n\");\n            const indent = \" \".repeat(width.value);\n            const indented = lines.map(\n              (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x\n            );\n            return new StringValue(indented.join(\"\\n\"));\n          }\n          case \"replace\": {\n            const replaceFn = operand.builtins.get(\"replace\");\n            if (!(replaceFn instanceof FunctionValue)) {\n              throw new Error(\"replace filter not available\");\n            }\n            const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n            return replaceFn.value([...args, new KeywordArgumentsValue(kwargs)], environment);\n          }\n        }\n        throw new Error(`Unknown StringValue filter: ${filterName}`);\n      } else if (operand instanceof ObjectValue) {\n        const builtin = operand.builtins.get(filterName);\n        if (builtin && builtin instanceof FunctionValue) {\n          const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n          if (kwargs.size > 0) {\n            args.push(new KeywordArgumentsValue(kwargs));\n          }\n          return builtin.value(args, environment);\n        }\n        throw new Error(`Unknown ObjectValue filter: ${filterName}`);\n      } else {\n        throw new Error(`Cannot apply filter \"${filterName}\" to type: ${operand.type}`);\n      }\n    }\n    throw new Error(`Unknown filter: ${filterNode.type}`);\n  }\n  /**\n   * Evaluates expressions following the filter operation type.\n   */\n  evaluateFilterExpression(node, environment) {\n    const operand = this.evaluate(node.operand, environment);\n    return this.applyFilter(operand, node.filter, environment);\n  }\n  /**\n   * Evaluates expressions following the test operation type.\n   */\n  evaluateTestExpression(node, environment) {\n    const operand = this.evaluate(node.operand, environment);\n    const test = environment.tests.get(node.test.value);\n    if (!test) {\n      throw new Error(`Unknown test: ${node.test.value}`);\n    }\n    const result = test(operand);\n    return new BooleanValue(node.negate ? !result : result);\n  }\n  /**\n   * Evaluates expressions following the select operation type.\n   */\n  evaluateSelectExpression(node, environment) {\n    const predicate = this.evaluate(node.test, environment);\n    if (!predicate.__bool__().value) {\n      return new UndefinedValue();\n    }\n    return this.evaluate(node.lhs, environment);\n  }\n  /**\n   * Evaluates expressions following the unary operation type.\n   */\n  evaluateUnaryExpression(node, environment) {\n    const argument = this.evaluate(node.argument, environment);\n    switch (node.operator.value) {\n      case \"not\":\n        return new BooleanValue(!argument.value);\n      default:\n        throw new SyntaxError(`Unknown operator: ${node.operator.value}`);\n    }\n  }\n  evaluateTernaryExpression(node, environment) {\n    const cond = this.evaluate(node.condition, environment);\n    return cond.__bool__().value ? this.evaluate(node.trueExpr, environment) : this.evaluate(node.falseExpr, environment);\n  }\n  evalProgram(program, environment) {\n    return this.evaluateBlock(program.body, environment);\n  }\n  evaluateBlock(statements, environment) {\n    let result = \"\";\n    for (const statement of statements) {\n      const lastEvaluated = this.evaluate(statement, environment);\n      if (lastEvaluated.type !== \"NullValue\" && lastEvaluated.type !== \"UndefinedValue\") {\n        result += lastEvaluated.toString();\n      }\n    }\n    return new StringValue(result);\n  }\n  evaluateIdentifier(node, environment) {\n    return environment.lookupVariable(node.value);\n  }\n  evaluateCallExpression(expr, environment) {\n    const [args, kwargs] = this.evaluateArguments(expr.args, environment);\n    if (kwargs.size > 0) {\n      args.push(new KeywordArgumentsValue(kwargs));\n    }\n    const fn = this.evaluate(expr.callee, environment);\n    if (fn.type !== \"FunctionValue\") {\n      throw new Error(`Cannot call something that is not a function: got ${fn.type}`);\n    }\n    return fn.value(args, environment);\n  }\n  evaluateSliceExpression(object, expr, environment) {\n    if (!(object instanceof ArrayValue || object instanceof StringValue)) {\n      throw new Error(\"Slice object must be an array or string\");\n    }\n    const start = this.evaluate(expr.start, environment);\n    const stop = this.evaluate(expr.stop, environment);\n    const step = this.evaluate(expr.step, environment);\n    if (!(start instanceof IntegerValue || start instanceof UndefinedValue)) {\n      throw new Error(\"Slice start must be numeric or undefined\");\n    }\n    if (!(stop instanceof IntegerValue || stop instanceof UndefinedValue)) {\n      throw new Error(\"Slice stop must be numeric or undefined\");\n    }\n    if (!(step instanceof IntegerValue || step instanceof UndefinedValue)) {\n      throw new Error(\"Slice step must be numeric or undefined\");\n    }\n    if (object instanceof ArrayValue) {\n      return new ArrayValue(slice(object.value, start.value, stop.value, step.value));\n    } else {\n      return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join(\"\"));\n    }\n  }\n  evaluateMemberExpression(expr, environment) {\n    const object = this.evaluate(expr.object, environment);\n    let property;\n    if (expr.computed) {\n      if (expr.property.type === \"SliceExpression\") {\n        return this.evaluateSliceExpression(object, expr.property, environment);\n      } else {\n        property = this.evaluate(expr.property, environment);\n      }\n    } else {\n      property = new StringValue(expr.property.value);\n    }\n    let value;\n    if (object instanceof ObjectValue) {\n      if (!(property instanceof StringValue)) {\n        throw new Error(`Cannot access property with non-string: got ${property.type}`);\n      }\n      value = object.value.get(property.value) ?? object.builtins.get(property.value);\n    } else if (object instanceof ArrayValue || object instanceof StringValue) {\n      if (property instanceof IntegerValue) {\n        value = object.value.at(property.value);\n        if (object instanceof StringValue) {\n          value = new StringValue(object.value.at(property.value));\n        }\n      } else if (property instanceof StringValue) {\n        value = object.builtins.get(property.value);\n      } else {\n        throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);\n      }\n    } else {\n      if (!(property instanceof StringValue)) {\n        throw new Error(`Cannot access property with non-string: got ${property.type}`);\n      }\n      value = object.builtins.get(property.value);\n    }\n    return value instanceof RuntimeValue ? value : new UndefinedValue();\n  }\n  evaluateSet(node, environment) {\n    const rhs = node.value ? this.evaluate(node.value, environment) : this.evaluateBlock(node.body, environment);\n    if (node.assignee.type === \"Identifier\") {\n      const variableName = node.assignee.value;\n      environment.setVariable(variableName, rhs);\n    } else if (node.assignee.type === \"TupleLiteral\") {\n      const tuple = node.assignee;\n      if (!(rhs instanceof ArrayValue)) {\n        throw new Error(`Cannot unpack non-iterable type in set: ${rhs.type}`);\n      }\n      const arr = rhs.value;\n      if (arr.length !== tuple.value.length) {\n        throw new Error(`Too ${tuple.value.length > arr.length ? \"few\" : \"many\"} items to unpack in set`);\n      }\n      for (let i = 0; i < tuple.value.length; ++i) {\n        const elem = tuple.value[i];\n        if (elem.type !== \"Identifier\") {\n          throw new Error(`Cannot unpack to non-identifier in set: ${elem.type}`);\n        }\n        environment.setVariable(elem.value, arr[i]);\n      }\n    } else if (node.assignee.type === \"MemberExpression\") {\n      const member = node.assignee;\n      const object = this.evaluate(member.object, environment);\n      if (!(object instanceof ObjectValue)) {\n        throw new Error(\"Cannot assign to member of non-object\");\n      }\n      if (member.property.type !== \"Identifier\") {\n        throw new Error(\"Cannot assign to member with non-identifier property\");\n      }\n      object.value.set(member.property.value, rhs);\n    } else {\n      throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);\n    }\n    return new NullValue();\n  }\n  evaluateIf(node, environment) {\n    const test = this.evaluate(node.test, environment);\n    return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);\n  }\n  evaluateFor(node, environment) {\n    const scope = new Environment(environment);\n    let test, iterable;\n    if (node.iterable.type === \"SelectExpression\") {\n      const select = node.iterable;\n      iterable = this.evaluate(select.lhs, scope);\n      test = select.test;\n    } else {\n      iterable = this.evaluate(node.iterable, scope);\n    }\n    if (!(iterable instanceof ArrayValue || iterable instanceof ObjectValue)) {\n      throw new Error(`Expected iterable or object type in for loop: got ${iterable.type}`);\n    }\n    if (iterable instanceof ObjectValue) {\n      iterable = iterable.keys();\n    }\n    const items = [];\n    const scopeUpdateFunctions = [];\n    for (let i = 0; i < iterable.value.length; ++i) {\n      const loopScope = new Environment(scope);\n      const current = iterable.value[i];\n      let scopeUpdateFunction;\n      if (node.loopvar.type === \"Identifier\") {\n        scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current);\n      } else if (node.loopvar.type === \"TupleLiteral\") {\n        const loopvar = node.loopvar;\n        if (current.type !== \"ArrayValue\") {\n          throw new Error(`Cannot unpack non-iterable type: ${current.type}`);\n        }\n        const c = current;\n        if (loopvar.value.length !== c.value.length) {\n          throw new Error(`Too ${loopvar.value.length > c.value.length ? \"few\" : \"many\"} items to unpack`);\n        }\n        scopeUpdateFunction = (scope2) => {\n          for (let j = 0; j < loopvar.value.length; ++j) {\n            if (loopvar.value[j].type !== \"Identifier\") {\n              throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);\n            }\n            scope2.setVariable(loopvar.value[j].value, c.value[j]);\n          }\n        };\n      } else {\n        throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`);\n      }\n      if (test) {\n        scopeUpdateFunction(loopScope);\n        const testValue = this.evaluate(test, loopScope);\n        if (!testValue.__bool__().value) {\n          continue;\n        }\n      }\n      items.push(current);\n      scopeUpdateFunctions.push(scopeUpdateFunction);\n    }\n    let result = \"\";\n    let noIteration = true;\n    for (let i = 0; i < items.length; ++i) {\n      const loop = /* @__PURE__ */ new Map([\n        [\"index\", new IntegerValue(i + 1)],\n        [\"index0\", new IntegerValue(i)],\n        [\"revindex\", new IntegerValue(items.length - i)],\n        [\"revindex0\", new IntegerValue(items.length - i - 1)],\n        [\"first\", new BooleanValue(i === 0)],\n        [\"last\", new BooleanValue(i === items.length - 1)],\n        [\"length\", new IntegerValue(items.length)],\n        [\"previtem\", i > 0 ? items[i - 1] : new UndefinedValue()],\n        [\"nextitem\", i < items.length - 1 ? items[i + 1] : new UndefinedValue()]\n      ]);\n      scope.setVariable(\"loop\", new ObjectValue(loop));\n      scopeUpdateFunctions[i](scope);\n      try {\n        const evaluated = this.evaluateBlock(node.body, scope);\n        result += evaluated.value;\n      } catch (err) {\n        if (err instanceof ContinueControl) {\n          continue;\n        }\n        if (err instanceof BreakControl) {\n          break;\n        }\n        throw err;\n      }\n      noIteration = false;\n    }\n    if (noIteration) {\n      const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope);\n      result += defaultEvaluated.value;\n    }\n    return new StringValue(result);\n  }\n  /**\n   * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information.\n   */\n  evaluateMacro(node, environment) {\n    environment.setVariable(\n      node.name.value,\n      new FunctionValue((args, scope) => {\n        const macroScope = new Environment(scope);\n        args = args.slice();\n        let kwargs;\n        if (args.at(-1)?.type === \"KeywordArgumentsValue\") {\n          kwargs = args.pop();\n        }\n        for (let i = 0; i < node.args.length; ++i) {\n          const nodeArg = node.args[i];\n          const passedArg = args[i];\n          if (nodeArg.type === \"Identifier\") {\n            const identifier = nodeArg;\n            if (!passedArg) {\n              throw new Error(`Missing positional argument: ${identifier.value}`);\n            }\n            macroScope.setVariable(identifier.value, passedArg);\n          } else if (nodeArg.type === \"KeywordArgumentExpression\") {\n            const kwarg = nodeArg;\n            const value = passedArg ?? // Try positional arguments first\n            kwargs?.value.get(kwarg.key.value) ?? // Look in user-passed kwargs\n            this.evaluate(kwarg.value, macroScope);\n            macroScope.setVariable(kwarg.key.value, value);\n          } else {\n            throw new Error(`Unknown argument type: ${nodeArg.type}`);\n          }\n        }\n        return this.evaluateBlock(node.body, macroScope);\n      })\n    );\n    return new NullValue();\n  }\n  evaluateCallStatement(node, environment) {\n    const callerFn = new FunctionValue((callerArgs, callerEnv) => {\n      const callBlockEnv = new Environment(callerEnv);\n      if (node.callerArgs) {\n        for (let i = 0; i < node.callerArgs.length; ++i) {\n          const param = node.callerArgs[i];\n          if (param.type !== \"Identifier\") {\n            throw new Error(`Caller parameter must be an identifier, got ${param.type}`);\n          }\n          callBlockEnv.setVariable(param.value, callerArgs[i] ?? new UndefinedValue());\n        }\n      }\n      return this.evaluateBlock(node.body, callBlockEnv);\n    });\n    const [macroArgs, macroKwargs] = this.evaluateArguments(node.call.args, environment);\n    macroArgs.push(new KeywordArgumentsValue(macroKwargs));\n    const fn = this.evaluate(node.call.callee, environment);\n    if (fn.type !== \"FunctionValue\") {\n      throw new Error(`Cannot call something that is not a function: got ${fn.type}`);\n    }\n    const newEnv = new Environment(environment);\n    newEnv.setVariable(\"caller\", callerFn);\n    return fn.value(macroArgs, newEnv);\n  }\n  evaluateFilterStatement(node, environment) {\n    const rendered = this.evaluateBlock(node.body, environment);\n    return this.applyFilter(rendered, node.filter, environment);\n  }\n  evaluate(statement, environment) {\n    if (!statement)\n      return new UndefinedValue();\n    switch (statement.type) {\n      case \"Program\":\n        return this.evalProgram(statement, environment);\n      case \"Set\":\n        return this.evaluateSet(statement, environment);\n      case \"If\":\n        return this.evaluateIf(statement, environment);\n      case \"For\":\n        return this.evaluateFor(statement, environment);\n      case \"Macro\":\n        return this.evaluateMacro(statement, environment);\n      case \"CallStatement\":\n        return this.evaluateCallStatement(statement, environment);\n      case \"Break\":\n        throw new BreakControl();\n      case \"Continue\":\n        throw new ContinueControl();\n      case \"IntegerLiteral\":\n        return new IntegerValue(statement.value);\n      case \"FloatLiteral\":\n        return new FloatValue(statement.value);\n      case \"StringLiteral\":\n        return new StringValue(statement.value);\n      case \"ArrayLiteral\":\n        return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));\n      case \"TupleLiteral\":\n        return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));\n      case \"ObjectLiteral\": {\n        const mapping = /* @__PURE__ */ new Map();\n        for (const [key, value] of statement.value) {\n          const evaluatedKey = this.evaluate(key, environment);\n          if (!(evaluatedKey instanceof StringValue)) {\n            throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`);\n          }\n          mapping.set(evaluatedKey.value, this.evaluate(value, environment));\n        }\n        return new ObjectValue(mapping);\n      }\n      case \"Identifier\":\n        return this.evaluateIdentifier(statement, environment);\n      case \"CallExpression\":\n        return this.evaluateCallExpression(statement, environment);\n      case \"MemberExpression\":\n        return this.evaluateMemberExpression(statement, environment);\n      case \"UnaryExpression\":\n        return this.evaluateUnaryExpression(statement, environment);\n      case \"BinaryExpression\":\n        return this.evaluateBinaryExpression(statement, environment);\n      case \"FilterExpression\":\n        return this.evaluateFilterExpression(statement, environment);\n      case \"FilterStatement\":\n        return this.evaluateFilterStatement(statement, environment);\n      case \"TestExpression\":\n        return this.evaluateTestExpression(statement, environment);\n      case \"SelectExpression\":\n        return this.evaluateSelectExpression(statement, environment);\n      case \"Ternary\":\n        return this.evaluateTernaryExpression(statement, environment);\n      case \"Comment\":\n        return new NullValue();\n      default:\n        throw new SyntaxError(`Unknown node type: ${statement.type}`);\n    }\n  }\n};\nfunction convertToRuntimeValues(input) {\n  switch (typeof input) {\n    case \"number\":\n      return Number.isInteger(input) ? new IntegerValue(input) : new FloatValue(input);\n    case \"string\":\n      return new StringValue(input);\n    case \"boolean\":\n      return new BooleanValue(input);\n    case \"undefined\":\n      return new UndefinedValue();\n    case \"object\":\n      if (input === null) {\n        return new NullValue();\n      } else if (Array.isArray(input)) {\n        return new ArrayValue(input.map(convertToRuntimeValues));\n      } else {\n        return new ObjectValue(\n          new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)]))\n        );\n      }\n    case \"function\":\n      return new FunctionValue((args, _scope) => {\n        const result = input(...args.map((x) => x.value)) ?? null;\n        return convertToRuntimeValues(result);\n      });\n    default:\n      throw new Error(`Cannot convert to runtime value: ${input}`);\n  }\n}\n\n// src/format.ts\nvar NEWLINE = \"\\n\";\nvar OPEN_STATEMENT = \"{%- \";\nvar CLOSE_STATEMENT = \" -%}\";\nfunction getBinaryOperatorPrecedence(expr) {\n  switch (expr.operator.type) {\n    case \"MultiplicativeBinaryOperator\":\n      return 4;\n    case \"AdditiveBinaryOperator\":\n      return 3;\n    case \"ComparisonBinaryOperator\":\n      return 2;\n    case \"Identifier\":\n      if (expr.operator.value === \"and\")\n        return 1;\n      if (expr.operator.value === \"in\" || expr.operator.value === \"not in\")\n        return 2;\n      return 0;\n  }\n  return 0;\n}\nfunction format(program, indent = \"\t\") {\n  const indentStr = typeof indent === \"number\" ? \" \".repeat(indent) : indent;\n  const body = formatStatements(program.body, 0, indentStr);\n  return body.replace(/\\n$/, \"\");\n}\nfunction createStatement(...text) {\n  return OPEN_STATEMENT + text.join(\" \") + CLOSE_STATEMENT;\n}\nfunction formatStatements(stmts, depth, indentStr) {\n  return stmts.map((stmt) => formatStatement(stmt, depth, indentStr)).join(NEWLINE);\n}\nfunction formatStatement(node, depth, indentStr) {\n  const pad = indentStr.repeat(depth);\n  switch (node.type) {\n    case \"Program\":\n      return formatStatements(node.body, depth, indentStr);\n    case \"If\":\n      return formatIf(node, depth, indentStr);\n    case \"For\":\n      return formatFor(node, depth, indentStr);\n    case \"Set\":\n      return formatSet(node, depth, indentStr);\n    case \"Macro\":\n      return formatMacro(node, depth, indentStr);\n    case \"Break\":\n      return pad + createStatement(\"break\");\n    case \"Continue\":\n      return pad + createStatement(\"continue\");\n    case \"CallStatement\":\n      return formatCallStatement(node, depth, indentStr);\n    case \"FilterStatement\":\n      return formatFilterStatement(node, depth, indentStr);\n    case \"Comment\":\n      return pad + \"{# \" + node.value + \" #}\";\n    default:\n      return pad + \"{{- \" + formatExpression(node) + \" -}}\";\n  }\n}\nfunction formatIf(node, depth, indentStr) {\n  const pad = indentStr.repeat(depth);\n  const clauses = [];\n  let current = node;\n  while (current) {\n    clauses.push({ test: current.test, body: current.body });\n    if (current.alternate.length === 1 && current.alternate[0].type === \"If\") {\n      current = current.alternate[0];\n    } else {\n      break;\n    }\n  }\n  let out = pad + createStatement(\"if\", formatExpression(clauses[0].test)) + NEWLINE + formatStatements(clauses[0].body, depth + 1, indentStr);\n  for (let i = 1; i < clauses.length; ++i) {\n    out += NEWLINE + pad + createStatement(\"elif\", formatExpression(clauses[i].test)) + NEWLINE + formatStatements(clauses[i].body, depth + 1, indentStr);\n  }\n  if (current && current.alternate.length > 0) {\n    out += NEWLINE + pad + createStatement(\"else\") + NEWLINE + formatStatements(current.alternate, depth + 1, indentStr);\n  }\n  out += NEWLINE + pad + createStatement(\"endif\");\n  return out;\n}\nfunction formatFor(node, depth, indentStr) {\n  const pad = indentStr.repeat(depth);\n  let formattedIterable = \"\";\n  if (node.iterable.type === \"SelectExpression\") {\n    const n = node.iterable;\n    formattedIterable = `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`;\n  } else {\n    formattedIterable = formatExpression(node.iterable);\n  }\n  let out = pad + createStatement(\"for\", formatExpression(node.loopvar), \"in\", formattedIterable) + NEWLINE + formatStatements(node.body, depth + 1, indentStr);\n  if (node.defaultBlock.length > 0) {\n    out += NEWLINE + pad + createStatement(\"else\") + NEWLINE + formatStatements(node.defaultBlock, depth + 1, indentStr);\n  }\n  out += NEWLINE + pad + createStatement(\"endfor\");\n  return out;\n}\nfunction formatSet(node, depth, indentStr) {\n  const pad = indentStr.repeat(depth);\n  const left = formatExpression(node.assignee);\n  const right = node.value ? formatExpression(node.value) : \"\";\n  const value = pad + createStatement(\"set\", `${left}${node.value ? \" = \" + right : \"\"}`);\n  if (node.body.length === 0) {\n    return value;\n  }\n  return value + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement(\"endset\");\n}\nfunction formatMacro(node, depth, indentStr) {\n  const pad = indentStr.repeat(depth);\n  const args = node.args.map(formatExpression).join(\", \");\n  return pad + createStatement(\"macro\", `${node.name.value}(${args})`) + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement(\"endmacro\");\n}\nfunction formatCallStatement(node, depth, indentStr) {\n  const pad = indentStr.repeat(depth);\n  const params = node.callerArgs && node.callerArgs.length > 0 ? `(${node.callerArgs.map(formatExpression).join(\", \")})` : \"\";\n  const callExpr = formatExpression(node.call);\n  let out = pad + createStatement(`call${params}`, callExpr) + NEWLINE;\n  out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE;\n  out += pad + createStatement(\"endcall\");\n  return out;\n}\nfunction formatFilterStatement(node, depth, indentStr) {\n  const pad = indentStr.repeat(depth);\n  const spec = node.filter.type === \"Identifier\" ? node.filter.value : formatExpression(node.filter);\n  let out = pad + createStatement(\"filter\", spec) + NEWLINE;\n  out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE;\n  out += pad + createStatement(\"endfilter\");\n  return out;\n}\nfunction formatExpression(node, parentPrec = -1) {\n  switch (node.type) {\n    case \"SpreadExpression\": {\n      const n = node;\n      return `*${formatExpression(n.argument)}`;\n    }\n    case \"Identifier\":\n      return node.value;\n    case \"IntegerLiteral\":\n      return `${node.value}`;\n    case \"FloatLiteral\":\n      return `${node.value}`;\n    case \"StringLiteral\":\n      return JSON.stringify(node.value);\n    case \"BinaryExpression\": {\n      const n = node;\n      const thisPrecedence = getBinaryOperatorPrecedence(n);\n      const left = formatExpression(n.left, thisPrecedence);\n      const right = formatExpression(n.right, thisPrecedence + 1);\n      const expr = `${left} ${n.operator.value} ${right}`;\n      return thisPrecedence < parentPrec ? `(${expr})` : expr;\n    }\n    case \"UnaryExpression\": {\n      const n = node;\n      const val = n.operator.value + (n.operator.value === \"not\" ? \" \" : \"\") + formatExpression(n.argument, Infinity);\n      return val;\n    }\n    case \"CallExpression\": {\n      const n = node;\n      const args = n.args.map(formatExpression).join(\", \");\n      return `${formatExpression(n.callee)}(${args})`;\n    }\n    case \"MemberExpression\": {\n      const n = node;\n      let obj = formatExpression(n.object);\n      if (![\n        \"Identifier\",\n        \"MemberExpression\",\n        \"CallExpression\",\n        \"StringLiteral\",\n        \"IntegerLiteral\",\n        \"FloatLiteral\",\n        \"ArrayLiteral\",\n        \"TupleLiteral\",\n        \"ObjectLiteral\"\n      ].includes(n.object.type)) {\n        obj = `(${obj})`;\n      }\n      let prop = formatExpression(n.property);\n      if (!n.computed && n.property.type !== \"Identifier\") {\n        prop = `(${prop})`;\n      }\n      return n.computed ? `${obj}[${prop}]` : `${obj}.${prop}`;\n    }\n    case \"FilterExpression\": {\n      const n = node;\n      const operand = formatExpression(n.operand, Infinity);\n      if (n.filter.type === \"CallExpression\") {\n        return `${operand} | ${formatExpression(n.filter)}`;\n      }\n      return `${operand} | ${n.filter.value}`;\n    }\n    case \"SelectExpression\": {\n      const n = node;\n      return `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`;\n    }\n    case \"TestExpression\": {\n      const n = node;\n      return `${formatExpression(n.operand)} is${n.negate ? \" not\" : \"\"} ${n.test.value}`;\n    }\n    case \"ArrayLiteral\":\n    case \"TupleLiteral\": {\n      const elems = node.value.map(formatExpression);\n      const brackets = node.type === \"ArrayLiteral\" ? \"[]\" : \"()\";\n      return `${brackets[0]}${elems.join(\", \")}${brackets[1]}`;\n    }\n    case \"ObjectLiteral\": {\n      const entries = Array.from(node.value.entries()).map(\n        ([k, v]) => `${formatExpression(k)}: ${formatExpression(v)}`\n      );\n      return `{${entries.join(\", \")}}`;\n    }\n    case \"SliceExpression\": {\n      const n = node;\n      const s = n.start ? formatExpression(n.start) : \"\";\n      const t = n.stop ? formatExpression(n.stop) : \"\";\n      const st = n.step ? `:${formatExpression(n.step)}` : \"\";\n      return `${s}:${t}${st}`;\n    }\n    case \"KeywordArgumentExpression\": {\n      const n = node;\n      return `${n.key.value}=${formatExpression(n.value)}`;\n    }\n    case \"Ternary\": {\n      const n = node;\n      const expr = `${formatExpression(n.trueExpr)} if ${formatExpression(n.condition, 0)} else ${formatExpression(\n        n.falseExpr\n      )}`;\n      return parentPrec > -1 ? `(${expr})` : expr;\n    }\n    default:\n      throw new Error(`Unknown expression type: ${node.type}`);\n  }\n}\n\n// src/index.ts\nvar Template = class {\n  parsed;\n  /**\n   * @param {string} template The template string\n   */\n  constructor(template) {\n    const tokens = tokenize(template, {\n      lstrip_blocks: true,\n      trim_blocks: true\n    });\n    this.parsed = parse(tokens);\n  }\n  render(items) {\n    const env = new Environment();\n    setupGlobals(env);\n    if (items) {\n      for (const [key, value] of Object.entries(items)) {\n        env.set(key, value);\n      }\n    }\n    const interpreter = new Interpreter(env);\n    const result = interpreter.run(this.parsed);\n    return result.value;\n  }\n  format(options) {\n    return format(this.parsed, options?.indent || \"\t\");\n  }\n};\nexport {\n  Environment,\n  Interpreter,\n  Template,\n  parse,\n  tokenize\n};\n", "\n\nconst WHISPER_LANGUAGES = [\n    [\"en\", \"english\"],\n    [\"zh\", \"chinese\"],\n    [\"de\", \"german\"],\n    [\"es\", \"spanish\"],\n    [\"ru\", \"russian\"],\n    [\"ko\", \"korean\"],\n    [\"fr\", \"french\"],\n    [\"ja\", \"japanese\"],\n    [\"pt\", \"portuguese\"],\n    [\"tr\", \"turkish\"],\n    [\"pl\", \"polish\"],\n    [\"ca\", \"catalan\"],\n    [\"nl\", \"dutch\"],\n    [\"ar\", \"arabic\"],\n    [\"sv\", \"swedish\"],\n    [\"it\", \"italian\"],\n    [\"id\", \"indonesian\"],\n    [\"hi\", \"hindi\"],\n    [\"fi\", \"finnish\"],\n    [\"vi\", \"vietnamese\"],\n    [\"he\", \"hebrew\"],\n    [\"uk\", \"ukrainian\"],\n    [\"el\", \"greek\"],\n    [\"ms\", \"malay\"],\n    [\"cs\", \"czech\"],\n    [\"ro\", \"romanian\"],\n    [\"da\", \"danish\"],\n    [\"hu\", \"hungarian\"],\n    [\"ta\", \"tamil\"],\n    [\"no\", \"norwegian\"],\n    [\"th\", \"thai\"],\n    [\"ur\", \"urdu\"],\n    [\"hr\", \"croatian\"],\n    [\"bg\", \"bulgarian\"],\n    [\"lt\", \"lithuanian\"],\n    [\"la\", \"latin\"],\n    [\"mi\", \"maori\"],\n    [\"ml\", \"malayalam\"],\n    [\"cy\", \"welsh\"],\n    [\"sk\", \"slovak\"],\n    [\"te\", \"telugu\"],\n    [\"fa\", \"persian\"],\n    [\"lv\", \"latvian\"],\n    [\"bn\", \"bengali\"],\n    [\"sr\", \"serbian\"],\n    [\"az\", \"azerbaijani\"],\n    [\"sl\", \"slovenian\"],\n    [\"kn\", \"kannada\"],\n    [\"et\", \"estonian\"],\n    [\"mk\", \"macedonian\"],\n    [\"br\", \"breton\"],\n    [\"eu\", \"basque\"],\n    [\"is\", \"icelandic\"],\n    [\"hy\", \"armenian\"],\n    [\"ne\", \"nepali\"],\n    [\"mn\", \"mongolian\"],\n    [\"bs\", \"bosnian\"],\n    [\"kk\", \"kazakh\"],\n    [\"sq\", \"albanian\"],\n    [\"sw\", \"swahili\"],\n    [\"gl\", \"galician\"],\n    [\"mr\", \"marathi\"],\n    [\"pa\", \"punjabi\"],\n    [\"si\", \"sinhala\"],\n    [\"km\", \"khmer\"],\n    [\"sn\", \"shona\"],\n    [\"yo\", \"yoruba\"],\n    [\"so\", \"somali\"],\n    [\"af\", \"afrikaans\"],\n    [\"oc\", \"occitan\"],\n    [\"ka\", \"georgian\"],\n    [\"be\", \"belarusian\"],\n    [\"tg\", \"tajik\"],\n    [\"sd\", \"sindhi\"],\n    [\"gu\", \"gujarati\"],\n    [\"am\", \"amharic\"],\n    [\"yi\", \"yiddish\"],\n    [\"lo\", \"lao\"],\n    [\"uz\", \"uzbek\"],\n    [\"fo\", \"faroese\"],\n    [\"ht\", \"haitian creole\"],\n    [\"ps\", \"pashto\"],\n    [\"tk\", \"turkmen\"],\n    [\"nn\", \"nynorsk\"],\n    [\"mt\", \"maltese\"],\n    [\"sa\", \"sanskrit\"],\n    [\"lb\", \"luxembourgish\"],\n    [\"my\", \"myanmar\"],\n    [\"bo\", \"tibetan\"],\n    [\"tl\", \"tagalog\"],\n    [\"mg\", \"malagasy\"],\n    [\"as\", \"assamese\"],\n    [\"tt\", \"tatar\"],\n    [\"haw\", \"hawaiian\"],\n    [\"ln\", \"lingala\"],\n    [\"ha\", \"hausa\"],\n    [\"ba\", \"bashkir\"],\n    [\"jw\", \"javanese\"],\n    [\"su\", \"sundanese\"],\n]\n\n// @ts-ignore\nexport const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES);\n// @ts-ignore\nexport const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([\n    ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]),\n    ...[\n        [\"burmese\", \"my\"],\n        [\"valencian\", \"ca\"],\n        [\"flemish\", \"nl\"],\n        [\"haitian\", \"ht\"],\n        [\"letzeburgesch\", \"lb\"],\n        [\"pushto\", \"ps\"],\n        [\"panjabi\", \"pa\"],\n        [\"moldavian\", \"ro\"],\n        [\"moldovan\", \"ro\"],\n        [\"sinhalese\", \"si\"],\n        [\"castilian\", \"es\"],\n    ]\n]);\n\n/**\n * @param {string} language The language name or code\n * @returns {string} The language code\n */\nexport function whisper_language_to_code(language) {\n    language = language.toLowerCase();\n\n    // Map to code from user-friendly name (e.g., \"english\" -> \"en\")\n    let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language);\n\n    if (language_code === undefined) {\n        // User provided something that is not a language name\n\n        // Perhaps the user passed the special token itself\n        const language_special_token = language.match(/^<\\|([a-z]{2})\\|>$/);\n        if (language_special_token) {\n            language = language_special_token[1];\n        }\n\n        if (WHISPER_LANGUAGE_MAPPING.has(language)) {\n            // User provided the language code directly (e.g., \"en\")\n            language_code = language;\n\n        } else {\n            // User provided something that is not a language code or name\n            const is_language_code = language.length === 2;\n            const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values();\n\n            throw new Error(`Language \"${language}\" is not supported. Must be one of: ${JSON.stringify(Array.from(langs))}`);\n        }\n    }\n    return language_code;\n}\n", "\n/**\n * @file Tokenizers are used to prepare textual inputs for a model.\n * \n * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.\n * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.\n * ```javascript\n * import { AutoTokenizer } from '@huggingface/transformers';\n * \n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * const { input_ids } = await tokenizer('I love transformers!');\n * // Tensor {\n * //   data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],\n * //   dims: [1, 6],\n * //   type: 'int64',\n * //   size: 6,\n * // }\n * ```\n * \n * @module tokenizers\n */\nimport {\n    Callable,\n} from './utils/generic.js';\n\nimport {\n    reverseDictionary,\n    escapeRegExp,\n    isIntegralNumber,\n    mergeArrays,\n    len,\n} from './utils/core.js';\n\nimport {\n    getModelJSON,\n} from './utils/hub.js';\n\nimport { max, min, round } from './utils/maths.js';\nimport { Tensor } from './utils/tensor.js';\n\nimport {\n    PriorityQueue,\n    TokenLattice,\n    CharTrie,\n    DictionarySplitter,\n    LRUCache,\n} from './utils/data-structures.js';\n\nimport { Template } from '@huggingface/jinja';\n\nimport {\n    WHISPER_LANGUAGE_MAPPING\n} from './models/whisper/common_whisper.js';\n\n/**\n * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.\n * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used.\n * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions\n */\n\n/**\n * Loads a tokenizer from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the tokenizer directory.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * @returns {Promise<any[]>} A promise that resolves with information about the loaded tokenizer.\n */\nasync function loadTokenizer(pretrained_model_name_or_path, options) {\n\n    const info = await Promise.all([\n        getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options),\n        getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),\n    ])\n\n    // Override legacy option if `options.legacy` is not null\n    if (options.legacy !== null) {\n        info[1].legacy = options.legacy;\n    }\n    return info;\n}\n\n\n/**\n * Helper function to split a string on a regex, but keep the delimiters.\n * This is required, because the JavaScript `.split()` method does not keep the delimiters,\n * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting).\n * @param {string} text The text to split.\n * @param {RegExp} regex The regex to split on.\n * @returns {string[]} The split string.\n */\nfunction regexSplit(text, regex) {\n    const result = [];\n    let prev = 0;\n    for (const match of text.matchAll(regex)) {\n        const fullMatch = match[0];\n        if (prev < match.index) {\n            result.push(text.slice(prev, match.index));\n        }\n        if (fullMatch.length > 0) {\n            result.push(fullMatch);\n        }\n        prev = match.index + fullMatch.length;\n    }\n    if (prev < text.length) {\n        result.push(text.slice(prev));\n    }\n    return result;\n}\n\n\n/**\n * Helper method to construct a pattern from a config object.\n * @param {Object} pattern The pattern object.\n * @param {boolean} invert Whether to invert the pattern.\n * @returns {RegExp|null} The compiled pattern.\n */\nfunction createPattern(pattern, invert = true) {\n\n    if (pattern.Regex !== undefined) {\n        // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \\# or \\& or \\~).\n        // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).\n        // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.\n        // For this reason, it is necessary to remove these backslashes before creating the regex.\n        // See https://stackoverflow.com/a/63007777/13989043 for more information\n        let regex = pattern.Regex.replace(/\\\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary\n\n        // We also handle special cases where the regex contains invalid (non-JS compatible) syntax.\n        for (const [key, value] of PROBLEMATIC_REGEX_MAP) {\n            regex = regex.replaceAll(key, value);\n        }\n\n        return new RegExp(regex, 'gu');\n\n    } else if (pattern.String !== undefined) {\n        const escaped = escapeRegExp(pattern.String);\n        // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()\n        return new RegExp(invert ? escaped : `(${escaped})`, 'gu');\n\n    } else {\n        console.warn('Unknown pattern type:', pattern)\n        return null;\n    }\n}\n\n/**\n * Helper function to convert an Object to a Map\n * @param {Object} obj The object to convert.\n * @returns {Map<string, any>} The map.\n */\nfunction objectToMap(obj) {\n    return new Map(Object.entries(obj));\n}\n\n/**\n * Helper function to convert a tensor to a list before decoding.\n * @param {Tensor} tensor The tensor to convert.\n * @returns {number[]} The tensor as a list.\n */\nfunction prepareTensorForDecode(tensor) {\n    const dims = tensor.dims;\n    switch (dims.length) {\n        case 1:\n            return tensor.tolist();\n        case 2:\n            if (dims[0] !== 1) {\n                throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');\n            }\n            return tensor.tolist()[0];\n        default:\n            throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)\n    }\n}\n\n/**\n * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms\n * @param {string} text The text to clean up.\n * @returns {string} The cleaned up text.\n */\nfunction clean_up_tokenization(text) {\n    // Clean up a list of simple English tokenization artifacts\n    // like spaces before punctuations and abbreviated forms\n    return text.replace(/ \\./g, '.')\n        .replace(/ \\?/g, '?')\n        .replace(/ \\!/g, '!')\n        .replace(/ ,/g, ',')\n        .replace(/ \\' /g, \"'\")\n        .replace(/ n\\'t/g, \"n't\")\n        .replace(/ \\'m/g, \"'m\")\n        .replace(/ \\'s/g, \"'s\")\n        .replace(/ \\'ve/g, \"'ve\")\n        .replace(/ \\'re/g, \"'re\");\n}\n\n/**\n * Helper function to remove accents from a string.\n * @param {string} text The text to remove accents from.\n * @returns {string} The text with accents removed.\n */\nfunction remove_accents(text) {\n    return text.replace(/\\p{M}/gu, '');\n}\n\n/**\n * Helper function to lowercase a string and remove accents.\n * @param {string} text The text to lowercase and remove accents from.\n * @returns {string} The lowercased text with accents removed.\n */\nfunction lowercase_and_remove_accent(text) {\n    return remove_accents(text.toLowerCase());\n}\n\n\n/**\n * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.\n *\n * A \"chinese character\" is defined as anything in the CJK Unicode block:\n * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n *\n * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.\n * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.\n * Those alphabets are used to write space-separated words, so they are not treated specially\n * and are handled like all other languages.\n *\n * @param {number|bigint} cp The Unicode codepoint to check.\n * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.\n */\nexport function is_chinese_char(cp) {\n    return (\n        (cp >= 0x4E00 && cp <= 0x9FFF)\n        || (cp >= 0x3400 && cp <= 0x4DBF)\n        || (cp >= 0x20000 && cp <= 0x2A6DF)\n        || (cp >= 0x2A700 && cp <= 0x2B73F)\n        || (cp >= 0x2B740 && cp <= 0x2B81F)\n        || (cp >= 0x2B820 && cp <= 0x2CEAF)\n        || (cp >= 0xF900 && cp <= 0xFAFF)\n        || (cp >= 0x2F800 && cp <= 0x2FA1F)\n    )\n}\n\n/**\n * Helper function to fuse consecutive unknown tokens.\n * @param {string[]} arr The list of input tokens\n * @param {Map<string, any>} tokens_to_ids The mapping from tokens to token ids.\n * @param {number} unk_token_id The value to fuse on.\n * @private\n */\nfunction fuse_unk(arr, tokens_to_ids, unk_token_id) {\n    const fused = [];\n    let i = 0;\n    while (i < arr.length) {\n        fused.push(arr[i])\n        if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) {\n            ++i;\n            continue;\n        }\n\n        while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) {\n            if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) {\n                fused[fused.length - 1] += arr[i];\n            }\n        }\n    }\n\n    return fused;\n}\n\n/**\n * Split a string on whitespace.\n * @param {string} text The text to split.\n * @returns {string[]} The split string.\n */\nfunction whitespace_split(text) {\n    return text.match(/\\S+/g) || [];\n}\n\nconst PUNCTUATION_REGEX = '\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E';\nconst PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, 'gu');\nconst BLOOM_SPLIT_CHARS = '.,!?\\u2026\\u3002\\uff0c\\u3001\\u0964\\u06d4\\u060c';\n\n// A mapping of regex patterns to their equivalent (but possibly longer) JS-compatible versions.\nconst PROBLEMATIC_REGEX_MAP = new Map([\n    // These use the case insensitive group modifier, which is not supported in JavaScript.\n    // When parsing the regex, an \"Invalid group\" error is thrown.\n    [\"(?i:'s|'t|'re|'ve|'m|'ll|'d)\", \"(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))\"],\n    [\"(?i:[sdmt]|ll|ve|re)\", \"(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])\"],\n\n    // JS doesn't support possessive quantifiers (these are used in recent OpenAI tokenizers).\n    [\"[^\\\\r\\\\n\\\\p{L}\\\\p{N}]?+\", \"[^\\\\r\\\\n\\\\p{L}\\\\p{N}]?\"],\n    [\"[^\\\\s\\\\p{L}\\\\p{N}]++\", \"[^\\\\s\\\\p{L}\\\\p{N}]+\"],\n\n    // Used to override the default (invalid) regex of the bloom pretokenizer.\n    // For more information, see https://github.com/huggingface/transformers.js/issues/94\n    [` ?[^(\\\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\\\s${BLOOM_SPLIT_CHARS}]+`],\n])\n\n\n/**\n * Represent a token added by the user on top of the existing Model vocabulary.\n * AddedToken can be configured to specify the behavior they should have in various situations like:\n *   - Whether they should only match single words\n *   - Whether to include any whitespace on its left or right\n */\nclass AddedToken {\n    /**\n     * Creates a new instance of AddedToken.\n     * @param {Object} config Added token configuration object.\n     * @param {string} config.content The content of the added token.\n     * @param {number} config.id The id of the added token.\n     * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.\n     * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.\n     * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.\n     * @param {boolean} [config.normalized=false] Whether this token should be normalized.\n     * @param {boolean} [config.special=false] Whether this token is special.\n     */\n    constructor(config) {\n        this.content = config.content;\n        this.id = config.id;\n        this.single_word = config.single_word ?? false;\n        this.lstrip = config.lstrip ?? false;\n        this.rstrip = config.rstrip ?? false;\n        this.special = config.special ?? false;\n        this.normalized = config.normalized ?? null;\n    }\n}\n\n/**\n * Abstract base class for tokenizer models.\n *\n * @extends Callable\n */\nexport class TokenizerModel extends Callable {\n    /**\n     * Creates a new instance of TokenizerModel.\n     * @param {Object} config The configuration object for the TokenizerModel.\n     */\n    constructor(config) {\n        super();\n        this.config = config;\n\n        /** @type {string[]} */\n        this.vocab = [];\n\n        /**\n         * A mapping of tokens to ids.\n         * @type {Map<string, number>}\n         */\n        this.tokens_to_ids = new Map();\n\n        this.unk_token_id = undefined;\n        this.unk_token = undefined;\n        this.end_of_word_suffix = undefined;\n\n        /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */\n        this.fuse_unk = this.config.fuse_unk ?? false;\n    }\n\n    /**\n     * Instantiates a new TokenizerModel instance based on the configuration object provided.\n     * @param {Object} config The configuration object for the TokenizerModel.\n     * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.\n     * @returns {TokenizerModel} A new instance of a TokenizerModel.\n     * @throws Will throw an error if the TokenizerModel type in the config is not recognized.\n     */\n    static fromConfig(config, ...args) {\n        switch (config.type) {\n            case 'WordPiece':\n                return new WordPieceTokenizer(config);\n            case 'Unigram':\n                // @ts-ignore\n                return new Unigram(config, ...args);\n            case 'BPE':\n                return new BPE(config);\n\n            default:\n                // Some older tokenizers, like `google-t5/t5-small`, `openai-community/gpt2`, and `distilbert/distilbert-base-uncased`, do not have a `type` field.\n                // In this case, we can infer the tokenizer type based on the structure of the `vocab` field and other properties.\n                if (config.vocab) {\n                    if (Array.isArray(config.vocab)) {\n                        // config.vocab is of type `[string, number][]`\n                        // @ts-ignore\n                        return new Unigram(config, ...args);\n                    } else if (Object.hasOwn(config, 'continuing_subword_prefix') && Object.hasOwn(config, 'unk_token')) {\n                        if (Object.hasOwn(config, 'merges')) {\n                            return new BPE(config);\n                        } else {\n                            return new WordPieceTokenizer(config);\n                        }\n                    } else {\n                        // @ts-ignore\n                        return new LegacyTokenizerModel(config, ...args);\n                    }\n                }\n                throw new Error(`Unknown TokenizerModel type: ${config.type}`);\n        }\n    }\n\n    /**\n     * Internal function to call the TokenizerModel instance.\n     * @param {string[]} tokens The tokens to encode.\n     * @returns {string[]} The encoded tokens.\n     */\n    _call(tokens) {\n        tokens = this.encode(tokens);\n        if (this.fuse_unk) {\n            // Fuse unknown tokens\n            tokens = fuse_unk(tokens, this.tokens_to_ids, this.unk_token_id);\n        }\n        return tokens;\n    }\n\n    /**\n     * Encodes a list of tokens into a list of token IDs.\n     * @param {string[]} tokens The tokens to encode.\n     * @returns {string[]} The encoded tokens.\n     * @throws Will throw an error if not implemented in a subclass.\n     */\n    encode(tokens) {\n        throw Error(\"encode should be implemented in subclass.\")\n    }\n\n    /**\n     * Converts a list of tokens into a list of token IDs.\n     * @param {string[]} tokens The tokens to convert.\n     * @returns {number[]} The converted token IDs.\n     */\n    convert_tokens_to_ids(tokens) {\n        return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);\n    }\n\n    /**\n     * Converts a list of token IDs into a list of tokens.\n     * @param {number[]|bigint[]} ids The token IDs to convert.\n     * @returns {string[]} The converted tokens.\n     */\n    convert_ids_to_tokens(ids) {\n        return ids.map(i => this.vocab[i] ?? this.unk_token);\n    }\n}\n\n/**\n * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.\n * @extends TokenizerModel\n */\nclass WordPieceTokenizer extends TokenizerModel {\n    /**\n     * @param {Object} config The configuration object.\n     * @param {Object} config.vocab A mapping of tokens to ids.\n     * @param {string} config.unk_token The unknown token string.\n     * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.\n     * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.\n     */\n    constructor(config) {\n        super(config);\n        /**\n         * A mapping of tokens to ids.\n         * @type {Map<string, number>}\n         */\n        this.tokens_to_ids = objectToMap(config.vocab);\n\n        /**\n         * The id of the unknown token.\n         * @type {number}\n         */\n        this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n\n        /**\n         * The unknown token string.\n         * @type {string}\n         */\n        this.unk_token = config.unk_token;\n\n        /**\n         * The maximum number of characters allowed per word.\n         * @type {number}\n         */\n        this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;\n\n        /**\n         * An array of tokens.\n         * @type {string[]}\n         */\n        this.vocab = new Array(this.tokens_to_ids.size);\n        for (const [key, value] of this.tokens_to_ids) {\n            this.vocab[value] = key;\n        }\n    }\n\n    /**\n     * Encodes an array of tokens using WordPiece encoding.\n     * @param {string[]} tokens The tokens to encode.\n     * @returns {string[]} An array of encoded tokens.\n     */\n    encode(tokens) {\n        const outputTokens = [];\n        for (const token of tokens) {\n            const chars = [...token];\n            if (chars.length > this.max_input_chars_per_word) {\n                outputTokens.push(this.unk_token);\n                continue;\n            }\n\n            let isUnknown = false;\n            let start = 0;\n            const subTokens = [];\n\n            while (start < chars.length) {\n                let end = chars.length;\n                let currentSubstring = null;\n                while (start < end) {\n                    let substr = chars.slice(start, end).join('');\n\n                    if (start > 0) {\n                        substr = this.config.continuing_subword_prefix + substr;\n                    }\n                    if (this.tokens_to_ids.has(substr)) {\n                        currentSubstring = substr;\n                        break;\n                    }\n\n                    --end;\n                }\n                if (currentSubstring === null) {\n                    isUnknown = true;\n                    break;\n                }\n                subTokens.push(currentSubstring);\n                start = end;\n            }\n            if (isUnknown) {\n                outputTokens.push(this.unk_token);\n            } else {\n                outputTokens.push(...subTokens);\n            }\n        }\n\n        return outputTokens;\n    }\n\n}\n\n/**\n * Class representing a Unigram tokenizer model.\n * @extends TokenizerModel\n */\nclass Unigram extends TokenizerModel {\n    /**\n     * Create a new Unigram tokenizer model.\n     * @param {Object} config The configuration object for the Unigram model.\n     * @param {number} config.unk_id The ID of the unknown token\n     * @param {[string, number][]} config.vocab A 2D array representing a mapping of tokens to scores.\n     * @param {Object} moreConfig Additional configuration object for the Unigram model.\n     */\n    constructor(config, moreConfig) {\n        super(config);\n\n        const vocabSize = config.vocab.length;\n        this.vocab = new Array(vocabSize);\n        /** @type {number[]} */\n        this.scores = new Array(vocabSize);\n        for (let i = 0; i < vocabSize; ++i) {\n            [this.vocab[i], this.scores[i]] = config.vocab[i];\n        }\n\n        this.unk_token_id = config.unk_id;\n        this.unk_token = this.vocab[config.unk_id];\n\n        this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));\n        this.bos_token = ' '; // beginning of a sentence token\n\n        this.bos_token_id = this.tokens_to_ids.get(this.bos_token); // NOTE: may be undefined\n        this.eos_token = moreConfig.eos_token;\n\n        this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n        this.unk_token = this.vocab[this.unk_token_id];\n\n        this.minScore = min(this.scores)[0];\n\n        this.unk_score = this.minScore - 10.0;\n        this.scores[this.unk_token_id] = this.unk_score;\n\n        this.trie = new CharTrie();\n        this.trie.extend(this.vocab);\n\n        // NOTE: `fuse_unk` is hardcoded to true for Unigram models\n        // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119\n        this.fuse_unk = true;\n    }\n\n    /**\n     * Populates lattice nodes.\n     * @param {TokenLattice} lattice The token lattice to populate with nodes.\n     */\n    populateNodes(lattice) {\n        const chars = lattice.chars;\n        const mblen = 1;\n        let beginPos = 0;\n        while (beginPos < chars.length) {\n            let hasSingleNode = false;\n\n            const tokens = [];\n            const sliced = chars.slice(beginPos).join('');\n            const prefixedTokens = this.trie.commonPrefixSearch(sliced);\n            for (const token of prefixedTokens) {\n                tokens.push(token);\n                const tokenId = this.tokens_to_ids.get(token);\n                const tokenScore = this.scores[tokenId];\n                const n = len(token);\n                lattice.insert(beginPos, n, tokenScore, tokenId);\n                if (!hasSingleNode && n === mblen) {\n                    hasSingleNode = true;\n                }\n            }\n            if (!hasSingleNode) {\n                lattice.insert(beginPos, mblen, this.unk_score, this.unk_token_id);\n            }\n            beginPos += mblen;\n        }\n    }\n\n    /**\n     * Encodes an array of tokens into an array of subtokens using the unigram model.\n     *\n     * @param {string} normalized The normalized string.\n     * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.\n     */\n    tokenize(normalized) {\n        const lattice = new TokenLattice(normalized, this.bos_token_id, this.eos_token_id);\n        this.populateNodes(lattice);\n        return lattice.tokens();\n    }\n\n    /**\n     * Encodes an array of tokens using Unigram encoding.\n     * @param {string[]} tokens The tokens to encode.\n     * @returns {string[]} An array of encoded tokens.\n     */\n    encode(tokens) {\n        const toReturn = [];\n        for (const token of tokens) {\n            const tokenized = this.tokenize(token);\n            toReturn.push(...tokenized);\n        }\n        return toReturn;\n    }\n\n}\n\n/**\n * Returns list of utf-8 byte and a mapping to unicode strings.\n * Specifically avoids mapping to whitespace/control characters the BPE code barfs on.\n * @returns {Object} Object with utf-8 byte keys and unicode string values.\n */\nconst BYTES_TO_UNICODE = (() => {\n    // Returns list of utf-8 byte and a mapping to unicode strings.\n    // We specifically avoids mapping to whitespace/control characters\n    // the bpe code barfs on.\n\n    const bs = [\n        ...Array.from({ length: \"~\".charCodeAt(0) - \"!\".charCodeAt(0) + 1 }, (_, i) => i + \"!\".charCodeAt(0)),\n        ...Array.from({ length: \"\u00AC\".charCodeAt(0) - \"\u00A1\".charCodeAt(0) + 1 }, (_, i) => i + \"\u00A1\".charCodeAt(0)),\n        ...Array.from({ length: \"\u00FF\".charCodeAt(0) - \"\u00AE\".charCodeAt(0) + 1 }, (_, i) => i + \"\u00AE\".charCodeAt(0)),\n    ];\n    const cs = bs.slice();\n    let n = 0;\n    for (let b = 0; b < 256; ++b) {\n        if (!bs.includes(b)) {\n            bs.push(b);\n            cs.push(256 + n);\n            n += 1;\n        }\n    }\n    const ccs = cs.map(n => String.fromCharCode(n));\n    return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));\n})();\n\nconst UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);\n\n\n/**\n * @typedef {Object} BPENode\n * @property {string} token The token associated with the node\n * @property {number} bias A positional bias for the node.\n * @property {number} [score] The score of the node.\n * @property {BPENode} [prev] The previous node in the linked list.\n * @property {BPENode} [next] The next node in the linked list.\n */\n\n/**\n * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens.\n * @extends TokenizerModel\n */\nclass BPE extends TokenizerModel {\n    /**\n     * Create a BPE instance.\n     * @param {Object} config The configuration object for BPE.\n     * @param {Object} config.vocab A mapping of tokens to ids.\n     * @param {string[]|[string, string][]} config.merges An array of BPE merges as strings.\n     * @param {string} config.unk_token The unknown token used for out of vocabulary words.\n     * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.\n     * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.\n     * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)\n     * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.\n     */\n    constructor(config) {\n        super(config);\n\n        /** @type {Map<string, number>} */\n        this.tokens_to_ids = objectToMap(config.vocab);\n\n        this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n        this.unk_token = config.unk_token;\n\n        this.vocab = new Array(this.tokens_to_ids.size);\n        for (const [key, value] of this.tokens_to_ids) {\n            this.vocab[value] = key;\n        }\n\n        // Tokenizers >= 0.20.0 serializes BPE merges as a [string, string][] instead of a string[],\n        // which resolves the ambiguity for merges containing spaces.\n        const use_new_merge_format = Array.isArray(config.merges[0]);\n\n        /** @type {[string, string][]} */\n        this.merges = use_new_merge_format\n            ? /** @type {[string, string][]} */(config.merges)\n            : (/** @type {string[]} */(config.merges)).map(x => /** @type {[string, string]} */(x.split(' ', 2)));\n        this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i]));\n\n        this.end_of_word_suffix = config.end_of_word_suffix;\n\n        // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)\n        this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;\n\n        this.byte_fallback = this.config.byte_fallback ?? false;\n\n        if (this.byte_fallback) {\n            this.text_encoder = new TextEncoder();\n        }\n\n        this.ignore_merges = this.config.ignore_merges ?? false;\n\n        /**\n         * The maximum length we should cache in a model.\n         * Strings that are too long have minimal chances to cache hit anyway\n         */\n        this.max_length_to_cache = 256;\n\n        /**\n         * The default capacity for a `BPE`'s internal cache.\n         */\n        this.cache_capacity = 10000;\n        this.cache = new LRUCache(this.cache_capacity);\n    }\n\n    /**\n     * Clears the cache.\n     */\n    clear_cache() {\n        this.cache.clear();\n    }\n\n    /**\n     * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority\n     * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.\n     * @param {string} token The token to encode.\n     * @returns {string[]} The BPE encoded tokens.\n     */\n    bpe(token) {\n        if (token.length === 0) {\n            return [];\n        }\n\n        const cached = this.cache.get(token);\n        if (cached !== undefined) {\n            return cached;\n        }\n\n        const word = Array.from(token);\n        if (this.end_of_word_suffix) {\n            word[word.length - 1] += this.end_of_word_suffix;\n        }\n\n        let result = [];\n        if (word.length > 1) {\n            // Create a priority queue to store the nodes that will be merged.\n            // The comparator function compares the scores of the nodes.\n            const queue = new PriorityQueue((a, b) => a.score < b.score);\n\n            // Construct a doubly-linked list of nodes that will be inserted into the priority queue,\n            // starting with the individual characters. We also populate each node with a positional\n            // bias to break ties in the priority queue.\n            let startingNode = {\n                token: word[0],\n                bias: 0,\n                prev: null,\n                next: null,\n            }\n\n            let previousNode = startingNode\n            for (let i = 1; i < word.length; ++i) {\n                const currentNode = {\n                    bias: i / word.length, // Add fractional component to break ties\n                    token: word[i],\n                    prev: previousNode,\n                    next: null,\n                }\n                previousNode.next = currentNode\n                this._add_node(queue, previousNode)\n                previousNode = currentNode\n            }\n\n            while (!queue.isEmpty()) {\n                // Get the next node with the highest priority\n                const node = queue.pop();\n\n                // Check that this merge is still possible\n                if (node.deleted || !node.next || node.next.deleted) continue;\n\n                // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.\n                // This is because they will both be replaced by a new node representing the merge result.\n                node.deleted = true;\n                node.next.deleted = true;\n\n                // Next, we fix the node that comes before the current node (i.e., left side of the merge).\n                if (node.prev) {\n\n                    // Make a shallow copy of the previous node\n                    const newPreviousNode = { ...node.prev };\n\n                    // Mark the old previous node as deleted. This avoids erroneous merges later,\n                    // because there may still be references to this node in the priority queue.\n                    node.prev.deleted = true;\n                    node.prev = newPreviousNode;\n\n                    // Update the reference of the previous node, by pointing its previous node to this new previous node.\n                    if (newPreviousNode.prev) {\n                        newPreviousNode.prev.next = newPreviousNode;\n                    } else {\n                        // If the previous of the previous node does not exist, it means that\n                        // `newPreviousNode` must be the new `startingNode`.\n                        startingNode = newPreviousNode;\n                    }\n                }\n\n                // Create a new node which represents the result of the merge.\n                const merged = {\n                    token: node.token + node.next.token,\n                    bias: node.bias,\n                    prev: node.prev,\n                    next: node.next.next,\n                }\n\n                // We now consider where we can add the new merged node to the priority queue:\n                // 1. prev <-> merged\n                if (merged.prev) {\n                    merged.prev.next = merged;\n                    this._add_node(queue, merged.prev);\n                } else {\n                    // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.\n                    startingNode = merged;\n                }\n\n                // 2. merged <-> next\n                if (merged.next) {\n                    merged.next.prev = merged;\n                    this._add_node(queue, merged);\n                }\n            }\n\n            // Traverse the linked list, starting from the `startingNode`, and collect the tokens.\n            for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {\n                result.push(currentNode.token);\n            }\n        } else {\n            result = word;\n        }\n\n        // Possibly append suffix\n        if (this.continuing_subword_suffix) {\n            // Do not append suffix to the last token\n            for (let i = 0; i < result.length - 1; ++i) {\n                result[i] += this.continuing_subword_suffix;\n            }\n        }\n\n        if (token.length < this.max_length_to_cache) {\n            // Save the result to the cache\n            this.cache.put(token, result);\n        }\n\n        return result;\n    }\n\n\n    /**\n     * Helper function to add a node to the priority queue.\n     * @param {PriorityQueue} queue \n     * @param {BPENode} node\n     * @private\n     */\n    _add_node(queue, node) {\n        // `score` is a measure of the merge priority: lower means higher priority\n        // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)\n        // We also add a fractional component to the score to break ties (with the earlier character having higher priority)\n        const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token]));\n        if (rank !== undefined) {\n            node.score = rank + node.bias;\n            queue.push(node);\n        }\n    }\n\n    /**\n     * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.\n     * @param {string[]} tokens The input sequence of tokens to encode.\n     * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.\n     */\n    encode(tokens) {\n        const outputTokens = [];\n\n        for (const token of tokens) {\n            if (this.ignore_merges && this.tokens_to_ids.has(token)) {\n                outputTokens.push(token);\n                continue;\n            }\n            const bpe_token_list = this.bpe(token);\n\n            for (const t of bpe_token_list) {\n                if (this.tokens_to_ids.has(t)) {\n                    outputTokens.push(t);\n                } else if (this.byte_fallback) {\n                    const byteTokens = Array.from(this.text_encoder.encode(t))\n                        .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`);\n                    if (byteTokens.every(x => this.tokens_to_ids.has(x))) {\n                        // Ensure the byte tokens are actually in the vocabulary, otherwise\n                        // we fall back to the unknown token. For more information, see\n                        // https://github.com/huggingface/transformers/issues/28096.\n                        outputTokens.push(...byteTokens);\n                    } else {\n                        outputTokens.push(this.unk_token);\n                    }\n                } else {\n                    outputTokens.push(this.unk_token);\n                }\n            }\n        }\n\n        return outputTokens;\n    }\n\n}\n\n/**\n * Legacy tokenizer class for tokenizers with only a vocabulary.\n */\nclass LegacyTokenizerModel extends TokenizerModel {\n    /**\n     * Create a LegacyTokenizerModel instance.\n     * @param {Object} config The configuration object for LegacyTokenizerModel.\n     * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.\n     * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.\n     */\n    constructor(config, moreConfig) {\n        super(config);\n\n        /**@type {Map<string, number>} */\n        this.tokens_to_ids = objectToMap(\n            moreConfig.target_lang\n                ? config.vocab[moreConfig.target_lang]\n                : config.vocab\n        );\n\n        this.bos_token = moreConfig.bos_token;\n        this.bos_token_id = this.tokens_to_ids.get(this.bos_token);\n\n        this.eos_token = moreConfig.eos_token;\n        this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n\n        this.pad_token = moreConfig.pad_token;\n        this.pad_token_id = this.tokens_to_ids.get(this.pad_token);\n\n        this.unk_token = moreConfig.unk_token;\n        this.unk_token_id = this.tokens_to_ids.get(this.unk_token);\n\n        this.vocab = new Array(this.tokens_to_ids.size);\n        for (const [key, value] of this.tokens_to_ids) {\n            this.vocab[value] = key;\n        }\n    }\n\n    encode(tokens) {\n        return tokens;\n    }\n}\n\n\n/**\n * A base class for text normalization.\n * @abstract\n */\nclass Normalizer extends Callable {\n    /**\n     * @param {Object} config The configuration object for the normalizer.\n     */\n    constructor(config) {\n        super();\n        this.config = config;\n    }\n\n    /**\n     * Factory method for creating normalizers from config objects.\n     * @static\n     * @param {Object} config The configuration object for the normalizer.\n     * @returns {Normalizer} A Normalizer object.\n     * @throws {Error} If an unknown Normalizer type is specified in the config.\n     */\n    static fromConfig(config) {\n        if (config === null) return null;\n        switch (config.type) {\n            case 'BertNormalizer':\n                return new BertNormalizer(config);\n            case 'Precompiled':\n                return new Precompiled(config);\n            case 'Sequence':\n                return new NormalizerSequence(config);\n            case 'Replace':\n                return new Replace(config);\n            case 'NFC':\n                return new NFC(config);\n            case 'NFD':\n                return new NFD(config);\n            case 'NFKC':\n                return new NFKC(config);\n            case 'NFKD':\n                return new NFKD(config);\n            case 'Strip':\n                return new StripNormalizer(config);\n            case 'StripAccents':\n                return new StripAccents(config);\n            case 'Lowercase':\n                return new Lowercase(config);\n            case 'Prepend':\n                return new Prepend(config);\n            default:\n                throw new Error(`Unknown Normalizer type: ${config.type}`);\n        }\n    }\n\n    /**\n     * Normalize the input text.\n     * @abstract\n     * @param {string} text The text to normalize.\n     * @returns {string} The normalized text.\n     * @throws {Error} If this method is not implemented in a subclass.\n     */\n    normalize(text) {\n        throw Error(\"normalize should be implemented in subclass.\")\n    }\n\n    /**\n     * Alias for {@link Normalizer#normalize}.\n     * @param {string} text The text to normalize.\n     * @returns {string} The normalized text.\n     */\n    _call(text) {\n        return this.normalize(text);\n    }\n\n}\n\n/**\n * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression.\n * @extends Normalizer\n */\nclass Replace extends Normalizer {\n    /**\n     * Normalize the input text by replacing the pattern with the content.\n     * @param {string} text The input text to be normalized.\n     * @returns {string} The normalized text after replacing the pattern with the content.\n     */\n    normalize(text) {\n        const pattern = createPattern(this.config.pattern);\n        return pattern === null\n            ? text\n            : text.replaceAll(pattern, this.config.content);\n    }\n}\n\n/**\n * A normalizer that applies Unicode normalization to the input text.\n * @extends Normalizer\n * @abstract\n */\nclass UnicodeNormalizer extends Normalizer {\n    /**\n     * @type {string} The Unicode normalization form to apply.\n     * Should be one of: 'NFC', 'NFD', 'NFKC', or 'NFKD'.\n     */\n    form = undefined;\n\n    /**\n     * Normalize the input text by applying Unicode normalization.\n     * @param {string} text The input text to be normalized.\n     * @returns {string} The normalized text.\n     */\n    normalize(text) {\n        text = text.normalize(this.form)\n        return text;\n    }\n}\n\n/**\n * A normalizer that applies Unicode normalization form C (NFC) to the input text.\n * Canonical Decomposition, followed by Canonical Composition.\n * @extends UnicodeNormalizer\n */\nclass NFC extends UnicodeNormalizer {\n    form = 'NFC';\n}\n\n/**\n * A normalizer that applies Unicode normalization form D (NFD) to the input text.\n * Canonical Decomposition.\n * @extends UnicodeNormalizer\n */\nclass NFD extends UnicodeNormalizer {\n    form = 'NFD';\n}\n\n/**\n * A normalizer that applies Unicode normalization form KC (NFKC) to the input text.\n * Compatibility Decomposition, followed by Canonical Composition.\n * @extends UnicodeNormalizer\n */\nclass NFKC extends UnicodeNormalizer {\n    form = 'NFKC';\n}\n\n/**\n * A normalizer that applies Unicode normalization form KD (NFKD) to the input text.\n * Compatibility Decomposition.\n * @extends UnicodeNormalizer\n */\nclass NFKD extends UnicodeNormalizer {\n    form = 'NFKD';\n}\n\n/**\n * A normalizer that strips leading and/or trailing whitespace from the input text.\n */\nclass StripNormalizer extends Normalizer {\n    /**\n     * Strip leading and/or trailing whitespace from the input text.\n     * @param {string} text The input text.\n     * @returns {string} The normalized text.\n     */\n    normalize(text) {\n        if (this.config.strip_left && this.config.strip_right) {\n            // Fast path to avoid an extra trim call\n            text = text.trim();\n        } else {\n            if (this.config.strip_left) {\n                text = text.trimStart();\n            }\n            if (this.config.strip_right) {\n                text = text.trimEnd();\n            }\n        }\n        return text;\n    }\n}\n\n/**\n * StripAccents normalizer removes all accents from the text.\n * @extends Normalizer\n */\nclass StripAccents extends Normalizer {\n    /**\n     * Remove all accents from the text.\n     * @param {string} text The input text.\n     * @returns {string} The normalized text without accents.\n     */\n    normalize(text) {\n        text = remove_accents(text);\n        return text;\n    }\n}\n\n/**\n * A Normalizer that lowercases the input string.\n * @extends Normalizer\n */\nclass Lowercase extends Normalizer {\n    /**\n     * Lowercases the input string.\n     * @param {string} text The text to normalize.\n     * @returns {string} The normalized text.\n     */\n    normalize(text) {\n        text = text.toLowerCase();\n        return text;\n    }\n}\n\n/**\n * A Normalizer that prepends a string to the input string.\n * @extends Normalizer\n */\nclass Prepend extends Normalizer {\n    /**\n     * Prepends the input string.\n     * @param {string} text The text to normalize.\n     * @returns {string} The normalized text.\n     */\n    normalize(text) {\n        text = this.config.prepend + text;\n        return text;\n    }\n}\n\n/**\n * A Normalizer that applies a sequence of Normalizers.\n * @extends Normalizer\n */\nclass NormalizerSequence extends Normalizer {\n    /**\n   * Create a new instance of NormalizerSequence.\n   * @param {Object} config The configuration object.\n   * @param {Object[]} config.normalizers An array of Normalizer configuration objects.\n   */\n    constructor(config) {\n        super(config);\n        this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));\n    }\n    /**\n    * Apply a sequence of Normalizers to the input text.\n    * @param {string} text The text to normalize.\n    * @returns {string} The normalized text.\n    */\n    normalize(text) {\n        return this.normalizers.reduce((t, normalizer) => {\n            return normalizer.normalize(t);\n        }, text);\n    }\n}\n\n/**\n * A class representing a normalizer used in BERT tokenization.\n * @extends Normalizer\n */\nclass BertNormalizer extends Normalizer {\n    /**\n     * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.\n     *\n     * @param {string} text The input text to tokenize.\n     * @returns {string} The tokenized text with whitespace added around CJK characters.\n     */\n    _tokenize_chinese_chars(text) {\n        /* Adds whitespace around any CJK character. */\n        const output = [];\n        for (let i = 0; i < text.length; ++i) {\n            const char = text[i];\n            const cp = char.charCodeAt(0);\n            if (is_chinese_char(cp)) {\n                output.push(\" \");\n                output.push(char);\n                output.push(\" \");\n            } else {\n                output.push(char);\n            }\n        }\n        return output.join(\"\");\n    }\n\n    /**\n     * Strips accents from the given text.\n     * @param {string} text The text to strip accents from.\n     * @returns {string} The text with accents removed.\n     */\n    stripAccents(text) {\n        // \"Mark, Nonspacing\" (Mn)\n        return text.normalize('NFD').replace(/\\p{Mn}/gu, '');\n    }\n\n\n    /**\n     * Checks whether `char` is a control character.\n     * @param {string} char The character to check.\n     * @returns {boolean} Whether `char` is a control character.\n     * @private\n     */\n    _is_control(char) {\n        switch (char) {\n            case '\\t':\n            case '\\n':\n            case '\\r':\n                // These are technically control characters but we count them as whitespace characters.\n                return false;\n\n            default:\n                // Check if unicode category starts with C:\n                // Cc - Control\n                // Cf - Format\n                // Co - Private Use\n                // Cs - Surrogate\n                return /^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$/u.test(char);\n        }\n    }\n\n    /**\n     * Performs invalid character removal and whitespace cleanup on text.\n     * @param {string} text The text to clean.\n     * @returns {string} The cleaned text.\n     * @private\n     */\n    _clean_text(text) {\n        const output = [];\n        for (const char of text) {\n            const cp = char.charCodeAt(0);\n            if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {\n                continue;\n            }\n            if (/^\\s$/.test(char)) { // is whitespace\n                output.push(\" \");\n            } else {\n                output.push(char);\n            }\n        }\n        return output.join(\"\");\n    }\n    /**\n     * Normalizes the given text based on the configuration.\n     * @param {string} text The text to normalize.\n     * @returns {string} The normalized text.\n     */\n    normalize(text) {\n        if (this.config.clean_text) {\n            text = this._clean_text(text);\n        }\n\n        if (this.config.handle_chinese_chars) {\n            text = this._tokenize_chinese_chars(text);\n        }\n\n        if (this.config.lowercase) {\n            text = text.toLowerCase();\n\n            if (this.config.strip_accents !== false) {\n                text = this.stripAccents(text);\n            }\n        } else if (this.config.strip_accents) {\n            text = this.stripAccents(text);\n        }\n\n        return text;\n    }\n}\n\n/**\n * A callable class representing a pre-tokenizer used in tokenization. Subclasses\n * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic.\n * @extends Callable\n */\nclass PreTokenizer extends Callable {\n    /**\n   * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.\n   *\n   * @static\n   * @param {Object} config A configuration object for the pre-tokenizer.\n   * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.\n   * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.\n   */\n    static fromConfig(config) {\n        if (config === null) return null;\n\n        switch (config.type) {\n            case 'BertPreTokenizer':\n                return new BertPreTokenizer(config);\n            case 'Sequence':\n                return new PreTokenizerSequence(config);\n            case 'Whitespace':\n                return new WhitespacePreTokenizer(config);\n            case 'WhitespaceSplit':\n                return new WhitespaceSplit(config);\n            case 'Metaspace':\n                return new MetaspacePreTokenizer(config);\n\n            case 'ByteLevel':\n                return new ByteLevelPreTokenizer(config);\n            case 'Split':\n                return new SplitPreTokenizer(config);\n            case 'Punctuation':\n                return new PunctuationPreTokenizer(config);\n            case 'Digits':\n                return new DigitsPreTokenizer(config);\n            case 'Replace':\n                return new ReplacePreTokenizer(config);\n            case 'FixedLength':\n                return new FixedLengthPreTokenizer(config);\n            default:\n                throw new Error(`Unknown PreTokenizer type: ${config.type}`);\n        }\n    }\n\n    /**\n     * Method that should be implemented by subclasses to define the specific pre-tokenization logic.\n     *\n     * @abstract\n     * @param {string} text The text to pre-tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} The pre-tokenized text.\n     * @throws {Error} If the method is not implemented in the subclass.\n     */\n    pre_tokenize_text(text, options) {\n        throw Error(\"pre_tokenize_text should be implemented in subclass.\")\n    }\n\n    /**\n     * Tokenizes the given text into pre-tokens.\n     * @param {string|string[]} text The text or array of texts to pre-tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of pre-tokens.\n     */\n    pre_tokenize(text, options) {\n        return (Array.isArray(text)\n            ? text.map(x => this.pre_tokenize_text(x, options))\n            : this.pre_tokenize_text(text, options)\n        ).flat();\n    }\n\n    /**\n     * Alias for {@link PreTokenizer#pre_tokenize}.\n     * @param {string|string[]} text The text or array of texts to pre-tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of pre-tokens.\n     */\n    _call(text, options) {\n        return this.pre_tokenize(text, options);\n    }\n}\n\n/**\n * @extends PreTokenizer\n */\nclass BertPreTokenizer extends PreTokenizer {\n    /**\n     * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme\n     * similar to that used in the original implementation of BERT.\n     * \n     * @param {Object} config The configuration object.\n     */\n    constructor(config) {\n        super();\n        // Construct a pattern which matches the rust implementation:\n        // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11\n        // Equivalent to removing whitespace and splitting on punctuation (both \\p{P} and other ascii characters)\n        this.pattern = new RegExp(`[^\\\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');\n    }\n    /**\n     * Tokenizes a single text using the BERT pre-tokenization scheme.\n     * \n     * @param {string} text The text to tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens.\n     */\n    pre_tokenize_text(text, options) {\n        return text.trim().match(this.pattern) || [];\n    }\n}\n\n/**\n * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords.\n * @extends PreTokenizer\n */\nclass ByteLevelPreTokenizer extends PreTokenizer {\n    /**\n     * Creates a new instance of the `ByteLevelPreTokenizer` class.\n     * @param {Object} config The configuration object.\n     */\n    constructor(config) {\n        super();\n        this.config = config;\n\n        /**\n         * @type {boolean} Whether to add a leading space to the first word.\n         * This allows to treat the leading word just as any other word.\n         */\n        this.add_prefix_space = this.config.add_prefix_space;\n\n        /**\n         * @type {boolean} Whether the post processing step should trim offsets\n         * to avoid including whitespaces.\n         * @todo Use this in the pretokenization step.\n         */\n        this.trim_offsets = this.config.trim_offsets;\n\n        /**\n         * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.\n         * Set it to False if you want to use your own splitting. Defaults to true.\n         */\n        this.use_regex = this.config.use_regex ?? true;\n        this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+/gu;\n\n        this.byte_encoder = BYTES_TO_UNICODE;\n        this.text_encoder = new TextEncoder();\n    }\n\n    /**\n     * Tokenizes a single piece of text using byte-level tokenization.\n     * @param {string} text The text to tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens.\n     */\n    pre_tokenize_text(text, options) {\n        // Add a leading space if the option is enabled\n        if (this.add_prefix_space && !text.startsWith(' ')) {\n            text = ' ' + text;\n        }\n\n        // Split on whitespace and punctuation\n        const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];\n\n        // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)\n        return tokens.map(\n            token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')\n        );\n    }\n}\n\n/**\n * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior\n */\n\n/**\n * Splits text using a given pattern.\n * @extends PreTokenizer\n */\nclass SplitPreTokenizer extends PreTokenizer {\n    /**\n     * @param {Object} config The configuration options for the pre-tokenizer.\n     * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n     * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.\n     * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.\n     * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n     * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.\n     */\n    constructor(config) {\n        super();\n        this.config = config;\n        // TODO support all behaviours (config.behavior)\n\n        this.pattern = createPattern(this.config.pattern, this.config.invert);\n    }\n\n    /**\n     * Tokenizes text by splitting it using the given pattern.\n     * @param {string} text The text to tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens.\n     */\n    pre_tokenize_text(text, options) {\n        if (this.pattern === null) {\n            return [];\n        }\n\n        if (this.config.invert) {\n            return text.match(this.pattern) || [];\n        } else if (this.config.behavior?.toLowerCase() === 'removed') {\n            return text.split(this.pattern).filter(x => x);\n        } else {\n            return regexSplit(text, this.pattern);\n        }\n    }\n}\n\n/**\n * Splits text based on punctuation.\n * @extends PreTokenizer\n */\nclass PunctuationPreTokenizer extends PreTokenizer {\n    /**\n     * @param {Object} config The configuration options for the pre-tokenizer.\n     * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n     */\n    constructor(config) {\n        super();\n        this.config = config;\n        this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');\n    }\n\n    /**\n     * Tokenizes text by splitting it using the given pattern.\n     * @param {string} text The text to tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens.\n     */\n    pre_tokenize_text(text, options) {\n        return text.match(this.pattern) || [];\n    }\n}\n\n\n/**\n * Splits text based on digits.\n * @extends PreTokenizer\n */\nclass DigitsPreTokenizer extends PreTokenizer {\n    /**\n     * @param {Object} config The configuration options for the pre-tokenizer.\n     * @param {boolean} config.individual_digits Whether to split on individual digits.\n     */\n    constructor(config) {\n        super();\n        this.config = config;\n\n        // Construct a pattern which matches the rust implementation:\n        const digit_pattern = `[^\\\\d]+|\\\\d${this.config.individual_digits ? '' : '+'}`;\n        this.pattern = new RegExp(digit_pattern, 'gu');\n    }\n\n    /**\n     * Tokenizes text by splitting it using the given pattern.\n     * @param {string} text The text to tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens.\n     */\n    pre_tokenize_text(text, options) {\n        return text.match(this.pattern) || [];\n    }\n}\n\n/**\n * @typedef {Object} PostProcessedOutput\n * @property {string[]} tokens List of token produced by the post-processor.\n * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.\n */\n\n\n/**\n * @typedef {Object} EncodingSingle\n * @property {number[]} input_ids List of token ids to be fed to a model.\n * @property {number[]} attention_mask List of token type ids to be fed to a model\n * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model\n */\n\n\n/**\n * @extends Callable\n */\nclass PostProcessor extends Callable {\n\n    /**\n     * @param {Object} config The configuration for the post-processor.\n     */\n    constructor(config) {\n        super();\n        this.config = config;\n    }\n\n    /**\n     * Factory method to create a PostProcessor object from a configuration object.\n     *\n     * @param {Object} config Configuration object representing a PostProcessor.\n     * @returns {PostProcessor} A PostProcessor object created from the given configuration.\n     * @throws {Error} If an unknown PostProcessor type is encountered.\n     */\n    static fromConfig(config) {\n        if (config === null) return null;\n        switch (config.type) {\n            case 'TemplateProcessing':\n                return new TemplateProcessing(config);\n\n            case 'ByteLevel':\n                return new ByteLevelPostProcessor(config);\n\n            case 'RobertaProcessing':\n                return new RobertaProcessing(config);\n            case 'BertProcessing':\n                return new BertProcessing(config);\n\n            case 'Sequence':\n                return new PostProcessorSequence(config);\n            default:\n                throw new Error(`Unknown PostProcessor type: ${config.type}`);\n        }\n    }\n\n    /**\n     * Method to be implemented in subclass to apply post-processing on the given tokens.\n     *\n     * @param {Array} tokens The input tokens to be post-processed.\n     * @param {...*} args Additional arguments required by the post-processing logic.\n     * @returns {PostProcessedOutput} The post-processed tokens.\n     * @throws {Error} If the method is not implemented in subclass.\n     */\n    post_process(tokens, ...args) {\n        throw Error(\"post_process should be implemented in subclass.\")\n    }\n\n    /**\n     * Alias for {@link PostProcessor#post_process}.\n     * @param {Array} tokens The text or array of texts to post-process.\n     * @param {...*} args Additional arguments required by the post-processing logic.\n     * @returns {PostProcessedOutput} The post-processed tokens.\n     */\n    _call(tokens, ...args) {\n        return this.post_process(tokens, ...args);\n    }\n}\n\n/**\n * A post-processor that adds special tokens to the beginning and end of the input.\n */\nclass BertProcessing extends PostProcessor {\n    /**\n     * @param {Object} config The configuration for the post-processor.\n     * @param {string[]} config.cls The special tokens to add to the beginning of the input.\n     * @param {string[]} config.sep The special tokens to add to the end of the input.\n     */\n    constructor(config) {\n        super(config);\n        // TODO use all of config: add_prefix_space, trim_offsets\n\n        this.cls = config.cls[0];\n        this.sep = config.sep[0];\n    }\n\n    /**\n     * Adds the special tokens to the beginning and end of the input.\n     * @param {string[]} tokens The input tokens.\n     * @param {string[]} [tokens_pair=null] An optional second set of input tokens.\n     * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.\n     */\n    post_process(tokens, tokens_pair = null, {\n        add_special_tokens = true,\n    } = {}) {\n        if (add_special_tokens) {\n            tokens = mergeArrays([this.cls], tokens, [this.sep]);\n        }\n\n        let token_type_ids = new Array(tokens.length).fill(0);\n        if (tokens_pair !== null) {\n            // NOTE: It is intended to add 2 EOS tokens after the first set of tokens\n            // https://github.com/huggingface/tokenizers/issues/983\n            const middle = (add_special_tokens && this instanceof RobertaProcessing)\n                ? [this.sep]\n                : [];\n            const after = add_special_tokens ? [this.sep] : [];\n\n            tokens = mergeArrays(tokens, middle, tokens_pair, after);\n            token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));\n        }\n        return { tokens, token_type_ids };\n    }\n}\nclass RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing\n\n/**\n * Post processor that replaces special tokens in a template with actual tokens.\n * @extends PostProcessor\n */\nclass TemplateProcessing extends PostProcessor {\n    /**\n     * Creates a new instance of `TemplateProcessing`.\n     * @param {Object} config The configuration options for the post processor.\n     * @param {Array} config.single The template for a single sequence of tokens.\n     * @param {Array} config.pair The template for a pair of sequences of tokens.\n     */\n    constructor(config) {\n        super(config);\n\n        this.single = config.single;\n        this.pair = config.pair;\n    }\n\n    /**\n     * Replaces special tokens in the template with actual tokens.\n     * @param {string[]} tokens The list of tokens for the first sequence.\n     * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n     * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.\n     */\n    post_process(tokens, tokens_pair = null, {\n        add_special_tokens = true,\n    } = {}) {\n        const type = tokens_pair === null ? this.single : this.pair\n\n        let processedTokens = [];\n        let types = [];\n        for (const item of type) {\n            if ('SpecialToken' in item) {\n                if (add_special_tokens) {\n                    processedTokens.push(item.SpecialToken.id);\n                    types.push(item.SpecialToken.type_id);\n                }\n            } else if ('Sequence' in item) {\n                if (item.Sequence.id === 'A') {\n                    processedTokens = mergeArrays(processedTokens, tokens);\n                    types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));\n\n                } else if (item.Sequence.id === 'B') {\n                    processedTokens = mergeArrays(processedTokens, tokens_pair);\n                    types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));\n                }\n            }\n        }\n        return { tokens: processedTokens, token_type_ids: types };\n    }\n}\n\n/**\n * A PostProcessor that returns the given tokens as is.\n * @extends PostProcessor\n */\nclass ByteLevelPostProcessor extends PostProcessor {\n    /**\n     * Post process the given tokens.\n     * @param {string[]} tokens The list of tokens for the first sequence.\n     * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n     * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n     */\n    post_process(tokens, tokens_pair = null) {\n        if (tokens_pair) {\n            tokens = mergeArrays(tokens, tokens_pair);\n        }\n        return { tokens };\n    }\n}\n\n\n/**\n * A post-processor that applies multiple post-processors in sequence.\n */\nclass PostProcessorSequence extends PostProcessor {\n\n    /**\n     * Creates a new instance of PostProcessorSequence.\n     * @param {Object} config The configuration object.\n     * @param {Object[]} config.processors The list of post-processors to apply.\n     */\n    constructor(config) {\n        super(config);\n\n        this.processors = config.processors.map(x => PostProcessor.fromConfig(x));\n    }\n\n    /**\n     * Post process the given tokens.\n     * @param {string[]} tokens The list of tokens for the first sequence.\n     * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n     * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n     */\n    post_process(tokens, tokens_pair = null, options = {}) {\n        let token_type_ids;\n        for (const processor of this.processors) {\n            if (processor instanceof ByteLevelPostProcessor) {\n                // Special case where we need to pass the tokens_pair to the post-processor\n                const output = processor.post_process(tokens);\n                tokens = output.tokens;\n                if (tokens_pair) {\n                    const pair_output = processor.post_process(tokens_pair);\n                    tokens_pair = pair_output.tokens;\n                }\n            } else {\n                const output = processor.post_process(tokens, tokens_pair, options);\n                tokens = output.tokens;\n                token_type_ids = output.token_type_ids;\n            }\n        }\n        return { tokens, token_type_ids };\n    }\n}\n\n/**\n * The base class for token decoders.\n * @extends Callable\n */\nclass Decoder extends Callable {\n\n    /**\n    * Creates an instance of `Decoder`.\n    *\n    * @param {Object} config The configuration object.\n    */\n    constructor(config) {\n        super();\n        this.config = config;\n\n        /** @type {AddedToken[]} */\n        this.added_tokens = [];\n        this.end_of_word_suffix = null;\n        this.trim_offsets = config.trim_offsets;\n    }\n\n    /**\n   * Creates a decoder instance based on the provided configuration.\n   *\n   * @param {Object} config The configuration object.\n   * @returns {Decoder} A decoder instance.\n   * @throws {Error} If an unknown decoder type is provided.\n   */\n    static fromConfig(config) {\n        if (config === null) return null;\n        switch (config.type) {\n            case 'WordPiece':\n                return new WordPieceDecoder(config);\n            case 'Metaspace':\n                return new MetaspaceDecoder(config);\n            case 'ByteLevel':\n                return new ByteLevelDecoder(config);\n\n            case 'Replace':\n                return new ReplaceDecoder(config);\n            case 'ByteFallback':\n                return new ByteFallback(config);\n            case 'Fuse':\n                return new FuseDecoder(config);\n            case 'Strip':\n                return new StripDecoder(config);\n\n            case 'Sequence':\n                return new DecoderSequence(config);\n\n            case 'CTC':\n                return new CTCDecoder(config);\n            case 'BPEDecoder':\n                return new BPEDecoder(config);\n            default:\n                throw new Error(`Unknown Decoder type: ${config.type}`);\n        }\n    }\n\n    /**\n    * Calls the `decode` method.\n    *\n    * @param {string[]} tokens The list of tokens.\n    * @returns {string} The decoded string.\n    */\n    _call(tokens) {\n        return this.decode(tokens);\n    }\n\n    /**\n    * Decodes a list of tokens.\n    * @param {string[]} tokens The list of tokens.\n    * @returns {string} The decoded string.\n    */\n    decode(tokens) {\n        return this.decode_chain(tokens).join('');\n    }\n\n    /**\n     * Apply the decoder to a list of tokens.\n     * \n     * @param {string[]} tokens The list of tokens.\n     * @returns {string[]} The decoded list of tokens.\n     * @throws {Error} If the `decode_chain` method is not implemented in the subclass.\n     */\n    decode_chain(tokens) {\n        throw Error(\"`decode_chain` should be implemented in subclass.\")\n    }\n\n}\n\nclass ReplaceDecoder extends Decoder {\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        const pattern = createPattern(this.config.pattern);\n        return pattern === null\n            ? tokens\n            : tokens.map(token => token.replaceAll(pattern, this.config.content))\n    }\n}\n\n\nclass ByteFallback extends Decoder {\n    constructor(config) {\n        super(config);\n\n        this.text_decoder = new TextDecoder();\n    }\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n\n        const new_tokens = [];\n        let previous_byte_tokens = [];\n\n        for (const token of tokens) {\n            let bytes = null;\n            if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {\n                const byte = parseInt(token.slice(3, 5), 16);\n                if (!isNaN(byte)) {\n                    bytes = byte;\n                }\n            }\n            if (bytes !== null) {\n                previous_byte_tokens.push(bytes);\n            } else {\n                if (previous_byte_tokens.length > 0) {\n                    const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n                    new_tokens.push(string);\n                    previous_byte_tokens = [];\n                }\n                new_tokens.push(token);\n            }\n        }\n        if (previous_byte_tokens.length > 0) {\n            const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n            new_tokens.push(string);\n            previous_byte_tokens = [];\n        }\n\n        return new_tokens;\n    }\n}\n\n/**\n * Fuse simply fuses all tokens into one big string.\n * It's usually the last decoding step anyway, but this decoder\n * exists incase some decoders need to happen after that step\n */\nclass FuseDecoder extends Decoder {\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        return [tokens.join('')];\n    }\n}\n\n\nclass StripDecoder extends Decoder {\n    constructor(config) {\n        super(config);\n\n        this.content = this.config.content;\n        this.start = this.config.start;\n        this.stop = this.config.stop;\n    }\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        return tokens.map(token => {\n            let start_cut = 0;\n            for (let i = 0; i < this.start; ++i) {\n                if (token[i] === this.content) {\n                    start_cut = i + 1;\n                    continue;\n                } else {\n                    break;\n                }\n            }\n\n            let stop_cut = token.length;\n            for (let i = 0; i < this.stop; ++i) {\n                const index = token.length - i - 1;\n                if (token[index] === this.content) {\n                    stop_cut = index;\n                    continue;\n                } else {\n                    break;\n                }\n            }\n\n            return token.slice(start_cut, stop_cut)\n        });\n    }\n}\n\n/**\n * A decoder that decodes a list of WordPiece tokens into a single string.\n * @extends Decoder\n */\nclass WordPieceDecoder extends Decoder {\n\n    /**\n     * Creates a new instance of WordPieceDecoder.\n     * @param {Object} config The configuration object.\n     * @param {string} config.prefix The prefix used for WordPiece encoding.\n     * @param {boolean} config.cleanup Whether to cleanup the decoded string.\n     */\n    constructor(config) {\n        super(config);\n        this.cleanup = config.cleanup;\n    }\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        return tokens.map((token, i) => {\n            if (i !== 0) {\n                if (token.startsWith(this.config.prefix)) {\n                    // NOTE: .replace() is intended; only replace first occurrence\n                    token = token.replace(this.config.prefix, '');\n                } else {\n                    token = ' ' + token;\n                }\n            }\n            if (this.cleanup) {\n                token = clean_up_tokenization(token)\n            }\n\n            return token;\n        });\n    }\n}\n\n/**\n * Byte-level decoder for tokenization output. Inherits from the `Decoder` class.\n * @extends Decoder\n */\nclass ByteLevelDecoder extends Decoder {\n\n    /**\n     * Create a `ByteLevelDecoder` object.\n     * @param {Object} config Configuration object.\n     */\n    constructor(config) {\n        super(config);\n\n        this.byte_decoder = UNICODE_TO_BYTES;\n        this.text_decoder = new TextDecoder(\"utf-8\", {\n            fatal: false,\n            ignoreBOM: true,\n        });\n\n        this.end_of_word_suffix = null;\n    }\n\n    /**\n     * Convert an array of tokens to string by decoding each byte.\n     * @param {string[]} tokens Array of tokens to be decoded.\n     * @returns {string} The decoded string.\n     */\n    convert_tokens_to_string(tokens) {\n        const text = tokens.join('');\n        const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));\n        const decoded_text = this.text_decoder.decode(byteArray);\n        return decoded_text;\n    }\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        // TODO move to base class (like HF)\n        // tokens === filtered_tokens\n\n        // To avoid mixing byte-level and unicode for byte-level BPT\n        // we need to build string separately for added tokens and byte-level tokens\n        // cf. https://github.com/huggingface/transformers/issues/1133\n        const sub_texts = [];\n        let current_sub_text = [];\n        for (const token of tokens) {\n            // tokens sent here are already filtered, so we don't need to do this\n            // if (skip_special_tokens && this.all_special_ids.includes(token)) {\n            //     continue;\n            // }\n\n            if (this.added_tokens.find(x => x.content === token) !== undefined) {\n                if (current_sub_text.length > 0) {\n                    sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n                    current_sub_text = [];\n                }\n                sub_texts.push(token);\n            } else {\n                current_sub_text.push(token);\n            }\n        }\n        if (current_sub_text.length > 0) {\n            sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n        }\n\n        // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options\n\n        return sub_texts;\n    }\n}\n\n/**\n * The CTC (Connectionist Temporal Classification) decoder.\n * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs\n */\nclass CTCDecoder extends Decoder {\n\n    constructor(config) {\n        super(config);\n\n        this.pad_token = this.config.pad_token;\n        this.word_delimiter_token = this.config.word_delimiter_token;\n        this.cleanup = this.config.cleanup;\n    }\n    /**\n     * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.\n     * @param {string[]} tokens Array of tokens to be decoded.\n     * @returns {string} The decoded string.\n     */\n    convert_tokens_to_string(tokens) {\n        if (tokens.length === 0) return '';\n\n        // group same tokens into non-repeating tokens in CTC style decoding\n        const grouped_tokens = [tokens[0]];\n        for (let i = 1; i < tokens.length; ++i) {\n            if (tokens[i] !== grouped_tokens.at(-1)) {\n                grouped_tokens.push(tokens[i]);\n            }\n        }\n\n        // filter self.pad_token which is used as CTC-blank token\n        const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);\n\n        let text = filtered_tokens.join('');\n        if (this.cleanup) {\n            // cleanup and replace delimiter token\n            text = clean_up_tokenization(text)\n                .replaceAll(this.word_delimiter_token, ' ')\n                .trim();\n        }\n        return text;\n    }\n\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        return [this.convert_tokens_to_string(tokens)];\n    }\n}\n\n/**\n * Apply a sequence of decoders.\n * @extends Decoder\n */\nclass DecoderSequence extends Decoder {\n\n    /**\n     * Creates a new instance of DecoderSequence.\n     * @param {Object} config The configuration object.\n     * @param {Object[]} config.decoders The list of decoders to apply.\n     */\n    constructor(config) {\n        super(config);\n        this.decoders = config.decoders.map(x => Decoder.fromConfig(x));\n    }\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        // Use reduce to apply each decoder to the tokens\n        return this.decoders.reduce((toks, decoder) => {\n            return decoder.decode_chain(toks);\n        }, tokens);\n    }\n\n}\n\nclass BPEDecoder extends Decoder {\n    constructor(config) {\n        super(config);\n\n        this.suffix = this.config.suffix;\n    }\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        return tokens.map((token, i) => {\n            return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')\n        });\n    }\n}\n\n// Custom decoder for VITS\nclass VitsDecoder extends Decoder {\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        let decoded = '';\n        for (let i = 1; i < tokens.length; i += 2) {\n            decoded += tokens[i];\n        }\n        return [decoded];\n    }\n}\n\n\n/**\n * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,\n * and returns a list of tokens.\n * @extends PreTokenizer\n */\nclass MetaspacePreTokenizer extends PreTokenizer {\n    /**\n     * @param {Object} config The configuration object for the MetaspacePreTokenizer.\n     * @param {string} config.replacement The character to replace spaces with.\n     * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.\n     * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.\n     */\n    constructor(config) {\n        super();\n\n        this.replacement = config.replacement;\n        this.strRep = config.str_rep || this.replacement;\n        this.prepend_scheme = config.prepend_scheme ?? 'always';\n    }\n\n    /**\n     * This method takes a string, replaces spaces with the replacement character,\n     * adds a prefix space if requested, and returns a new list of tokens.\n     * @param {string} text The text to pre-tokenize.\n     * @param {Object} [options] The options for the pre-tokenization.\n     * @param {number} [options.section_index] The index of the section to pre-tokenize.\n     * @returns {string[]} A new list of pre-tokenized tokens.\n     */\n    pre_tokenize_text(text, {\n        section_index = undefined,\n    } = {}) {\n\n        let normalized = text.replaceAll(' ', this.strRep);\n\n        if (\n            // We add a prefix space if:\n            //  (1) The normalized token does not already start with the replacement character.\n            !normalized.startsWith(this.replacement)\n\n            // and (2) either:\n            //  (a) prepend_scheme is 'always'\n            //  (b) prepend_scheme is 'first' and this is the first section\n            && (\n                this.prepend_scheme === 'always' ||\n                (this.prepend_scheme === 'first' && section_index === 0)\n            )\n        ) {\n            normalized = this.strRep + normalized;\n        }\n        return [normalized];\n    }\n}\n\n/**\n * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization.\n * @extends Decoder\n */\nclass MetaspaceDecoder extends Decoder {\n    /**\n     * Constructs a new MetaspaceDecoder object.\n     * @param {Object} config The configuration object for the MetaspaceDecoder.\n     * @param {string} config.replacement The string to replace spaces with.\n     */\n    constructor(config) {\n        super(config);\n\n        this.replacement = config.replacement;\n    }\n\n    /** @type {Decoder['decode_chain']} */\n    decode_chain(tokens) {\n        const result = [];\n        for (let i = 0; i < tokens.length; ++i) {\n            let normalized = tokens[i].replaceAll(this.replacement, ' ');\n            if (i == 0 && normalized.startsWith(' ')) {\n                normalized = normalized.substring(1);\n            }\n            result.push(normalized);\n        }\n        return result;\n    }\n}\n\n/**\n * A normalizer that applies a precompiled charsmap.\n * This is useful for applying complex normalizations in C++ and exposing them to JavaScript.\n * @extends Normalizer\n * @param {Object} config The configuration object for the Precompiled normalizer.\n * @param {Object} config.precompiled_charsmap The precompiled charsmap object.\n */\nclass Precompiled extends Normalizer {\n    /**\n     * Create a new instance of Precompiled normalizer.\n     * @param {Object} config The configuration object.\n     * @param {any} config.precompiled_charsmap Precompiled chars mapping.\n     */\n    constructor(config) {\n        super(config);\n        this.charsmap = config.precompiled_charsmap;\n    }\n\n    /**\n     * Normalizes the given text by applying the precompiled charsmap.\n     * @param {string} text The text to normalize.\n     * @returns {string} The normalized text.\n     */\n    normalize(text) {\n        // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),\n        // there are 5 pre-defined normalization rules:\n        //  1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)\n        //  2. nfkc: original NFKC normalization.\n        //  3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)\n        //  4. nfkc_cf: nfkc + Unicode case folding.\n        //  5. identity: no normalization\n        // \n        // For now, we only implement the default (nmt_nfkc).\n        // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.\n        // TODO: detect when a different `this.charsmap` is used.\n\n        text = text.replace(/[\\u0001-\\u0008\\u000B\\u000E-\\u001F\\u007F\\u008F\\u009F]/gm, ''); // Remove control characters\n        text = text.replace(/[\\u0009\\u000A\\u000C\\u000D\\u00A0\\u1680\\u2000-\\u200F\\u2028\\u2029\\u202F\\u205F\\u2581\\u3000\\uFEFF\\uFFFD]/gm, '\\u0020'); // Replace certain characters with a space\n\n        if (text.includes('\\uFF5E')) {\n            // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.\n            // For some reason, the \"Fullwidth Tilde\" character (\\uFF5E) should not be converted to the standard Tilde character (\\u007E).\n            // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,\n            // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.\n            const parts = text.split('\\uFF5E');\n            text = parts.map(part => part.normalize('NFKC')).join('\\uFF5E');\n        } else {\n            text = text.normalize('NFKC');\n        }\n\n        return text;\n    }\n}\n\n/**\n * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.\n * @extends PreTokenizer\n */\nclass PreTokenizerSequence extends PreTokenizer {\n    /**\n     * Creates an instance of PreTokenizerSequence.\n     * @param {Object} config The configuration object for the pre-tokenizer sequence.\n     * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.\n     */\n    constructor(config) {\n        super();\n        this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));\n    }\n\n    /**\n     * Applies each pre-tokenizer in the sequence to the input text in turn.\n     * @param {string} text The text to pre-tokenize.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} The pre-tokenized text.\n     */\n    pre_tokenize_text(text, options) {\n        // Use reduce to apply each tokenizer to the text\n        return this.tokenizers.reduce((preTokenizedText, tokenizer) => {\n            return tokenizer.pre_tokenize(preTokenizedText, options);\n        }, [text]);\n    }\n}\n\n/**\n * Splits on word boundaries (using the following regular expression: `\\w+|[^\\w\\s]+`).\n */\nclass WhitespacePreTokenizer extends PreTokenizer {\n    /**\n     * Creates an instance of WhitespacePreTokenizer.\n     * @param {Object} config The configuration object for the pre-tokenizer.\n     */\n    constructor(config) {\n        super();\n    }\n    /**\n     * Pre-tokenizes the input text by splitting it on word boundaries.\n     * @param {string} text The text to be pre-tokenized.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n     */\n    pre_tokenize_text(text, options) {\n        return text.match(/\\w+|[^\\w\\s]+/g) || [];\n    }\n}\n\n/**\n * Splits a string of text by whitespace characters into individual tokens.\n * @extends PreTokenizer\n */\nclass WhitespaceSplit extends PreTokenizer {\n    /**\n     * Creates an instance of WhitespaceSplit.\n     * @param {Object} config The configuration object for the pre-tokenizer.\n     */\n    constructor(config) {\n        super();\n    }\n    /**\n     * Pre-tokenizes the input text by splitting it on whitespace characters.\n     * @param {string} text The text to be pre-tokenized.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n     */\n    pre_tokenize_text(text, options) {\n        return whitespace_split(text);\n    }\n}\n\n// NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)\nclass ReplacePreTokenizer extends PreTokenizer {\n    /**\n     * @param {Object} config The configuration options for the pre-tokenizer.\n     * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n     * @param {string} config.content What to replace the pattern with.\n     */\n    constructor(config) {\n        super();\n        this.config = config;\n        this.pattern = createPattern(this.config.pattern);\n        this.content = this.config.content;\n    }\n\n    /**\n     * Pre-tokenizes the input text by replacing certain characters.\n     * @param {string} text The text to be pre-tokenized.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens produced by replacing certain characters.\n     */\n    pre_tokenize_text(text, options) {\n        if (this.pattern === null) {\n            return [text];\n        }\n        return [text.replaceAll(this.pattern, this.config.content)];\n    }\n}\n\nclass FixedLengthPreTokenizer extends PreTokenizer {\n    /**\n     * @param {Object} config The configuration options for the pre-tokenizer.\n     * @param {number} config.length The fixed length to split the text into.\n     */\n    constructor(config) {\n        super();\n        this._length = config.length;\n    }\n\n    /**\n     * Pre-tokenizes the input text by splitting it into fixed-length tokens.\n     * @param {string} text The text to be pre-tokenized.\n     * @param {Object} [options] Additional options for the pre-tokenization logic.\n     * @returns {string[]} An array of tokens produced by splitting the input text into fixed-length tokens.\n     */\n    pre_tokenize_text(text, options) {\n        const tokens = [];\n        for (let i = 0; i < text.length; i += this._length) {\n            tokens.push(text.slice(i, i + this._length));\n        }\n        return tokens;\n    }\n}\n\nconst SPECIAL_TOKEN_ATTRIBUTES = [\n    'bos_token',\n    'eos_token',\n    'unk_token',\n    'sep_token',\n    'pad_token',\n    'cls_token',\n    'mask_token',\n    // additional_special_tokens (TODO)\n]\n\n/**\n * \n * Helper function for padding values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record<string, any[]>} item The input object.\n * @param {number} length The length to pad to.\n * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key.\n * @param {string} side Which side to pad the array.\n * @private\n */\nfunction padHelper(item, length, value_fn, side) {\n    for (const key of Object.keys(item)) {\n        const diff = length - item[key].length;\n        const value = value_fn(key);\n\n        const padData = new Array(diff).fill(value);\n        item[key] = side === 'right'\n            ? mergeArrays(item[key], padData)\n            : mergeArrays(padData, item[key]);\n    }\n}\n\n/**\n * Helper function for truncating values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record<string, any[]>} item The input object.\n * @param {number} length The length to truncate to.\n * @private\n */\nfunction truncateHelper(item, length) {\n    // Setting .length to a lower value truncates the array in-place:\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length\n    for (const key of Object.keys(item)) {\n        item[key].length = length;\n    }\n}\n\n\n/**\n * @typedef {Object} Message\n * @property {string} role The role of the message (e.g., \"user\" or \"assistant\" or \"system\").\n * @property {string} content The content of the message.\n */\n\nexport class PreTrainedTokenizer extends Callable {\n    return_token_type_ids = false;\n\n    padding_side = 'right';\n    /**\n     * Create a new PreTrainedTokenizer instance.\n     * @param {Object} tokenizerJSON The JSON of the tokenizer.\n     * @param {Object} tokenizerConfig The config of the tokenizer.\n     */\n    constructor(tokenizerJSON, tokenizerConfig) {\n        super();\n\n        this.config = tokenizerConfig;\n\n        // Construct parts of the tokenizer from the JSON\n        this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);\n        this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);\n        this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);\n        this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);\n        this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);\n\n        // Add added_tokens to model\n        this.special_tokens = [];\n        this.all_special_ids = [];\n\n        /** @type {AddedToken[]} */\n        this.added_tokens = [];\n        for (const addedToken of tokenizerJSON.added_tokens) {\n            const token = new AddedToken(addedToken);\n            this.added_tokens.push(token);\n\n            this.model.tokens_to_ids.set(token.content, token.id);\n            this.model.vocab[token.id] = token.content;\n\n            if (token.special) {\n                this.special_tokens.push(token.content);\n                this.all_special_ids.push(token.id);\n            }\n        }\n\n        // Update additional_special_tokens\n        this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];\n        this.special_tokens.push(...this.additional_special_tokens);\n        this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates\n\n        if (this.decoder) {\n            // Slight hack, but it prevents code duplication:\n            this.decoder.added_tokens = this.added_tokens;\n\n            // Another slight hack to add `end_of_word_suffix` (if present) to the decoder\n            // This is needed for cases where BPE model and ByteLevel decoder are used\n            // For more information, see https://github.com/huggingface/transformers.js/issues/74\n            // TODO: save this to the decoder when exporting?\n            this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;\n        }\n\n        this.added_tokens_splitter = new DictionarySplitter(\n            this.added_tokens.map(x => x.content),\n        );\n\n        /** @type {Map<string, AddedToken>} */\n        this.added_tokens_map = new Map(this.added_tokens.map(x => [x.content, x]))\n\n        // Set mask token if present (otherwise will be undefined, which is fine)\n        this.mask_token = this.getToken('mask_token');\n        this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);\n\n        this.pad_token = this.getToken('pad_token', 'eos_token');\n        this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);\n\n        this.sep_token = this.getToken('sep_token');\n        this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);\n\n        this.unk_token = this.getToken('unk_token');\n        this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);\n\n        this.bos_token = this.getToken('bos_token');\n        this.bos_token_id = this.model.tokens_to_ids.get(this.bos_token);\n\n        this.eos_token = this.getToken('eos_token');\n        this.eos_token_id = this.model.tokens_to_ids.get(this.eos_token);\n\n        this.model_max_length = tokenizerConfig.model_max_length;\n\n        /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */\n        this.remove_space = tokenizerConfig.remove_space;\n\n        this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;\n        this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;\n\n        if (tokenizerConfig.padding_side) {\n            this.padding_side = tokenizerConfig.padding_side;\n        }\n\n        this.add_bos_token = tokenizerConfig.add_bos_token;\n        this.add_eos_token = tokenizerConfig.add_eos_token;\n\n        this.legacy = false;\n\n        this.chat_template = tokenizerConfig.chat_template ?? null;\n        if (Array.isArray(this.chat_template)) {\n            // Chat templates are stored as lists of dicts with fixed key names,\n            // we reconstruct that into a single dict while loading them.\n            const chat_template = Object.create(null);\n            for (const { name, template } of this.chat_template) {\n                if (typeof name !== 'string' || typeof template !== 'string') {\n                    throw new Error('Chat template must be a list of objects with \"name\" and \"template\" properties');\n                }\n                chat_template[name] = template;\n            }\n            this.chat_template = chat_template;\n        }\n        this._compiled_template_cache = new Map();\n    }\n\n    /**\n     * Returns the value of the first matching key in the tokenizer config object.\n     * @param {...string} keys One or more keys to search for in the tokenizer config object.\n     * @returns {string|null} The value associated with the first matching key, or null if no match is found.\n     * @throws {Error} If an object is found for a matching key and its __type property is not \"AddedToken\".\n     * @private\n     */\n    getToken(...keys) {\n        for (const key of keys) {\n            const item = this.config[key];\n\n            if (!item) continue;\n\n            if (typeof item === 'object') {\n                if (item.__type === 'AddedToken') {\n                    return item.content;\n                } else {\n                    throw Error(`Unknown token: ${item}`);\n                }\n            } else {\n                return item;\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. \n     * \n     * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.\n     * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n     * \n     * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.\n     * @returns {Promise<PreTrainedTokenizer>} A new instance of the `PreTrainedTokenizer` class.\n     */\n    static async from_pretrained(pretrained_model_name_or_path, {\n        progress_callback = null,\n        config = null,\n        cache_dir = null,\n        local_files_only = false,\n        revision = 'main',\n        legacy = null,\n    } = {}) {\n\n        const info = await loadTokenizer(pretrained_model_name_or_path, {\n            progress_callback,\n            config,\n            cache_dir,\n            local_files_only,\n            revision,\n            legacy,\n        })\n\n        // @ts-ignore\n        return new this(...info);\n    }\n\n    /**\n     * @typedef {number[]|number[][]|Tensor} BatchEncodingItem\n     * \n     * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.\n     * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.\n     * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.\n     * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.\n     */\n\n    /**\n     * Encode/tokenize the given text(s).\n     * @param {string|string[]} text The text to tokenize.\n     * @param {Object} options An optional object containing the following properties:\n     * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.\n     * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.\n     * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n     * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.\n     * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.\n     * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.\n     * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.\n     * @returns {BatchEncoding} Object to be passed to the model.\n     */\n    _call(\n        // Required positional arguments\n        text,\n\n        // Optional keyword arguments\n        {\n            text_pair = null,\n            add_special_tokens = true,\n            padding = false,\n            truncation = null,\n            max_length = null,\n            return_tensor = true, // Different to HF\n            return_token_type_ids = null,\n        } = {},\n    ) {\n\n        const isBatched = Array.isArray(text);\n\n        /** @type {EncodingSingle[]} */\n        let encodedTokens;\n\n        if (isBatched) {\n            if (text.length === 0) {\n                throw Error('text array must be non-empty')\n            }\n\n            if (text_pair !== null) {\n                if (!Array.isArray(text_pair)) {\n                    throw Error('text_pair must also be an array')\n\n                } else if (text.length !== text_pair.length) {\n                    throw Error('text and text_pair must have the same length')\n                }\n\n                encodedTokens = text.map(\n                    (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids })\n                )\n\n            } else {\n                encodedTokens = text.map(x => this._encode_plus(x, { add_special_tokens, return_token_type_ids }));\n            }\n\n        } else {\n            if (text === null || text === undefined) {\n                throw Error('text may not be null or undefined')\n            }\n\n            if (Array.isArray(text_pair)) {\n                throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')\n            }\n\n            // For single input, we just wrap in an array, and then unwrap later.\n            encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })];\n        }\n        // At this point, `encodedTokens` is batched, of shape [batch_size, tokens].\n        // However, array may be jagged. So, we may need pad to max_length.\n        if (max_length === null) {\n            max_length = this.model_max_length;\n        } else if (truncation === null) {\n            if (padding === true) {\n                console.warn(\n                    \"`max_length` is ignored when `padding: true` and there is no truncation strategy. \" +\n                    \"To pad to max length, use `padding: 'max_length'`.\"\n                )\n                max_length = this.model_max_length;\n            } else if (padding === false) {\n                console.warn(\"Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length.\");\n                truncation = true;\n            }\n        }\n\n        // padding: 'max_length' doesn't require any additional calculation\n        // but padding: true has to calculate max_length from the sequences\n        if (padding === true) {\n            max_length = Math.min(max(encodedTokens.map(x => x.input_ids.length))[0], max_length ?? Infinity);\n        }\n\n        // Ensure it is less than model max length\n        max_length = Math.min(max_length, this.model_max_length ?? Infinity);\n\n        if (padding || truncation) {\n\n            // Perform padding and/or truncation\n            for (let i = 0; i < encodedTokens.length; ++i) {\n                if (encodedTokens[i].input_ids.length === max_length) {\n                    continue;\n\n                } else if (encodedTokens[i].input_ids.length > max_length) {\n                    // possibly truncate\n                    if (truncation) {\n                        truncateHelper(encodedTokens[i], max_length);\n                    }\n\n                } else { // t.length < max_length\n                    // possibly pad\n                    if (padding) {\n                        padHelper(\n                            encodedTokens[i],\n                            max_length,\n                            key => key === 'input_ids' ? this.pad_token_id : 0,\n                            this.padding_side\n                        );\n                    }\n                }\n            }\n        }\n\n        const result = {};\n\n        if (return_tensor) {\n            if (!(padding && truncation)) {\n                // Not, guaranteed that all items have same length, so\n                // we perform additional check\n\n                if (\n                    encodedTokens.some(x => {\n                        for (const key of Object.keys(x)) {\n                            if (x[key].length !== encodedTokens[0][key]?.length) {\n                                return true;\n                            }\n                        }\n                        return false;\n                    })\n                ) {\n                    throw Error(\n                        \"Unable to create tensor, you should probably activate truncation and/or padding \" +\n                        \"with 'padding=true' and 'truncation=true' to have batched tensors with the same length.\"\n                    )\n                }\n            }\n\n            // Now we actually convert to tensor\n            // NOTE: In the same way as the python library, we return a batched tensor, regardless of\n            // whether we have a single input or multiple inputs.\n            const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];\n\n            for (const key of Object.keys(encodedTokens[0])) {\n                result[key] = new Tensor('int64',\n                    BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),\n                    dims\n                );\n            }\n\n        } else {\n            for (const key of Object.keys(encodedTokens[0])) {\n                result[key] = encodedTokens.map(x => x[key]);\n            }\n\n            // If not returning a tensor, we match the input type\n            if (!isBatched) {\n                // Input was not batched, so we unwrap\n                for (const key of Object.keys(result)) {\n                    result[key] = result[key][0];\n                }\n            }\n        }\n\n        return /** @type {BatchEncoding} */(result);\n    }\n\n    /**\n     * Encodes a single text using the preprocessor pipeline of the tokenizer.\n     *\n     * @param {string|null} text The text to encode.\n     * @returns {string[]|null} The encoded tokens.\n     */\n    _encode_text(text) {\n        if (text === null) return null;\n\n        // Actual function which does encoding, for a single text\n        // First, we take care of special tokens. Needed to avoid issues arising from\n        // normalization and/or pretokenization (which may not preserve special tokens)\n        const sections = this.added_tokens_splitter.split(text);\n\n        // Process left/right stripping of added tokens\n        for (let i = 0; i < sections.length; ++i) {\n            const addedToken = this.added_tokens_map.get(sections[i]);\n            if (addedToken) {\n                if (addedToken.lstrip && i > 0) {\n                    sections[i - 1] = sections[i - 1].trimEnd();\n                }\n                if (addedToken.rstrip && i < sections.length - 1) {\n                    sections[i + 1] = sections[i + 1].trimStart();\n                }\n            }\n        }\n\n        const tokens = sections.flatMap((x, section_index) => {\n            if (x.length === 0) return [];\n            if (this.added_tokens_map.has(x)) return [x]; // Return added tokens unchanged\n\n            if (this.remove_space === true) {\n                x = x.trim().split(/\\s+/).join(' ');\n            }\n            if (this.do_lowercase_and_remove_accent) {\n                x = lowercase_and_remove_accent(x);\n            }\n\n            if (this.normalizer !== null) {\n                x = this.normalizer(x);\n            }\n\n            // If, after normalization, this section is empty (e.g., trimming whitespace),\n            // we return an empty array\n            if (x.length === 0) {\n                return [];\n            }\n\n            const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {\n                section_index,\n            }) : [x];\n\n            const tokens = this.model(sectionTokens);\n\n            return tokens;\n        });\n\n        return tokens;\n    }\n\n    /**\n     * Encodes a single text or a pair of texts using the model's tokenizer.\n     *\n     * @param {string} text The text to encode.\n     * @param {Object} options An optional object containing the following properties:\n     * @param {string} [options.text_pair=null] The optional second text to encode.\n     * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n     * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n     * @returns {EncodingSingle} An object containing the encoded text.\n     * @private\n     */\n    _encode_plus(text, {\n        text_pair = null,\n        add_special_tokens = true,\n        return_token_type_ids = null,\n    } = {}) {\n\n        const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens });\n\n        const input_ids = this.model.convert_tokens_to_ids(tokens);\n\n        const result = {\n            input_ids,\n            attention_mask: new Array(input_ids.length).fill(1),\n        }\n        if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) {\n            result.token_type_ids = token_type_ids;\n        }\n        return result;\n    }\n\n    /**\n     * Internal helper function to tokenize a text, and optionally a pair of texts.\n     * @param {string} text The text to tokenize.\n     * @param {Object} options An optional object containing the following properties:\n     * @param {string} [options.pair=null] The optional second text to tokenize.\n     * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n     * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs.\n     */\n    _tokenize_helper(text, {\n        pair = null,\n        add_special_tokens = false,\n    } = {}) {\n        const tokens = this._encode_text(text);\n        const tokens2 = this._encode_text(pair);\n\n        return this.post_processor\n            ? this.post_processor(tokens, tokens2, { add_special_tokens })\n            : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };\n    }\n\n    /**\n     * Converts a string into a sequence of tokens.\n     * @param {string} text The sequence to be encoded.\n     * @param {Object} options An optional object containing the following properties:\n     * @param {string} [options.pair] A second sequence to be encoded with the first.\n     * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n     * @returns {string[]} The list of tokens.\n     */\n    tokenize(text, {\n        pair = null,\n        add_special_tokens = false,\n    } = {}) {\n        return this._tokenize_helper(text, { pair, add_special_tokens }).tokens;\n    }\n\n    /**\n     * Encodes a single text or a pair of texts using the model's tokenizer.\n     *\n     * @param {string} text The text to encode.\n     * @param {Object} options An optional object containing the following properties:\n     * @param {string} [options.text_pair=null] The optional second text to encode.\n     * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n     * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n     * @returns {number[]} An array of token IDs representing the encoded text(s).\n     */\n    encode(text, {\n        text_pair = null,\n        add_special_tokens = true,\n        return_token_type_ids = null,\n    } = {}) {\n        return this._encode_plus(text, {\n            text_pair,\n            add_special_tokens,\n            return_token_type_ids,\n        }).input_ids;\n    }\n\n    /**\n     * Decode a batch of tokenized sequences.\n     * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.\n     * @param {Object} decode_args (Optional) Object with decoding arguments.\n     * @returns {string[]} List of decoded sequences.\n     */\n    batch_decode(batch, decode_args = {}) {\n        if (batch instanceof Tensor) {\n            batch = batch.tolist();\n        }\n        return batch.map(x => this.decode(x, decode_args));\n    }\n\n    /**\n     * Decodes a sequence of token IDs back to a string.\n     *\n     * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode.\n     * @param {Object} [decode_args={}]\n     * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.\n     * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.\n     *\n     * @returns {string} The decoded string.\n     * @throws {Error} If `token_ids` is not a non-empty array of integers.\n     */\n    decode(\n        token_ids,\n        decode_args = {},\n    ) {\n        if (token_ids instanceof Tensor) {\n            token_ids = prepareTensorForDecode(token_ids);\n        }\n\n        if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) {\n            throw Error(\"token_ids must be a non-empty array of integers.\");\n        }\n\n        return this.decode_single(token_ids, decode_args)\n    }\n\n    /**\n     * Decode a single list of token ids to a string.\n     * @param {number[]|bigint[]} token_ids List of token ids to decode\n     * @param {Object} decode_args Optional arguments for decoding\n     * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding\n     * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.\n     * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.\n     * @returns {string} The decoded string\n     */\n    decode_single(\n        token_ids,\n        {\n            skip_special_tokens = false,\n            clean_up_tokenization_spaces = null,\n        }\n    ) {\n        let tokens = this.model.convert_ids_to_tokens(token_ids);\n        if (skip_special_tokens) {\n            tokens = tokens.filter(x => !this.special_tokens.includes(x));\n        }\n\n        // If `this.decoder` is null, we just join tokens with a space:\n        // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835\n        /** @type {string} */\n        let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' ');\n\n        // Slight hack, but prevents having to pass `skip_special_tokens` to\n        // each call to `decode`, which would lead to code duplication.\n        if (this.decoder && this.decoder.end_of_word_suffix) {\n            decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' ');\n            if (skip_special_tokens) {\n                decoded = decoded.trim();\n            }\n        }\n\n        if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) {\n            decoded = clean_up_tokenization(decoded);\n        }\n\n        return decoded;\n    }\n\n    /**\n     * Retrieve the chat template string used for tokenizing chat messages. This template is used\n     * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat\n     * template for better generation tracking.\n     * \n     * @param {Object} options An optional object containing the following properties:\n     * @param {string} [options.chat_template=null]\n     * A Jinja template or the name of a template to use for this conversion.\n     * It is usually not necessary to pass anything to this argument,\n     * as the model's template will be used by default.\n     * @param {Object[]} [options.tools=null]\n     * A list of tools (callable functions) that will be accessible to the model. If the template does not\n     * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n     * giving the name, description and argument types for the tool. See our\n     * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n     * for more information.\n     * @returns {string} The chat template string.\n     */\n    get_chat_template({\n        chat_template = null,\n        tools = null,\n    } = {}) {\n\n        // First, handle the cases when the model has a dict of multiple templates\n        if (this.chat_template && typeof this.chat_template === 'object') {\n            const template_dict = this.chat_template;\n\n            if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) {\n                // The user can pass the name of a template to the chat template argument instead of an entire template\n                chat_template = template_dict[chat_template];\n            } else if (chat_template === null) {\n                if (tools !== null && 'tool_use' in template_dict) {\n                    chat_template = template_dict['tool_use'];\n                } else if ('default' in template_dict) {\n                    chat_template = template_dict['default'];\n                } else {\n                    throw Error(\n                        `This model has multiple chat templates with no default specified! Please either pass a chat ` +\n                        `template or the name of the template you wish to use to the 'chat_template' argument. Available ` +\n                        `template names are ${Object.keys(template_dict).sort()}.`\n                    )\n                }\n            }\n        } else if (chat_template === null) {\n            // These are the cases when the model has a single template\n            // priority: `chat_template` argument > `tokenizer.chat_template`\n            if (this.chat_template) {\n                chat_template = this.chat_template;\n            } else {\n                throw Error(\n                    \"Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template \" +\n                    \"argument was passed! For information about writing templates and setting the \" +\n                    \"tokenizer.chat_template attribute, please see the documentation at \" +\n                    \"https://huggingface.co/docs/transformers/main/en/chat_templating\"\n                )\n            }\n        }\n        return chat_template;\n    }\n\n    /**\n     * Converts a list of message objects with `\"role\"` and `\"content\"` keys to a list of token\n     * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to\n     * determine the format and control tokens to use when converting.\n     * \n     * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.\n     * \n     * **Example:** Applying a chat template to a conversation.\n     * \n     * ```javascript\n     * import { AutoTokenizer } from \"@huggingface/transformers\";\n     * \n     * const tokenizer = await AutoTokenizer.from_pretrained(\"Xenova/mistral-tokenizer-v1\");\n     * \n     * const chat = [\n     *   { \"role\": \"user\", \"content\": \"Hello, how are you?\" },\n     *   { \"role\": \"assistant\", \"content\": \"I'm doing great. How can I help you today?\" },\n     *   { \"role\": \"user\", \"content\": \"I'd like to show off how chat templating works!\" },\n     * ]\n     * \n     * const text = tokenizer.apply_chat_template(chat, { tokenize: false });\n     * // \"<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]\"\n     * \n     * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });\n     * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]\n     * ```\n     * \n     * @param {Message[]} conversation A list of message objects with `\"role\"` and `\"content\"` keys,\n     * representing the chat history so far.\n     * @param {Object} options An optional object containing the following properties:\n     * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If\n     * this is not passed, the model's chat template will be used instead.\n     * @param {Object[]} [options.tools=null]\n     * A list of tools (callable functions) that will be accessible to the model. If the template does not\n     * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n     * giving the name, description and argument types for the tool. See our\n     * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n     * for more information.\n     * @param {Record<string, string>[]} [options.documents=null]\n     * A list of dicts representing documents that will be accessible to the model if it is performing RAG\n     * (retrieval-augmented generation). If the template does not support RAG, this argument will have no\n     * effect. We recommend that each document should be a dict containing \"title\" and \"text\" keys. Please\n     * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)\n     * for examples of passing documents with chat templates.\n     * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate\n     * the start of an assistant message. This is useful when you want to generate a response from the model.\n     * Note that this argument will be passed to the chat template, and so it must be supported in the\n     * template for this argument to have any effect.\n     * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.\n     * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.\n     * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.\n     * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.\n     * If not specified, the tokenizer's `max_length` attribute will be used as a default.\n     * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.\n     * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false.\n     * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.\n     * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output.\n     */\n    apply_chat_template(conversation, {\n        tools = null,\n        documents = null,\n        chat_template = null,\n        add_generation_prompt = false,\n        tokenize = true,\n        padding = false,\n        truncation = false,\n        max_length = null,\n        return_tensor = true,\n        return_dict = false,\n        tokenizer_kwargs = {},\n        ...kwargs\n    } = {}) {\n\n        chat_template = this.get_chat_template({ chat_template, tools });\n\n        if (typeof chat_template !== 'string') {\n            throw Error(`chat_template must be a string, but got ${typeof chat_template}`);\n        }\n\n        // Compilation function uses a cache to avoid recompiling the same template\n        let compiledTemplate = this._compiled_template_cache.get(chat_template);\n        if (compiledTemplate === undefined) {\n            compiledTemplate = new Template(chat_template);\n            this._compiled_template_cache.set(chat_template, compiledTemplate);\n        }\n\n        const special_tokens_map = Object.create(null);\n        for (const key of SPECIAL_TOKEN_ATTRIBUTES) {\n            const value = this.getToken(key);\n            if (value) {\n                special_tokens_map[key] = value;\n            }\n        }\n\n        const rendered = compiledTemplate.render({\n            messages: conversation,\n            add_generation_prompt,\n            tools,\n            documents,\n            ...special_tokens_map,\n            ...kwargs,\n        });\n\n        if (tokenize) {\n            const out = this._call(rendered, {\n                add_special_tokens: false,\n                padding,\n                truncation,\n                max_length,\n                return_tensor,\n                ...tokenizer_kwargs,\n            });\n            return return_dict ? out : out.input_ids;\n        }\n\n        return rendered;\n    }\n}\n\n/**\n * BertTokenizer is a class used to tokenize text for BERT models.\n * @extends PreTrainedTokenizer\n */\nexport class BertTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\n/**\n * Albert tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class AlbertTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\nexport class MobileBertTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\nexport class SqueezeBertTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\nexport class DebertaTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\nexport class DebertaV2Tokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\nexport class HerbertTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\nexport class ConvBertTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\nexport class RoFormerTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\nexport class DistilBertTokenizer extends PreTrainedTokenizer { }\nexport class CamembertTokenizer extends PreTrainedTokenizer { }\nexport class XLMTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n\n    constructor(tokenizerJSON, tokenizerConfig) {\n        super(tokenizerJSON, tokenizerConfig);\n        console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n    }\n}\nexport class ElectraTokenizer extends PreTrainedTokenizer {\n    return_token_type_ids = true;\n}\n\nexport class T5Tokenizer extends PreTrainedTokenizer { }\nexport class GPT2Tokenizer extends PreTrainedTokenizer { }\nexport class BartTokenizer extends PreTrainedTokenizer { }\nexport class MBartTokenizer extends PreTrainedTokenizer {\n    constructor(tokenizerJSON, tokenizerConfig) {\n        super(tokenizerJSON, tokenizerConfig);\n\n        this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/;\n        this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n        this.lang_to_token = x => x; // Identity function\n    }\n\n    /**\n     * Helper function to build translation inputs for an `MBartTokenizer`.\n     * @param {string|string[]} raw_inputs The text to tokenize.\n     * @param {Object} tokenizer_options Options to be sent to the tokenizer\n     * @param {Object} generate_kwargs Generation options.\n     * @returns {Object} Object to be passed to the model.\n     */\n    _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n        return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n    }\n}\nexport class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer\n\nexport class RobertaTokenizer extends PreTrainedTokenizer { }\n\nexport class BloomTokenizer extends PreTrainedTokenizer { }\n\nconst SPIECE_UNDERLINE = \"\u2581\";\n\nexport class LlamaTokenizer extends PreTrainedTokenizer {\n\n    padding_side = 'left';\n\n    constructor(tokenizerJSON, tokenizerConfig) {\n        super(tokenizerJSON, tokenizerConfig);\n\n        this.legacy = tokenizerConfig.legacy ?? true;\n        if (!this.legacy) {\n            // See https://github.com/huggingface/transformers/pull/24565 for more information\n            this.normalizer = null;\n            this.pre_tokenizer = new MetaspacePreTokenizer({\n                replacement: SPIECE_UNDERLINE,\n                prepend_scheme: \"first\",\n            });\n        }\n    }\n\n    /**\n     * Helper function to handle legacy encoding of SPM tokenizers.\n     * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387\n     * @param {string} text The text to encode.\n     * @returns {string[]} The encoded tokens.\n     */\n    _encode_text(text) {\n        if (text === null) return null;\n\n        if (this.legacy || text.length === 0) {\n            return super._encode_text(text);\n        }\n\n        let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, \" \"));\n        if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) {\n            tokens = tokens.slice(1);\n        }\n        return tokens;\n    }\n}\nexport class CodeLlamaTokenizer extends PreTrainedTokenizer { }\n\nexport class XLMRobertaTokenizer extends PreTrainedTokenizer { }\nexport class MPNetTokenizer extends PreTrainedTokenizer { }\n\nexport class FalconTokenizer extends PreTrainedTokenizer { }\n\nexport class GPTNeoXTokenizer extends PreTrainedTokenizer { }\n\nexport class EsmTokenizer extends PreTrainedTokenizer { }\n\nexport class Qwen2Tokenizer extends PreTrainedTokenizer { }\n\nexport class GemmaTokenizer extends PreTrainedTokenizer { }\n\nexport class Grok1Tokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`.\n * @param {PreTrainedTokenizer} self The tokenizer instance.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n * @private\n */\nfunction _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) {\n    if (!('language_codes' in self) || !Array.isArray(self.language_codes)) {\n        throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.')\n    }\n    if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) {\n        throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.')\n    }\n    if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') {\n        throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.')\n    }\n    const src_lang_token = generate_kwargs.src_lang;\n    const tgt_lang_token = generate_kwargs.tgt_lang;\n\n    // Check that the target language is valid:\n    if (!self.language_codes.includes(tgt_lang_token)) {\n        throw new Error(`Target language code \"${tgt_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n    }\n\n    // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default.\n    if (src_lang_token !== undefined) {\n        // Check that the source language is valid:\n        if (!self.language_codes.includes(src_lang_token)) {\n            throw new Error(`Source language code \"${src_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n        }\n\n        // In the same way as the Python library, we override the post-processor\n        // to force the source language to be first:\n        for (const item of self.post_processor.config.single) {\n            if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) {\n                item.SpecialToken.id = self.lang_to_token(src_lang_token);\n                break;\n            }\n        }\n        // TODO: Do the same for pair?\n    }\n\n    // Override the `forced_bos_token_id` to force the correct language\n    generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0];\n\n    return self._call(raw_inputs, tokenizer_options);\n}\n\n/**\n * The NllbTokenizer class is used to tokenize text for NLLB (\"No Language Left Behind\") models.\n * \n * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project\n * that open-sources models capable of delivering high-quality translations directly\n * between any pair of 200+ languages \u2014 including low-resource languages like Asturian,\n * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere,\n * regardless of their language preferences. For more information, check out their\n * [paper](https://huggingface.co/papers/2207.04672).\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}\n */\nexport class NllbTokenizer extends PreTrainedTokenizer {\n\n    constructor(tokenizerJSON, tokenizerConfig) {\n        super(tokenizerJSON, tokenizerConfig);\n\n        this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/;\n        this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n        this.lang_to_token = x => x; // Identity function\n    }\n\n    /**\n     * Helper function to build translation inputs for an `NllbTokenizer`.\n     * @param {string|string[]} raw_inputs The text to tokenize.\n     * @param {Object} tokenizer_options Options to be sent to the tokenizer\n     * @param {Object} generate_kwargs Generation options.\n     * @returns {Object} Object to be passed to the model.\n     */\n    _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n        return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n    }\n}\n\n/**\n * The M2M100Tokenizer class is used to tokenize text for M2M100 (\"Many-to-Many\") models.\n * \n * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many\n * multilingual translation. It was introduced in this [paper](https://huggingface.co/papers/2010.11125)\n * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository.\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}\n */\nexport class M2M100Tokenizer extends PreTrainedTokenizer {\n    constructor(tokenizerJSON, tokenizerConfig) {\n        super(tokenizerJSON, tokenizerConfig);\n\n        this.languageRegex = /^__[a-z]{2,3}__$/;\n        this.language_codes = this.special_tokens\n            .filter(x => this.languageRegex.test(x))\n            .map(x => x.slice(2, -2));\n        this.lang_to_token = x => `__${x}__`;\n    }\n\n    /**\n     * Helper function to build translation inputs for an `M2M100Tokenizer`.\n     * @param {string|string[]} raw_inputs The text to tokenize.\n     * @param {Object} tokenizer_options Options to be sent to the tokenizer\n     * @param {Object} generate_kwargs Generation options.\n     * @returns {Object} Object to be passed to the model.\n     */\n    _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n        return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n    }\n}\n\n/**\n * WhisperTokenizer tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class WhisperTokenizer extends PreTrainedTokenizer {\n\n    get timestamp_begin() {\n        return this.model.convert_tokens_to_ids([\"<|notimestamps|>\"])[0] + 1;\n    }\n\n    /**\n     * Decodes automatic speech recognition (ASR) sequences.\n     * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.\n     * @param {Object} options The options to use for decoding.\n     * @returns {Array<string|{chunks?: undefined|Array<{language: string|null, timestamp: Array<number|null>, text: string}>}>} The decoded sequences.\n     */\n    _decode_asr(sequences, {\n        return_timestamps = false,\n        return_language = false,\n        time_precision = null,\n        force_full_sequences = true\n    } = {}) {\n        // Set force_full_sequences=false if you want streaming\n        // TODO add support for `return_language`\n\n        // Internal method meant to only be used by asr pipeline.\n        // Handles all the little quirks specific to whisper to handle\n        // the various options not allowed in other seq2seq models\n\n        // =========== Overview ============\n        // - iterate over all outputs\n        // - all tokens within output\n        // - Each token can be\n        //   - language token\n        //   - special token\n        //   - timestamp token\n        //   - text token\n        // - We accumulate the text tokens.\n        // - We split on end timestamps\n        // - Lots of complexity comes from stride and timestamps\n\n        if (time_precision === null) {\n            throw Error(\"Must specify time_precision\")\n        }\n        let last_language = null;\n\n        const returnWordTimestamps = return_timestamps === \"word\";\n\n        function new_chunk() {\n            return { \"language\": last_language, \"timestamp\": [null, null], \"text\": \"\" };\n        }\n\n        // Welcome to the state machine!\n        const chunks = [];\n        let chunk = new_chunk();\n        let time_offset = 0.0;\n        const timestamp_begin = this.timestamp_begin;\n        // Whisper timestamp tokens start from 0.00 and go to timestamp 30.00 in 0.02 increments. \n        // We can calculate the last time stamp token as timestamp_begin plus the number of tokens \n        // tokens from 0.00 to 30.00 which is 1500. \n        const total_timestamp_tokens = 1500; // (30.00 - 0.00) / 0.02\n        const timestamp_end = timestamp_begin + total_timestamp_tokens;\n\n        let previous_tokens = [];\n        let previous_token_timestamps = [];\n\n        let skip = false;\n        let right_stride_start = null;\n\n\n        const all_special_ids = new Set(this.all_special_ids);\n\n        for (const output of sequences) {\n            // NOTE: python version has batches, so it uses [0]\n            const token_ids = output.tokens;\n            const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;\n\n            // These keep track of timestamps within strides, which need\n            // to be skipped and resolve all tokens in a single chunk.\n            let last_timestamp = null;\n            let first_timestamp = timestamp_begin;\n\n            if (\"stride\" in output) {\n                const [chunk_len, stride_left, stride_right] = output.stride;\n\n                // Offset the timings to account for the other `model_outputs`.\n                time_offset -= stride_left;\n                right_stride_start = chunk_len - stride_right;\n\n                // Keeping track of timestamps within strides\n                // We're going to NOT split on those, and delay until we're\n                // out of BOTH stride. Otherwise lots of issues occur and\n                // corner cases\n                if (stride_left) {\n                    first_timestamp = stride_left / time_precision + timestamp_begin;\n                }\n\n                if (stride_right) {\n                    for (let i = token_ids.length - 1; i >= 0; --i) {\n                        const token = Number(token_ids[i]);\n                        if (token >= timestamp_begin) {\n                            // There can be several token in the right stride\n                            // But the last one is ALWAYS going to be skipped\n                            if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {\n                                break;\n                            }\n                            last_timestamp = token;\n                        }\n                    }\n                }\n            }\n\n            let current_tokens = [];\n            let current_token_timestamps = [];\n\n            // - all tokens within output\n            for (let i = 0; i < token_ids.length; ++i) {\n                const token = Number(token_ids[i]);\n                // 4 possible states for each token\n                // - 1/ Language code\n                // - 2/ all other special tokens (which we ignore)\n                // - 3/ Timestamp\n                // - 4/ Regular text\n\n                if (all_special_ids.has(token)) {\n                    const text = this.decode([token]);\n                    const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));\n\n                    if (language !== undefined) {\n                        // 1/ Indeed some language\n                        // TODO Handle when language is different from the previous\n                        // one, and we cannot use timestamped tokens to create chunks\n                        if (last_language !== null && language !== last_language && !return_timestamps) {\n                            previous_tokens.push(current_tokens);\n                            const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0];\n                            const resolved_text = this.decode(resolved_tokens);\n                            chunk.text = resolved_text;\n                            chunks.push(chunk);\n\n                            // Flush all our temporary context\n                            previous_tokens = [];\n                            current_tokens = [];\n                            chunk = new_chunk();\n                        }\n\n                        last_language = chunk.language = language;\n                    } else {\n                        // 2/ This is a regular special token, ignoring it\n                    }\n                } else if (token >= timestamp_begin && token <= timestamp_end) {\n                    // 3/ Timestamp token\n                    const time = (token - timestamp_begin) * time_precision + time_offset;\n                    const rounded_time = round(time, 2);\n\n                    if (last_timestamp !== null && token >= last_timestamp) {\n                        // Whisper outputted a timestamp token, but it falls within\n                        // our stride, so we're going to skip it for the time being\n                        // and resolve this later\n                        // Skip is necessary because timestamp tokens always come\n                        // by pair, so we need to skip the next one too (which would mark the start of another chunk).\n                        skip = true;\n                    } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) {\n                        skip = false;\n                    } else if (chunk.timestamp[0] === null) {\n                        chunk.timestamp[0] = rounded_time;\n                    } else {\n                        // This is the end of the timestamp chunk\n                        if (rounded_time === chunk.timestamp[0]) {\n                            // This is a bug in timestamp token output\n                            // where we're taking the duplicate token\n                            // as a stop where it should be a start.\n                            // This is an issue in the underlying model output\n                            // Let's just skip it so it becomes de-factor a start agin\n                        } else {\n                            chunk.timestamp[1] = rounded_time;\n\n                            // Handling merges\n                            previous_tokens.push(current_tokens)\n\n                            if (returnWordTimestamps) {\n                                previous_token_timestamps.push(current_token_timestamps);\n                            }\n                            const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(\n                                previous_tokens, previous_token_timestamps\n                            )\n\n                            const resolved_text = this.decode(resolved_tokens)\n                            chunk.text = resolved_text\n\n                            if (returnWordTimestamps) {\n                                chunk.words = this.collateWordTimestamps(\n                                    resolved_tokens, resolved_token_timestamps, last_language,\n                                )\n                            }\n\n                            chunks.push(chunk)\n\n                            // Flush all our temporary context\n                            previous_tokens = []\n                            current_tokens = []\n                            previous_token_timestamps = []\n                            current_token_timestamps = []\n                            chunk = new_chunk()\n                        }\n                    }\n\n                } else {\n                    // 4/ Regular token\n                    // We just append to the list of all tokens so we can handle\n                    // merges later and decode into text.\n                    current_tokens.push(token)\n\n                    if (returnWordTimestamps) {\n                        let start_time = round(token_timestamps[i] + time_offset, 2);\n\n                        let end_time;\n                        if (i + 1 < token_timestamps.length) {\n                            end_time = round(token_timestamps[i + 1] + time_offset, 2);\n\n                            // Do not allow punctuation-only tokens to have a duration.\n                            // This prevents long pauses from messing up the timestamps.\n                            const decoded_text = this.decode([token]);\n                            if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) {\n                                // Add `time_precision` to avoid overlapping timestamps\n                                end_time = round(Math.min(start_time + time_precision, end_time), 2);\n                            }\n                        } else {\n                            // should never happen\n                            end_time = null;\n                        }\n                        current_token_timestamps.push([start_time, end_time]);\n                    }\n\n                }\n            }\n\n            if ('stride' in output) {\n                const [chunk_len, stride_left, stride_right] = output.stride;\n                time_offset += chunk_len - stride_right\n            }\n\n            // Leftover tokens\n            if (current_tokens.length > 0) {\n                previous_tokens.push(current_tokens)\n                if (returnWordTimestamps) {\n                    previous_token_timestamps.push(current_token_timestamps);\n                }\n            } else if (previous_tokens.every(p => p.length === 0)) {\n                // Flushing previous tokens (END)\"\n                chunk = new_chunk()\n                previous_tokens = []\n                current_tokens = []\n                previous_token_timestamps = [];\n                current_token_timestamps = [];\n            }\n\n        }\n\n        if (previous_tokens.length > 0) {\n            if (force_full_sequences && return_timestamps) {\n                // Last token should always be timestamps, so there shouldn't be\n                // leftover\n                throw new Error(\n                    \"Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. \" +\n                    \"Also make sure WhisperTimeStampLogitsProcessor was used during generation.\"\n                );\n            }\n\n            // Happens when we don't use timestamps\n            const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps);\n\n            // Flushing previous tokens (FINAL)\n            const resolved_text = this.decode(resolved_tokens);\n            chunk.text = resolved_text;\n            if (returnWordTimestamps) {\n                chunk.words = this.collateWordTimestamps(\n                    resolved_tokens, resolved_token_timestamps, last_language,\n                )\n            }\n            chunks.push(chunk);\n        }\n\n        let optional = Object.create(null);\n\n        // Preparing and cleaning up the pipeline output\n        const full_text = chunks.map(chunk => chunk.text).join('');\n        if (return_timestamps || return_language) {\n            for (let i = 0; i < chunks.length; ++i) {\n                const chunk = chunks[i];\n                if (!return_timestamps) {\n                    delete chunk[\"timestamp\"];\n                }\n\n                if (!return_language) {\n                    delete chunk[\"language\"];\n                }\n            }\n            if (returnWordTimestamps) {\n                const new_chunks = [];\n                for (const chunk of chunks) {\n                    for (const word of chunk.words) {\n                        new_chunks.push(word);\n                    }\n                }\n                optional = { \"chunks\": new_chunks };\n            } else {\n                optional = { \"chunks\": chunks };\n            }\n        }\n        return [full_text, optional];\n\n    }\n\n    /**\n     * Finds the longest common sequence among the provided sequences.\n     * @param {number[][]} sequences An array of sequences of token ids to compare.\n     * @returns {number[][]} The longest common sequence found.\n     * @throws {Error} If there is a bug within the function.\n     * @private\n     */\n    findLongestCommonSequence(sequences, token_timestamp_sequences = null) {\n        // It would be much harder to do O(n) because of fault tolerance.\n        // We actually have a really good property which is that the total sequence\n        // MUST be those subsequences in order.\n        // If token_timestamp_sequences is provided, will split those sequences in\n        // exactly the same way.\n        let leftSequence = sequences[0];\n        let leftLength = leftSequence.length;\n        let totalSequence = [];\n\n        const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0;\n        let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null;\n        let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null;\n        for (let i = 1; i < sequences.length; ++i) {\n            const rightSequence = sequences[i];\n            let max = 0.0;\n            let maxIndices = [leftLength, leftLength, 0, 0];\n            // Here we're sliding matches\n            // [a, b, c, d]\n            //          [c, d, f]\n            // =        [c] == [d]\n\n            // [a, b, c, d]\n            //       [c, d, f]\n            // =     [c, d] == [c, d]\n\n\n            // [a, b, c, d]\n            //    [c, d, f]\n\n            // =  [b, c, d] == [c, d, f]\n\n            // [a, b, c, d]\n            // [c, d, f]\n\n            // [a, b, c] == [c, d, f]\n\n            // [a, b, c, d]\n            // [d, f]\n\n            // [a, b] == [d, f]\n\n            // [a, b, c, d]\n            // [f]\n\n            // [a] == [f]\n\n            const rightLength = rightSequence.length;\n            for (let j = 1; j < leftLength + rightLength; ++j) {\n                // Slightly convoluted because we don't want out of bound indices\n                // This will be necessary for a small conflict resolution optimization\n                // later\n                const leftStart = Math.max(0, leftLength - j);\n                const leftStop = Math.min(leftLength, leftLength + rightLength - j);\n                const left = leftSequence.slice(leftStart, leftStop);\n                const rightStart = Math.max(0, j - leftLength);\n                const rightStop = Math.min(rightLength, j);\n                const right = rightSequence.slice(rightStart, rightStop);\n                if (left.length !== right.length) {\n                    throw new Error(\"There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.\");\n                }\n\n                let matches;\n                if (use_token_timestamp_sequences) {\n                    // Get length of longest subsequence of tokens that match\n                    // and have timestamps that are in order\n                    matches = left.filter((elem, idx) => (\n                        elem === right[idx]\n                        && left_token_timestamp_sequence[leftStart + idx] <= token_timestamp_sequences[i][rightStart + idx]\n                    )).length;\n                } else {\n                    matches = left.filter((elem, idx) => elem === right[idx]).length;\n                }\n\n                // epsilon to favor long perfect matches\n                const eps = j / 10000.0;\n                const matching = matches / j + eps;\n                if (matches > 1 && matching > max) {\n                    max = matching;\n                    maxIndices = [leftStart, leftStop, rightStart, rightStop];\n                }\n            }\n            const [leftStart, leftStop, rightStart, rightStop] = maxIndices;\n            const leftMid = Math.floor((leftStop + leftStart) / 2);\n            const rightMid = Math.floor((rightStop + rightStart) / 2);\n            totalSequence.push(...leftSequence.slice(0, leftMid));\n            leftSequence = rightSequence.slice(rightMid);\n            leftLength = leftSequence.length;\n\n            if (use_token_timestamp_sequences) {\n                total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid));\n                left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid);\n            }\n        }\n        totalSequence.push(...leftSequence);\n\n        if (use_token_timestamp_sequences) {\n            total_token_timestamp_sequence.push(...left_token_timestamp_sequence);\n            return [totalSequence, total_token_timestamp_sequence];\n        } else {\n            return [totalSequence, []];\n        }\n    }\n\n    /** @private */\n    collateWordTimestamps(tokens, token_timestamps, language) {\n\n        const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language);\n\n        const timings = [];\n        for (let i = 0; i < words.length; ++i) {\n            const indices = token_indices[i];\n            timings.push({\n                text: words[i],\n                timestamp: [\n                    token_timestamps[indices.at(0)][0],\n                    token_timestamps[indices.at(-1)][1],\n                ],\n            });\n        }\n        return timings;\n    }\n\n    /**\n     * Groups tokens by word. Returns a tuple containing a list of strings with the words,\n     * and a list of `token_id` sequences with the tokens making up each word.\n     * @param {number[]} tokens \n     * @param {string} [language] \n     * @param {string} prepend_punctionations \n     * @param {string} append_punctuations \n     * \n     * @private\n     */\n    combineTokensIntoWords(tokens, language, prepend_punctionations = \"\\\"'\u201C\u00A1\u00BF([{-\", append_punctuations = \"\\\"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001\") {\n        language = language ?? 'english';\n\n        let words, word_tokens, token_indices;\n\n        if ([\"chinese\", \"japanese\", \"thai\", \"lao\", \"myanmar\"].includes(language)) {\n            // These languages don't typically use spaces.\n            [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens)\n        } else {\n            [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens)\n        }\n\n        return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations);\n    }\n\n    /** @type {PreTrainedTokenizer['decode']} */\n    decode(\n        token_ids,\n        decode_args,\n    ) {\n        let text;\n        // @ts-ignore\n        if (decode_args?.decode_with_timestamps) {\n            if (token_ids instanceof Tensor) {\n                token_ids = prepareTensorForDecode(token_ids);\n            }\n            text = this.decodeWithTimestamps(token_ids, decode_args);\n        } else {\n            text = super.decode(token_ids, decode_args);\n        }\n        // TODO: implement offsets\n        // if (decode_args.output_offsets) {\n        //     let offsets = this.computeOffsets\n        // }\n        return text;\n    }\n\n    /**\n     * @param {number[]|bigint[]} token_ids List of token IDs to decode.\n     * @param {Object} decode_args Optional arguments for decoding\n     * @private\n     */\n    decodeWithTimestamps(token_ids, decode_args) {\n        const time_precision = decode_args?.time_precision ?? 0.02;\n\n        const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1;\n        /**@type {Array} */\n        let outputs = [[]];\n        for (let token of token_ids) {\n            token = Number(token);\n            if (token >= timestamp_begin) {\n                const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2);\n                outputs.push(`<|${timestamp}|>`);\n                outputs.push([]);\n            } else {\n                outputs[outputs.length - 1].push(token);\n            }\n        }\n        outputs = outputs.map(\n            s => typeof s === 'string' ? s : super.decode(s, decode_args)\n        )\n\n        return outputs.join('');\n    }\n\n    /**\n     * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.\n     * @param {number[]} tokens \n     * @returns {*}\n     * @private\n     */\n    splitTokensOnUnicode(tokens) {\n        const decoded_full = this.decode(tokens, {\n            // @ts-ignore\n            decode_with_timestamps: true,\n        });\n        const replacement_char = '\\uFFFD';\n\n        const words = []\n        const word_tokens = []\n        const token_indices = []\n        let current_tokens = []\n        let current_indices = []\n        let unicode_offset = 0\n\n        for (let token_idx = 0; token_idx < tokens.length; ++token_idx) {\n            const token = tokens[token_idx];\n\n            current_tokens.push(token);\n            current_indices.push(token_idx);\n\n            const decoded = this.decode(current_tokens, {\n                // @ts-ignore\n                decode_with_timestamps: true,\n            });\n\n            if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) {\n                words.push(decoded)\n                word_tokens.push(current_tokens)\n                token_indices.push(current_indices)\n                current_tokens = []\n                current_indices = []\n                unicode_offset += decoded.length;\n            }\n\n        }\n\n        return [words, word_tokens, token_indices]\n    }\n\n    /**\n     * Combine tokens into words by splitting at whitespace and punctuation tokens.\n     * @param {number[]} tokens \n     * @private\n     */\n    splitTokensOnSpaces(tokens) {\n\n        const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens);\n\n        const words = []\n        const word_tokens = []\n        const token_indices = []\n\n        const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu');\n\n        for (let i = 0; i < subwords.length; ++i) {\n\n            const subword = subwords[i];\n            const subword_tokens = subword_tokens_list[i];\n            const subword_indices = subword_indices_list[i];\n\n            // @ts-ignore\n            const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>');\n            const with_space = subword.startsWith(' ');\n            const trimmed = subword.trim();\n            const punctuation = punctuationRegex.test(trimmed);\n\n            if (special || with_space || punctuation || words.length === 0) {\n                words.push(subword);\n                word_tokens.push(subword_tokens);\n                token_indices.push(subword_indices);\n            } else {\n                const ix = words.length - 1;\n                words[ix] += subword;\n                word_tokens[ix].push(...subword_tokens);\n                token_indices[ix].push(...subword_indices);\n            }\n        }\n\n        return [words, word_tokens, token_indices];\n\n    }\n\n    /**\n     * Merges punctuation tokens with neighboring words.\n     * @param {string[]} words \n     * @param {number[][]} tokens \n     * @param {number[][]} indices \n     * @param {string} prepended \n     * @param {string} appended \n     * @private\n     */\n    mergePunctuations(words, tokens, indices, prepended, appended) {\n\n        const newWords = structuredClone(words);\n        const newTokens = structuredClone(tokens);\n        const newIndices = structuredClone(indices);\n\n\n        // prepend punctuations\n        let i = newWords.length - 2;\n        let j = newWords.length - 1;\n\n        while (i >= 0) {\n            if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) {\n                newWords[j] = newWords[i] + newWords[j];\n                newTokens[j] = mergeArrays(newTokens[i], newTokens[j]);\n                newIndices[j] = mergeArrays(newIndices[i], newIndices[j]);\n                newWords[i] = '';\n                newTokens[i] = [];\n                newIndices[i] = [];\n            } else {\n                j = i;\n            }\n            --i;\n        }\n\n        // append punctuations\n        i = 0;\n        j = 1;\n        while (j < newWords.length) {\n            if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) {\n                newWords[i] += newWords[j];\n                newTokens[i] = mergeArrays(newTokens[i], newTokens[j]);\n                newIndices[i] = mergeArrays(newIndices[i], newIndices[j]);\n                newWords[j] = '';\n                newTokens[j] = [];\n                newIndices[j] = [];\n            } else {\n                i = j;\n            }\n            ++j;\n        }\n\n        return [\n            newWords.filter(x => x),\n            newTokens.filter(x => x.length > 0),\n            newIndices.filter(x => x.length > 0),\n        ]\n    }\n}\nexport class CodeGenTokenizer extends PreTrainedTokenizer { }\nexport class CLIPTokenizer extends PreTrainedTokenizer { }\nexport class SiglipTokenizer extends PreTrainedTokenizer { }\n\n/**\n * @todo This model is not yet supported by Hugging Face's \"fast\" tokenizers library (https://github.com/huggingface/tokenizers).\n * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.\n */\nexport class MarianTokenizer extends PreTrainedTokenizer {\n    /**\n     * Create a new MarianTokenizer instance.\n     * @param {Object} tokenizerJSON The JSON of the tokenizer.\n     * @param {Object} tokenizerConfig The config of the tokenizer.\n     */\n    constructor(tokenizerJSON, tokenizerConfig) {\n        super(tokenizerJSON, tokenizerConfig);\n\n        this.languageRegex = /^(>>\\w+<<)\\s*/g;\n\n        this.supported_language_codes = this.model.vocab.filter(\n            x => this.languageRegex.test(x)\n        );\n\n        console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n    }\n\n    /**\n     * Encodes a single text. Overriding this method is necessary since the language codes\n     * must be removed before encoding with sentencepiece model.\n     * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213\n     *\n     * @param {string|null} text The text to encode.\n     * @returns {Array} The encoded tokens.\n     */\n    _encode_text(text) {\n        if (text === null) return null;\n\n        // Check if text starts with language code:\n        const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);\n\n        if (remainder.length === 0) {\n            // No language code, encode normally\n            return super._encode_text(matchInfo);\n\n        } else if (remainder.length === 2) {\n            // Text starts with language code, so we do not encode it with sentencepiece.\n            const [language, text] = remainder;\n\n            if (!this.supported_language_codes.includes(language)) {\n                console.warn(`Unsupported language code \"${language}\" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)\n            }\n            return mergeArrays([language], super._encode_text(text));\n        }\n    }\n\n}\n\nexport class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { }\n\nexport class BlenderbotTokenizer extends PreTrainedTokenizer { }\nexport class BlenderbotSmallTokenizer extends PreTrainedTokenizer { }\n\nexport class SpeechT5Tokenizer extends PreTrainedTokenizer { }\n\nexport class NougatTokenizer extends PreTrainedTokenizer { }\n\nexport class VitsTokenizer extends PreTrainedTokenizer {\n\n    constructor(tokenizerJSON, tokenizerConfig) {\n        super(tokenizerJSON, tokenizerConfig);\n\n        // Custom decoder function\n        this.decoder = new VitsDecoder({});\n    }\n}\n\nexport class CohereTokenizer extends PreTrainedTokenizer { }\n\nexport class MgpstrTokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.\n * The chosen tokenizer class is determined by the type specified in the tokenizer config.\n * \n * @example\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoTokenizer {\n    static TOKENIZER_CLASS_MAPPING = {\n        T5Tokenizer,\n        DistilBertTokenizer,\n        CamembertTokenizer,\n        DebertaTokenizer,\n        DebertaV2Tokenizer,\n        BertTokenizer,\n        HerbertTokenizer,\n        ConvBertTokenizer,\n        RoFormerTokenizer,\n        XLMTokenizer,\n        ElectraTokenizer,\n        MobileBertTokenizer,\n        SqueezeBertTokenizer,\n        AlbertTokenizer,\n        GPT2Tokenizer,\n        BartTokenizer,\n        MBartTokenizer,\n        MBart50Tokenizer,\n        RobertaTokenizer,\n        WhisperTokenizer,\n        CodeGenTokenizer,\n        CLIPTokenizer,\n        SiglipTokenizer,\n        MarianTokenizer,\n        BloomTokenizer,\n        NllbTokenizer,\n        M2M100Tokenizer,\n        LlamaTokenizer,\n        CodeLlamaTokenizer,\n        XLMRobertaTokenizer,\n        MPNetTokenizer,\n        FalconTokenizer,\n        GPTNeoXTokenizer,\n        EsmTokenizer,\n        Wav2Vec2CTCTokenizer,\n        BlenderbotTokenizer,\n        BlenderbotSmallTokenizer,\n        SpeechT5Tokenizer,\n        NougatTokenizer,\n        VitsTokenizer,\n        Qwen2Tokenizer,\n        GemmaTokenizer,\n        Grok1Tokenizer,\n        CohereTokenizer,\n        MgpstrTokenizer,\n\n        // Base case:\n        PreTrainedTokenizer,\n    }\n\n\n    /**\n     * Instantiate one of the tokenizer classes of the library from a pretrained model.\n     * \n     * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object\n     * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n     * \n     * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n     * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.\n     *   Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n     *   user or organization name, like `dbmdz/bert-base-german-cased`.\n     * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.\n     * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n     * \n     * @returns {Promise<PreTrainedTokenizer>} A new instance of the PreTrainedTokenizer class.\n     */\n    static async from_pretrained(pretrained_model_name_or_path, {\n        progress_callback = null,\n        config = null,\n        cache_dir = null,\n        local_files_only = false,\n        revision = 'main',\n        legacy = null,\n    } = {}) {\n\n        const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, {\n            progress_callback,\n            config,\n            cache_dir,\n            local_files_only,\n            revision,\n            legacy,\n        })\n\n        // Some tokenizers are saved with the \"Fast\" suffix, so we remove that if present.\n        const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer';\n\n        let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName];\n        if (!cls) {\n            console.warn(`Unknown tokenizer class \"${tokenizerName}\", attempting to construct from base class.`);\n            cls = PreTrainedTokenizer;\n        }\n        return new cls(tokenizerJSON, tokenizerConfig);\n    }\n}\n", "import { registerKernel } from \"@tensorflow/tfjs-core\";\nimport { MathBackendCPU } from \"@tensorflow/tfjs-backend-cpu/dist/base.js\";\nimport { castConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Cast.js\";\nimport { gatherV2Config } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/GatherV2.js\";\nimport { expandDimsConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/ExpandDims.js\";\nimport { stridedSliceConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/StridedSlice.js\";\nimport { reshapeConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Reshape.js\";\nimport { packConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Pack.js\";\nimport { subConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Sub.js\";\nimport { multiplyConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Multiply.js\";\nimport { addConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Add.js\";\nimport { rangeConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Range.js\";\nimport { meanConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Mean.js\";\nimport { squaredDifferenceConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/SquaredDifference.js\";\nimport { rsqrtConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Rsqrt.js\";\nimport { prodConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Prod.js\";\nimport { concatConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Concat.js\";\nimport { batchMatMulConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/BatchMatMul.js\";\nimport { transposeConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Transpose.js\";\nimport { softmaxConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Softmax.js\";\nimport { erfConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Erf.js\";\nimport { tileConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Tile.js\";\nimport { sumConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Sum.js\";\nimport { minimumConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Minimum.js\";\nimport { maximumConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Maximum.js\";\nimport { realDivConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/RealDiv.js\";\nimport { squareConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Square.js\";\nimport { identityConfig } from \"@tensorflow/tfjs-backend-cpu/dist/kernels/Identity.js\";\n\n// Force MathBackendCPU to be included in the bundle\nconst _unused = MathBackendCPU;\n\n[castConfig, gatherV2Config, expandDimsConfig, stridedSliceConfig, reshapeConfig, packConfig, subConfig, multiplyConfig, addConfig, rangeConfig, meanConfig, squaredDifferenceConfig, rsqrtConfig, prodConfig, concatConfig, batchMatMulConfig, transposeConfig, softmaxConfig, erfConfig, tileConfig, sumConfig, minimumConfig, maximumConfig, realDivConfig, squareConfig, identityConfig].forEach(c => registerKernel(c));\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/*\n * base.ts contains all the exports from tfjs-backend-cpu\n * without auto-kernel registration\n */\nimport {registerBackend} from '@tensorflow/tfjs-core';\nimport {MathBackendCPU} from './backend_cpu';\nimport * as shared from './shared';\n\nexport {MathBackendCPU} from './backend_cpu';\nexport {version as version_cpu} from './version';\nexport {shared};\n\n// Side effects for default initialization of MathBackendCPU\nregisterBackend('cpu', () => new MathBackendCPU(), 1 /* priority */);\n", "/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BackendTimingInfo, buffer, DataStorage, DataType, engine, env, kernel_impls, KernelBackend, Rank, ShapeMap, Tensor, Tensor2D, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nconst whereImpl = kernel_impls.whereImpl;\nimport {assertNotComplex} from './cpu_util';\n\ninterface DataId {}\n\nexport interface TensorData<D extends DataType> {\n  values?: backend_util.BackendValues;\n  dtype: D;\n  // For complex numbers, the real and imaginary parts are stored as their own\n  // individual tensors, with a parent joining the two with the\n  // complexTensorInfos field.\n  complexTensorInfos?: {real: TensorInfo, imag: TensorInfo};\n  // refCount keeps track of how many tensors reference it. Used for memory\n  // management.\n  refCount: number;\n}\n\nexport class MathBackendCPU extends KernelBackend {\n  public blockSize = 48;\n\n  data: DataStorage<TensorData<DataType>>;\n  private firstUse = true;\n  private static nextDataId = 0;\n  private nextDataId(): number {\n    return MathBackendCPU.nextDataId++;\n  }\n\n  constructor() {\n    super();\n    this.data = new DataStorage(this, engine());\n  }\n\n  override write(\n      values: backend_util.BackendValues, shape: number[],\n      dtype: DataType): DataId {\n    if (this.firstUse) {\n      this.firstUse = false;\n      if (env().get('IS_NODE')) {\n        backend_util.warn(\n            '\\n============================\\n' +\n            'Hi, looks like you are running TensorFlow.js in ' +\n            'Node.js. To speed things up dramatically, install our node ' +\n            'backend, visit https://github.com/tensorflow/tfjs-node for more details. ' +\n            '\\n============================');\n      }\n    }\n    const dataId = {id: this.nextDataId()};\n\n    this.data.set(dataId, {values, dtype, refCount: 1});\n\n    return dataId;\n  }\n\n  /**\n   * Create a data bucket in cpu backend.\n   * @param shape Shape of the `TensorInfo`.\n   * @param dtype DType of the `TensorInfo`.\n   * @param values The value of the `TensorInfo` stored as a flattened array.\n   */\n  makeTensorInfo(\n      shape: number[], dtype: DataType,\n      values?: backend_util.BackendValues|string[]): TensorInfo {\n    let outId;\n    if (dtype === 'string' && values != null && values.length > 0 &&\n        util.isString(values[0])) {\n      const encodedValues =\n          (values as unknown as string[]).map(d => util.encodeString(d));\n\n      outId = this.write(encodedValues, shape, dtype);\n    } else {\n      outId = this.write(values as TypedArray, shape, dtype);\n    }\n\n    return {dataId: outId, shape, dtype};\n  }\n\n  /** Return refCount of a `TensorData`. */\n  override refCount(dataId: DataId): number {\n    if (this.data.has(dataId)) {\n      const tensorData = this.data.get(dataId);\n      return tensorData.refCount;\n    }\n    return 0;\n  }\n\n  /** Increase refCount of a `TensorData`. */\n  override incRef(dataId: DataId): void {\n    const tensorData = this.data.get(dataId);\n    tensorData.refCount++;\n  }\n\n  /** Decrease refCount of a `TensorData`. */\n  decRef(dataId: DataId): void {\n    if (this.data.has(dataId)) {\n      const tensorData = this.data.get(dataId);\n      tensorData.refCount--;\n    }\n  }\n\n  override move(\n      dataId: DataId, values: backend_util.BackendValues, shape: number[],\n      dtype: DataType, refCount: number): void {\n    this.data.set(dataId, {values, dtype, refCount});\n  }\n\n  override numDataIds(): number {\n    return this.data.numDataIds();\n  }\n\n  override async read(dataId: DataId): Promise<backend_util.BackendValues> {\n    return this.readSync(dataId);\n  }\n  override readSync(dataId: DataId): backend_util.BackendValues {\n    const {dtype, complexTensorInfos} = this.data.get(dataId);\n\n    if (dtype === 'complex64') {\n      const realValues =\n          this.readSync(complexTensorInfos.real.dataId) as Float32Array;\n      const imagValues =\n          this.readSync(complexTensorInfos.imag.dataId) as Float32Array;\n      return backend_util.mergeRealAndImagArrays(realValues, imagValues);\n    }\n    return util.convertBackendValuesAndArrayBuffer(\n        this.data.get(dataId).values, dtype);\n  }\n\n  bufferSync<R extends Rank, D extends DataType>(t: TensorInfo):\n      TensorBuffer<R, D> {\n    const data = this.readSync(t.dataId);\n    if (t.dtype === 'string') {\n      try {\n        // Decode the bytes into string.\n        const strings = (data as Uint8Array[]).map(d => util.decodeString(d));\n        return buffer(t.shape as ShapeMap[R], t.dtype, strings) as\n            TensorBuffer<R, D>;\n      } catch {\n        throw new Error('Failed to decode encoded string bytes into utf-8');\n      }\n    }\n    return buffer(t.shape as ShapeMap[R], t.dtype, data as TypedArray) as\n        TensorBuffer<R, D>;\n  }\n\n  makeOutput<T extends Tensor>(\n      values: backend_util.BackendValues, shape: number[], dtype: DataType): T {\n    return engine().makeTensorFromTensorInfo(\n               this.makeTensorInfo(shape, dtype, values), this) as T;\n  }\n\n  /**\n   * Dispose the memory if the dataId has 0 refCount. Return true if the memory\n   * is released or memory is not managed in this backend, false if memory is\n   * not cleared.\n   * @param dataId\n   * @oaram force Optional, remove the data regardless of refCount\n   */\n  override disposeData(dataId: DataId, force = false): boolean {\n    if (this.data.has(dataId)) {\n      this.data.get(dataId).refCount--;\n      if (!force && this.data.get(dataId).refCount > 0) {\n        return false;\n      }\n\n      const {complexTensorInfos} = this.data.get(dataId);\n\n      if (complexTensorInfos != null) {\n        this.disposeData(complexTensorInfos.real.dataId, true);\n        this.disposeData(complexTensorInfos.imag.dataId, true);\n      }\n\n      this.data.delete(dataId);\n    }\n    return true;\n  }\n\n  disposeIntermediateTensorInfo(tensorInfo: TensorInfo): void {\n    this.disposeData(tensorInfo.dataId);\n  }\n\n  override async time(f: () => void): Promise<BackendTimingInfo> {\n    const start = util.now();\n    f();\n    const kernelMs = util.now() - start;\n    return {kernelMs};\n  }\n\n  override memory() {\n    return {\n      // Unreliable due to automatic gc. The numbers above are cumulative.\n      unreliable: true,\n      reasons:\n          ['The reported memory is an upper bound. Due to automatic garbage ' +\n           'collection, the true allocated memory may be less.']\n    };\n  }\n\n  where(condition: Tensor): Tensor2D {\n    assertNotComplex([condition], 'where');\n\n    const condVals = this.readSync(condition.dataId) as TypedArray;\n    return whereImpl(condition.shape, condVals);\n  }\n\n  override dispose() {}\n\n  override floatPrecision(): 16|32 {\n    return 32;\n  }\n\n  /** Returns the smallest representable number.  */\n  override epsilon(): number {\n    return super.epsilon();\n  }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nexport function assertNotComplex(\n    tensor: TensorInfo|TensorInfo[], opName: string): void {\n  if (!Array.isArray(tensor)) {\n    tensor = [tensor];\n  }\n  tensor.forEach(t => {\n    if (t != null) {\n      util.assert(\n          t.dtype !== 'complex64',\n          () => `${\n              opName} does not support complex64 tensors in the CPU backend.`);\n    }\n  });\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Add, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc, createComplexBinaryKernelImpl} from '../utils/binary_utils';\n\nexport const addImpl =\n    createSimpleBinaryKernelImpl(((a: number, b: number) => a + b));\nexport const addComplexImpl =\n    createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n      return {real: aReal + bReal, imag: aImag + bImag};\n    }));\n\nexport const add = binaryKernelFunc(Add, addImpl, addComplexImpl);\n\nexport const addConfig: KernelConfig = {\n  kernelName: Add,\n  backendName: 'cpu',\n  kernelFunc: add\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataType, DataValues, NumericDataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {SimpleBinaryKernelImpl, SimpleBinaryOperation} from './binary_types';\n\n/**\n * Template that creates implementation for binary ops. Supports broadcast.\n */\nexport function createSimpleBinaryKernelImpl(op: SimpleBinaryOperation):\n    SimpleBinaryKernelImpl {\n  return (aShape: number[], bShape: number[], aVals: DataValues,\n          bVals: DataValues, dtype: DataType): [TypedArray, number[]] => {\n    const newShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n\n    const resultRank = newShape.length;\n    const resultStrides = util.computeStrides(newShape);\n    const resultSize = util.sizeFromShape(newShape);\n\n    const result =\n        util.getTypedArrayFromDType(dtype as NumericDataType, resultSize);\n\n    const aRank = aShape.length;\n    const bRank = bShape.length;\n\n    const aStrides = util.computeStrides(aShape);\n    const bStrides = util.computeStrides(bShape);\n\n    const aBroadcastDims = backend_util.getBroadcastDims(aShape, newShape);\n    const bBroadcastDims = backend_util.getBroadcastDims(bShape, newShape);\n\n    if (aBroadcastDims.length + bBroadcastDims.length === 0) {\n      for (let i = 0; i < result.length; ++i) {\n        result[i] = op(aVals[i % aVals.length], bVals[i % bVals.length]);\n      }\n    } else {\n      for (let i = 0; i < result.length; ++i) {\n        const loc = util.indexToLoc(i, resultRank, resultStrides);\n\n        const aLoc = loc.slice(-aRank);\n        aBroadcastDims.forEach(d => aLoc[d] = 0);\n        const aIndex = util.locToIndex(aLoc, aRank, aStrides);\n\n        const bLoc = loc.slice(-bRank);\n        bBroadcastDims.forEach(d => bLoc[d] = 0);\n        const bIndex = util.locToIndex(bLoc, bRank, bStrides);\n\n        result[i] = op(aVals[aIndex], bVals[bIndex]);\n      }\n    }\n\n    return [result, newShape];\n  };\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BinaryInputs, DataType, KernelFunc, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {cast} from '../kernels/Cast';\nimport {complex} from '../kernels/Complex';\n\nimport {ComplexBinaryKernelImpl, ComplexBinaryOperation, SimpleBinaryKernelImpl} from './binary_types';\n\n/**\n * Template that creates a `KernelFunc` for binary ops.\n * @param name Kernel name.\n * @param binaryKernelImpl A `SimpleBinaryKernelImpl` for the kernel.\n * @param binaryKernelComplexImpl Optional. If exists, represents a\n *     `ComplexBinaryKernelImpl` for the kernel, will be used when input dtype\n *     is `complex64`.\n * @param dtype Optional. If set, the result has this dtype. Otherwise, the\n *     result has the same dtype as the first input. This is mainly used in\n *     comparison kernels, such as Equal, Less, Greater, etc.\n */\nexport function binaryKernelFunc(\n    name: string, simpleImpl: SimpleBinaryKernelImpl,\n    complexImpl?: ComplexBinaryKernelImpl, dtype?: DataType): KernelFunc {\n  if (complexImpl == null) {\n    return ({inputs, backend}) => {\n      const {a, b} = inputs as BinaryInputs;\n      const cpuBackend = backend as MathBackendCPU;\n\n      assertNotComplex([a, b], name);\n\n      const aVals = cpuBackend.data.get(a.dataId).values as TypedArray;\n      const bVals = cpuBackend.data.get(b.dataId).values as TypedArray;\n\n      const decodedAVals = a.dtype === 'string' ?\n          // tslint:disable-next-line: no-any\n          backend_util.fromUint8ToStringArray(aVals as any as Uint8Array[]) :\n          aVals;\n      const decodedBVals = a.dtype === 'string' ?\n          // tslint:disable-next-line: no-any\n          backend_util.fromUint8ToStringArray(bVals as any as Uint8Array[]) :\n          bVals;\n      const $dtype = dtype || a.dtype;\n\n      const [resultData, resultShape] =\n          simpleImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype);\n\n      return cpuBackend.makeTensorInfo(resultShape, $dtype, resultData);\n    };\n  }\n\n  return ({inputs, backend}) => {\n    const {a, b} = inputs as BinaryInputs;\n    const cpuBackend = backend as MathBackendCPU;\n\n    if (a.dtype === 'complex64' || b.dtype === 'complex64') {\n      const $aComplex = cast(\n          {inputs: {x: a}, backend: cpuBackend, attrs: {dtype: 'complex64'}});\n\n      const $aComplexVals = cpuBackend.data.get($aComplex.dataId);\n\n      const aReal = $aComplexVals.complexTensorInfos.real;\n      const aImag = $aComplexVals.complexTensorInfos.imag;\n\n      const aRealVals =\n          cpuBackend.data.get(aReal.dataId).values as Float32Array;\n      const aImagVals =\n          cpuBackend.data.get(aImag.dataId).values as Float32Array;\n\n      const $bComplex = cast(\n          {inputs: {x: b}, backend: cpuBackend, attrs: {dtype: 'complex64'}});\n\n      const $bComplexVals = cpuBackend.data.get($bComplex.dataId);\n\n      const bReal = $bComplexVals.complexTensorInfos.real;\n      const bImag = $bComplexVals.complexTensorInfos.imag;\n\n      const bRealVals =\n          cpuBackend.data.get(bReal.dataId).values as Float32Array;\n      const bImagVals =\n          cpuBackend.data.get(bImag.dataId).values as Float32Array;\n\n      const [resultRealData, resultImagData, resultShape] = complexImpl(\n          a.shape, b.shape, aRealVals, aImagVals, bRealVals, bImagVals);\n\n      const resultReal =\n          cpuBackend.makeTensorInfo(resultShape, 'float32', resultRealData);\n\n      const resultImag =\n          cpuBackend.makeTensorInfo(resultShape, 'float32', resultImagData);\n\n      const result = complex(\n          {inputs: {real: resultReal, imag: resultImag}, backend: cpuBackend});\n\n      cpuBackend.disposeIntermediateTensorInfo($aComplex);\n      cpuBackend.disposeIntermediateTensorInfo($bComplex);\n      cpuBackend.disposeIntermediateTensorInfo(resultReal);\n      cpuBackend.disposeIntermediateTensorInfo(resultImag);\n\n      return result;\n    } else {\n      const aVals = cpuBackend.data.get(a.dataId).values as TypedArray;\n      const bVals = cpuBackend.data.get(b.dataId).values as TypedArray;\n\n      const $dtype = dtype || a.dtype;\n\n      const [resultData, resultShape] =\n          simpleImpl(a.shape, b.shape, aVals, bVals, $dtype);\n\n      return cpuBackend.makeTensorInfo(resultShape, $dtype, resultData);\n    }\n  };\n}\n\n/**\n * Template that creates the complex type implementation for binary ops.\n * Supports broadcast.\n */\nexport function createComplexBinaryKernelImpl(op: ComplexBinaryOperation):\n    ComplexBinaryKernelImpl {\n  return (aShape: number[], bShape: number[], aRealVals: Float32Array,\n          aImagVals: Float32Array, bRealVals: Float32Array,\n          bImagVals: Float32Array): [TypedArray, TypedArray, number[]] => {\n    const resultShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n    const resultSize = util.sizeFromShape(resultShape);\n    const resultRank = resultShape.length;\n    const resultStrides = util.computeStrides(resultShape);\n\n    const resultRealVals = util.getTypedArrayFromDType('float32', resultSize);\n    const resultImagVals = util.getTypedArrayFromDType('float32', resultSize);\n\n    const aBroadcastDims = backend_util.getBroadcastDims(aShape, resultShape);\n    const bBroadcastDims = backend_util.getBroadcastDims(bShape, resultShape);\n\n    const aVals = backend_util.mergeRealAndImagArrays(aRealVals, aImagVals);\n    const bVals = backend_util.mergeRealAndImagArrays(bRealVals, bImagVals);\n\n    const aRank = aShape.length;\n    const aStrides = util.computeStrides(aShape);\n\n    const bRank = bShape.length;\n    const bStrides = util.computeStrides(bShape);\n\n    if (aBroadcastDims.length + bBroadcastDims.length === 0) {\n      for (let i = 0; i < resultRealVals.length; i++) {\n        const aIdx = i % aVals.length;\n        const bIdx = i % bVals.length;\n\n        const result =\n            op(aVals[aIdx * 2], aVals[aIdx * 2 + 1], bVals[bIdx * 2],\n               bVals[bIdx * 2 + 1]);\n\n        resultRealVals[i] = result.real;\n        resultImagVals[i] = result.imag;\n      }\n    } else {\n      for (let i = 0; i < resultRealVals.length; i++) {\n        const loc = util.indexToLoc(i, resultRank, resultStrides);\n\n        const aLoc = loc.slice(-aRank);\n        aBroadcastDims.forEach(d => aLoc[d] = 0);\n        const aIndex = util.locToIndex(aLoc, aRank, aStrides);\n\n        const bLoc = loc.slice(-bRank);\n        bBroadcastDims.forEach(d => bLoc[d] = 0);\n        const bIndex = util.locToIndex(bLoc, bRank, bStrides);\n\n        const opResult =\n            op(aVals[aIndex * 2], aVals[aIndex * 2 + 1], bVals[bIndex * 2],\n               bVals[bIndex * 2 + 1]);\n\n        resultRealVals[i] = opResult.real;\n        resultImagVals[i] = opResult.imag;\n      }\n    }\n    return [resultRealVals, resultImagVals, resultShape];\n  };\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {Cast, CastAttrs, CastInputs, DataType, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {zeros} from '../utils/zeros_impl';\n\nimport {complex} from './Complex';\nimport {identity} from './Identity';\nimport {real} from './Real';\n\nexport function castImpl(\n    values: TypedArray, shape: number[], inputType: DataType,\n    dtype: DataType): [number[], DataType, TypedArray] {\n  if (dtype === 'int32') {\n    const resultValues = Int32Array.from(values);\n    return [shape, 'int32', resultValues];\n  }\n\n  if (dtype === 'bool') {\n    // This is essentially the result of notEqual(x, 0). We avoid using\n    // kernel notEqual to avoid circular dependency, i.e. binary_utils ->\n    // cast -> notEqual -> binary_utils.\n    const zero = util.toTypedArray([0], inputType);\n\n    const [resultData, resultShape] = createSimpleBinaryKernelImpl(\n        (a, b) => (a !== b) ? 1 : 0)(shape, [], values, zero, 'bool');\n\n    return [resultShape, 'bool', resultData];\n  }\n  throw new Error(`Error in Cast: failed to cast ${inputType} to ${dtype}`);\n}\n\nexport function cast(\n    args: {inputs: CastInputs, backend: MathBackendCPU, attrs: CastAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {dtype} = attrs;\n\n  // Casting to complex64.\n  if (dtype === 'complex64') {\n    if (x.dtype === 'complex64') {\n      return identity({inputs: {x}, backend});\n    }\n\n    const zerosTensorInfo = zeros(backend, x.shape, x.dtype);\n    const floatX = cast({inputs: {x}, backend, attrs: {dtype: 'float32'}});\n\n    const result =\n        complex({inputs: {real: floatX, imag: zerosTensorInfo}, backend});\n\n    backend.disposeIntermediateTensorInfo(zerosTensorInfo);\n    backend.disposeIntermediateTensorInfo(floatX);\n\n    return result;\n  }\n\n  // Casting from complex64\n  if (x.dtype === 'complex64') {\n    const realPart = real({inputs: {input: x}, backend});\n    const result = cast({inputs: {x: realPart}, backend, attrs: {dtype}});\n\n    backend.disposeIntermediateTensorInfo(realPart);\n\n    return result;\n  }\n\n  if (!util.hasEncodingLoss(x.dtype, dtype)) {\n    // We don't change the underlying data, since we cast to higher\n    // precision.\n    const result = identity({inputs: {x}, backend});\n    return {dataId: result.dataId, shape: result.shape, dtype};\n  }\n\n  const values = backend.data.get(x.dataId).values as TypedArray;\n  const [resultShape, resultType, resultData] =\n      castImpl(values, x.shape, x.dtype, dtype);\n  return backend.makeTensorInfo(resultShape, resultType, resultData);\n}\n\nexport const castConfig: KernelConfig = {\n  kernelName: Cast,\n  backendName: 'cpu',\n  kernelFunc: cast as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TensorInfo, util} from '@tensorflow/tfjs-core';\nimport {MathBackendCPU} from '../backend_cpu';\nimport {complex} from '../kernels/Complex';\n\n/**\n * Generates a tensorInfo with all zeros value.\n * @param backend cpu backend.\n * @param shape Shape for the zeros tensor.\n * @param dtype Optional. If set, the result has this dtype.\n */\nexport function zeros(\n    backend: MathBackendCPU, shape: number[],\n    dtype: DataType = 'float32'): TensorInfo {\n  if (dtype === 'complex64') {\n    const real = zeros(backend, shape, 'float32');\n    const imag = zeros(backend, shape, 'float32');\n\n    return complex({inputs: {real, imag}, backend});\n  }\n\n  const values = util.makeZerosTypedArray(util.sizeFromShape(shape), dtype);\n\n  return backend.makeTensorInfo(shape, dtype, values);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Complex, ComplexInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function complex(args: {inputs: ComplexInputs, backend: MathBackendCPU}):\n    TensorInfo {\n  const {inputs, backend} = args;\n  const {real, imag} = inputs;\n\n  const realVals = backend.data.get(real.dataId).values as TypedArray;\n  const imagVals = backend.data.get(imag.dataId).values as TypedArray;\n\n  const complexInfo = backend.makeTensorInfo(real.shape, 'complex64');\n\n  const complex = backend.data.get(complexInfo.dataId);\n\n  // The complex tensor owns the underlying real and imag tensorInfos, only the\n  // complex tensor tracks refCount, when complexData is disposed the\n  // underlying tensorData will be disposed.\n  complex.complexTensorInfos = {\n    real: backend.makeTensorInfo(real.shape, 'float32', realVals),\n    imag: backend.makeTensorInfo(imag.shape, 'float32', imagVals)\n  };\n\n  return complexInfo;\n}\n\nexport const complexConfig: KernelConfig = {\n  kernelName: Complex,\n  backendName: 'cpu',\n  kernelFunc: complex as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Identity, IdentityInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function identity(\n    args: {inputs: IdentityInputs, backend: MathBackendCPU}): TensorInfo {\n  const {inputs, backend} = args;\n  const {x} = inputs;\n\n  backend.incRef(x.dataId);\n\n  return {dataId: x.dataId, shape: x.shape, dtype: x.dtype};\n}\n\nexport const identityConfig: KernelConfig = {\n  kernelName: Identity,\n  backendName: 'cpu',\n  kernelFunc: identity as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Real, RealInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function real(args: {inputs: RealInputs, backend: MathBackendCPU}):\n    TensorInfo {\n  const {inputs, backend} = args;\n  const {input} = inputs;\n\n  const real = backend.data.get(input.dataId).complexTensorInfos.real;\n  const realVal = backend.data.get(real.dataId).values;\n\n  // When complex tensor is disposed, its underlying parts will be disposed too.\n  // Make new tensor out of the real value of the complex. This makes sure the\n  // value is still accessible even if complex tensor is disposed.\n  return backend.makeTensorInfo(real.shape, real.dtype, realVal);\n}\n\nexport const realConfig: KernelConfig = {\n  kernelName: Real,\n  backendName: 'cpu',\n  kernelFunc: real as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {util} from '@tensorflow/tfjs-core';\n\nimport {SimpleUnaryImpl, SimpleUnaryOperation} from './unary_types';\n\n/**\n * Template that creates implementation for unary op.\n */\nexport function createSimpleUnaryImpl<I extends number | string = number,\n  O extends number | string = number>(op: SimpleUnaryOperation<I, O>):\n    SimpleUnaryImpl<I, O> {\n  return (values, dtype, attrs) => {\n    const newValues =\n        util.getArrayFromDType(dtype, values.length);\n    for (let i = 0; i < values.length; ++i) {\n      newValues[i] = op(values[i], attrs);\n    }\n    return newValues;\n  };\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataTypeFor, KernelFunc, UnaryInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {createSimpleUnaryImpl} from './unary_impl';\n\nimport {SimpleUnaryImpl, SimpleUnaryOperation} from './unary_types';\n\n/**\n * Template that creates a `KernelFunc` for unary ops.\n * @param name Kernel name.\n * @param op A `SimpleUnaryOperation` for the kernel.\n * @param dtype Optional. If set, the result has this dtype. Otherwise, the\n *     result has the same dtype as the input. This is mainly used in certain\n *     kernels that return bool type, such as isFinite, isInf, etc.\n */\nexport function unaryKernelFunc<I extends number | string = number,\n  O extends number | string = number>(\n  name: string, op: SimpleUnaryOperation<I, O>,\n  dtype?: DataTypeFor<O>): KernelFunc {\n\n  const impl = createSimpleUnaryImpl<I, O>(op);\n\n  return unaryKernelFuncFromImpl<I, O>(name, impl, dtype);\n}\n\n/**\n * Template that creates a `KernelFunc` for unary ops from the given\n * `SimpleUnaryImpl`..\n * @param name Kernel name.\n * @param unaryImpl A `SimpleUnaryImpl` that implements the op.\n * @param dtype Optional. If set, the result has this dtype. Otherwise, the\n *     result has the same dtype as the input. This is mainly used in certain\n *     kernels that return bool type, such as isFinite, isInf, etc.\n */\nexport function unaryKernelFuncFromImpl<I extends number | string = number,\n  O extends number | string = number>(\n  name: string, unaryImpl: SimpleUnaryImpl<I, O>,\n  dtype?: DataTypeFor<O>): KernelFunc {\n\n  return ({inputs, attrs, backend}) => {\n    const {x} = inputs as UnaryInputs;\n    assertNotComplex(x, name);\n\n    const cpuBackend = backend as MathBackendCPU;\n    const values = cpuBackend.data.get(x.dataId).values;\n    let decoded: ArrayLike<I>;\n    if (x.dtype === 'string') {\n      if (!Array.isArray(values)) {\n        throw new Error('String tensor\\'s value was not an instance of Array');\n      }\n      decoded = backend_util.fromUint8ToStringArray(values) as unknown as\n        ArrayLike<I>;\n    } else {\n      decoded = values as unknown as ArrayLike<I>;\n    }\n\n    const $dtype = dtype || x.dtype as DataTypeFor<O>;\n    const newValues = unaryImpl(decoded, $dtype, attrs);\n    return cpuBackend.makeTensorInfo(x.shape, $dtype, newValues);\n  };\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BackendValues, DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function concatImpl(\n    inputs: Array<{vals: BackendValues, shape: number[]}>, outShape: number[],\n    dtype: DataType, simplyConcat: boolean): TypedArray|string[] {\n  const outVals = util.getArrayFromDType(dtype, util.sizeFromShape(outShape));\n\n  if (simplyConcat && dtype !== 'string') {\n    // Use built-in TypedArray.set() method for speed.\n    let offset = 0;\n    inputs.forEach(input => {\n      const size = util.sizeFromShape(input.shape);\n\n      (outVals as TypedArray).set(input.vals as TypedArray, offset);\n      offset += size;\n    });\n  } else {\n    let colOffset = 0;\n\n    inputs.forEach(input => {\n      const decodedData = dtype === 'string' ?\n          backend_util.fromUint8ToStringArray(input.vals as Uint8Array[]) :\n          input.vals as TypedArray;\n\n      let tIdx = 0;\n\n      for (let row = 0; row < input.shape[0]; ++row) {\n        const resIdx = row * outShape[1] + colOffset;\n        for (let col = 0; col < input.shape[1]; ++col) {\n          outVals[resIdx + col] = decodedData[tIdx++];\n        }\n      }\n\n      colOffset += input.shape[1];\n    });\n  }\n\n  return outVals;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Exp, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const expImpl = createSimpleUnaryImpl((xi) => Math.exp(xi));\nexport const exp = unaryKernelFuncFromImpl(Exp, expImpl, 'float32');\n\nexport const expConfig: KernelConfig = {\n  kernelName: Exp,\n  backendName: 'cpu',\n  kernelFunc: exp,\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, DataType, Rank, TensorBuffer} from '@tensorflow/tfjs-core';\n\nexport function gatherV2Impl<R extends Rank, D extends DataType>(\n    xBuf: TensorBuffer<R, D>, indicesBuf: TensorBuffer<R, D>,\n    flattenOutputShape: number[]): TensorBuffer<R, D> {\n  const outBuf = buffer(flattenOutputShape, xBuf.dtype);\n  for (let i = 0; i < outBuf.size; ++i) {\n    const newLoc = outBuf.indexToLoc(i);\n\n    const originalLoc: number[] = newLoc.slice();\n    const batchIdx = originalLoc[0];\n    const indicesIdx = originalLoc[2];\n    const indicesIndex = indicesBuf.locToIndex([batchIdx, indicesIdx]);\n    originalLoc[2] = indicesBuf.values[indicesIndex] as number;\n\n    const originalIndex = xBuf.locToIndex(originalLoc);\n\n    if (0 <= originalIndex && originalIndex < xBuf.values.length) {\n      outBuf.values[i] = xBuf.values[originalIndex];\n    } // Else, index is out of bounds, so leave the default zero val in outBuf.\n  }\n\n  return outBuf as TensorBuffer<R, D>;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, NumericDataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function maxImpl(\n    aVals: TypedArray, reduceSize: number, outShape: number[],\n    dtype: DataType): TypedArray {\n  const vals = util.getTypedArrayFromDType(\n      dtype as NumericDataType, util.sizeFromShape(outShape));\n\n  for (let i = 0; i < vals.length; ++i) {\n    const offset = i * reduceSize;\n    let max = aVals[offset];\n    for (let j = 0; j < reduceSize; ++j) {\n      const value = aVals[offset + j];\n      if (Number.isNaN(value) ||\n          value > max) {  // comparison with NaN always return false\n        max = value;\n      }\n    }\n    vals[i] = max;\n  }\n  return vals;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Maximum} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const maximumImpl = createSimpleBinaryKernelImpl(\n    ((aValue, bValue) => Math.max(aValue as number, bValue as number)));\nexport const maximum = binaryKernelFunc(Maximum, maximumImpl);\n\nexport const maximumConfig: KernelConfig = {\n  kernelName: Maximum,\n  backendName: 'cpu',\n  kernelFunc: maximum\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Minimum} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const minimumImpl = createSimpleBinaryKernelImpl(\n    ((aValue, bValue) => Math.min(aValue as number, bValue as number)));\nexport const minimum = binaryKernelFunc(Minimum, minimumImpl);\n\nexport const minimumConfig: KernelConfig = {\n  kernelName: Minimum,\n  backendName: 'cpu',\n  kernelFunc: minimum\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Multiply} from '@tensorflow/tfjs-core';\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc, createComplexBinaryKernelImpl} from '../utils/binary_utils';\n\nexport const multiplyImpl = createSimpleBinaryKernelImpl(\n    ((aValue: number, bValue: number) => aValue * bValue));\nexport const multiplyComplexImpl =\n    createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n      return {\n        real: aReal * bReal - aImag * bImag,\n        imag: aReal * bImag + aImag * bReal\n      };\n    }));\n\nexport const multiply =\n    binaryKernelFunc(Multiply, multiplyImpl, multiplyComplexImpl);\n\nexport const multiplyConfig: KernelConfig = {\n  kernelName: Multiply,\n  backendName: 'cpu',\n  kernelFunc: multiply\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, DataType, KernelConfig, KernelFunc, Prod, ProdAttrs, ProdInputs, TensorInfo, TypedArray, upcastType, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {transpose} from './Transpose';\n\nexport function prodImpl(\n    xShape: number[], xDtype: DataType, xVals: TypedArray,\n    reductionAxes: number[]):\n    {outVals: TypedArray, outShape: number[], outDtype: DataType} {\n  const [outShape, reduceShape] =\n      backend_util.computeOutAndReduceShapes(xShape, reductionAxes);\n  const outDtype = upcastType(xDtype, 'int32');\n  const outVals = util.makeZerosTypedArray(\n                      util.sizeFromShape(outShape), outDtype) as TypedArray;\n  const reduceSize = util.sizeFromShape(reduceShape);\n\n  for (let i = 0; i < outVals.length; ++i) {\n    const offset = i * reduceSize;\n    let prod = 1;\n    for (let j = 0; j < reduceSize; ++j) {\n      prod *= xVals[offset + j];\n    }\n    outVals[i] = prod;\n  }\n\n  return {outVals, outShape, outDtype};\n}\n\nexport function prod(\n    args: {inputs: ProdInputs, backend: MathBackendCPU, attrs: ProdAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {axis, keepDims} = attrs;\n\n  assertNotComplex(x, 'prod');\n\n  const xRank = x.shape.length;\n  const axes = util.parseAxisParam(axis, x.shape);\n\n  const permutation = backend_util.getAxesPermutation(axes, xRank);\n  let reductionAxes = axes;\n  let permutedX = x;\n  const intermediateTensorInfos = [];\n  if (permutation != null) {\n    permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n    intermediateTensorInfos.push(permutedX);\n    reductionAxes = backend_util.getInnerMostAxes(reductionAxes.length, xRank);\n  }\n\n  const xVals = backend.data.get(permutedX.dataId).values as TypedArray;\n  const {outVals, outShape, outDtype} =\n      prodImpl(permutedX.shape, permutedX.dtype, xVals, reductionAxes);\n\n  let resultShape = outShape;\n  if (keepDims) {\n    resultShape = backend_util.expandShapeToKeepDim(outShape, axes);\n  }\n\n  intermediateTensorInfos.forEach(\n      t => backend.disposeIntermediateTensorInfo(t));\n\n  return backend.makeTensorInfo(resultShape, outDtype, outVals);\n}\n\nexport const prodConfig: KernelConfig = {\n  kernelName: Prod,\n  backendName: 'cpu',\n  kernelFunc: prod as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Transpose, TransposeAttrs, TransposeInputs, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {transposeImpl} from './Transpose_impl';\n\nexport function transpose(args: {\n  inputs: TransposeInputs,\n  attrs: TransposeAttrs,\n  backend: MathBackendCPU\n}): TensorInfo {\n  const {inputs, attrs, backend} = args;\n  const {x} = inputs;\n  const {perm} = attrs;\n\n  assertNotComplex(x, 'transpose');\n\n  const xRank = x.shape.length;\n\n  const newShape: number[] = new Array(xRank);\n  for (let i = 0; i < newShape.length; i++) {\n    newShape[i] = x.shape[perm[i]];\n  }\n\n  const values = backend.data.get(x.dataId).values as TypedArray;\n  const result = transposeImpl(values, x.shape, x.dtype, perm, newShape);\n\n  const dataId = backend.write(result, newShape, x.dtype);\n  return {dataId, shape: newShape, dtype: x.dtype};\n}\n\nexport const transposeConfig: KernelConfig = {\n  kernelName: Transpose,\n  backendName: 'cpu',\n  kernelFunc: transpose as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, NumericDataType, TypedArray} from '@tensorflow/tfjs-core';\nimport {util} from '@tensorflow/tfjs-core';\n\nexport function transposeImpl(\n    xVals: TypedArray, xShape: number[], dtype: DataType, perm: number[],\n    newShape: number[]): TypedArray {\n  const xRank = xShape.length;\n  const xSize = util.sizeFromShape(xShape);\n  const xStrides = util.computeStrides(xShape);\n  const newStrides = util.computeStrides(newShape);\n\n  const result = util.getTypedArrayFromDType(\n      dtype as NumericDataType, util.sizeFromShape(newShape));\n\n  for (let i = 0; i < xSize; ++i) {\n    const loc = util.indexToLoc(i, xRank, xStrides);\n\n    // Permute location.\n    const newLoc: number[] = new Array(loc.length);\n    for (let i = 0; i < newLoc.length; i++) {\n      newLoc[i] = loc[perm[i]];\n    }\n\n    const newIndex = util.locToIndex(newLoc, xRank, newStrides);\n    result[newIndex] = xVals[i];\n  }\n  return result;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataTypeMap, util} from '@tensorflow/tfjs-core';\n\nexport function rangeImpl(\n    start: number, stop: number, step: number,\n    dtype: 'float32'|'int32'): DataTypeMap['float32' | 'int32'] {\n  const sameStartStop = start === stop;\n  const increasingRangeNegativeStep = start < stop && step < 0;\n  const decreasingRangePositiveStep = stop < start && step > 1;\n\n  if (sameStartStop || increasingRangeNegativeStep ||\n      decreasingRangePositiveStep) {\n    return util.makeZerosTypedArray(0, dtype);\n  }\n\n  const numElements = Math.abs(Math.ceil((stop - start) / step));\n  const values = util.makeZerosTypedArray(numElements, dtype);\n\n  if (stop < start && step === 1) {\n    // Auto adjust the step's sign if it hasn't been set\n    // (or was set to 1)\n    step = -1;\n  }\n\n  values[0] = start;\n  for (let i = 1; i < values.length; i++) {\n    values[i] = values[i - 1] + step;\n  }\n  return values;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Rsqrt} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const rsqrtImpl = createSimpleUnaryImpl((xi) => 1 / Math.sqrt(xi));\nexport const rsqrt = unaryKernelFuncFromImpl(Rsqrt, rsqrtImpl);\n\nexport const rsqrtConfig: KernelConfig = {\n  kernelName: Rsqrt,\n  backendName: 'cpu',\n  kernelFunc: rsqrt,\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, BackendValues, buffer, DataType, KernelConfig, KernelFunc, Slice, slice_util, SliceAttrs, SliceInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function sliceImpl(\n    vals: BackendValues, begin: number[], size: number[], shape: number[],\n    dtype: DataType): BackendValues {\n  const isContinous = slice_util.isSliceContinous(shape, begin, size);\n  const length = util.sizeFromShape(size);\n  const xStrides = util.computeStrides(shape);\n\n  if (isContinous) {\n    const flatOffset = slice_util.computeFlatOffset(begin, xStrides);\n\n    if (dtype === 'string') {\n      return (vals as Uint8Array[]).slice(flatOffset, flatOffset + length);\n    }\n\n    return (vals as TypedArray).subarray(flatOffset, flatOffset + length);\n  }\n\n  const decodedData = dtype === 'string' ?\n      backend_util.fromUint8ToStringArray(vals as Uint8Array[]) :\n      vals as TypedArray;\n\n  const inBuf = buffer(shape, dtype, decodedData);\n  const outBuf = buffer(size, dtype);\n  for (let i = 0; i < outBuf.size; ++i) {\n    const outLoc = outBuf.indexToLoc(i);\n    const inLoc = outLoc.map((idx: number, j) => idx + begin[j]);\n    outBuf.set(inBuf.get(...inLoc), ...outLoc);\n  }\n\n  if (dtype === 'string') {\n    return backend_util.fromStringArrayToUint8(outBuf.values as string[]);\n  }\n  return outBuf.values as TypedArray;\n}\n\nexport function slice(\n    args: {inputs: SliceInputs, backend: MathBackendCPU, attrs: SliceAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {begin, size} = attrs;\n\n  assertNotComplex(x, 'slice');\n\n  const [$begin, $size] = slice_util.parseSliceParams(x, begin, size);\n  slice_util.assertParamsValid(x, $begin, $size);\n\n  const vals = backend.data.get(x.dataId).values;\n  const outVals = sliceImpl(vals, $begin, $size, x.shape, x.dtype);\n  return backend.makeTensorInfo($size, x.dtype, outVals);\n}\n\nexport const sliceConfig: KernelConfig = {\n  kernelName: Slice,\n  backendName: 'cpu',\n  kernelFunc: slice as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, SquaredDifference} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const squaredDifferenceImpl =\n    createSimpleBinaryKernelImpl(((a: number, b: number) => {\n      const diff = a - b;\n      return diff * diff;\n    }));\nexport const squaredDifference =\n    binaryKernelFunc(SquaredDifference, squaredDifferenceImpl);\n\nexport const squaredDifferenceConfig: KernelConfig = {\n  kernelName: SquaredDifference,\n  backendName: 'cpu',\n  kernelFunc: squaredDifference\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, Rank, TensorBuffer} from '@tensorflow/tfjs-core';\n\nexport function stridedSliceImpl<R extends Rank>(\n    outShape: number[], xBuf: TensorBuffer<R>, strides: number[],\n    begin: number[]): TensorBuffer<R> {\n  const outBuf = buffer(outShape, xBuf.dtype);\n\n  for (let i = 0; i < outBuf.size; i++) {\n    const loc = outBuf.indexToLoc(i);\n\n    const newLoc: number[] = new Array(loc.length);\n    for (let j = 0; j < newLoc.length; j++) {\n      newLoc[j] = loc[j] * strides[j] + begin[j];\n    }\n    outBuf.set(xBuf.get(...newLoc), ...loc);\n  }\n\n  return outBuf as TensorBuffer<R>;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, Sub} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc, createComplexBinaryKernelImpl} from '../utils/binary_utils';\n\nexport const subImpl = createSimpleBinaryKernelImpl(\n    ((aValue: number, bValue: number) => aValue - bValue));\nexport const subComplexImpl =\n    createComplexBinaryKernelImpl(((aReal, aImag, bReal, bImag) => {\n      return {real: aReal - bReal, imag: aImag - bImag};\n    }));\nexport const sub = binaryKernelFunc(Sub, subImpl, subComplexImpl);\n\nexport const subConfig: KernelConfig = {\n  kernelName: Sub,\n  backendName: 'cpu',\n  kernelFunc: sub\n};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, DataType, Rank, TensorBuffer} from '@tensorflow/tfjs-core';\n\n/**\n * An implementation of the tile kernel shared between webgl and cpu for string\n * tensors only.\n */\n\nexport function tileImpl<R extends Rank>(\n    xBuf: TensorBuffer<R, DataType>,\n    reps: number[]): TensorBuffer<R, DataType> {\n  const newShape: number[] = new Array(xBuf.rank);\n  for (let i = 0; i < newShape.length; i++) {\n    newShape[i] = xBuf.shape[i] * reps[i];\n  }\n  const result = buffer(newShape, xBuf.dtype);\n  for (let i = 0; i < result.values.length; ++i) {\n    const newLoc = result.indexToLoc(i);\n\n    const originalLoc: number[] = new Array(xBuf.rank);\n    for (let j = 0; j < originalLoc.length; j++) {\n      originalLoc[j] = newLoc[j] % xBuf.shape[j];\n    }\n\n    const originalIndex = xBuf.locToIndex(originalLoc);\n\n    result.values[i] = xBuf.values[originalIndex];\n  }\n  return result as TensorBuffer<R, DataType>;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, GatherV2, GatherV2Attrs, GatherV2Inputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {gatherV2Impl} from './GatherV2_impl';\nimport {reshape} from './Reshape';\n\nexport function gatherV2(args: {\n  inputs: GatherV2Inputs,\n  backend: MathBackendCPU,\n  attrs: GatherV2Attrs\n}): TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x, indices} = inputs;\n  const {axis, batchDims} = attrs;\n\n  assertNotComplex([x, indices], 'gatherV2');\n\n  // Throw error when any index is out of bound.\n  const parsedAxis = util.parseAxisParam(axis, x.shape)[0];\n  const indicesVals = backend.data.get(indices.dataId).values as TypedArray;\n  const axisDim = x.shape[parsedAxis];\n  for (let i = 0; i < indicesVals.length; ++i) {\n    const index = indicesVals[i];\n    util.assert(\n        index <= axisDim - 1 && index >= 0,\n        () =>\n            `GatherV2: the index value ${index} is not in [0, ${axisDim - 1}]`);\n  }\n\n  let $batchDims = batchDims;\n\n  if (batchDims == null) {\n    $batchDims = 0;\n  }\n\n  const indicesSize = util.sizeFromShape(indices.shape);\n\n  const shapeInfo = backend_util.segment_util.collectGatherOpShapeInfo(\n      x, indices, parsedAxis, $batchDims);\n\n  const flattenX = reshape({\n    inputs: {x},\n    backend,\n    attrs: {\n      shape: [\n        shapeInfo.batchSize, shapeInfo.outerSize, shapeInfo.dimSize,\n        shapeInfo.sliceSize\n      ]\n    }\n  });\n\n  const flattenIndex = reshape({\n    inputs: {x: indices},\n    backend,\n    attrs: {shape: [shapeInfo.batchSize, indicesSize / shapeInfo.batchSize]}\n  });\n\n  const flattenOutputShape = [\n    shapeInfo.batchSize, shapeInfo.outerSize, indicesSize / shapeInfo.batchSize,\n    shapeInfo.sliceSize\n  ];\n\n  const indicesBuf = backend.bufferSync(flattenIndex);\n  const xBuf = backend.bufferSync(flattenX);\n  const outBuf = gatherV2Impl(xBuf, indicesBuf, flattenOutputShape);\n\n  backend.disposeIntermediateTensorInfo(flattenX);\n  backend.disposeIntermediateTensorInfo(flattenIndex);\n\n  return backend.makeTensorInfo(\n      shapeInfo.outputShape, outBuf.dtype, outBuf.values);\n}\n\nexport const gatherV2Config: KernelConfig = {\n  kernelName: GatherV2,\n  backendName: 'cpu',\n  kernelFunc: gatherV2 as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Reshape, ReshapeAttrs, ReshapeInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function reshape(\n    args:\n        {inputs: ReshapeInputs, backend: MathBackendCPU, attrs: ReshapeAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {shape} = attrs;\n\n  const xSize = util.sizeFromShape(x.shape);\n  const $shape = util.inferFromImplicitShape(shape, xSize);\n  const $xSize = util.sizeFromShape($shape);\n\n  util.assert(\n      xSize === $xSize,\n      () => `The new shape (${$shape}) has ${$xSize} elements and the old ` +\n          `shape (${x.shape}) has ${xSize} elements. The new shape and old ` +\n          `shape must have the same number of elements.`);\n\n  backend.incRef(x.dataId);\n\n  const xData = backend.data.get(x.dataId);\n\n  if (xData.complexTensorInfos != null) {\n    const real = xData.complexTensorInfos.real;\n    const imag = xData.complexTensorInfos.imag;\n\n    real.shape = $shape;\n    imag.shape = $shape;\n  }\n\n  return {dataId: x.dataId, shape: $shape, dtype: x.dtype};\n}\n\nexport const reshapeConfig: KernelConfig = {\n  kernelName: Reshape,\n  backendName: 'cpu',\n  kernelFunc: reshape as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {reshape} from './Reshape';\n\nexport function expandDims(args: {\n  inputs: ExpandDimsInputs,\n  backend: MathBackendCPU,\n  attrs: ExpandDimsAttrs\n}): TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {input} = inputs;\n  const {dim} = attrs;\n\n  const inputRank = input.shape.length;\n  const newShape = input.shape.slice();\n  let $dim = dim;\n  if (dim < 0) {\n    // Negative value is counted from the tail of rank.\n    util.assert(\n        -(inputRank + 1) <= dim,\n        () => `Axis must be in the interval [${- (inputRank + 1)}, ${\n            inputRank}]`);\n    $dim = inputRank + dim + 1;\n  }\n  newShape.splice($dim, 0, 1);\n\n  return reshape({inputs: {x: input}, backend, attrs: {shape: newShape}});\n}\n\nexport const expandDimsConfig: KernelConfig = {\n  kernelName: ExpandDims,\n  backendName: 'cpu',\n  kernelFunc: expandDims as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Rank, slice_util, StridedSlice, StridedSliceAttrs, StridedSliceInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\nimport {stridedSliceImpl} from './StridedSlice_impl';\n\nexport function stridedSlice(args: {\n  inputs: StridedSliceInputs,\n  backend: MathBackendCPU,\n  attrs: StridedSliceAttrs\n}): TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {\n    begin,\n    end,\n    strides,\n    beginMask,\n    endMask,\n    ellipsisMask,\n    newAxisMask,\n    shrinkAxisMask\n  } = attrs;\n\n  assertNotComplex(x, 'stridedSlice');\n\n  const {\n    finalShapeSparse,\n    finalShape,\n    isIdentity,\n    sliceDim0,\n    isSimpleSlice,\n    begin: $begin,\n    end: $end,\n    strides: $strides\n  } =\n      slice_util.sliceInfo(\n          x.shape, begin, end, strides, beginMask, endMask, ellipsisMask,\n          newAxisMask, shrinkAxisMask);\n\n  let result;\n\n  // ref:\n  // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/strided_slice_op.cc\n  if (isIdentity) {\n    // Optimization #1, slice is a no-op plus reshape\n    result = reshape({inputs: {x}, backend, attrs: {shape: finalShape}});\n  } else if (sliceDim0 || isSimpleSlice) {\n    // Optimization #2, slice is memory contiguous (only occurs in dim 0)\n    util.assert(\n        x.shape.length >= 1,\n        () => `Input must have rank at least 1, got: ${x.shape.length}`);\n\n    const size = slice_util.computeOutShape($begin, $end, $strides);\n    // To tolerate begin[0] > end[0] (a 0-output slice), we min(begin, end).\n    const sliced = slice({inputs: {x}, backend, attrs: {begin: $begin, size}});\n    result =\n        reshape({inputs: {x: sliced}, backend, attrs: {shape: finalShape}});\n    backend.disposeIntermediateTensorInfo(sliced);\n  } else {\n    const xBuf = backend.bufferSync<Rank, 'float32'>(x);\n    const outBuf = stridedSliceImpl(finalShapeSparse, xBuf, $strides, $begin);\n\n    result = backend.makeTensorInfo(finalShape, outBuf.dtype, outBuf.values);\n  }\n\n  return result;\n}\n\nexport const stridedSliceConfig: KernelConfig = {\n  kernelName: StridedSlice,\n  backendName: 'cpu',\n  kernelFunc: stridedSlice as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Pack, PackAttrs, PackInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {concat} from './Concat';\nimport {expandDims} from './ExpandDims';\n\nexport function pack(\n    args: {inputs: PackInputs, backend: MathBackendCPU, attrs: PackAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {axis} = attrs;\n\n  if (inputs.length === 1) {\n    return expandDims(\n        {inputs: {input: inputs[0]}, backend, attrs: {dim: axis}});\n  }\n\n  const shape = inputs[0].shape;\n  const dtype = inputs[0].dtype;\n\n  inputs.forEach(t => {\n    util.assertShapesMatch(\n        shape, t.shape,\n        'All tensors passed to stack must have matching shapes');\n    util.assert(\n        dtype === t.dtype,\n        () => 'All tensors passed to stack must have matching dtypes');\n  });\n\n  const intermediateTensorInfos: TensorInfo[] = [];\n  const expandedTensors = inputs.map(t => {\n    const expandedT =\n        expandDims({inputs: {input: t}, backend, attrs: {dim: axis}});\n    intermediateTensorInfos.push(expandedT);\n    return expandedT;\n  });\n\n  const result = concat({inputs: expandedTensors, backend, attrs: {axis}});\n\n  intermediateTensorInfos.forEach(\n      t => backend.disposeIntermediateTensorInfo(t));\n\n  return result;\n}\n\nexport const packConfig: KernelConfig = {\n  kernelName: Pack,\n  backendName: 'cpu',\n  kernelFunc: pack as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Concat, ConcatAttrs, ConcatInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {complex} from './Complex';\nimport {concatImpl} from './Concat_impl';\nimport {identity} from './Identity';\nimport {imag} from './Imag';\nimport {real} from './Real';\nimport {reshape} from './Reshape';\n\nexport function concat(\n    args: {inputs: ConcatInputs, backend: MathBackendCPU, attrs: ConcatAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {axis} = attrs;\n\n  const $axis = util.parseAxisParam(axis, inputs[0].shape)[0];\n\n  const shapes = inputs.map(t => t.shape);\n  backend_util.assertParamsConsistent(shapes, $axis);\n\n  let outShape = backend_util.computeOutShape(inputs.map(t => t.shape), $axis);\n\n  if (util.sizeFromShape(outShape) === 0) {\n    return backend.makeTensorInfo(outShape, inputs[0].dtype, []);\n  }\n\n  // Keep only non-empty tensors (ignore tensors with 0 in their shape).\n  const $inputs = inputs.filter(t => util.sizeFromShape(t.shape) > 0);\n  if ($inputs.length === 1) {\n    return identity({inputs: {x: $inputs[0]}, backend});\n  }\n\n  if ($inputs[0].dtype === 'complex64') {\n    const reals = $inputs.map((t) => real({inputs: {input: t}, backend}));\n    const imags = $inputs.map((t) => imag({inputs: {input: t}, backend}));\n\n    const realConcated = concat({inputs: reals, backend, attrs: {axis: $axis}});\n    const imagConcated = concat({inputs: imags, backend, attrs: {axis: $axis}});\n\n    const result =\n        complex({inputs: {real: realConcated, imag: imagConcated}, backend});\n\n    reals.forEach(r => backend.disposeIntermediateTensorInfo(r));\n    imags.forEach(i => backend.disposeIntermediateTensorInfo(i));\n    backend.disposeIntermediateTensorInfo(realConcated);\n    backend.disposeIntermediateTensorInfo(imagConcated);\n\n    return result;\n  }\n\n  // Any concat of n-dimensional tensors across any axis can be reduced to\n  // a concatenation of two-dimensional tensors across the axis 1 by first\n  // partitioning the axes of the original tensors into those less than the\n  // axis to be concatenated and the rest. Then reshape the tensors\n  // into a two-dimensional tensor by collapsing these two sets of axes and\n  // concatenate the resulting matrices across the axis 1, finally reshaping\n  // the result to have the proper shape.\n  const inputs2D = $inputs.map(t => {\n    const innerSize = util.sizeFromShape(t.shape.slice($axis));\n    const shape = [-1, innerSize];\n    return reshape({inputs: {x: t}, backend, attrs: {shape}});\n  });\n\n  const inputsValShapes = inputs2D.map(t => {\n    return {vals: backend.data.get(t.dataId).values, shape: t.shape};\n  });\n\n  // Concats 2d tensors along axis=1.\n  outShape =\n      backend_util.computeOutShape(inputs2D.map(t => t.shape), 1 /* axis */);\n  const simplyConcat = inputs2D[0].shape[0] === 1;\n  const outVals =\n      concatImpl(inputsValShapes, outShape, inputs[0].dtype, simplyConcat);\n\n  const finalOutShape =\n      backend_util.computeOutShape($inputs.map(t => t.shape), $axis);\n\n  const outInfo =\n      backend.makeTensorInfo(finalOutShape, inputs[0].dtype, outVals);\n\n  inputs2D.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n  return outInfo;\n}\n\nexport const concatConfig: KernelConfig = {\n  kernelName: Concat,\n  backendName: 'cpu',\n  kernelFunc: concat as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Imag, ImagInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function imag(args: {inputs: ImagInputs, backend: MathBackendCPU}):\n    TensorInfo {\n  const {inputs, backend} = args;\n  const {input} = inputs;\n\n  const imag = backend.data.get(input.dataId).complexTensorInfos.imag;\n  const imagVal = backend.data.get(imag.dataId).values;\n\n  // When complex tensor is disposed, its underlying parts will be disposed too.\n  // Make new tensor out of the imag value of the complex. This makes sure the\n  // value is still accessible even if complex tensor is disposed.\n  return backend.makeTensorInfo(imag.shape, imag.dtype, imagVal);\n}\n\nexport const imagConfig: KernelConfig = {\n  kernelName: Imag,\n  backendName: 'cpu',\n  kernelFunc: imag as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, Range, RangeAttrs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {rangeImpl} from './Range_impl';\n\nexport function range(args: {backend: MathBackendCPU, attrs: RangeAttrs}):\n    TensorInfo {\n  const {backend, attrs} = args;\n  const {start, stop, dtype, step} = attrs;\n\n  const values = rangeImpl(start, stop, step, dtype);\n  return backend.makeTensorInfo([values.length], dtype, values);\n}\n\nexport const rangeConfig: KernelConfig = {\n  kernelName: Range,\n  backendName: 'cpu',\n  kernelFunc: range as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Mean, MeanAttrs, MeanInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {cast} from './Cast';\nimport {div} from './RealDiv';\nimport {sum} from './Sum';\n\nexport function mean(\n    args: {inputs: MeanInputs, backend: MathBackendCPU, attrs: MeanAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {axis, keepDims} = attrs;\n\n  const axes = util.parseAxisParam(axis, x.shape);\n  const shapes = backend_util.computeOutAndReduceShapes(x.shape, axes);\n  const reduceShape = shapes[1];\n  const reduceSize = util.sizeFromShape(reduceShape);\n  const toDispose = [];\n  const reduceSizeScalar =\n      backend.makeTensorInfo([], 'float32', new Float32Array([reduceSize]));\n  toDispose.push(reduceSizeScalar);\n\n  const $x = cast({inputs: {x}, backend, attrs: {dtype: 'float32'}});\n  toDispose.push($x);\n\n  const res =\n      div({inputs: {a: $x, b: reduceSizeScalar}, backend}) as TensorInfo;\n  toDispose.push(res);\n\n  const result = sum({inputs: {x: res}, backend, attrs: {axis, keepDims}});\n\n  toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n  return result;\n}\n\nexport const meanConfig: KernelConfig = {\n  kernelName: Mean,\n  backendName: 'cpu',\n  kernelFunc: mean as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, RealDiv} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const realDivImpl =\n    createSimpleBinaryKernelImpl((a: number, b: number) => a / b);\nexport const div = binaryKernelFunc(RealDiv, realDivImpl);\n\nexport const realDivConfig: KernelConfig = {\n  kernelName: RealDiv,\n  backendName: 'cpu',\n  kernelFunc: div\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Sum, SumAttrs, SumInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {zeros} from '../utils/zeros_impl';\nimport {cast} from './Cast';\nimport {identity} from './Identity';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function sum(\n    args: {inputs: SumInputs, backend: MathBackendCPU, attrs: SumAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {axis, keepDims} = attrs;\n\n  assertNotComplex(x, 'sum');\n\n  let $x;\n  if (x.dtype === 'bool') {\n    $x = cast({inputs: {x}, backend, attrs: {dtype: 'int32'}});\n  } else {\n    $x = identity({inputs: {x}, backend});\n  }\n\n  const xRank = $x.shape.length;\n  const axes = util.parseAxisParam(axis, $x.shape);\n  const permutation = backend_util.getAxesPermutation(axes, xRank);\n\n  let reductionAxes = axes;\n  let permutedX = $x;\n  if (permutation != null) {\n    permutedX =\n        transpose({inputs: {x: $x}, backend, attrs: {perm: permutation}});\n    reductionAxes = backend_util.getInnerMostAxes(reductionAxes.length, xRank);\n  }\n\n  backend_util.assertAxesAreInnerMostDims(\n      'sum', reductionAxes, permutedX.shape.length);\n\n  const [outShape, reduceShape] =\n      backend_util.computeOutAndReduceShapes(permutedX.shape, reductionAxes);\n  const resultDtype = backend_util.upcastType(permutedX.dtype, 'int32');\n  let result = zeros(backend, outShape, resultDtype);\n  const reduceSize = util.sizeFromShape(reduceShape);\n  const vals = backend.data.get(result.dataId).values as TypedArray;\n\n  const aVals = backend.data.get(permutedX.dataId).values as TypedArray;\n  for (let i = 0; i < vals.length; ++i) {\n    const offset = i * reduceSize;\n    let sum = 0;\n    for (let j = 0; j < reduceSize; ++j) {\n      sum += aVals[offset + j];\n    }\n    vals[i] = sum;\n  }\n\n  if (keepDims) {\n    const newShape = backend_util.expandShapeToKeepDim(result.shape, axes);\n    const oldResult = result;\n    result = reshape({inputs: {x: result}, backend, attrs: {shape: newShape}});\n    backend.disposeIntermediateTensorInfo(oldResult);\n  }\n\n  backend.disposeIntermediateTensorInfo($x);\n\n  if (permutation != null) {\n    backend.disposeIntermediateTensorInfo(permutedX);\n  }\n\n  return result;\n}\n\nexport const sumConfig: KernelConfig = {\n  kernelName: Sum,\n  backendName: 'cpu',\n  kernelFunc: sum as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs, broadcast_util, buffer, KernelConfig, KernelFunc, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {reshape} from './Reshape';\n\nexport function batchMatMul(args: {\n  inputs: BatchMatMulInputs,\n  attrs: BatchMatMulAttrs,\n  backend: MathBackendCPU\n}) {\n  const {inputs, backend, attrs} = args;\n  const {a, b} = inputs;\n  const {transposeA, transposeB} = attrs;\n\n  assertNotComplex([a, b], 'matMul');\n\n  const aRank = a.shape.length;\n  const bRank = b.shape.length;\n\n  const innerShapeA = transposeA ? a.shape[aRank - 2] : a.shape[aRank - 1];\n  const innerShapeB = transposeB ? b.shape[bRank - 1] : b.shape[bRank - 2];\n\n  const outerShapeA = transposeA ? a.shape[aRank - 1] : a.shape[aRank - 2];\n  const outerShapeB = transposeB ? b.shape[bRank - 2] : b.shape[bRank - 1];\n\n  const outerDimsA = a.shape.slice(0, -2);\n  const outerDimsB = b.shape.slice(0, -2);\n\n  const batchDimA = util.sizeFromShape(outerDimsA);\n  const batchDimB = util.sizeFromShape(outerDimsB);\n\n  const outShapeOuterDims = broadcast_util.assertAndGetBroadcastShape(\n      a.shape.slice(0, -2), b.shape.slice(0, -2));\n  const outShape = outShapeOuterDims.concat([outerShapeA, outerShapeB]);\n\n  util.assert(\n      innerShapeA === innerShapeB,\n      () => `Error in matMul: inner shapes (${innerShapeA}) and (` +\n          `${innerShapeB}) of Tensors with shapes ${a.shape} and ` +\n          `${b.shape} and transposeA=${transposeA}` +\n          ` and transposeB=${transposeB} must match.`);\n\n  const a3dShape = transposeA ? [batchDimA, innerShapeA, outerShapeA] :\n                                [batchDimA, outerShapeA, innerShapeA];\n  const b3dShape = transposeB ? [batchDimB, outerShapeB, innerShapeB] :\n                                [batchDimB, innerShapeB, outerShapeB];\n\n  // The rest of the implementation is designed to operate on rank-3 tensors\n  const a3d = reshape({inputs: {x: a}, backend, attrs: {shape: a3dShape}});\n  const b3d = reshape({inputs: {x: b}, backend, attrs: {shape: b3dShape}});\n\n  const sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];\n  const leftDim = transposeA ? a3d.shape[2] : a3d.shape[1];\n  const rightDim = transposeB ? b3d.shape[1] : b3d.shape[2];\n  const batchDim = Math.max(batchDimA, batchDimB);\n\n  const a3dValues = backend.data.get(a3d.dataId).values as TypedArray;\n  const b3dValues = backend.data.get(b3d.dataId).values as TypedArray;\n\n  const a3dStrides = util.computeStrides(a3d.shape);\n  const b3dStrides = util.computeStrides(b3d.shape);\n\n  const [aBatch, aOuterStep, aInnerStep] = transposeA ?\n      [a3dStrides[0], 1, a3dStrides[1]] :\n      [a3dStrides[0], a3dStrides[1], 1];\n  const [bInnerStep, bOuterStep, bBatch] = transposeB ?\n      [1, b3dStrides[1], b3dStrides[0]] :\n      [b3dStrides[1], 1, b3dStrides[0]];\n\n  const size = leftDim * rightDim;\n  const result = buffer([batchDim, leftDim, rightDim], a3d.dtype);\n\n  const resVals = result.values as TypedArray;\n  const blockSize = backend.blockSize;\n\n  for (let bi = 0; bi < batchDim; bi++) {\n    const batchIndexA = bi % batchDimA;\n    const batchIndexB = bi % batchDimB;\n    for (let i0 = 0; i0 < leftDim; i0 += blockSize) {\n      // for when blockSize doesn't evenly divide the input\n      const iBlock = Math.min(i0 + blockSize, leftDim);\n      for (let j0 = 0; j0 < rightDim; j0 += blockSize) {\n        const jBlock = Math.min(j0 + blockSize, rightDim);\n        for (let k0 = 0; k0 < sharedDim; k0 += blockSize) {\n          const kBlock = Math.min(k0 + blockSize, sharedDim);\n\n          for (let i = i0; i < iBlock; i++) {\n            for (let j = j0; j < jBlock; j++) {\n              let sum = 0.0;\n\n              for (let k = k0; k < kBlock; k++) {\n                const aVal =\n                    // tslint:disable-next-line: max-line-length\n                    a3dValues[batchIndexA * aBatch + i * aOuterStep + k * aInnerStep];\n                const bVal =\n                    // tslint:disable-next-line: max-line-length\n                    b3dValues[k * bInnerStep + j * bOuterStep + batchIndexB * bBatch];\n                sum += aVal * bVal;\n              }\n              resVals[bi * size + (i * rightDim + j)] += sum;\n            }\n          }\n        }\n      }\n    }\n  }\n\n  backend.disposeIntermediateTensorInfo(a3d);\n  backend.disposeIntermediateTensorInfo(b3d);\n\n  // set correct shape on output.\n  return backend.makeTensorInfo(\n      outShape, result.dtype, result.values as TypedArray);\n}\n\nexport const batchMatMulConfig: KernelConfig = {\n  kernelName: BatchMatMul,\n  backendName: 'cpu',\n  kernelFunc: batchMatMul as unknown as KernelFunc,\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, KernelConfig, KernelFunc, Softmax, SoftmaxAttrs, SoftmaxInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {exp} from './Exp';\nimport {max} from './Max';\nimport {div} from './RealDiv';\nimport {reshape} from './Reshape';\nimport {sub} from './Sub';\nimport {sum} from './Sum';\n\nexport function softmax(\n    args:\n        {inputs: SoftmaxInputs, backend: MathBackendCPU, attrs: SoftmaxAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {logits} = inputs;\n  const {dim} = attrs;\n\n  const logitsRank = logits.shape.length;\n\n  let $dim = dim;\n  if ($dim === -1) {\n    $dim = logitsRank - 1;\n  }\n  if ($dim !== logitsRank - 1) {\n    throw Error(\n        'Softmax along a non-last dimension is not yet supported. ' +\n        `Logits was rank ${logitsRank} and dim was ${$dim}`);\n  }\n\n  const axes = util.parseAxisParam([$dim], logits.shape);\n  const maxLogit = max({\n    inputs: {x: logits},\n    backend,\n    attrs: {reductionIndices: axes, keepDims: false}\n  });\n  const expandedShape = backend_util.expandShapeToKeepDim(maxLogit.shape, axes);\n\n  const maxLogitReshaped =\n      reshape({inputs: {x: maxLogit}, backend, attrs: {shape: expandedShape}});\n  const a =\n      sub({inputs: {a: logits, b: maxLogitReshaped}, backend}) as TensorInfo;\n  const b = exp({inputs: {x: a}, backend}) as TensorInfo;\n  const sumExp =\n      sum({inputs: {x: b}, backend, attrs: {axis: axes, keepDims: false}});\n  const sumReshaped =\n      reshape({inputs: {x: sumExp}, backend, attrs: {shape: expandedShape}});\n\n  const result = div({inputs: {a: b, b: sumReshaped}, backend}) as TensorInfo;\n\n  backend.disposeIntermediateTensorInfo(maxLogit);\n  backend.disposeIntermediateTensorInfo(maxLogitReshaped);\n  backend.disposeIntermediateTensorInfo(a);\n  backend.disposeIntermediateTensorInfo(b);\n  backend.disposeIntermediateTensorInfo(sumExp);\n  backend.disposeIntermediateTensorInfo(sumReshaped);\n\n  return result;\n}\n\nexport const softmaxConfig: KernelConfig = {\n  kernelName: Softmax,\n  backendName: 'cpu',\n  kernelFunc: softmax as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelFunc, Max, MaxAttrs, MaxInputs, TensorInfo} from '@tensorflow/tfjs-core';\nimport {backend_util, KernelConfig} from '@tensorflow/tfjs-core';\nimport {TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {maxImpl} from './Max_impl';\nimport {transposeImpl} from './Transpose_impl';\n\nexport function max(\n    args: {inputs: MaxInputs, backend: MathBackendCPU, attrs: MaxAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {reductionIndices, keepDims} = attrs;\n  const cpuBackend = backend;\n  let xShape = x.shape;\n  const xRank = xShape.length;\n\n  const origAxes = util.parseAxisParam(reductionIndices, xShape);\n  let axes = origAxes;\n  const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n  let xVals = cpuBackend.data.get(x.dataId).values as TypedArray;\n  if (permutedAxes != null) {\n    const newShape: number[] = new Array(xRank);\n    for (let i = 0; i < newShape.length; i++) {\n      newShape[i] = xShape[permutedAxes[i]];\n    }\n\n    xVals = transposeImpl(xVals, xShape, x.dtype, permutedAxes, newShape);\n    axes = backend_util.getInnerMostAxes(axes.length, xRank);\n\n    xShape = newShape;\n  }\n\n  assertNotComplex(x, 'max');\n  backend_util.assertAxesAreInnerMostDims('max', axes, xRank);\n  const [maxOutShape, reduceShape] =\n      backend_util.computeOutAndReduceShapes(xShape, axes);\n\n  const reduceSize = util.sizeFromShape(reduceShape);\n\n  const result = maxImpl(xVals, reduceSize, maxOutShape, x.dtype);\n  const dataId = cpuBackend.write(result, maxOutShape, x.dtype);\n\n  let outShape = maxOutShape;\n  if (keepDims) {\n    // reshape\n    const newShape = backend_util.expandShapeToKeepDim(maxOutShape, origAxes);\n    outShape = newShape;\n  }\n\n  return {dataId, shape: outShape, dtype: x.dtype};\n}\n\nexport const maxConfig: KernelConfig = {\n  kernelName: Max,\n  backendName: 'cpu',\n  kernelFunc: max as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {backend_util, Erf, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nconst p = backend_util.ERF_P;\nconst a1 = backend_util.ERF_A1;\nconst a2 = backend_util.ERF_A2;\nconst a3 = backend_util.ERF_A3;\nconst a4 = backend_util.ERF_A4;\nconst a5 = backend_util.ERF_A5;\n\nexport const erf = unaryKernelFunc(\n    Erf,\n    (xi) => {\n      const sign = Math.sign(xi);\n      const v = Math.abs(xi);\n      const t = 1.0 / (1.0 + p * v);\n      return sign *\n          (1.0 -\n           (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t *\n               Math.exp(-v * v));\n    },\n);\n\nexport const erfConfig: KernelConfig = {\n  kernelName: Erf,\n  backendName: 'cpu',\n  kernelFunc: erf,\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelConfig, KernelFunc, TensorInfo, Tile, TileAttrs, TileInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {tileImpl} from './Tile_impl';\n\nexport function tile(\n    args: {inputs: TileInputs, backend: MathBackendCPU, attrs: TileAttrs}):\n    TensorInfo {\n  const {inputs, backend, attrs} = args;\n  const {x} = inputs;\n  const {reps} = attrs;\n\n  assertNotComplex(x, 'tile');\n  const outBuf = tileImpl(backend.bufferSync(x), reps);\n\n  return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n}\n\nexport const tileConfig: KernelConfig = {\n  kernelName: Tile,\n  backendName: 'cpu',\n  kernelFunc: tile as unknown as KernelFunc\n};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Square, SquareInputs} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport const squareConfig: KernelConfig = {\n  kernelName: Square,\n  backendName: 'cpu',\n  kernelFunc: ({inputs, backend}) => {\n    const {x} = inputs as SquareInputs;\n    const cpuBackend = backend as MathBackendCPU;\n    assertNotComplex(x, 'square');\n\n    const values = cpuBackend.data.get(x.dataId).values as Float32Array;\n    const newValues = new Float32Array(values.length);\n    for (let i = 0; i < values.length; ++i) {\n      const value = values[i];\n      newValues[i] = value * value;\n    }\n    const dataId = cpuBackend.write(newValues, x.shape, x.dtype);\n    return {dataId, shape: x.shape, dtype: x.dtype};\n  }\n};\n", "import { appendFileSync } from \"fs\";\nimport path from \"path\";\nimport { MODERN_WEB_LOG_FILE } from \"../../constants.ts\";\n\nexport function logToolResult(toolName: string, result: { id?: string; distance?: string | number; similarity?: string | number; count?: number }[]) {\n  if (process.env.ENABLE_FILE_LOGGING !== 'true') {\n    return;\n  }\n  try {\n    const logDir = process.env.MODERN_WEB_LOG_DIR || process.cwd();\n    const logPath = path.join(logDir, MODERN_WEB_LOG_FILE);\n    const logEntry = {\n      timestamp: new Date().toISOString(),\n      tool: toolName,\n      result\n    };\n    appendFileSync(logPath, JSON.stringify(logEntry) + \"\\n\", \"utf8\");\n  } catch (err) {\n    console.error(\"Failed to log tool result:\", err);\n  }\n}\n", "export const MODERN_WEB_LOG_FILE = 'modern-web.log';\n"],
  "mappings": ";;;62BAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,cAEA,IAAIC,GAAY,GAAQ,YAAY,EAGpCD,GAAO,QAAQ,QAAUE,GAUzB,SAASA,GAAQC,EAAKC,EAAIC,EAAM,CAC5BA,EAAOC,GAAcD,GAAQ,OAAO,EACpCD,EAAKE,GAAcF,GAAM,OAAO,EAChCD,EAAMA,GAAO,GAEb,IAAII,EAMJ,GAJIF,IAAS,SAAW,OAAOF,GAAQ,WACnCA,EAAM,OAAO,KAAKA,EAAK,QAAQ,GAG/BE,IAASD,EACL,OAAOD,GAAQ,SACfI,EAAS,OAAO,KAAKJ,CAAG,EAExBI,EAASJ,MAGb,IAAI,CACAI,EAASC,GAAiBL,EAAKC,EAAIC,CAAI,CAC3C,OAASI,EAAG,CACR,QAAQ,MAAMA,CAAC,EACfF,EAASJ,CACb,CAGJ,OAAI,OAAOI,GAAW,WAClBA,EAAS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A,EAAK,YAAc,EAC/B,OAAQA,EAAK,OACb,KAAMA,EAAK,OAASlB,GAAckB,EAAK,MAAM,EAAI,CACnD,EAAE,EAAE,OAAOA,GAAQA,EAAK,MAAM,CAChC,CAEA,IAAMC,EAAa,IAAI,IAEvB,QAAWD,KAAQvB,GAAe,CAChC,GAAIuB,EAAK,OAAS,GAAKP,IAAc,EAAG,SAExC,IAAMS,EAAMxB,GAAWa,EAAaS,EAAK,MAAM,GAAKP,EAAYO,EAAK,MAErE,GAAIE,EAAMb,EAAe,SAEzB,IAAMc,EAAWF,EAAW,IAAID,EAAK,EAAE,GACnC,CAACG,GAAYD,EAAMC,EAAS,aAC9BF,EAAW,IAAID,EAAK,GAAI,CAAE,KAAAA,EAAM,WAAYE,CAAI,CAAC,CAErD,CAEA,IAAME,EAAU,MAAM,KAAKH,EAAW,OAAO,CAAC,EAG9CG,EAAQ,KAAK,CAACzB,EAAGC,IAAMA,EAAE,WAAaD,EAAE,UAAU,EAElD,IAAM0B,EAAiBD,EAAQ,MAAM,EAAGhB,CAAK,EAAE,IAAIkB,IAAM,CACvD,GAAIA,EAAE,KAAK,GACX,YAAaA,EAAE,KAAK,YACpB,SAAUA,EAAE,KAAK,SACjB,aAAcA,EAAE,KAAK,cAAc,OAASA,EAAE,KAAK,aAAe,OAClE,WAAYA,EAAE,KAAK,WACnB,WAAY,WAAWA,EAAE,WAAW,QAAQ,CAAC,CAAC,CAChD,EAAE,EAGF,OAAAC,GAAc,mBAAoBF,EAAe,IAAIC,IAAM,CAAE,GAAIA,EAAE,GAAI,WAAYA,EAAE,UAAW,EAAE,CAAC,EAE5FD,CACT",
  "names": ["require_encoding", "__commonJSMin", "exports", "module", "iconvLite", "convert", "str", "to", "from", "checkEncoding", "result", "convertIconvLite", "E", "name", "require_lib", "__commonJSMin", "exports", "module", "_interopDefault", "ex", "Stream", "http", "Url", "whatwgUrl", "https", "zlib", "Readable", "BUFFER", "TYPE", "Blob", "_Blob", "blobParts", "options", "buffers", "size", "a", "length", "i", "element", "buffer", "type", "buf", "ab", "readable", "start", "end", "relativeStart", "relativeEnd", "span", "slicedBuffer", "blob", "FetchError", "message", "systemError", "convert", "INTERNALS", "PassThrough", "Body", "body", "_this", "_ref", "_ref$size", "_ref$timeout", "timeout", "isURLSearchParams", "isBlob", "err", "error", "consumeBody", "ct", "_this2", "_this3", "convertBody", "proto", "name", "desc", "_this4", "accum", "accumBytes", "abort", "resolve", "reject", "resTimeout", "chunk", "headers", "charset", "res", "str", "obj", "clone", "instance", "p1", "p2", "extractContentType", "getTotalBytes", "writeToStream", "dest", "invalidTokenRegex", "invalidHeaderCharRegex", "validateName", "validateValue", "value", "find", "map", "key", "MAP", "Headers", "_Headers", "init", "rawHeaders", "headerNames", "headerName", "method", "pairs", "pair", "callback", "thisArg", "getHeaders", "_pairs$i", "createHeadersIterator", "kind", "k", "INTERNAL", "target", "iterator", "HeadersIteratorPrototype", "_INTERNAL", "index", "values", "len", "exportNodeCompatibleHeaders", "hostHeaderKey", "createHeadersLenient", "val", "INTERNALS$1", "STATUS_CODES", "Response", "_Response", "opts", "status", "contentType", "INTERNALS$2", "URL", "parse_url", "format_url", "parseURL", "urlStr", "streamDestructionSupported", "isRequest", "input", "isAbortSignal", "signal", "Request", "_Request", "parsedURL", "inputBody", "getNodeRequestOptions", "request", "contentLengthValue", "totalBytes", "agent", "AbortError", "URL$1", "PassThrough$1", "isDomainOrSubdomain", "destination", "original", "orig", "isSameProtocol", "fetch", "url", "send", "response", "destroyStream", "abortAndFinalize", "finalize", "req", "reqTimeout", "socket", "fixResponseChunkedTransferBadEnding", "s", "hadError", "hasDataListener", "location", "locationURL", "requestOpts", "response_options", "codings", "zlibOptions", "raw", "errorCallback", "stream", "code", "extendStatics", "d", "b", "p", "__extends", "__", "__awaiter", "thisArg", "_arguments", "P", "generator", "adopt", "value", "resolve", "reject", "fulfilled", "step", "e", "rejected", "result", "__generator", "body", "_", "t", "f", "y", "g", "verb", "n", "v", "op", "__values", "o", "s", "m", "i", "__read", "r", "ar", "error", "__spreadArray", "to", "from", "pack", "l", "EPSILON_FLOAT32", "EPSILON_FLOAT16", "DataStorage", "backend", "dataMover", "dataId", "KernelBackend", "notYetImplemented", "options", "force", "values", "shape", "dtype", "refCount", "kernelName", "shuffle", "array", "counter", "index", "swap", "shuffleCombo", "array2", "clamp", "min", "x", "max", "nearestLargerEven", "val", "object", "left", "right", "temp", "sum", "arr", "randUniform", "a", "distSquared", "diff", "assert", "expr", "msg", "assertShapesMatch", "shapeA", "shapeB", "errorMessagePrefix", "arraysEqual", "assertNonNull", "sizeFromShape", "size", "isScalarShape", "arraysEqualWithNull", "n1", "n2", "isInt", "tanh", "e2x", "sizeToSquarishShape", "width", "createShuffledIndices", "shuffledIndices", "rightPad", "repeatedTry", "checkFn", "delayFn", "maxCounter", "scheduleFn", "tryCount", "tryFn", "nextBackoff", "inferFromImplicitShape", "shapeProd", "implicitIdx", "newShape", "parseAxisParam", "axis", "rank", "ax", "squeezeShape", "keptDims", "isEmptyArray", "axes", "j", "getTypedArrayFromDType", "getArrayFromDType", "checkConversionForErrors", "vals", "num", "isValidDtype", "hasEncodingLoss", "oldType", "newType", "bytesPerElement", "bytesFromStringArray", "bytes", "isString", "isBoolean", "isNumber", "inferDtype", "isFunction", "nearestDivisor", "start", "computeStrides", "strides", "createNestedArray", "offset", "isComplex", "ret", "rest", "len", "acc", "c", "toNestedArray", "convertBackendValuesAndArrayBuffer", "data", "makeOnesTypedArray", "makeZerosTypedArray", "makeZerosNestedTypedArray", "prev", "curr", "assertNonNegativeIntegerDimensions", "dimSize", "locToIndex", "locs", "indexToLoc", "isPromise", "TENSORFLOWJS_FLAGS_PREFIX", "Environment", "global", "getQueryParams", "platformName", "platform", "env", "flagName", "evaluationFn", "setHook", "flagValue", "_a", "_b", "_c", "flags", "_this", "urlParams", "keyValues", "keyValue", "key", "parseValue", "queryString", "params", "_i", "decodeParam", "name", "lowerCaseValue", "ENV", "setEnvironmentGlobal", "environment", "globalNameSpace", "getGlobalNamespace", "ns", "getGlobalMap", "getGlobal", "init", "globalMap", "singleton", "Abs", "Acos", "Acosh", "Add", "AddN", "All", "Any", "ArgMax", "ArgMin", "Asin", "Asinh", "Atan", "Atanh", "Atan2", "AvgPool", "AvgPoolGrad", "AvgPool3D", "AvgPool3DGrad", "BatchMatMul", "BatchToSpaceND", "Bincount", "BitwiseAnd", "BroadcastTo", "BroadcastArgs", "Cast", "Ceil", "ClipByValue", "Complex", "ComplexAbs", "Concat", "Conv2D", "Conv2DBackpropFilter", "Conv2DBackpropInput", "Conv3D", "Conv3DBackpropFilterV2", "Conv3DBackpropInputV2", "Cos", "Cosh", "Cumprod", "Cumsum", "CropAndResize", "DenseBincount", "DepthToSpace", "DepthwiseConv2dNative", "DepthwiseConv2dNativeBackpropFilter", "DepthwiseConv2dNativeBackpropInput", "Diag", "Dilation2D", "Dilation2DBackpropInput", "Dilation2DBackpropFilter", "Draw", "RealDiv", "Einsum", "Elu", "EluGrad", "Erf", "Equal", "Exp", "ExpandDims", "Expm1", "FFT", "Fill", "FlipLeftRight", "Floor", "FloorDiv", "FusedBatchNorm", "GatherV2", "GatherNd", "Greater", "GreaterEqual", "Identity", "IFFT", "Imag", "IsFinite", "IsInf", "IsNan", "LeakyRelu", "Less", "LessEqual", "LinSpace", "Log", "Log1p", "LogicalAnd", "LogicalNot", "LogicalOr", "LogicalXor", "LogSoftmax", "LowerBound", "LRN", "LRNGrad", "MatrixBandPart", "Max", "Maximum", "MaxPool", "MaxPoolGrad", "MaxPool3D", "MaxPool3DGrad", "MaxPoolWithArgmax", "Mean", "Min", "Minimum", "MirrorPad", "Mod", "Multinomial", "Multiply", "Neg", "NotEqual", "NonMaxSuppressionV3", "NonMaxSuppressionV4", "NonMaxSuppressionV5", "OnesLike", "OneHot", "Pack", "PadV2", "Pool", "Pow", "Prelu", "Prod", "RaggedGather", "RaggedRange", "RaggedTensorToTensor", "Range", "Real", "Reciprocal", "Relu", "Reshape", "ResizeNearestNeighbor", "ResizeNearestNeighborGrad", "ResizeBilinear", "ResizeBilinearGrad", "Relu6", "Reverse", "Round", "Rsqrt", "ScatterNd", "TensorScatterUpdate", "SearchSorted", "Select", "Selu", "Slice", "Sin", "Sinh", "Sign", "Sigmoid", "Softplus", "Sqrt", "Sum", "SpaceToBatchND", "SplitV", "Softmax", "SparseFillEmptyRows", "SparseReshape", "SparseSegmentMean", "SparseSegmentSum", "SparseToDense", "SquaredDifference", "Square", "StaticRegexReplace", "StridedSlice", "StringNGrams", "StringSplit", "StringToHashBucketFast", "Sub", "Tan", "Tanh", "Tile", "TopK", "Transform", "Transpose", "Unique", "Unpack", "UnsortedSegmentSum", "UpperBound", "ZerosLike", "Step", "FromPixels", "RotateWithOffset", "_FusedMatMul", "FusedConv2D", "FusedDepthwiseConv2D", "warn", "log", "kernelRegistry", "gradRegistry", "getKernel", "backendName", "makeKey", "getGradient", "getKernelsForBackend", "it", "done", "config", "registerKernel", "log.warn", "registerGradient", "unregisterKernel", "unregisterGradient", "copyRegisteredKernels", "registeredBackendName", "newBackendName", "kernels", "kernelConfig", "newKernelConfig", "isTypedArrayBrowser", "long", "Long", "wasm", "low", "high", "unsigned", "isLong", "obj", "INT_CACHE", "UINT_CACHE", "fromInt", "cachedObj", "cache", "fromBits", "fromNumber", "UZERO", "ZERO", "TWO_PWR_64_DBL", "MAX_UNSIGNED_VALUE", "TWO_PWR_63_DBL", "MIN_VALUE", "MAX_VALUE", "TWO_PWR_32_DBL", "lowBits", "highBits", "pow_dbl", "fromString", "str", "radix", "radixToPower", "power", "fromValue", "TWO_PWR_16_DBL", "TWO_PWR_24_DBL", "TWO_PWR_24", "ONE", "UONE", "NEG_ONE", "LongPrototype", "radixLong", "div", "rem1", "rem", "remDiv", "intval", "digits", "bit", "other", "thisNeg", "otherNeg", "addend", "a48", "a32", "a16", "a00", "b48", "b32", "b16", "b00", "c48", "c32", "c16", "c00", "subtrahend", "multiplier", "divisor", "approx", "res", "halfThis", "log2", "delta", "approxRes", "approxRem", "numBits", "le", "hi", "lo", "LongExports.default", "LongExports", "hexToLong", "hex", "k0", "k1", "k2", "shiftMix", "fetch", "numBytes", "fetch64", "fetch32", "rotate64", "shift", "hashLen16", "u", "mul", "weakHashLen32WithSeeds", "w", "z", "weakHashLen32WithSeedsStr", "hashLen0to16", "hashLen17to32", "hashLen33to64", "h", "fingerPrint64", "seed", "end", "last64", "createScalarValue", "encodeString", "toTypedArray", "noConversionNeeded", "flatten", "base.checkConversionForErrors", "bool", "now", "path", "requestInits", "encoding", "decodeString", "isTypedArray", "skipTypedArray", "base.isPromise", "maxIndex", "Profiler", "backendTimer", "logger", "Logger", "inputs", "outputs", "holdResultWrapperFn", "timer", "util.now", "outputs_1", "outputs_1_1", "output", "tensorVals", "checkComputationForErrors", "kernelProfile", "timing", "timeMs", "extraInfo", "valueContainer", "time", "util.rightPad", "paddedName", "inputShapesDescription", "name_1", "input", "inputShape", "inputRank", "getFilteredNodesXToY", "tape", "xs", "tensorsFromX", "nodesFromX", "node", "nodeInputs", "inputName", "anyInputFromX", "tensorsLeadToY", "nodesToY", "filteredTape", "prunedInputs", "nodeInput", "prunedNode", "backpropagateGradients", "tensorAccumulatedGradientMap", "tidy", "add", "dys", "gradTensor", "inputGradients", "dx", "util.arraysEqual", "curGradient", "FORMAT_LIMIT_NUM_VALS", "FORMAT_NUM_FIRST_LAST_VALS", "FORMAT_NUM_SIG_DIGITS", "tensorToString", "verbose", "padPerCol", "computeMaxSizePerColumn", "valsLines", "subTensorToString", "lines", "numCols", "valuesOrTuples", "createComplexTuples", "row", "valToString", "pad", "valStr", "boolNumToString", "isLast", "storagePerElement", "complexTuple", "firstValsSize", "firstVals", "lastVals", "displayVals", "subshape", "substrides", "stride", "sep", "newLineSep", "complexTuples", "TensorBuffer", "util.sizeFromShape", "n_1", "util.assert", "util.getArrayFromDType", "locs_1", "locs_1_1", "loc", "i_1", "trackerFn", "opHandler", "setTensorTracker", "fn", "setOpHandler", "handler", "Tensor", "id", "util.decodeString", "trainable", "instance", "getGlobalTensorClass", "Variable", "_super", "initialValue", "tensorId", "newValue", "Rank", "UpcastInt32AndMap", "UpcastBoolAndMap", "UpcastFloat32AndMap", "UpcastComplex64AndMap", "upcastTypeMap", "upcastType", "typeA", "typeB", "sumOutType", "type", "isWebGLData", "isWebGPUData", "makeTypesMatch", "assertTypesMatch", "isTensorInList", "tensor", "tensorList", "getTensorsInContainer", "list", "seen", "walkTensorContainer", "container", "isIterable", "iterable", "k", "isRegisteredKernelInvocation", "kernelInvocation", "EngineState", "variableName", "Engine", "sortedBackends", "success", "asyncInit", "factory", "priority", "kernel", "registryFactoryEntry", "promiseId_1", "backendInstance", "err", "info", "srcBackend", "nameOrFn", "ex", "ENGINE", "grad", "dy", "gradInputs", "attrs", "saved", "hasKernel", "numDataIdsBefore", "outInfos", "numDataIdsAfter", "numOutputDataIds", "numMoves", "dataIdsLeaked", "kernelParams", "isTapeOn", "startingBytecount", "startingNumTensors", "kernelFunc", "out", "kernelOrScopeName", "kernelName_1", "inputs_1", "attrs_1", "kernel_1", "outTensors", "outInfo", "tensorsToSave", "forwardFunc_1", "saveFunc_1", "tensors", "outs", "backwardsFunc", "item", "gradConfig", "inputsToSave", "outputsToSave_1", "inputTensorsToSave", "outputTensorsToSave", "backendVals", "util.isString", "util.encodeString", "newBytes", "tensorInfo", "util.bytesPerElement", "varName", "query", "startBytes", "startNumTensors", "_g", "_d", "_e", "gradientsFunc", "tapeNode", "util.makeZerosTypedArray", "scopeInfo", "tensorsToTrackInParent", "tensorsToTrackInParentSet", "oldScope", "allowNoGradients", "accumulatedGradientMap", "ones", "grads", "util.isFunction", "inputMap", "forwardFunc", "save", "gradRes", "gradMap", "timingInfo", "getOrMakeEngine", "_isNavigatorDefined", "isMobileMockValue", "mockIsMobile", "isMobile", "nav", "navAny", "isBrowser", "debugValue", "device_util.isBrowser", "inferShape", "firstElem", "usedChannels", "deepAssertShapeConsistency", "indices", "subShape", "assertDtype", "expectedDtype", "actualDType", "argName", "functionName", "convertToTensor", "parseAsDtype", "inferredDtype", "inferredShape", "convertToTensorArray", "arg", "OP_SCOPE_SUFFIX", "keys", "opName", "f2", "args", "complex_", "real", "imag", "$real", "$imag", "util.assertShapesMatch", "complex", "makeTensor", "providedSize_1", "inferredSize_1", "inferred", "flatDimsDontMatch", "DTYPE_VALUE_SIZE_MAP", "CompositeArrayBuffer", "buffers", "bufferOrTypedArray", "util.isTypedArray", "buffer", "startShardIndex", "outputBuffer", "outputArray", "sliced", "shard", "globalStart", "localStart", "outputStart", "globalEnd", "localEnd", "outputSlice", "byteIndex", "check", "search", "sortedArray", "compare", "middle", "side", "enableProdMode", "enableDebugMode", "disableDeprecationWarnings", "deprecationWarn", "disposeVariables", "engine", "memory", "profile", "dispose", "keep", "setBackend", "ready", "getBackend", "removeBackend", "findBackend", "findBackendFactory", "registerBackend", "setPlatform", "NUM_BYTES_STRING_LENGTH", "encodeWeights", "group", "specs", "dataPromises", "names", "spec", "utf8bytes", "totalNumBytes", "bytesOfLength", "tensorValues", "concatenateTypedArrays", "decodeWeights", "weightData", "compositeBuffer", "specs_1", "specs_1_1", "byteLength", "getWeightBytelength", "decodeWeight", "slice", "bytesPerValue", "quantization", "getWeightBytelengthAsync", "byteBuffer", "quantizationSizeFactor", "quantizedArray", "float16Decode", "getFloat16Decoder", "size_1", "dtypeFactor", "image", "realTensor", "imageTensor", "complexTensor", "readToLength", "reader", "initialData", "length", "missing", "newData", "decodeWeightsStream", "weightStream", "specs_2", "specs_2_1", "tensorData", "weightTensor", "totalByteLength", "normalizedXs", "useNodeBuffer", "stringByteLength", "arrayBufferToBase64String", "buf", "base64StringToArrayBuffer", "concatenateArrayBuffers", "basename", "SEPARATOR", "items", "getModelJSONForModelArtifacts", "artifacts", "manifest", "getModelArtifactsForJSONSync", "modelJSON", "weightSpecs", "modelArtifacts", "getModelArtifactsForJSON", "loadWeights", "getModelArtifactsInfoForJSON", "getWeightSpecs", "weightsManifest", "weightsManifest_1", "weightsManifest_1_1", "entry", "computeFloat16MantisaTable", "convertMantissa", "mantisaTable", "computeFloat16ExponentTable", "exponentTable", "computeFloat16OffsetTable", "offsetTable", "bufferUint32View", "float16Bits", "float32Bits", "IORouterRegistry", "saveRouter", "loadRouter", "url", "loadOptions", "handlerType", "validHandlers", "routers", "router", "registerSaveRouter", "loudRouter", "registerLoadRouter", "getSaveHandlers", "getLoadHandlers", "DATABASE_NAME", "DATABASE_VERSION", "MODEL_STORE_NAME", "INFO_STORE_NAME", "getIndexedDBFactory", "theWindow", "setUpDatabase", "openRequest", "db", "BrowserIndexedDB", "modelPath", "modelTx", "modelStore", "getRequest_1", "modelArtifactsInfo_1", "infoTx_1", "infoStore_1", "putInfoRequest_1", "modelTx_1", "putModelRequest", "deleteInfoRequest", "indexedDBRouter", "browserIndexedDB", "maybeStripScheme", "BrowserIndexedDBManager", "tx", "store", "getAllInfoRequest", "infoTx", "infoStore", "getInfoRequest", "deleteModelData_1", "deleteModelRequest", "PATH_SEPARATOR", "PATH_PREFIX", "INFO_SUFFIX", "MODEL_TOPOLOGY_SUFFIX", "WEIGHT_SPECS_SUFFIX", "WEIGHT_DATA_SUFFIX", "MODEL_METADATA_SUFFIX", "getModelKeys", "removeItems", "getModelPathFromKey", "BrowserLocalStorage", "topology", "modelArtifactsInfo", "weightBuffer", "metadata", "metadataString", "weightDataBase64", "localStorageRouter", "browserLocalStorage", "BrowserLocalStorageManager", "prefix", "suffix", "URL_SCHEME_SUFFIX", "ModelStoreManagerRegistry", "scheme", "manager", "registry", "parseURL", "cloneModelInternal", "sourceURL", "destURL", "deleteSource", "loadHandlers", "loadHandler", "saveHandlers", "saveHandler", "sourceScheme", "sourcePath", "sameMedium", "saveResult", "listModels", "schemes", "schemes_1", "schemes_1_1", "schemeOut", "removeModel", "schemeAndPath", "copyModel", "moveModel", "PlatformBrowser", "text", "functionRef", "delay", "event", "functionRef_1", "getNodeFetch", "systemFetch", "PlatformNode", "util.assertNonNegativeIntegerDimensions", "cast_", "$x", "util.isValidDtype", "cast", "clone_", "clone", "print", "add_", "$a", "$b", "floorDiv_", "floorDiv", "div_", "mul_", "abs_", "abs", "acos_", "acos", "acosh_", "acosh", "addN_", "$tensors", "firstTensor", "addN", "all_", "keepDims", "all", "any_", "any", "argMax_", "argMax", "argMin_", "argMin", "asin_", "asin", "asinh_", "asinh", "atan_", "atan", "atan2_", "atan2", "atanh_", "atanh", "computeDilation2DInfo", "filterShape", "dataFormat", "dilations", "inputChannels", "$filterShape", "$dataFormat", "convertConv2DDataFormat", "computeConv2DInfo", "computePool2DInfo", "inShape", "filterSize", "roundingMode", "parseTupleParam", "filterHeight", "filterWidth", "computePool3DInfo", "parse3TupleParam", "filterDepth", "computeConv3DInfo", "depthwise", "batchSize", "inHeight", "inWidth", "inChannels", "filterChannels", "strideHeight", "strideWidth", "_f", "dilationHeight", "dilationWidth", "effectiveFilterHeight", "getEffectiveFilterSize", "effectiveFilterWidth", "getPadAndOutInfo", "padInfo", "outHeight", "outWidth", "outChannels", "outShape", "inDepth", "strideDepth", "dilationDepth", "effectiveFilterDepth", "get3DPadAndOutInfo", "outDepth", "computeOutputShape2D", "fieldSize", "zeroPad", "computeDefaultPad", "inputRows", "inputCols", "outputRows", "round", "outputCols", "computeOutputShape4D", "dilation", "effectiveFieldSize", "param", "padType", "padAlongHeight", "padAlongWidth", "top", "bottom", "padAlongDepth", "front", "back", "tupleValuesAreOne", "dimA", "dimB", "dimC", "eitherStridesOrDilationsAreOne", "stridesOrDilationsArePositive", "checkPadOnDimRoundingMode", "opDesc", "dimRoundingMode", "util.isInt", "reshape_", "reshape", "avgPool_", "conv_util.eitherStridesOrDilationsAreOne", "x4D", "reshapedTo4D", "conv_util.checkPadOnDimRoundingMode", "avgPool", "avgPool3d_", "x5D", "reshapedTo5D", "avgPool3d", "concat_", "attr", "concat", "matMul_", "transposeA", "transposeB", "matMul", "sigmoid_", "sigmoid", "slice_", "begin", "tanh_", "basicLSTMCell_", "forgetBias", "lstmKernel", "lstmBias", "$forgetBias", "$lstmKernel", "$lstmBias", "$data", "$c", "$h", "combined", "weighted", "sliceCols", "sliceSize", "newC", "newH", "basicLSTMCell", "batchToSpaceND_", "blockShape", "crops", "prod", "batchToSpaceND", "xAs4D", "batchNorm_", "mean", "variance", "scale", "varianceEpsilon", "$mean", "$variance", "$scale", "$offset", "batchNorm", "batchNorm2d_", "batchNorm2d", "batchNorm3d_", "batchNorm3d", "batchNorm4d_", "batchNorm4d", "bincount_", "weights", "$weights", "bincount", "bitwiseAnd_", "$y", "bitwiseAnd", "broadcastArgs_", "s0", "s1", "shape1Input", "shape2Input", "broadcastArgs", "broadcastTo_", "xShape", "reps", "broadcastTo", "ceil_", "ceil", "fill", "clipByValue_", "clipValueMin", "clipValueMax", "clipByValue", "concat1d_", "concat1d", "concat2d_", "concat2d", "concat3d_", "concat3d", "concat4d_", "concat4d", "conv2d_", "filter", "$filter", "conv_util.stridesOrDilationsArePositive", "conv2d", "conv1d_", "x3D", "reshapedTo3D", "filter4D", "input4D", "conv2dDataFormat", "conv1d", "conv2DBackpropInput_", "xShape4D", "dy4D", "conv2DBackpropInput", "conv2dTranspose_", "outputShape", "conv2dTranspose", "conv3d_", "conv3d", "conv3DBackpropInput_", "xShape5D", "dy5D", "conv3DBackpropInput", "conv3dTranspose_", "conv3dTranspose", "cos_", "cos", "cosh_", "cosh", "cumprod_", "exclusive", "reverse", "cumprod", "cumsum_", "cumsum", "denseBincount_", "binaryOutput", "denseBincount", "depthToSpace_", "blockSize", "inputHeight", "inputWidth", "inputDepth", "depthToSpace", "depthwiseConv2d_", "depthwiseConv2d", "diag_", "diag", "dilation2d_", "dilation2d", "getBroadcastDims", "inRank", "dims", "dim", "getReductionAxes", "inDim", "outAxis", "outDim", "assertAndGetBroadcastShape", "errMsg", "equal_", "equal", "where_", "condition", "$condition", "broadcastShape", "$broadcastedCondition", "$broadcastedA", "$broadcastedB", "where", "zerosLike_", "zerosLike", "divNoNan_", "divResult", "zeros", "bEqualsZero", "divNoNan", "dot_", "t1", "t2", "$t1", "$t2", "t1Inner", "t2Inner", "t12D", "t22D", "t1t2", "dot", "einsum_", "equation", "einsum", "elu_", "elu", "ensureShape_", "ensureShape", "erf_", "erf", "axesAreInnerMostDims", "combineLocations", "outputLoc", "reduceLoc", "outIdx", "reduceIdx", "computeOutAndReduceShapes", "aShape", "reduceShape", "expandShapeToKeepDim", "reduceSubShape", "assertAxesAreInnerMostDims", "getAxesPermutation", "getUndoAxesPermutation", "getInnerMostAxes", "numAxes", "max_", "min_", "pow_", "base", "exp", "$base", "$exp", "pow", "scalar", "sqrt_", "sqrt", "square_", "square", "sum_", "norm_", "ord", "norm", "normImpl", "keepDimsShape", "axis_util.expandShapeToKeepDim", "euclideanNorm_", "euclideanNorm", "exp_", "expandDims_", "expandDims", "expm1_", "expm1", "tile_", "tile", "eye_", "numRows", "numColumns", "batchShape", "buff", "eye", "floor_", "floor", "gather_", "batchDims", "$indices", "gather", "greater_", "greater", "greaterEqual_", "greaterEqual", "imag_", "$input", "isFinite_", "isFinite", "isInf_", "isInf", "isNaN_", "isNaN", "leakyRelu_", "alpha", "leakyRelu", "less_", "less", "lessEqual_", "lessEqual", "linspace", "stop", "localResponseNormalization_", "depthRadius", "bias", "beta", "localResponseNormalization", "log_", "log1p_", "log1p", "$dy", "checkGrads", "$args", "valueAndGrad", "valueAndGrads", "variableGrads", "varList", "specifiedVarList", "specifiedNonTrainable", "variable", "originalVarCount", "namedGrads", "customGrad", "numNullGradients", "neg_", "neg", "softplus_", "softplus", "logSigmoid_", "customOp", "gradFunc", "derX", "logSigmoid", "sub_", "sub", "logSoftmax_", "logits", "$logits", "xMax", "shifted", "softmax", "logSoftmax", "logSumExp_", "logSumExp", "logicalAnd_", "logicalAnd", "logicalNot_", "logicalNot", "logicalOr_", "logicalOr", "logicalXor_", "logicalXor", "INT32_MAX", "searchSorted_", "sortedSequence", "$sortedSequence", "$values", "sequenceSize", "valuesSize", "$sortedSequence2D", "$values2D", "searchSorted", "lowerBound", "maxPool_", "maxPool", "maxPool3d_", "maxPool3d", "maxPoolWithArgmax_", "includeBatchInIndex", "maxPoolWithArgmax", "maximum_", "maximum", "mean_", "meshgrid", "indexing", "minimum_", "minimum", "mirrorPad_", "paddings", "mode", "shapeOffset", "mirrorPad", "mod_", "mod", "moments_", "xMean", "devSquared", "moments", "multiRNNCell_", "lstmCells", "newStates", "multiRNNCell", "multinomial_", "numSamples", "normalized", "numOutcomes", "origRank", "logits2D", "multinomial", "notEqual_", "notEqual", "oneHot_", "depth", "onValue", "offValue", "oneHot", "onesLike_", "onesLike", "outerProduct_", "v1", "v2", "$v1", "$v2", "v12D", "v22D", "outerProduct", "pad_", "constantValue", "pad1d_", "pad1d", "pad2d_", "pad2d", "pad3d_", "pad3d", "pad4d_", "pad4d", "spaceToBatchND_", "spaceToBatchND", "pool_", "windowShape", "poolingType", "convInfo", "conv_util.computePool2DInfo", "basePadding", "withSpaceToBatchBasePaddings", "isDilationOne", "requiredSpaceToBatchPaddings", "adjustedPadding", "adjustedCrops", "convertedPad", "convertedX", "forwardOp", "padStart", "origPadEnd", "fullInputShape", "padEndExtra", "padEnd", "dilatedFilterShape", "padExtraShape", "padExtraStart", "padExtraEnd", "pool", "prelu_", "$alpha", "prelu", "prod_", "raggedGather_", "paramsNestedSplits", "paramsDenseValues", "outputRaggedRank", "$paramsNestedSplits", "$paramsDenseValues", "raggedGather", "raggedRange_", "starts", "limits", "deltas", "$starts", "$limits", "$deltas", "raggedRange", "raggedTensorToTensor_", "defaultValue", "rowPartitionTensors", "rowPartitionTypes", "$shape", "$defaultValue", "$rowPartitionTensors", "raggedTensorToTensor", "rand_", "randFunction", "rand", "module", "define", "Alea", "me", "mash", "Mash", "copy", "impl", "opts", "xg", "state", "prng", "this", "XorGen", "strseed", "bot", "X", "limit", "math", "chunks", "rngname", "startdenom", "significance", "overflow", "mask", "nodecrypto", "seedrandom", "callback", "shortseed", "mixkey", "tostring", "autoseed", "arc4", "ARC4", "is_math_call", "keylen", "count", "typ", "prop", "stringseed", "smear", "browser", "plugins", "alea", "require$$0", "xor128", "require$$1", "xorwow", "require$$2", "xorshift7", "require$$3", "xor4096", "require$$4", "tychei", "require$$5", "sr", "require$$6", "TEST_EPSILON_FLOAT32", "TEST_EPSILON_FLOAT16", "expectArraysClose", "actual", "expected", "epsilon", "testEpsilon", "expectArraysPredicate", "areClose", "predicate", "checkClassType", "aType", "bType", "actualShape", "expectedShape", "actualFlat", "expectedFlat", "expectPromiseToFail", "expectArraysEqual", "expectNumbersClose", "expectValuesInRange", "expectArrayBuffersEqual", "actualArray", "expectedArray", "encodeStrings", "createVideoElement", "source", "video", "play", "MPRandGauss", "stdDeviation", "truncated", "seedValue", "seedrandom.alea", "resultX", "resultY", "isValid", "RandGamma", "x2", "v0", "UniformRandom", "randomGamma_", "rgamma", "randomGamma", "randomNormal_", "stdDev", "randGauss", "randomNormal", "randomStandardNormal_", "randomStandardNormal", "randomUniform_", "minval", "maxval", "random", "randomUniform", "randomUniformInt_", "randomUniformInt", "range", "real_", "reciprocal_", "reciprocal", "relu_", "relu", "relu6_", "relu6", "reverse_", "reverse1d_", "reverse1d", "reverse2d_", "reverse2d", "reverse3d_", "reverse3d", "reverse4d_", "reverse4d", "round_", "rsqrt_", "rsqrt", "selu_", "selu", "separableConv2d_", "depthwiseFilter", "pointwiseFilter", "$depthwiseFilter", "$pointwiseFilter", "channelMultiplier", "pointwiseStride", "separableConv2d", "setdiff1dAsync_", "xVals", "yVals", "ySet", "outputSize", "setdiff1dAsync", "sign_", "sign", "sin_", "sin", "sinh_", "sinh", "slice1d_", "slice1d", "slice2d_", "slice2d", "slice3d_", "slice3d", "slice4d_", "slice4d", "softmax_", "fft_", "fft", "ifft_", "ifft", "irfft_", "innerDimensionSize", "batch", "complexInput", "realInput", "imagInput", "realConjugate", "imagConjugate", "batch_1", "irfft", "split_", "numOrSizeSplits", "split", "rfft_", "fftLength", "adjustedInput", "zerosShape", "zerosInput", "half", "realValues", "imagValues", "realComplexConjugate", "imagComplexConjugate", "rfft", "squaredDifference_", "squaredDifference", "squeeze_", "squeeze", "stack_", "stack", "step_", "stridedSlice_", "beginMask", "endMask", "ellipsisMask", "newAxisMask", "shrinkAxisMask", "stridedSlice", "tan_", "tan", "tensor1d", "tensor2d", "tensor3d", "tensor4d", "tensor5d", "tensor6d", "validateUpdateShape", "updates", "sliceDim", "batchDim", "shapeError", "validateInput", "calculateShapes", "indicesRank", "sliceRank", "totalNd", "safeSliceDim", "numUpdates", "tensorScatterUpdate_", "$tensor", "$updates", "scatter_nd_util.validateInput", "tensorScatterUpdate", "topk_", "sorted", "lastDim", "topk", "truncatedNormal_", "truncatedNormal", "unique_", "unique", "unsortedSegmentSum_", "segmentIds", "numSegments", "$segmentIds", "unsortedSegmentSum", "unstack_", "unstack", "upperBound", "whereImpl", "condShape", "condVals", "inBuffer", "whereAsync_", "whereAsync", "booleanMaskAsync_", "$mask", "axisFrom", "maskDim", "tensorShape", "leadingSize", "targetTensorShape", "reshapedTensor", "reshapedMask", "positivePositions", "booleanMaskAsync", "transpose_", "perm", "conjugate", "transpose", "movingAverage_", "decay", "zeroDebias", "$v", "$decay", "one", "oneMinusDecay", "update", "$step", "movingAverage", "scatterND_", "scatterND", "sparseIndices", "sparseValues", "defaultValues", "numElems", "numDims", "numValues", "sparseToDense_", "$sparseIndices", "$sparseValues", "sparse_to_dense.validateInput", "sparseToDense", "gatherND_", "gatherND", "getNoiseShape", "noiseShape", "newDimension", "dropout_", "rate", "$noiseShape", "keepProb", "dropout", "enclosingPowerOfTwo", "cosineWindow", "windowLength", "even", "newValues", "cosArg", "inTopKAsync_", "predictions", "targets", "$predictions", "$targets", "predictionsVals", "targetsVals", "precision", "valAndInd", "inTopKAsync", "conv2DBackpropFilter_", "conv2DBackpropFilter", "getFusedDyActivation", "activation", "getFusedBiasGradient", "dyActivation", "reduceAxes", "broadcast_util.getReductionAxes", "applyActivation", "preluActivationWeights", "leakyreluAlpha", "shouldFuse", "gradientDepth", "gradientMode", "fusedConv2d_", "unfusedConv2d", "conv_util.computeConv2DInfo", "$bias", "broadcast_util.assertAndGetBroadcastShape", "$preluActivationWeights", "alphaShape_1", "conv_util.tupleValuesAreOne", "xDer", "filterDer", "der", "biasDer", "customOpWithBias", "depthwiseConv2dNativeBackpropFilter_", "depthwiseConv2dNativeBackpropFilter", "depthwiseConv2dNativeBackpropInput_", "depthwiseConv2dNativeBackpropInput", "fusedDepthwiseConv2d_", "unfusedDepthwiseConv2d", "fusedMatMul_", "unfusedMatMul", "innerShapeA", "innerShapeB", "outerShapeA", "outerShapeB", "outerDimsA", "outerDimsB", "batchDimA", "batchDimB", "outShapeOuterDims", "a3D", "b3D", "aDer", "bDer", "hammingWindow_", "hammingWindow", "hannWindow_", "hannWindow", "frame_", "signal", "frameLength", "frameStep", "padValue", "padLen", "frame", "stft_", "windowFn", "framedSignal", "windowedSignal", "stft", "cropAndResize_", "boxes", "boxInd", "cropSize", "method", "extrapolationValue", "$image", "$boxes", "$boxInd", "numBoxes", "cropAndResize", "flipLeftRight_", "flipLeftRight", "grayscaleToRGB_", "lastDimsIdx", "lastDims", "grayscaleToRGB", "rgbToGrayscale_", "origDtype", "fltImage", "rgbWeights", "grayFloat", "rgbToGrayscale", "rotateWithOffset_", "radians", "fillValue", "center", "rotateWithOffset", "nonMaxSuppSanityCheck", "scores", "maxOutputSize", "iouThreshold", "scoreThreshold", "softNmsSigma", "nonMaxSuppression_", "$scores", "nonMaxSuppression", "binaryInsert", "element", "comparator", "binarySearch", "insertionPoint", "target", "binarySearch_", "defaultComparator", "found", "compareResult", "nonMaxSuppressionV3Impl", "nonMaxSuppressionImpl_", "nonMaxSuppressionV4Impl", "padToMaxOutputSize", "nonMaxSuppressionV5Impl", "returnScoresTensor", "returnValidOutputs", "candidates", "ascendingComparator", "selectedIndices", "selectedScores", "candidate", "originalScore", "boxIndex", "suppressBeginIndex", "ignoreCandidate", "iou", "intersectionOverUnion", "suppressWeight", "validOutputs", "elemsToPad", "iCoord", "jCoord", "yminI", "xminI", "ymaxI", "xmaxI", "yminJ", "xminJ", "ymaxJ", "xmaxJ", "areaI", "areaJ", "intersectionYmin", "intersectionXmin", "intersectionYmax", "intersectionXmax", "intersectionArea", "weight", "c1", "c2", "nonMaxSuppressionAsync_", "boxesAndScores", "boxesVals", "scoresVals", "nonMaxSuppressionAsync", "nonMaxSuppressionWithScore_", "nonMaxSuppressionWithScore", "nonMaxSuppressionWithScoreAsync_", "nonMaxSuppressionWithScoreAsync", "nonMaxSuppressionPadded_", "$maxOutputSize", "$iouThreshold", "$scoreThreshold", "nonMaxSuppressionPadded", "nonMaxSuppressionPaddedAsync_", "nonMaxSuppressionPaddedAsync", "resizeBilinear_", "images", "alignCorners", "halfPixelCenters", "$images", "batchImages", "resizeBilinear", "resizeNearestNeighbor_", "resizeNearestNeighbor", "threshold_", "inverted", "threshValue", "RED_INTENCITY_COEF", "GREEN_INTENCITY_COEF", "BLUE_INTENCITY_COEF", "totalPixelsInImage", "$threshold", "grayscale", "$r", "$g", "$histogram", "otsu", "invCondition", "histogram", "total", "bestThresh", "bestInBetVar", "cInBetVar", "classFirst", "classSecond", "meanFirst", "meanSec", "weightForeground", "weightBack", "meanFirstDivA", "meanSecFill", "meanSecAdd", "meanSecMul", "cInBetVarSubA", "cInBetVarSubB", "cInBetVarMul", "threshold", "transform_", "transforms", "interpolation", "fillMode", "$transforms", "transform", "bandPart_", "numLower", "numUpper", "M", "N", "$numLower", "$numUpper", "ij", "inBand", "zero", "mat", "bandPart", "gramSchmidt_", "inputIsTensor2D", "dim_1", "ys", "xs1d", "proj", "gramSchmidt", "qr_", "fullMatrices", "qr2d", "outerDimsProd", "x2ds", "q2ds_1", "r2ds_1", "x2d", "q2d", "r2d", "q", "one2D", "iters", "rTemp", "wTemp", "qTemp", "rjEnd1", "normX", "rjj", "u1", "wPre", "tau", "rjEndAll", "tauTimesW", "wT", "rTimesTau", "tawTimesWT", "qAllJEnd", "qTimesTau", "qr", "Reduction", "computeWeightedLoss_", "losses", "reduction", "$losses", "weightedLoss", "broadcastFactor", "broadcastedWeights", "numNonZeros", "computeWeightedLoss", "absoluteDifference_", "labels", "$labels", "absoluteDifference", "cosineDistance_", "cosineDistance", "hingeLoss_", "hingeLoss", "huberLoss_", "deltaScalar", "quadratic", "linear", "huberLoss", "logLoss_", "epsilonScalar", "l1", "l2", "logLoss", "meanSquaredError_", "meanSquaredError", "sigmoidCrossEntropyWithLogits_", "maxOutput", "outputXTarget", "sigmoidOutput", "sigmoidCrossEntropy_", "multiClassLabels", "labelSmoothing", "$multiClassLabels", "labelSmoothingScalar", "sigmoidCrossEntropy", "softmaxCrossEntropyWithLogits_", "lse", "logResult", "costVector", "dyShape", "softmaxCrossEntropy_", "onehotLabels", "$onehotLabels", "numClasses", "softmaxCrossEntropy", "sparseFillEmptyRows_", "denseShape", "$denseShape", "sparseFillEmptyRows", "sparseReshape_", "inputIndices", "$inputIndices", "$inputShape", "$newShape", "sparseReshape", "sparseSegmentMean_", "sparseSegmentMean", "sparseSegmentSum_", "sparseSegmentSum", "stringNGrams_", "dataSplits", "separator", "nGramWidths", "leftPad", "padWidth", "preserveShortSequences", "$dataSplits", "stringNGrams", "stringSplit_", "delimiter", "skipEmpty", "$delimiter", "stringSplit", "stringToHashBucketFast_", "numBuckets", "stringToHashBucketFast", "staticRegexReplace_", "pattern", "rewrite", "replaceGlobal", "staticRegexReplace", "spectral", "linalg", "sparse", "string", "GLOBAL_CUSTOM_OBJECT", "GLOBAL_CUSTOM_NAMES", "Serializable", "cls", "SerializationMap", "registerClass", "pkg", "className", "registerName", "getRegisteredName", "Optimizer", "returnCost", "gradArray", "weightValues", "AdadeltaOptimizer", "learningRate", "rho", "variableGradients", "variableNames", "gradient", "accumulatedGrad", "accumulatedUpdate", "newAccumulatedGrad", "newAccumulatedUpdate", "variables", "variableCount", "AdagradOptimizer", "initialAccumulatorValue", "trainable_1", "AdamOptimizer", "beta1", "beta2", "varNames", "oneMinusAccBeta1", "oneMinusAccBeta2", "firstMoment", "secondMoment", "newFirstMoment", "newSecondMoment", "biasCorrectedFirstMoment", "biasCorrectedSecondMoment", "AdamaxOptimizer", "lr", "weightedInfNorm", "ut0", "ut1", "newWeightedInfNorm", "SGDOptimizer", "MomentumOptimizer", "momentum", "useNesterov", "accumulation", "newAccumulation", "RMSPropOptimizer", "centered", "accumulatedMeanSquare", "accumulatedMoments", "newAccumulatedMeanSquare", "accumulatedMeanGrad", "newAccumulatedMeanGrad", "gradContribution", "newAccumulatedMoments", "newAccumulatedMeanSquare_1", "OPTIMIZERS", "registerOptimizers", "OPTIMIZERS_1", "OPTIMIZERS_1_1", "optimizer", "DEFAULT_FILE_NAME_PREFIX", "DEFAULT_JSON_EXTENSION_NAME", "DEFAULT_WEIGHT_DATA_EXTENSION_NAME", "defer", "BrowserDownloads", "fileNamePrefix", "weightsURL", "modelJsonURL", "jsonAnchor_1", "weightDataAnchor_1", "BrowserFiles", "files", "jsonReader", "modelTopology", "modelArtifactsPromise", "paths", "pathToFile", "promises", "file", "weightFileReader", "basenames", "fileNames", "manifest_1", "manifest_1_1", "pathBasename", "browserDownloadsRouter", "browserDownloads", "browserFiles", "monitorPromisesProgress", "onProgress", "startFraction", "endFraction", "checkPromises", "checkFraction", "resolvedPromise", "registerMonitor", "promise", "fraction", "loadWeightsAsArrayBuffer", "fetchURLs", "fetchFunc", "requests", "fetchURL", "fetchStartFraction", "fetchEndFraction", "responses", "bufferPromises", "response", "bufferStartFraction", "bufferEndFraction", "streamWeights", "fetchIndex", "chunkReader", "controller", "filePathPrefix", "weightNames", "requestInit", "fetchWeights", "fetchUrls", "weightsLoaderFactory", "fetchWeightsFunction", "groupIndicesToFetchMap", "groupWeightsToFetch", "weightsFound", "allManifestWeightNames", "manifestGroupConfig", "groupIndex", "groupOffset", "weightsEntry", "rawDtype", "weightsBytes", "enqueueWeightsForFetchingFn", "weightName", "weightIndex", "weightsNotFound", "groupIndicesToFetch", "accumulator", "shouldFetch", "filepath", "fetchUrl", "weightsTensorMap", "bufferIndexOffset", "numBuffers", "weightsBuffer", "weightsEntries", "nameToTensorMap", "OCTET_STREAM_MIME_TYPE", "JSON_TYPE", "HTTPRequest", "modelTopologyAndWeightManifest", "modelConfigRequest", "message", "stream", "weightPath", "parseUrl", "pathPrefix", "urlPromises", "weightsGroup", "e_3", "_k", "lastSlash", "lastSearchParam", "isHTTPScheme", "httpRouter", "isHTTP", "urlItem", "http", "browserHTTPRequest", "PassthroughLoader", "PassthroughSaver", "PassthroughAsync", "fromMemory", "trainingConfig", "fromMemorySync", "isModelArtifacts", "withSaveHandler", "withSaveHandlerSync", "confusionMatrix_", "oneHotLabels", "oneHotPredictions", "oneHotLabelsT", "product", "confusionMatrix", "fromPixels2DContext", "hasToPixelsWarned", "fromPixels_", "pixels", "numChannels", "isPixelData", "isImageData", "isVideo", "isImage", "isCanvasLike", "isImageBitmap", "height", "numPixels", "channel", "isImageBitmapFullySupported", "isNonEmptyPixels", "canWrapPixelsToImageBitmap", "fromPixelsAsync", "imageBitmap", "validateImgTensor", "img", "validateImageOptions", "imageOptions", "toPixels", "canvas", "$img", "originalImgTensor", "rgba", "ctx", "imageData", "draw", "fromPixels", "prepareAndValidate", "tensorRank", "indicesShape", "nResult", "resultShape", "NEW_AXIS", "SHRINK_AXIS", "assertParamsValid", "maskToAxes", "computeOutShape", "stridesWithElidedDims", "ellipsisInsertionIndex", "numElidedAxes", "newStrides", "unnormalizeAxis", "normalizedAxis", "getElidedAxes", "elidedAxes", "getNormalizedAxes", "ellipsisAxes", "numInterpolatedAxes", "normalizedBegin", "normalizedEnd", "normalizedStrides", "fullIndex", "startIndicesWithElidedDims", "stopIndicesWithElidedDims", "startForAxis", "stopForAxis", "stridesForAxis", "originalBegin", "newIndices", "originalAxis", "originalValue", "originalEnd", "axisSize", "util.clamp", "startIndices", "stopIndices", "isSliceContinous", "firstNonOneAxis", "computeFlatOffset", "flatOffset", "parseSliceParams", "begin_", "xRank", "size_", "sliceInfo", "stridesNonNull", "ellipsisSeen", "sparseSpec", "denseSpec", "buildDenseSpec", "isIdentity", "sliceDim0", "isSimpleSlice", "processingShape", "finalShape", "shrinkI", "dimI", "masks", "validRange", "beginAndEndMasked", "xFwd", "canonical", "takeAllInDimension", "intervalLength", "knownInterval", "sizeI", "denseDim", "gatherIndex", "finalShapeSparse", "dense", "nextIndex", "strideI", "version", "OptimizerConstructors", "train", "delayCallback", "nextFrame", "assertParamsConsistent", "shapes", "firstShape", "RowPartitionType", "combineRaggedTensorToTensorShapes", "raggedRank", "valueShape", "valueDim", "outputShapeDimIndex", "outputShapeDim", "getRowPartitionTypesHelper", "rowPartitionTypeStrings", "stringToType", "rowPartitionTypeStrings_1", "rowPartitionTypeStrings_1_1", "typeStr", "getRaggedRank", "validateDefaultValueShape", "defaultValueShape", "defaultNDims", "valuesNDims", "defaultDim", "PARALLELIZE_THRESHOLD", "computeOptimalWindowSize", "inSize", "getImageCenter", "imageHeight", "imageWidth", "centerX", "centerY", "getReshaped", "batchToSpace", "reshaped", "spatialLength", "getPermuted", "reshapedRank", "blockShapeRank", "permuted", "permutedBeforeBatch", "permutedAfterBatch", "getReshapedPermuted", "reshapedPermuted", "getSliceBeginCoords", "sliceBeginCoords", "getSliceSize", "uncroppedShape", "SELU_SCALEALPHA", "SELU_SCALE", "ERF_P", "ERF_A1", "ERF_A2", "ERF_A3", "ERF_A4", "ERF_A5", "mergeRealAndImagArrays", "splitRealAndImagArrays", "complexWithEvenIndex", "complexWithOddIndex", "getComplexWithIndex", "assignToTypedArray", "exponents", "inverse", "exponent", "ARROW", "ARROW_REGEX", "COMMA", "ELLIPSIS", "decodeEinsumEquation", "numTensors", "numArrows", "inputString", "outputString", "inputTerms", "numInputs", "allDims", "dimName", "inputTerm", "idDims", "numOutDims", "summedDims", "getEinsumPermutation", "nDims", "permutationIndices", "checkEinsumDimSizes", "dimSizes", "getEinsumComputePath", "steps", "nSteps", "computedTermIndices", "summedDim", "termIndices", "findTermsWithDim", "termIndices_1", "e_1", "termIndices_1_1", "termIndex", "isIdentityPermutation", "prepareSplitSize", "splitSizes", "numOfNegs", "negIndex", "getSparseFillEmptyRowsIndicesDenseShapeMismatch", "indicesLength", "getSparseFillEmptyRowsNegativeIndexErrorMessage", "getSparseFillEmptyRowsOutOfRangeIndexErrorMessage", "getSparseReshapeMultipleNegativeOneOutputDimErrorMessage", "dim1", "dim2", "getSparseReshapeNegativeOutputDimErrorMessage", "getSparseReshapeEmptyTensorZeroOutputDimErrorMessage", "getSparseReshapeInputOutputMultipleErrorMessage", "inputSize", "getSparseReshapeInputOutputMismatchErrorMessage", "getSparseSegmentReductionNegativeSegmentIdsErrorMessage", "getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage", "getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage", "segmentId", "getSparseSegmentReductionIndicesOutOfRangeErrorMessage", "indexValue", "segOpComputeOptimalWindowSize", "collectGatherOpShapeInfo", "outerSize", "fromUint8ToStringArray", "fromStringArrayToUint8", "strings", "ENV", "env", "debugValue", "extendStatics", "d", "b", "p", "__extends", "__", "__awaiter", "thisArg", "_arguments", "P", "generator", "adopt", "value", "resolve", "reject", "fulfilled", "step", "e", "rejected", "result", "__generator", "body", "_", "t", "f", "y", "g", "verb", "n", "v", "op", "__values", "o", "s", "m", "i", "__read", "r", "ar", "error", "__spreadArray", "to", "from", "pack", "l", "DataType", "SaverDef", "CheckpointFormatVersion", "CUSTOM_OPS", "registerOp", "name", "opFunc", "opMapper", "getRegisteredOp", "deregisterOp", "getParamValue", "paramName", "node", "tensorMap", "context", "resourceManager", "inputParam", "start", "end", "shiftedStart", "getTensor", "inputs_1", "inputNames", "_name", "index", "_a", "tensor", "data", "util", "attrParam", "tensorsMap", "_b", "parseNodeName", "nodeName", "contextId", "getNodeNameWithContextId", "getTensorsForCurrentContext", "getNodeNameAndIndex", "inputName", "outputName", "isCacheEnabled", "cachedResult", "parts", "getPadding", "pad", "explicitPadding", "cloneTensor", "clone", "json", "OperationMapper", "ops", "arithmetic", "basicMath", "control", "convolution", "creation", "dynamic", "evaluation", "graph", "hashTable", "image", "logical", "matrices", "normalization", "reduction", "sliceJoin", "sparse", "spectral", "string", "transformation", "mappersJson", "map", "mapper", "signature", "_this", "tfNodes", "placeholders", "weights", "initNodes", "nodes", "inputs", "outputs", "inputNodeNameToKey", "outputNodeNameToKey", "allNodes", "key", "inputNode", "outputIndex", "functions", "func", "entries", "prev", "curr", "newNode", "input", "param", "type", "getStringParam", "getStringArrayParam", "getNumberParam", "getNumericArrayParam", "getBoolParam", "getBoolArrayParam", "getTensorShapeParam", "getTensorShapeArrayParam", "getDtypeParam", "getDtypeArrayParam", "getFuncParam", "functionDef", "arg", "parseDtypeParam", "returnNodeMap", "output", "nameMap", "decodeBase64", "text", "global", "parseStringParam", "keepCase", "attrs", "def", "tensorflow.DataType", "parseTensorShapeParam", "shape", "dim", "NodeValueImpl", "defaultValue", "EPSILON_FLOAT32", "EPSILON_FLOAT16", "KernelBackend", "dataId", "notYetImplemented", "options", "force", "values", "dtype", "refCount", "kernelName", "assert", "expr", "msg", "assertShapesMatch", "shapeA", "shapeB", "errorMessagePrefix", "arraysEqual", "assertNonNull", "a", "sizeFromShape", "size", "arraysEqualWithNull", "n1", "n2", "isInt", "rightPad", "parseAxisParam", "axis", "rank", "ax", "squeezeShape", "newShape", "keptDims", "isEmptyArray", "axes", "j", "getTypedArrayFromDType", "getArrayFromDType", "checkConversionForErrors", "vals", "num", "isValidDtype", "bytesPerElement", "bytesFromStringArray", "arr", "bytes", "x", "isString", "isBoolean", "isNumber", "inferDtype", "isFunction", "computeStrides", "strides", "createNestedArray", "offset", "isComplex", "ret", "rest", "len", "acc", "c", "toNestedArray", "makeOnesTypedArray", "array", "makeZerosTypedArray", "assertNonNegativeIntegerDimensions", "dimSize", "isPromise", "object", "TENSORFLOWJS_FLAGS_PREFIX", "Environment", "getQueryParams", "platformName", "platform", "flagName", "evaluationFn", "setHook", "flagValue", "_c", "flags", "urlParams", "keyValues", "keyValue", "parseValue", "queryString", "params", "_i", "decodeParam", "lowerCaseValue", "setEnvironmentGlobal", "environment", "globalNameSpace", "getGlobalNamespace", "ns", "getGlobalMap", "getGlobal", "init", "globalMap", "singleton", "Abs", "Acos", "Acosh", "Add", "AddN", "All", "Any", "ArgMax", "ArgMin", "Asin", "Asinh", "Atan", "Atanh", "Atan2", "AvgPool", "AvgPool3D", "BatchMatMul", "BatchToSpaceND", "Bincount", "BitwiseAnd", "BroadcastArgs", "Cast", "Ceil", "ClipByValue", "Complex", "ComplexAbs", "Concat", "Conv2D", "Conv2DBackpropFilter", "Conv2DBackpropInput", "Conv3D", "Conv3DBackpropInputV2", "Cos", "Cosh", "Cumprod", "Cumsum", "CropAndResize", "DenseBincount", "DepthToSpace", "DepthwiseConv2dNative", "DepthwiseConv2dNativeBackpropFilter", "DepthwiseConv2dNativeBackpropInput", "Diag", "Dilation2D", "RealDiv", "Einsum", "Elu", "Erf", "Equal", "Exp", "ExpandDims", "Expm1", "FFT", "Fill", "FlipLeftRight", "Floor", "FloorDiv", "FusedBatchNorm", "GatherV2", "GatherNd", "Greater", "GreaterEqual", "Identity", "IFFT", "Imag", "IsFinite", "IsInf", "IsNan", "LeakyRelu", "Less", "LessEqual", "LinSpace", "Log", "Log1p", "LogicalAnd", "LogicalNot", "LogicalOr", "LRN", "Max", "Maximum", "MaxPool", "MaxPool3D", "MaxPoolWithArgmax", "Mean", "Min", "Minimum", "MirrorPad", "Mod", "Multinomial", "Multiply", "Neg", "NotEqual", "NonMaxSuppressionV3", "NonMaxSuppressionV4", "NonMaxSuppressionV5", "OnesLike", "OneHot", "Pack", "PadV2", "Pow", "Prelu", "Prod", "RaggedGather", "RaggedRange", "RaggedTensorToTensor", "Range", "Real", "Reciprocal", "Relu", "Reshape", "ResizeNearestNeighbor", "ResizeBilinear", "Relu6", "Reverse", "Round", "Rsqrt", "ScatterNd", "TensorScatterUpdate", "SearchSorted", "Select", "Selu", "Slice", "Sin", "Sinh", "Sign", "Sigmoid", "Softplus", "Sqrt", "Sum", "SpaceToBatchND", "SplitV", "Softmax", "SparseFillEmptyRows", "SparseReshape", "SparseSegmentMean", "SparseSegmentSum", "SparseToDense", "SquaredDifference", "StaticRegexReplace", "StridedSlice", "StringNGrams", "StringSplit", "StringToHashBucketFast", "Sub", "Tan", "Tanh", "Tile", "TopK", "Transform", "Transpose", "Unique", "Unpack", "UnsortedSegmentSum", "ZerosLike", "Step", "RotateWithOffset", "_FusedMatMul", "FusedConv2D", "FusedDepthwiseConv2D", "warn", "kernelRegistry", "gradRegistry", "getKernel", "backendName", "makeKey", "getGradient", "getKernelsForBackend", "it", "done", "config", "backend", "isTypedArrayBrowser", "long", "Long", "wasm", "low", "high", "unsigned", "isLong", "obj", "INT_CACHE", "UINT_CACHE", "fromInt", "cachedObj", "cache", "fromBits", "fromNumber", "UZERO", "ZERO", "TWO_PWR_64_DBL", "MAX_UNSIGNED_VALUE", "TWO_PWR_63_DBL", "MIN_VALUE", "MAX_VALUE", "TWO_PWR_32_DBL", "lowBits", "highBits", "pow_dbl", "fromString", "str", "radix", "radixToPower", "power", "fromValue", "val", "TWO_PWR_16_DBL", "TWO_PWR_24_DBL", "TWO_PWR_24", "ONE", "UONE", "NEG_ONE", "LongPrototype", "radixLong", "div", "rem1", "rem", "remDiv", "intval", "digits", "bit", "other", "thisNeg", "otherNeg", "addend", "a48", "a32", "a16", "a00", "b48", "b32", "b16", "b00", "c48", "c32", "c16", "c00", "subtrahend", "multiplier", "divisor", "approx", "res", "halfThis", "log2", "delta", "approxRes", "approxRem", "numBits", "le", "hi", "lo", "LongExports.default", "LongExports", "hexToLong", "hex", "noConversionNeeded", "toTypedArray", "flatten", "base.checkConversionForErrors", "bool", "now", "encodeString", "encoding", "decodeString", "isTypedArray", "skipTypedArray", "base.isPromise", "maxIndex", "Profiler", "backendTimer", "logger", "Logger", "holdResultWrapperFn", "timer", "util.now", "outputs_1", "outputs_1_1", "tensorVals", "checkComputationForErrors", "kernelProfile", "timing", "timeMs", "extraInfo", "valueContainer", "time", "util.rightPad", "paddedName", "inputShapesDescription", "name_1", "inputShape", "inputRank", "getFilteredNodesXToY", "tape", "xs", "tensorsFromX", "nodesFromX", "nodeInputs", "anyInputFromX", "tensorsLeadToY", "nodesToY", "filteredTape", "prunedInputs", "nodeInput", "prunedNode", "backpropagateGradients", "tensorAccumulatedGradientMap", "tidy", "add", "dys", "gradTensor", "inputGradients", "dx", "util.arraysEqual", "curGradient", "FORMAT_LIMIT_NUM_VALS", "FORMAT_NUM_FIRST_LAST_VALS", "FORMAT_NUM_SIG_DIGITS", "tensorToString", "verbose", "padPerCol", "computeMaxSizePerColumn", "valsLines", "subTensorToString", "lines", "numCols", "valuesOrTuples", "createComplexTuples", "row", "valToString", "valStr", "boolNumToString", "isLast", "storagePerElement", "complexTuple", "firstValsSize", "firstVals", "lastVals", "displayVals", "subshape", "substrides", "stride", "sep", "newLineSep", "complexTuples", "TensorBuffer", "util.sizeFromShape", "n_1", "util.assert", "util.getArrayFromDType", "locs", "locs_1", "locs_1_1", "loc", "i_1", "trackerFn", "opHandler", "setTensorTracker", "fn", "Tensor", "id", "util.decodeString", "trainable", "instance", "getGlobalTensorClass", "Variable", "_super", "initialValue", "tensorId", "newValue", "Rank", "UpcastInt32AndMap", "UpcastBoolAndMap", "UpcastFloat32AndMap", "UpcastComplex64AndMap", "upcastTypeMap", "upcastType", "typeA", "typeB", "isWebGLData", "isWebGPUData", "makeTypesMatch", "assertTypesMatch", "getTensorsInContainer", "list", "seen", "walkTensorContainer", "container", "isIterable", "iterable", "k", "isRegisteredKernelInvocation", "kernelInvocation", "EngineState", "variableName", "Engine", "sortedBackends", "success", "asyncInit", "factory", "priority", "log.warn", "kernels", "kernel", "registryFactoryEntry", "promiseId_1", "backendInstance", "err", "info", "srcBackend", "nameOrFn", "ex", "ENGINE", "grad", "dy", "gradInputs", "saved", "hasKernel", "numDataIdsBefore", "outInfos", "numDataIdsAfter", "numOutputDataIds", "numMoves", "dataIdsLeaked", "kernelParams", "isTapeOn", "startingBytecount", "startingNumTensors", "kernelFunc", "out", "kernelOrScopeName", "kernelName_1", "attrs_1", "kernel_1", "outTensors", "outInfo", "tensorsToSave", "forwardFunc_1", "saveFunc_1", "tensors", "outs", "backwardsFunc", "item", "gradConfig", "inputsToSave", "outputsToSave_1", "inputTensorsToSave", "outputTensorsToSave", "backendVals", "util.isString", "util.encodeString", "newBytes", "tensorInfo", "util.bytesPerElement", "varName", "query", "startBytes", "startNumTensors", "_g", "_d", "_e", "gradientsFunc", "tapeNode", "util.makeZerosTypedArray", "scopeInfo", "tensorsToTrackInParent", "tensorsToTrackInParentSet", "oldScope", "allowNoGradients", "accumulatedGradientMap", "ones", "grads", "util.isFunction", "inputMap", "forwardFunc", "save", "gradRes", "gradMap", "timingInfo", "getOrMakeEngine", "inferShape", "firstElem", "usedChannels", "deepAssertShapeConsistency", "indices", "subShape", "assertDtype", "expectedDtype", "actualDType", "argName", "functionName", "convertToTensor", "parseAsDtype", "inferredDtype", "inferredShape", "convertToTensorArray", "OP_SCOPE_SUFFIX", "keys", "opName", "f2", "args", "abs_", "$x", "abs", "acos_", "acos", "acosh_", "acosh", "add_", "$a", "$b", "addN_", "$tensors", "firstTensor", "addN", "all_", "keepDims", "all", "any_", "any", "argMax_", "argMax", "argMin_", "argMin", "asin_", "asin", "asinh_", "asinh", "atan_", "atan", "atan2_", "atan2", "atanh_", "atanh", "cast_", "util.isValidDtype", "cast", "computePool2DInfo", "inShape", "filterSize", "dilations", "roundingMode", "dataFormat", "parseTupleParam", "filterHeight", "filterWidth", "filterShape", "computeConv2DInfo", "depthwise", "batchSize", "inHeight", "inWidth", "inChannels", "filterChannels", "strideHeight", "strideWidth", "_f", "dilationHeight", "dilationWidth", "effectiveFilterHeight", "getEffectiveFilterSize", "effectiveFilterWidth", "getPadAndOutInfo", "padInfo", "outHeight", "outWidth", "outChannels", "outShape", "computeOutputShape2D", "fieldSize", "zeroPad", "computeDefaultPad", "inputRows", "inputCols", "outputRows", "round", "outputCols", "dilation", "effectiveFieldSize", "padType", "padAlongHeight", "padAlongWidth", "top", "bottom", "left", "right", "tupleValuesAreOne", "dimA", "dimB", "dimC", "eitherStridesOrDilationsAreOne", "stridesOrDilationsArePositive", "checkPadOnDimRoundingMode", "opDesc", "dimRoundingMode", "util.isInt", "reshape_", "reshape", "avgPool_", "conv_util.eitherStridesOrDilationsAreOne", "x4D", "reshapedTo4D", "conv_util.checkPadOnDimRoundingMode", "avgPool", "avgPool3d_", "x5D", "reshapedTo5D", "avgPool3d", "clone_", "concat_", "attr", "concat", "matMul_", "transposeA", "transposeB", "matMul", "mul_", "mul", "sigmoid_", "sigmoid", "slice_", "begin", "slice", "tanh_", "tanh", "basicLSTMCell_", "forgetBias", "lstmKernel", "lstmBias", "h", "$forgetBias", "$lstmKernel", "$lstmBias", "$data", "$c", "$h", "combined", "weighted", "sliceCols", "sliceSize", "newC", "newH", "basicLSTMCell", "batchToSpaceND_", "blockShape", "crops", "prod", "batchToSpaceND", "xAs4D", "batchNorm_", "mean", "variance", "scale", "varianceEpsilon", "$mean", "$variance", "$scale", "$offset", "batchNorm", "batchNorm2d_", "batchNorm2d", "batchNorm3d_", "batchNorm3d", "batchNorm4d_", "batchNorm4d", "bincount_", "$weights", "bincount", "bitwiseAnd_", "$y", "bitwiseAnd", "broadcastArgs_", "s0", "s1", "shape1Input", "shape2Input", "broadcastArgs", "broadcastTo_", "xShape", "reps", "broadcastTo", "buffer", "util.assertNonNegativeIntegerDimensions", "ceil_", "ceil", "fill", "clipByValue_", "clipValueMin", "clipValueMax", "clipByValue", "complex_", "real", "imag", "$real", "$imag", "util.assertShapesMatch", "complex", "concat1d_", "concat1d", "concat2d_", "concat2d", "concat3d_", "concat3d", "concat4d_", "concat4d", "conv2d_", "filter", "$filter", "inDepth", "conv_util.stridesOrDilationsArePositive", "conv2d", "conv1d_", "x3D", "reshapedTo3D", "filter4D", "input4D", "conv2dDataFormat", "conv1d", "conv2DBackpropInput_", "xShape4D", "dy4D", "outDepth", "conv2DBackpropInput", "conv2dTranspose_", "outputShape", "conv2dTranspose", "conv3d_", "conv3d", "conv3DBackpropInput_", "xShape5D", "dy5D", "conv3DBackpropInput", "conv3dTranspose_", "conv3dTranspose", "cos_", "cos", "cosh_", "cosh", "cumprod_", "exclusive", "reverse", "cumprod", "cumsum_", "cumsum", "denseBincount_", "binaryOutput", "denseBincount", "depthToSpace_", "blockSize", "inputHeight", "inputWidth", "inputDepth", "depthToSpace", "depthwiseConv2d_", "depthwiseConv2d", "diag_", "diag", "dilation2d_", "dilation2d", "floorDiv_", "floorDiv", "div_", "getReductionAxes", "inDim", "outAxis", "outDim", "assertAndGetBroadcastShape", "errMsg", "equal_", "equal", "where_", "condition", "$condition", "broadcastShape", "$broadcastedCondition", "$broadcastedA", "$broadcastedB", "where", "zerosLike_", "zerosLike", "divNoNan_", "divResult", "zeros", "bEqualsZero", "divNoNan", "dot_", "t1", "t2", "$t1", "$t2", "t1Inner", "t2Inner", "t12D", "t22D", "t1t2", "dot", "einsum_", "equation", "einsum", "elu_", "elu", "ensureShape_", "ensureShape", "erf_", "erf", "combineLocations", "outputLoc", "reduceLoc", "outIdx", "reduceIdx", "expandShapeToKeepDim", "reduceSubShape", "max_", "max", "min_", "min", "pow_", "base", "exp", "$base", "$exp", "pow", "makeTensor", "providedSize_1", "inferredSize_1", "inferred", "flatDimsDontMatch", "scalar", "sqrt_", "sqrt", "square_", "square", "sum_", "sum", "norm_", "ord", "norm", "normImpl", "keepDimsShape", "axis_util.expandShapeToKeepDim", "euclideanNorm_", "euclideanNorm", "exp_", "expandDims_", "expandDims", "expm1_", "expm1", "tile_", "tile", "eye_", "numRows", "numColumns", "batchShape", "buff", "eye", "floor_", "floor", "gather_", "batchDims", "$indices", "gather", "greater_", "greater", "greaterEqual_", "greaterEqual", "imag_", "$input", "isFinite_", "isFinite", "isInf_", "isInf", "isNaN_", "isNaN", "leakyRelu_", "alpha", "leakyRelu", "less_", "less", "lessEqual_", "lessEqual", "linspace", "stop", "localResponseNormalization_", "depthRadius", "bias", "beta", "localResponseNormalization", "log_", "log", "log1p_", "log1p", "customGrad", "neg_", "neg", "softplus_", "softplus", "logSigmoid_", "customOp", "gradFunc", "derX", "logSigmoid", "sub_", "sub", "logSoftmax_", "logits", "$logits", "xMax", "shifted", "softmax", "logSoftmax", "logSumExp_", "logSumExp", "logicalAnd_", "logicalAnd", "logicalNot_", "logicalNot", "logicalOr_", "logicalOr", "logicalXor_", "logicalXor", "INT32_MAX", "searchSorted_", "sortedSequence", "side", "$sortedSequence", "$values", "sequenceSize", "valuesSize", "$sortedSequence2D", "$values2D", "searchSorted", "lowerBound", "maxPool_", "maxPool", "maxPool3d_", "maxPool3d", "maxPoolWithArgmax_", "includeBatchInIndex", "maxPoolWithArgmax", "maximum_", "maximum", "mean_", "meshgrid", "indexing", "w", "minimum_", "minimum", "mirrorPad_", "paddings", "mode", "shapeOffset", "mirrorPad", "mod_", "mod", "moments_", "xMean", "devSquared", "moments", "multiRNNCell_", "lstmCells", "newStates", "multiRNNCell", "multinomial_", "numSamples", "seed", "normalized", "numOutcomes", "origRank", "logits2D", "multinomial", "notEqual_", "notEqual", "oneHot_", "depth", "onValue", "offValue", "oneHot", "onesLike_", "onesLike", "outerProduct_", "v1", "v2", "$v1", "$v2", "v12D", "v22D", "outerProduct", "pad_", "constantValue", "pad1d_", "pad1d", "pad2d_", "pad2d", "pad3d_", "pad3d", "pad4d_", "pad4d", "spaceToBatchND_", "spaceToBatchND", "pool_", "windowShape", "poolingType", "convInfo", "conv_util.computePool2DInfo", "basePadding", "withSpaceToBatchBasePaddings", "isDilationOne", "requiredSpaceToBatchPaddings", "adjustedPadding", "adjustedCrops", "convertedPad", "convertedX", "forwardOp", "padStart", "origPadEnd", "fullInputShape", "padEndExtra", "padEnd", "dilatedFilterShape", "padExtraShape", "padExtraStart", "padExtraEnd", "pool", "prelu_", "$alpha", "prelu", "print", "prod_", "raggedGather_", "paramsNestedSplits", "paramsDenseValues", "outputRaggedRank", "$paramsNestedSplits", "$paramsDenseValues", "raggedGather", "raggedRange_", "starts", "limits", "deltas", "$starts", "$limits", "$deltas", "raggedRange", "raggedTensorToTensor_", "rowPartitionTensors", "rowPartitionTypes", "$shape", "$defaultValue", "$rowPartitionTensors", "raggedTensorToTensor", "rand_", "randFunction", "rand", "module", "define", "Alea", "me", "mash", "Mash", "copy", "impl", "opts", "xg", "state", "prng", "this", "XorGen", "strseed", "bot", "X", "limit", "math", "width", "chunks", "rngname", "startdenom", "significance", "overflow", "mask", "nodecrypto", "seedrandom", "callback", "shortseed", "mixkey", "tostring", "autoseed", "arc4", "ARC4", "is_math_call", "keylen", "count", "typ", "prop", "stringseed", "smear", "browser", "plugins", "require$$0", "alea", "xor128", "require$$1", "xorwow", "require$$2", "xorshift7", "require$$3", "xor4096", "require$$4", "tychei", "require$$5", "sr", "require$$6", "MPRandGauss", "stdDeviation", "truncated", "seedValue", "seedrandom.alea", "resultX", "resultY", "isValid", "RandGamma", "x2", "v0", "u", "UniformRandom", "randomGamma_", "rgamma", "randomGamma", "randomNormal_", "stdDev", "randGauss", "randomNormal", "randomStandardNormal_", "randomStandardNormal", "randomUniform_", "minval", "maxval", "random", "randomUniform", "randomUniformInt_", "randomUniformInt", "range", "real_", "reciprocal_", "reciprocal", "relu_", "relu", "relu6_", "relu6", "reverse_", "reverse1d_", "reverse1d", "reverse2d_", "reverse2d", "reverse3d_", "reverse3d", "reverse4d_", "reverse4d", "round_", "rsqrt_", "rsqrt", "selu_", "selu", "separableConv2d_", "depthwiseFilter", "pointwiseFilter", "$depthwiseFilter", "$pointwiseFilter", "channelMultiplier", "pointwiseStride", "separableConv2d", "setdiff1dAsync_", "xVals", "yVals", "ySet", "outputSize", "setdiff1dAsync", "sign_", "sign", "sin_", "sin", "sinh_", "sinh", "slice1d_", "slice1d", "slice2d_", "slice2d", "slice3d_", "slice3d", "slice4d_", "slice4d", "softmax_", "fft_", "fft", "ifft_", "ifft", "irfft_", "innerDimensionSize", "batch", "complexInput", "realInput", "imagInput", "realConjugate", "imagConjugate", "temp", "batch_1", "irfft", "split_", "numOrSizeSplits", "split", "rfft_", "fftLength", "adjustedInput", "zerosShape", "zerosInput", "half", "realValues", "imagValues", "realComplexConjugate", "imagComplexConjugate", "rfft", "squaredDifference_", "squaredDifference", "squeeze_", "squeeze", "stack_", "stack", "step_", "stridedSlice_", "beginMask", "endMask", "ellipsisMask", "newAxisMask", "shrinkAxisMask", "stridedSlice", "tan_", "tan", "tensor1d", "tensor2d", "tensor3d", "tensor4d", "tensor5d", "tensor6d", "validateUpdateShape", "updates", "sliceDim", "batchDim", "shapeError", "validateInput", "tensorScatterUpdate_", "$tensor", "$updates", "scatter_nd_util.validateInput", "tensorScatterUpdate", "topk_", "sorted", "lastDim", "topk", "truncatedNormal_", "truncatedNormal", "unique_", "unique", "unsortedSegmentSum_", "segmentIds", "numSegments", "$segmentIds", "unsortedSegmentSum", "unstack_", "unstack", "upperBound", "variable", "whereImpl", "condShape", "condVals", "inBuffer", "whereAsync_", "whereAsync", "booleanMaskAsync_", "$mask", "axisFrom", "maskDim", "tensorShape", "leadingSize", "targetTensorShape", "reshapedTensor", "reshapedMask", "positivePositions", "booleanMaskAsync", "dispose", "getBackend", "transpose_", "perm", "conjugate", "transpose", "movingAverage_", "decay", "zeroDebias", "$v", "$decay", "one", "oneMinusDecay", "update", "$step", "movingAverage", "scatterND_", "scatterND", "sparseIndices", "sparseValues", "defaultValues", "numElems", "numDims", "numValues", "sparseToDense_", "$sparseIndices", "$sparseValues", "sparse_to_dense.validateInput", "sparseToDense", "gatherND_", "gatherND", "getNoiseShape", "noiseShape", "newDimension", "dropout_", "rate", "$noiseShape", "keepProb", "dropout", "enclosingPowerOfTwo", "cosineWindow", "windowLength", "even", "newValues", "cosArg", "inTopKAsync_", "predictions", "targets", "$predictions", "$targets", "predictionsVals", "targetsVals", "precision", "valAndInd", "inTopKAsync", "conv2DBackpropFilter_", "conv2DBackpropFilter", "getFusedDyActivation", "activation", "getFusedBiasGradient", "dyActivation", "reduceAxes", "broadcast_util.getReductionAxes", "applyActivation", "preluActivationWeights", "leakyreluAlpha", "shouldFuse", "gradientDepth", "gradientMode", "fusedConv2d_", "unfusedConv2d", "inputChannels", "conv_util.computeConv2DInfo", "$bias", "broadcast_util.assertAndGetBroadcastShape", "$preluActivationWeights", "alphaShape_1", "conv_util.tupleValuesAreOne", "xDer", "filterDer", "der", "biasDer", "customOpWithBias", "depthwiseConv2dNativeBackpropFilter_", "depthwiseConv2dNativeBackpropFilter", "depthwiseConv2dNativeBackpropInput_", "depthwiseConv2dNativeBackpropInput", "fusedDepthwiseConv2d_", "unfusedDepthwiseConv2d", "fusedMatMul_", "unfusedMatMul", "innerShapeA", "innerShapeB", "outerShapeA", "outerShapeB", "outerDimsA", "outerDimsB", "batchDimA", "batchDimB", "outShapeOuterDims", "a3D", "b3D", "aDer", "bDer", "hammingWindow_", "hammingWindow", "hannWindow_", "hannWindow", "frame_", "signal", "frameLength", "frameStep", "padValue", "padLen", "frame", "stft_", "windowFn", "framedSignal", "windowedSignal", "stft", "cropAndResize_", "boxes", "boxInd", "cropSize", "method", "extrapolationValue", "$image", "$boxes", "$boxInd", "numBoxes", "cropAndResize", "flipLeftRight_", "flipLeftRight", "grayscaleToRGB_", "lastDimsIdx", "lastDims", "grayscaleToRGB", "rgbToGrayscale_", "origDtype", "fltImage", "rgbWeights", "grayFloat", "rgbToGrayscale", "rotateWithOffset_", "radians", "fillValue", "center", "rotateWithOffset", "nonMaxSuppSanityCheck", "scores", "maxOutputSize", "iouThreshold", "scoreThreshold", "softNmsSigma", "nonMaxSuppression_", "$scores", "nonMaxSuppression", "binaryInsert", "element", "comparator", "binarySearch", "insertionPoint", "target", "binarySearch_", "defaultComparator", "middle", "found", "compareResult", "nonMaxSuppressionV3Impl", "nonMaxSuppressionImpl_", "nonMaxSuppressionV4Impl", "padToMaxOutputSize", "nonMaxSuppressionV5Impl", "returnScoresTensor", "returnValidOutputs", "candidates", "ascendingComparator", "selectedIndices", "selectedScores", "candidate", "originalScore", "boxIndex", "suppressBeginIndex", "ignoreCandidate", "iou", "intersectionOverUnion", "suppressWeight", "validOutputs", "elemsToPad", "iCoord", "jCoord", "yminI", "xminI", "ymaxI", "xmaxI", "yminJ", "xminJ", "ymaxJ", "xmaxJ", "areaI", "areaJ", "intersectionYmin", "intersectionXmin", "intersectionYmax", "intersectionXmax", "intersectionArea", "weight", "c1", "c2", "nonMaxSuppressionAsync_", "boxesAndScores", "boxesVals", "scoresVals", "nonMaxSuppressionAsync", "nonMaxSuppressionWithScore_", "nonMaxSuppressionWithScore", "nonMaxSuppressionWithScoreAsync_", "nonMaxSuppressionWithScoreAsync", "nonMaxSuppressionPadded_", "$maxOutputSize", "$iouThreshold", "$scoreThreshold", "nonMaxSuppressionPadded", "nonMaxSuppressionPaddedAsync_", "nonMaxSuppressionPaddedAsync", "resizeBilinear_", "images", "alignCorners", "halfPixelCenters", "$images", "batchImages", "resizeBilinear", "resizeNearestNeighbor_", "resizeNearestNeighbor", "threshold_", "inverted", "threshValue", "RED_INTENCITY_COEF", "GREEN_INTENCITY_COEF", "BLUE_INTENCITY_COEF", "totalPixelsInImage", "$threshold", "grayscale", "$r", "$g", "$histogram", "otsu", "invCondition", "histogram", "total", "bestThresh", "bestInBetVar", "cInBetVar", "classFirst", "classSecond", "meanFirst", "meanSec", "weightForeground", "weightBack", "meanFirstDivA", "meanSecFill", "meanSecAdd", "meanSecMul", "cInBetVarSubA", "cInBetVarSubB", "cInBetVarMul", "threshold", "transform_", "transforms", "interpolation", "fillMode", "$transforms", "transform", "bandPart_", "numLower", "numUpper", "M", "N", "$numLower", "$numUpper", "ij", "inBand", "zero", "mat", "bandPart", "gramSchmidt_", "inputIsTensor2D", "dim_1", "ys", "xs1d", "proj", "gramSchmidt", "qr_", "fullMatrices", "qr2d", "outerDimsProd", "x2ds", "q2ds_1", "r2ds_1", "x2d", "q2d", "r2d", "q", "one2D", "iters", "rTemp", "wTemp", "qTemp", "rjEnd1", "normX", "rjj", "u1", "wPre", "tau", "rjEndAll", "tauTimesW", "wT", "rTimesTau", "tawTimesWT", "qAllJEnd", "qTimesTau", "qr", "Reduction", "computeWeightedLoss_", "losses", "$losses", "weightedLoss", "broadcastFactor", "broadcastedWeights", "numNonZeros", "computeWeightedLoss", "absoluteDifference_", "labels", "$labels", "absoluteDifference", "cosineDistance_", "cosineDistance", "hingeLoss_", "hingeLoss", "huberLoss_", "deltaScalar", "quadratic", "linear", "huberLoss", "logLoss_", "epsilon", "epsilonScalar", "l1", "l2", "logLoss", "meanSquaredError_", "meanSquaredError", "sigmoidCrossEntropyWithLogits_", "maxOutput", "outputXTarget", "sigmoidOutput", "sigmoidCrossEntropy_", "multiClassLabels", "labelSmoothing", "$multiClassLabels", "labelSmoothingScalar", "sigmoidCrossEntropy", "softmaxCrossEntropyWithLogits_", "lse", "logResult", "costVector", "dyShape", "softmaxCrossEntropy_", "onehotLabels", "$onehotLabels", "numClasses", "softmaxCrossEntropy", "sparseFillEmptyRows_", "denseShape", "$denseShape", "sparseFillEmptyRows", "sparseReshape_", "inputIndices", "$inputIndices", "$inputShape", "$newShape", "sparseReshape", "sparseSegmentMean_", "sparseSegmentMean", "sparseSegmentSum_", "sparseSegmentSum", "stringNGrams_", "dataSplits", "separator", "nGramWidths", "leftPad", "padWidth", "preserveShortSequences", "$dataSplits", "stringNGrams", "stringSplit_", "delimiter", "skipEmpty", "$delimiter", "stringSplit", "stringToHashBucketFast_", "numBuckets", "stringToHashBucketFast", "staticRegexReplace_", "pattern", "rewrite", "replaceGlobal", "staticRegexReplace", "linalg", "executeOp", "tfOps", "assertShapesMatchAllowUndefinedSize", "dim0", "dim1", "fullDefinedShape", "elementShape", "inferElementShape", "listElementShape", "partialShape", "mergeElementShape", "notfullDefinedShape", "elementShapeA", "elementShapeB", "TensorArray", "maxSize", "identicalElementShapes", "dynamicSize", "clearAfterRead", "keep", "keepIds", "tensorWithState", "length", "totalLength", "cumulativeLengths", "elementPerRow", "previousLength", "indices_1", "sizes", "TensorList", "elementDtype", "maxNumElements", "numElements", "outputElementShape", "reshapedTensors", "destTensorList", "elementIndex", "fromTensor", "tensorElementShape", "tensorList", "reserve", "scatter", "shapeWithoutFirstDim", "thenFunc", "elseFunc", "cond", "condValue", "bodyFunc", "condFunc", "condResult", "argIds_1", "origResult", "resultIds", "condResult_1", "pred", "frameId", "tensorArray", "writeTensor", "writeTensorArray", "readId", "readIndex", "readTensorArray", "gatherId", "gatherIndices", "gatherDtype", "gatherTensorArray", "scatterId", "scatterIndices", "scatterTensor", "scatterTensorArray", "concatId", "concatTensorArray", "concatDtype", "splitId", "splitTensor", "lengths", "splitTensorArray", "sizeId", "sizeTensorArray", "closeId", "closeTensorArray", "idTensor", "elementDType", "numElementsParam", "srcTensorList", "fusedConvAndDepthWiseParams", "extraOp", "activationFunc", "isBiasAdd", "noBiasAdd", "isPrelu", "isBatchNorm", "numArgs", "biasArg", "preluArg", "kernelSize", "indexes", "nmsParams", "data_1", "snapshot", "message", "summarize", "HashTable", "keyDType", "valueDType", "tfOps.scalar", "$keys", "keysLength", "valuesLength", "existingTableHandle", "handle", "outputNestedSplits", "outputDenseValues", "rtNestedSplits", "rtDenseValues", "x_1", "weights_1", "size_1", "dims", "squeezedShape", "mapped", "sameShape", "outputIndices", "outputValues", "emptyRowIndicator", "reverseIndexMap", "outputData", "nGrams", "nGramsSplits", "tfc", "arithmetic.executeOp", "basicMath.executeOp", "control.executeOp", "convolution.executeOp", "creation.executeOp", "dynamic.executeOp", "evaluation.executeOp", "image.executeOp", "graph.executeOp", "logical.executeOp", "matrices.executeOp", "normalization.executeOp", "ragged.executeOp", "reduction.executeOp", "sliceJoin.executeOp", "sparse.executeOp", "spectral.executeOp", "string.executeOp", "transformation.executeOp", "hashTable.executeOp", "ExecutionContext", "weightMap", "tensorArrayMap", "tensorListMap", "functionMap", "parseNodeNameCache", "frameName", "contexts", "names", "getExecutionSubgraph", "usedNodes", "missingInputs", "dynamicNode", "syncInputs", "inputNodeNames", "initNodeNames", "frontier", "isControlFlow", "isDynamicShape", "isHashTable", "child", "getNodesInTopologicalOrder", "executionInfo", "inputNodes", "isUsed", "predefinedNodes", "nameToNode", "inCounts", "allNodes_1", "allNodes_1_1", "e_2", "inCount", "orderedNodeNames", "e_3", "orderedNodes", "filteredOrderedNodes", "filterPredefinedReachableNodes", "validateNodesExecutionOrder", "predefinedReachableNodeNames", "e_4", "NodesExecutionOrderError", "nodeNameToOrder", "order", "predefinedNodeNames", "isPredefined", "willBeExecutedNodeNames", "willBeExecuted", "orderedNodes_1", "orderedNodes_1_1", "e_6", "e_7", "getNodeLiveUntilMap", "INF_LIFE", "selfLifespans", "nodeOrder", "getSelfLifeSpan", "selfLife", "liveUntilOrders", "liveUntilMap", "liveUntilOrder", "liveUntilNode", "CONTROL_FLOW_OPS", "DYNAMIC_SHAPE_OPS", "HASH_TABLE_OPS", "GraphExecutor", "parent", "weightIds", "sortedInputs", "sortedOutputs", "outNames", "inNames", "nodeLiveUntilMap", "clonedTensor", "tensorsList", "outputNodeNames", "outputNodeNameSet", "outputNodes", "compilationKey", "compilation", "tensorsToKeep", "ids", "intermediateTensorConsumerCount", "_h", "_j", "tensors_1", "tensors_1_1", "liveUntilNodes", "isNonDisposableNode", "liveUntilNodes_1", "liveUntilNodes_1_1", "nodeToDispose", "tensors_2", "tensors_2_1", "tensorsList_1", "tensorsList_1_1", "isFunctionExecution", "results", "outputIds", "inputIds", "mappedInputs", "outputNames", "added", "promises", "missingOutputs", "alternativeMsg", "this_1", "currentContext_1", "childNode", "shape_1", "match", "notInGraph", "normalizedName", "ResourceManager", "hashTableNameToHandle", "hashTableMap", "DTYPE_VALUE_SIZE_MAP", "NUM_BYTES_STRING_LENGTH", "getWeightBytelengthAsync", "spec", "quantization", "bytesPerValue", "byteLength", "decodeWeight", "byteBuffer", "quantizationSizeFactor", "quantizedArray", "float16Decode", "getFloat16Decoder", "dtypeFactor", "realTensor", "imageTensor", "complexTensor", "readToLength", "reader", "initialData", "missing", "newData", "decodeWeightsStream", "weightStream", "specs", "specs_2", "specs_2_1", "tensorData", "weightTensor", "computeFloat16MantisaTable", "convertMantissa", "mantisaTable", "computeFloat16ExponentTable", "exponentTable", "computeFloat16OffsetTable", "offsetTable", "bufferUint32View", "float16Bits", "float32Bits", "TFHUB_SEARCH_PARAM", "DEFAULT_MODEL_NAME", "GraphModel", "modelUrl", "loadOptions", "tfio", "io", "path", "handlers", "loadResult", "artifacts", "metadata", "initializer", "handlerOrURL", "outputTensors", "outputTensorsArray", "outputTensorMap_1", "outputTensor", "signatureInputs", "numCapturedInputs", "inputIndex", "resourceId", "signatureOutputs", "newMap", "loadGraphModel", "getTFHubUrl", "model", "loadGraphModelSync", "modelSource", "ioHandler", "modelJSON", "weightSpecs", "modelArtifacts", "version", "fs", "path", "zlib", "import_tfjs_core", "import_tfjs_converter", "Callable", "closure", "args", "dispatchCallback", "progress_callback", "data", "reverseDictionary", "key", "value", "escapeRegExp", "string", "isIntegralNumber", "x", "mergeArrays", "arrs", "len", "s", "length", "c", "fs", "path", "fs", "path", "url", "VERSION", "IS_BROWSER_ENV", "IS_WEBWORKER_ENV", "IS_WEB_CACHE_AVAILABLE", "IS_WEBGPU_AVAILABLE", "IS_WEBNN_AVAILABLE", "IS_PROCESS_AVAILABLE", "IS_NODE_ENV", "IS_FS_AVAILABLE", "isEmpty", "IS_PATH_AVAILABLE", "IS_DENO_RUNTIME", "IS_BUN_RUNTIME", "apis", "RUNNING_LOCALLY", "dirname__", "_import_meta_url", "DEFAULT_CACHE_DIR", "DEFAULT_LOCAL_MODEL_PATH", "localModelPath", "env", "obj", "CONTENT_TYPE_MAP", "FileResponse", "_FileResponse", "filePath", "fs", "stats", "stream", "controller", "chunk", "err", "extension", "response", "data", "isValidUrl", "string", "protocols", "validHosts", "url", "REPO_ID_REGEX", "isValidHfModelId", "getFile", "urlOrPath", "env", "IS_CI", "version", "headers", "token", "ERROR_MAPPING", "handleError", "status", "remoteURL", "fatal", "message", "FileCache", "path", "request", "file", "progress_callback", "contentLength", "total", "loaded", "fileStream", "reader", "done", "value", "resolve", "reject", "progress", "error", "tryCache", "cache", "names", "name", "result", "getModelFile", "path_or_repo_id", "filename", "options", "return_path", "dispatchCallback", "e", "apis", "revision", "requestURL", "pathJoin", "validModelId", "localPath", "cacheKey", "proposedCacheKey", "toCacheResponse", "cacheHit", "buffer", "readResponse", "wrapped_progress", "cachedResponse", "getModelText", "modelPath", "fileName", "getModelJSON", "text", "read", "newLoaded", "newBuffer", "parts", "part", "index", "permute_data", "array", "dims", "axes", "shape", "stride", "s", "invStride", "_", "i", "permutedData", "newIndex", "j", "k", "min", "arr", "indexOfMin", "i", "max", "indexOfMax", "dummy_onnx_exports", "__export", "dummy_onnx_default", "esm_exports", "__export", "InferenceSession", "TRACE", "TRACE_FUNC_BEGIN", "TRACE_FUNC_END", "Tensor", "env", "registerBackend", "backends", "backendsSortedByPriority", "registerBackend", "name", "backend", "priority", "currentBackend", "i", "tryResolveAndInitializeBackend", "backendName", "backendInfo", "isInitializing", "e", "resolveBackendAndExecutionProviders", "options", "eps", "backendHints", "backendNames", "errors", "availableBackendNames", "resolveResult", "err", "filteredEps", "target", "prop", "version", "logLevelValue", "env", "version", "value", "env", "tensorToDataURL", "tensor", "options", "canvas", "pixels2DContext", "width", "height", "inputformat", "norm", "normMean", "normBias", "stride", "rTensorPointer", "gTensorPointer", "bTensorPointer", "aTensorPointer", "i", "j", "R", "G", "B", "A", "tensorToImageData", "image", "channels", "step", "rImagePointer", "gImagePointer", "bImagePointer", "aImagePointer", "bufferToTensor", "buffer", "options", "height", "width", "norm", "normMean", "normBias", "inputformat", "outputformat", "stride", "float32Data", "step", "rImagePointer", "gImagePointer", "bImagePointer", "aImagePointer", "rTensorPointer", "gTensorPointer", "bTensorPointer", "aTensorPointer", "i", "Tensor", "tensorFromImage", "image", "isHTMLImageEle", "isImageDataEle", "isImageBitmap", "isString", "data", "bufferToTensorOptions", "createCanvas", "createCanvasContext", "canvas", "pixels2DContext", "tempCanvas", "resolve", "reject", "context", "newImage", "img", "tensorFromTexture", "texture", "download", "dispose", "dims", "tensorFromGpuBuffer", "gpuBuffer", "dataType", "tensorFromMLTensor", "mlTensor", "tensorFromPinnedBuffer", "type", "NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP", "NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP", "isTypedArrayChecked", "checkTypedArray", "isBigInt64ArrayAvailable", "isBigUint64ArrayAvailable", "Float16Array", "isFloat16ArrayAvailable", "calculateSize", "dims", "size", "i", "dim", "tensorReshape", "tensor", "Tensor", "Tensor", "arg0", "arg1", "arg2", "checkTypedArray", "type", "dims", "expectedTypedArrayConstructor", "NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP", "data", "maybeDims", "typedArrayConstructor", "firstElementType", "mappedType", "NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP", "size", "calculateSize", "image", "options", "tensorFromImage", "texture", "tensorFromTexture", "gpuBuffer", "tensorFromGpuBuffer", "mlTensor", "tensorFromMLTensor", "buffer", "tensorFromPinnedBuffer", "tensorToDataURL", "tensorToImageData", "releaseData", "tensorReshape", "Tensor", "TRACE", "deviceType", "label", "env", "TRACE_FUNC", "msg", "extraMsg", "stack", "hasTraceFunc", "i", "TRACE_FUNC_BEGIN", "TRACE_FUNC_END", "InferenceSession", "_InferenceSession", "handler", "feeds", "arg1", "arg2", "TRACE_FUNC_BEGIN", "fetches", "options", "Tensor", "isFetchesEmpty", "name", "isFetches", "arg1Keys", "v", "results", "returnValue", "key", "result", "TRACE_FUNC_END", "arg0", "arg3", "filePathOrUint8Array", "buffer", "byteOffset", "byteLength", "backend", "optionsWithValidatedEPs", "resolveBackendAndExecutionProviders", "InferenceSession", "isNode", "init_wasm_utils_env", "__esmMin", "origin", "isEsmImportMetaUrlHardcodedAsFileUri", "getScriptSrc", "scriptSrc", "inferWasmPathPrefixFromScriptSrc", "isSameOrigin", "normalizeUrl", "fallbackUrl", "preload", "dynamicImportDefault", "embeddedWasmModule", "importWasmModule", "init_wasm_utils_import", "URL2", "filename", "prefixOverride", "baseUrl", "absoluteUrl", "blob", "url", "urlOverride", "isMultiThreaded", "wasmModuleFilename", "wasmModuleUrl", "needPreload", "wasm", "initialized", "initializing", "aborted", "isMultiThreadSupported", "isSimdSupported", "isRelaxedSimdSupported", "initializeWebAssembly", "getInstance", "init_wasm_factory", "flags", "timeout", "numThreads", "multiThreadSupported", "wasmPaths", "wasmPrefixOverride", "mjsPathOverrideFlag", "mjsPathOverride", "wasmPathOverrideFlag", "wasmPathOverride", "wasmBinaryOverride", "objectUrl", "ortWasmFactory", "isTimeout", "tasks", "resolve", "reject", "config", "fileName", "inferredWasmPathPrefix", "module", "what", "allocWasmString", "iterateExtraOptions", "checkLastError", "init_wasm_utils", "data", "allocs", "dataLength", "dataOffset", "options", "prefix", "seen", "handler", "key", "value", "name", "message", "stack", "ptrSize", "paramsOffset", "errorCode", "errorMessagePointer", "errorMessage", "setRunOptions", "init_run_options", "runOptionsHandle", "runOptions", "tagDataOffset", "keyDataOffset", "valueDataOffset", "e", "alloc", "getGraphOptimzationLevel", "getExecutionMode", "appendDefaultOptions", "appendSessionConfig", "setExecutionProviders", "setSessionOptions", "init_session_options", "graphOptimizationLevel", "executionMode", "session", "ep", "sessionOptionsHandle", "executionProviders", "epName", "epOptions", "deviceType", "webgpuOptions", "epNameDataOffset", "epOptionsCount", "keysOffset", "valuesOffset", "i", "sessionOptions", "logIdDataOffset", "logSeverityLevel", "logVerbosityLevel", "optimizedModelFilePathOffset", "nameOffset", "tensorDataTypeStringToEnum", "tensorDataTypeEnumToString", "calculateTensorSizeInBytes", "tensorTypeToTypedArrayConstructor", "logLevelStringToEnum", "isGpuBufferSupportedType", "isMLTensorSupportedType", "dataLocationStringToEnum", "init_wasm_common", "type", "typeProto", "dateType", "dimsOrSize", "elementSize", "size", "a", "b", "logLevel", "location", "loadFile", "init_wasm_utils_load_file", "file", "readFile", "de", "createReadStream", "stream", "chunks", "chunk", "response", "contentLengthHeader", "fileSize", "reader", "buffer", "pages", "offset", "done", "chunkSize", "initOrt", "initRuntime", "initEp", "activeSessions", "getSessionInputOutputCount", "getSessionInputOutputMetadata", "copyFromExternalBuffer", "createSession", "releaseSession", "prepareInputOutputTensor", "run", "endProfiling", "init_wasm_core_impl", "loggingLevel", "env", "sessionHandle", "index", "metadataOffset", "elementType", "dimsCount", "dims", "symbolicDimNameOffset", "model", "modelDataOffset", "modelData", "modelDataLength", "ioBindingHandle", "inputNamesUTF8Encoded", "outputNamesUTF8Encoded", "loadingPromises", "path", "provider", "webnnOptions", "context", "gpuDevice", "powerPreference", "inputCount", "outputCount", "enableGraphCapture", "inputNames", "outputNames", "inputMetadata", "outputMetadata", "outputPreferredLocations", "shape", "nameString", "buf", "sessionId", "ioBindingState", "tensor", "tensorHandles", "tensorNameUTF8Encoded", "dataType", "actualLocation", "rawData", "dataByteLength", "gpuBuffer", "registerBuffer", "mlTensor", "registerMLTensor", "isGraphInput", "tensorName", "dataTypeEnum", "createTemporaryTensor", "uploadTensor", "tensorId", "dimsOffset", "d", "inputIndices", "inputTensors", "outputIndices", "outputTensors", "inputOutputBound", "runOptionsAllocs", "inputTensorHandles", "outputTensorHandles", "inputOutputAllocs", "beforeRunStack", "inputValuesOffset", "inputNamesOffset", "outputValuesOffset", "outputNamesOffset", "output", "beforeGetTensorDataStack", "tensorDataOffset", "keepOutputTensor", "valueType", "dimsLength", "preferredLocation", "stringData", "nextOffset", "maxBytesToRead", "getBuffer", "bufferSize", "ensureTensor", "isInt64Supported", "typedArrayConstructor", "v", "p", "profileFileName", "initializeWebAssemblyAndOrtRuntime", "initializeOrtEp", "init_proxy_wrapper", "inputs", "outputs", "encodeTensorMetadata", "decodeTensorMetadata", "OnnxruntimeWebAssemblySessionHandler", "init_session_handler_inference", "getName", "Tensor", "download", "dispose", "pathOrBuffer", "TRACE_FUNC_BEGIN", "TRACE_FUNC_END", "feeds", "fetches", "inputArray", "kvp", "outputArray", "t", "results", "resultMap", "backend_wasm_exports", "__export", "OnnxruntimeWebAssemblyBackend", "initializeFlags", "wasmBackend", "init_backend_wasm", "simd", "numCpuLogicalCores", "backendName", "version", "index_default", "ort", "pt", "ht", "lt", "registerBackend", "version", "logLevelValue", "env", "version", "value", "tensorToDataURL", "tensor", "options", "canvas", "pixels2DContext", "width", "height", "inputformat", "norm", "normMean", "normBias", "stride", "rTensorPointer", "gTensorPointer", "bTensorPointer", "aTensorPointer", "i", "j", "R", "G", "B", "A", "tensorToImageData", "image", "channels", "step", "rImagePointer", "gImagePointer", "bImagePointer", "aImagePointer", "bufferToTensor", "buffer", "options", "height", "width", "norm", "normMean", "normBias", "inputformat", "outputformat", "stride", "float32Data", "step", "rImagePointer", "gImagePointer", "bImagePointer", "aImagePointer", "rTensorPointer", "gTensorPointer", "bTensorPointer", "aTensorPointer", "i", "Tensor", "tensorFromImage", "image", "isHTMLImageEle", "isImageDataEle", "isImageBitmap", "isString", "data", "bufferToTensorOptions", "createCanvas", "createCanvasContext", "canvas", "pixels2DContext", "tempCanvas", "resolve", "reject", "context", "newImage", "img", "tensorFromTexture", "texture", "download", "dispose", "dims", "tensorFromGpuBuffer", "gpuBuffer", "dataType", "tensorFromMLTensor", "mlTensor", "tensorFromPinnedBuffer", "type", "NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP", "NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP", "isTypedArrayChecked", "checkTypedArray", "isBigInt64ArrayAvailable", "isBigUint64ArrayAvailable", "Float16Array", "isFloat16ArrayAvailable", "calculateSize", "dims", "size", "i", "dim", "tensorReshape", "tensor", "Tensor", "Tensor", "arg0", "arg1", "arg2", "checkTypedArray", "type", "dims", "expectedTypedArrayConstructor", "NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP", "data", "maybeDims", "typedArrayConstructor", "firstElementType", "mappedType", "NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP", "size", "calculateSize", "image", "options", "tensorFromImage", "texture", "tensorFromTexture", "gpuBuffer", "tensorFromGpuBuffer", "mlTensor", "tensorFromMLTensor", "buffer", "tensorFromPinnedBuffer", "tensorToDataURL", "tensorToImageData", "releaseData", "tensorReshape", "Tensor", "DEVICE_TO_EXECUTION_PROVIDER_MAPPING", "supportedDevices", "defaultDevices", "ONNX", "ORT_SYMBOL", "apis", "dummy_onnx_default", "dummy_onnx_exports", "ort_node_min_exports", "InferenceSession", "webInferenceChain", "IS_WEB_ENV", "apis", "isONNXTensor", "x", "ONNX", "ONNX_ENV", "env", "env", "ONNX_ENV", "DataTypeMap", "Tensor", "_Tensor", "value", "args", "isONNXTensor", "obj", "key", "index", "iterLength", "iterDims", "iterSize", "b", "i", "safeIndex", "a", "item", "this_data", "o1", "o2", "data", "reshape", "callback", "val", "slices", "newTensorDims", "newOffsets", "sliceIndex", "slice", "start", "end", "offsets", "newDims", "newBufferSize", "stride", "isContiguous", "slicedData", "originalIndex", "j", "num", "size", "dims", "permute", "dim", "keepdim", "p", "fn", "type", "result", "resultDims", "reduce_helper", "norm", "norm_data", "resultIndex", "resultMultiplier", "dimsToStride", "calc_squeeze_dims", "calc_unsqueeze_dims", "start_dim", "end_dim", "dimsToKeepBefore", "dimsToFlatten", "dimsToKeepAfter", "inferredIndex", "productOther", "product", "curr", "mask", "min", "max", "mean", "map_fn", "is_source_bigint", "is_dest_bigint", "x", "dimensions", "totalElements", "dimensionSize", "reshapedArray", "acc", "lastArray", "tensor", "axes", "permutedData", "shape", "permute_data", "calc_squeeze_dims", "dims", "dim", "d", "x", "i", "calc_unsqueeze_dims", "safeIndex", "index", "size", "dimension", "boundsCheck", "reduce_helper", "callbackfn", "input", "dim", "keepdim", "initialValue", "inputData", "inputDims", "safeIndex", "resultDims", "result", "i", "resultIndex", "j", "num", "resultMultiplier", "size", "index", "mean", "input", "dim", "keepdim", "inputDims", "inputData", "val", "a", "b", "Tensor", "safeIndex", "type", "result", "resultDims", "reduce_helper", "i", "dimsToStride", "dims", "stride", "s2", "PriorityQueue", "comparator", "a", "b", "maxSize", "values", "value", "smallest", "poppedValue", "bottom", "replacedValue", "i", "j", "temp", "node", "maxChild", "CharTrie", "CharTrieNode", "texts", "text", "ch", "child", "prefix", "_CharTrieNode", "isLeaf", "children", "TokenLattice", "sentence", "bosTokenId", "eosTokenId", "bos", "TokenLatticeNode", "eos", "pos", "length", "score", "tokenId", "nodeId", "len", "rnode", "bestScore", "bestNode", "lnode", "results", "prev", "x", "_TokenLatticeNode", "n", "DictionarySplitter", "dictionary", "trie", "word", "result", "start", "match", "LRUCache", "capacity", "key", "TOKEN_TYPES", "Token", "value", "type", "isWord", "char", "isInteger", "isWhitespace", "ORDERED_MAPPING_TABLE", "ESCAPE_CHARACTERS", "preprocess", "template", "options", "tokenize", "source", "tokens", "src", "cursorPosition", "curlyBracketDepth", "consumeWhile", "predicate", "str", "escaped", "unescaped", "stripTrailingWhitespace", "lastToken", "skipLeadingWhitespace", "main", "lastTokenType", "text", "stripBefore", "comment", "stripAfter", "lastTokenType2", "num", "seq", "c", "frac", "word", "Statement", "Program", "body", "If", "test", "alternate", "For", "loopvar", "iterable", "defaultBlock", "Break", "Continue", "SetStatement", "assignee", "Macro", "name", "args", "Comment", "Expression", "MemberExpression", "object", "property", "computed", "CallExpression", "callee", "Identifier", "Literal", "IntegerLiteral", "FloatLiteral", "StringLiteral", "ArrayLiteral", "TupleLiteral", "ObjectLiteral", "BinaryExpression", "operator", "left", "right", "FilterExpression", "operand", "filter", "FilterStatement", "SelectExpression", "lhs", "TestExpression", "negate", "UnaryExpression", "argument", "SliceExpression", "start", "stop", "step", "KeywordArgumentExpression", "key", "SpreadExpression", "CallStatement", "call", "callerArgs", "Ternary", "condition", "trueExpr", "falseExpr", "parse", "program", "current", "expect", "error", "prev", "expectIdentifier", "isIdentifier", "parseAny", "parseText", "parseJinjaStatement", "parseJinjaExpression", "is", "types", "i", "isStatement", "names", "result", "parseSetStatement", "parseIfStatement", "parseMacroStatement", "parseForStatement", "parseArgs", "parsePrimaryExpression", "callArgs", "callExpr", "filterNode", "parseCallExpression", "filterBody", "parseExpression", "parseExpressionSequence", "primary", "fn", "expressions", "isTuple", "loopVariable", "alternative", "parseIfExpression", "a", "parseLogicalOrExpression", "parseLogicalAndExpression", "parseLogicalNegationExpression", "arg", "parseComparisonExpression", "parseAdditiveExpression", "parseMultiplicativeExpression", "parseCallMemberExpression", "member", "parseMemberExpression", "expression", "parseArgumentsList", "expr", "parseMemberExpressionArgumentsList", "slices", "isSlice", "parseTestExpression", "parseFilterExpression", "token", "values", "range", "slice", "array", "direction", "titleCase", "strftime_now", "format2", "strftime", "date", "monthFormatterLong", "monthFormatterShort", "pad2", "n", "escapeRegExp", "s", "replace", "oldvalue", "newvalue", "count", "remaining", "pattern", "match", "BreakControl", "ContinueControl", "RuntimeValue", "BooleanValue", "IntegerValue", "FloatValue", "StringValue", "FunctionValue", "ArrayValue", "item", "sep", "NullValue", "maxsplit", "index", "part", "oldValue", "newValue", "NON_ASCII_CHARS", "makeAsciiSafe", "toJSON", "input", "depth", "convertUndefinedToNull", "indent", "ensureAscii", "separators", "sortKeys", "itemSeparator", "keySeparator", "indentValue", "basePadding", "childrenPadding", "core", "x", "entries", "b", "keyStr", "v", "ObjectValue", "defaultValue", "kwargs", "positionalArgs", "KeywordArgumentsValue", "caseSensitive", "by", "reverse", "items", "aVal", "bVal", "compareRuntimeValues", "TupleValue", "UndefinedValue", "Environment", "parent", "convertToRuntimeValues", "setupGlobals", "env", "getAttributeValue", "attributePath", "parts", "isNumericLike", "getNumericValue", "aNum", "bNum", "aStr", "bStr", "Interpreter", "node", "environment", "res", "rem", "positionalArguments", "keywordArguments", "spreadNode", "val", "kwarg", "seen", "output", "builtin", "filterName", "separatorsArg", "itemSep", "keySep", "separator", "booleanValue", "attribute", "getSortValue", "attrPath", "select", "attr", "testName", "testFunction", "filtered", "mapped", "width", "first", "blank", "lines", "indented", "replaceFn", "statements", "statement", "lastEvaluated", "rhs", "variableName", "tuple", "arr", "elem", "scope", "scopeUpdateFunctions", "loopScope", "scopeUpdateFunction", "scope2", "j", "noIteration", "loop", "evaluated", "err", "defaultEvaluated", "macroScope", "nodeArg", "passedArg", "identifier", "callerFn", "callerEnv", "callBlockEnv", "param", "macroArgs", "macroKwargs", "newEnv", "rendered", "mapping", "evaluatedKey", "_scope", "NEWLINE", "OPEN_STATEMENT", "CLOSE_STATEMENT", "getBinaryOperatorPrecedence", "format", "indentStr", "formatStatements", "createStatement", "stmts", "stmt", "formatStatement", "pad", "formatIf", "formatFor", "formatSet", "formatMacro", "formatCallStatement", "formatFilterStatement", "formatExpression", "clauses", "out", "formattedIterable", "params", "spec", "parentPrec", "thisPrecedence", "obj", "prop", "elems", "brackets", "k", "t", "st", "Template", "WHISPER_LANGUAGES", "WHISPER_LANGUAGE_MAPPING", "WHISPER_TO_LANGUAGE_CODE_MAPPING", "k", "v", "loadTokenizer", "pretrained_model_name_or_path", "options", "info", "getModelJSON", "regexSplit", "text", "regex", "result", "prev", "match", "fullMatch", "createPattern", "pattern", "invert", "key", "value", "PROBLEMATIC_REGEX_MAP", "escaped", "escapeRegExp", "objectToMap", "obj", "prepareTensorForDecode", "tensor", "dims", "clean_up_tokenization", "remove_accents", "lowercase_and_remove_accent", "is_chinese_char", "cp", "fuse_unk", "arr", "tokens_to_ids", "unk_token_id", "fused", "i", "whitespace_split", "PUNCTUATION_REGEX", "PUNCTUATION_ONLY_REGEX", "BLOOM_SPLIT_CHARS", "AddedToken", "config", "TokenizerModel", "Callable", "args", "WordPieceTokenizer", "Unigram", "BPE", "LegacyTokenizerModel", "tokens", "t", "ids", "outputTokens", "token", "chars", "isUnknown", "start", "subTokens", "end", "currentSubstring", "substr", "moreConfig", "vocabSize", "x", "min", "CharTrie", "lattice", "mblen", "beginPos", "hasSingleNode", "sliced", "prefixedTokens", "tokenId", "tokenScore", "n", "len", "normalized", "TokenLattice", "toReturn", "tokenized", "BYTES_TO_UNICODE", "bs", "_", "cs", "b", "ccs", "UNICODE_TO_BYTES", "reverseDictionary", "use_new_merge_format", "LRUCache", "cached", "word", "queue", "PriorityQueue", "a", "startingNode", "previousNode", "currentNode", "node", "newPreviousNode", "merged", "rank", "bpe_token_list", "byteTokens", "Normalizer", "BertNormalizer", "Precompiled", "NormalizerSequence", "Replace", "NFC", "NFD", "NFKC", "NFKD", "StripNormalizer", "StripAccents", "Lowercase", "Prepend", "UnicodeNormalizer", "normalizer", "output", "char", "PreTokenizer", "BertPreTokenizer", "PreTokenizerSequence", "WhitespacePreTokenizer", "WhitespaceSplit", "MetaspacePreTokenizer", "ByteLevelPreTokenizer", "SplitPreTokenizer", "PunctuationPreTokenizer", "DigitsPreTokenizer", "ReplacePreTokenizer", "FixedLengthPreTokenizer", "byte", "digit_pattern", "PostProcessor", "TemplateProcessing", "ByteLevelPostProcessor", "RobertaProcessing", "BertProcessing", "PostProcessorSequence", "tokens_pair", "add_special_tokens", "mergeArrays", "token_type_ids", "middle", "after", "type", "processedTokens", "types", "item", "processor", "Decoder", "WordPieceDecoder", "MetaspaceDecoder", "ByteLevelDecoder", "ReplaceDecoder", "ByteFallback", "FuseDecoder", "StripDecoder", "DecoderSequence", "CTCDecoder", "BPEDecoder", "new_tokens", "previous_byte_tokens", "bytes", "string", "start_cut", "stop_cut", "index", "byteArray", "c", "sub_texts", "current_sub_text", "grouped_tokens", "toks", "decoder", "MetaspacePreTokenizer", "PreTokenizer", "config", "text", "section_index", "normalized", "MetaspaceDecoder", "Decoder", "tokens", "result", "i", "Precompiled", "Normalizer", "part", "PreTokenizerSequence", "x", "options", "preTokenizedText", "tokenizer", "WhitespacePreTokenizer", "WhitespaceSplit", "whitespace_split", "ReplacePreTokenizer", "createPattern", "FixedLengthPreTokenizer", "SPECIAL_TOKEN_ATTRIBUTES", "padHelper", "item", "length", "value_fn", "side", "key", "diff", "value", "padData", "mergeArrays", "truncateHelper", "PreTrainedTokenizer", "Callable", "tokenizerJSON", "tokenizerConfig", "TokenizerModel", "PostProcessor", "addedToken", "token", "AddedToken", "DictionarySplitter", "chat_template", "name", "template", "keys", "pretrained_model_name_or_path", "progress_callback", "cache_dir", "local_files_only", "revision", "legacy", "info", "loadTokenizer", "text_pair", "add_special_tokens", "padding", "truncation", "max_length", "return_tensor", "return_token_type_ids", "isBatched", "encodedTokens", "t", "max", "dims", "Tensor", "sections", "lowercase_and_remove_accent", "sectionTokens", "token_type_ids", "input_ids", "pair", "tokens2", "batch", "decode_args", "token_ids", "prepareTensorForDecode", "isIntegralNumber", "skip_special_tokens", "clean_up_tokenization_spaces", "decoded", "clean_up_tokenization", "tools", "template_dict", "conversation", "documents", "add_generation_prompt", "tokenize", "return_dict", "tokenizer_kwargs", "kwargs", "compiledTemplate", "Template", "special_tokens_map", "rendered", "out", "BertTokenizer", "import_tfjs_core", "import_tfjs_core", "import_tfjs_core", "import_tfjs_core", "assertNotComplex", "tensor", "opName", "t", "whereImpl", "MathBackendCPU", "_MathBackendCPU", "values", "shape", "dtype", "dataId", "outId", "encodedValues", "d", "tensorData", "refCount", "complexTensorInfos", "realValues", "imagValues", "t", "data", "strings", "force", "tensorInfo", "f", "start", "condition", "assertNotComplex", "condVals", "import_tfjs_core", "import_tfjs_core", "createSimpleBinaryKernelImpl", "op", "aShape", "bShape", "aVals", "bVals", "dtype", "newShape", "resultRank", "resultStrides", "resultSize", "result", "aRank", "bRank", "aStrides", "bStrides", "aBroadcastDims", "bBroadcastDims", "i", "loc", "aLoc", "d", "aIndex", "bLoc", "bIndex", "import_tfjs_core", "import_tfjs_core", "import_tfjs_core", "complex", "args", "inputs", "backend", "real", "imag", "realVals", "imagVals", "complexInfo", "zeros", "backend", "shape", "dtype", "real", "imag", "complex", "values", "import_tfjs_core", "identity", "args", "inputs", "backend", "x", "identityConfig", "real", "args", "inputs", "backend", "input", "realVal", "castImpl", "values", "shape", "inputType", "dtype", "resultValues", "zero", "resultData", "resultShape", "createSimpleBinaryKernelImpl", "a", "b", "cast", "args", "inputs", "backend", "attrs", "x", "identity", "zerosTensorInfo", "zeros", "floatX", "result", "complex", "realPart", "real", "resultType", "castConfig", "binaryKernelFunc", "name", "simpleImpl", "complexImpl", "dtype", "inputs", "backend", "a", "b", "cpuBackend", "assertNotComplex", "aVals", "bVals", "decodedAVals", "decodedBVals", "$dtype", "resultData", "resultShape", "$aComplex", "cast", "$aComplexVals", "aReal", "aImag", "aRealVals", "aImagVals", "$bComplex", "$bComplexVals", "bReal", "bImag", "bRealVals", "bImagVals", "resultRealData", "resultImagData", "resultReal", "resultImag", "result", "complex", "createComplexBinaryKernelImpl", "op", "aShape", "bShape", "resultSize", "resultRank", "resultStrides", "resultRealVals", "resultImagVals", "aBroadcastDims", "bBroadcastDims", "aRank", "aStrides", "bRank", "bStrides", "i", "aIdx", "bIdx", "loc", "aLoc", "d", "aIndex", "bLoc", "bIndex", "opResult", "addImpl", "createSimpleBinaryKernelImpl", "a", "b", "addComplexImpl", "createComplexBinaryKernelImpl", "aReal", "aImag", "bReal", "bImag", "add", "binaryKernelFunc", "addConfig", "import_tfjs_core", "createSimpleUnaryImpl", "op", "values", "dtype", "attrs", "newValues", "i", "import_tfjs_core", "unaryKernelFunc", "name", "op", "dtype", "impl", "createSimpleUnaryImpl", "unaryKernelFuncFromImpl", "unaryImpl", "inputs", "attrs", "backend", "x", "assertNotComplex", "cpuBackend", "values", "decoded", "$dtype", "newValues", "import_tfjs_core", "concatImpl", "inputs", "outShape", "dtype", "simplyConcat", "outVals", "offset", "input", "size", "colOffset", "decodedData", "tIdx", "row", "resIdx", "col", "import_tfjs_core", "expImpl", "createSimpleUnaryImpl", "xi", "exp", "unaryKernelFuncFromImpl", "import_tfjs_core", "gatherV2Impl", "xBuf", "indicesBuf", "flattenOutputShape", "outBuf", "i", "originalLoc", "batchIdx", "indicesIdx", "indicesIndex", "originalIndex", "import_tfjs_core", "maxImpl", "aVals", "reduceSize", "outShape", "dtype", "vals", "i", "offset", "max", "j", "value", "import_tfjs_core", "maximumImpl", "createSimpleBinaryKernelImpl", "aValue", "bValue", "maximum", "binaryKernelFunc", "maximumConfig", "import_tfjs_core", "minimumImpl", "createSimpleBinaryKernelImpl", "aValue", "bValue", "minimum", "binaryKernelFunc", "minimumConfig", "import_tfjs_core", "multiplyImpl", "createSimpleBinaryKernelImpl", "aValue", "bValue", "multiplyComplexImpl", "createComplexBinaryKernelImpl", "aReal", "aImag", "bReal", "bImag", "multiply", "binaryKernelFunc", "multiplyConfig", "import_tfjs_core", "import_tfjs_core", "import_tfjs_core", "transposeImpl", "xVals", "xShape", "dtype", "perm", "newShape", "xRank", "xSize", "xStrides", "newStrides", "result", "i", "loc", "newLoc", "newIndex", "transpose", "args", "inputs", "attrs", "backend", "x", "perm", "assertNotComplex", "xRank", "newShape", "i", "values", "result", "transposeImpl", "transposeConfig", "prodImpl", "xShape", "xDtype", "xVals", "reductionAxes", "outShape", "reduceShape", "outDtype", "outVals", "reduceSize", "i", "offset", "prod", "j", "args", "inputs", "backend", "attrs", "x", "axis", "keepDims", "assertNotComplex", "xRank", "axes", "permutation", "permutedX", "intermediateTensorInfos", "transpose", "resultShape", "t", "prodConfig", "import_tfjs_core", "rangeImpl", "start", "stop", "step", "dtype", "sameStartStop", "increasingRangeNegativeStep", "decreasingRangePositiveStep", "numElements", "values", "i", "import_tfjs_core", "rsqrtImpl", "createSimpleUnaryImpl", "xi", "rsqrt", "unaryKernelFuncFromImpl", "rsqrtConfig", "import_tfjs_core", "sliceImpl", "vals", "begin", "size", "shape", "dtype", "isContinous", "length", "xStrides", "flatOffset", "decodedData", "inBuf", "outBuf", "i", "outLoc", "inLoc", "idx", "j", "slice", "args", "inputs", "backend", "attrs", "x", "assertNotComplex", "$begin", "$size", "outVals", "import_tfjs_core", "squaredDifferenceImpl", "createSimpleBinaryKernelImpl", "a", "b", "diff", "squaredDifference", "binaryKernelFunc", "squaredDifferenceConfig", "import_tfjs_core", "stridedSliceImpl", "outShape", "xBuf", "strides", "begin", "outBuf", "i", "loc", "newLoc", "j", "import_tfjs_core", "subImpl", "createSimpleBinaryKernelImpl", "aValue", "bValue", "subComplexImpl", "createComplexBinaryKernelImpl", "aReal", "aImag", "bReal", "bImag", "sub", "binaryKernelFunc", "subConfig", "import_tfjs_core", "tileImpl", "xBuf", "reps", "newShape", "i", "result", "newLoc", "originalLoc", "j", "originalIndex", "MathBackendCPU", "import_tfjs_core", "import_tfjs_core", "reshape", "args", "inputs", "backend", "attrs", "x", "shape", "xSize", "$shape", "$xSize", "xData", "real", "imag", "reshapeConfig", "gatherV2", "args", "inputs", "backend", "attrs", "x", "indices", "axis", "batchDims", "assertNotComplex", "parsedAxis", "indicesVals", "axisDim", "i", "index", "$batchDims", "indicesSize", "shapeInfo", "flattenX", "reshape", "flattenIndex", "flattenOutputShape", "indicesBuf", "xBuf", "outBuf", "gatherV2Impl", "gatherV2Config", "import_tfjs_core", "expandDims", "args", "inputs", "backend", "attrs", "input", "dim", "inputRank", "newShape", "$dim", "reshape", "expandDimsConfig", "import_tfjs_core", "stridedSlice", "args", "inputs", "backend", "attrs", "x", "begin", "end", "strides", "beginMask", "endMask", "ellipsisMask", "newAxisMask", "shrinkAxisMask", "assertNotComplex", "finalShapeSparse", "finalShape", "isIdentity", "sliceDim0", "isSimpleSlice", "$begin", "$end", "$strides", "result", "reshape", "size", "sliced", "slice", "xBuf", "outBuf", "stridedSliceImpl", "stridedSliceConfig", "import_tfjs_core", "import_tfjs_core", "imag", "args", "inputs", "backend", "input", "imagVal", "concat", "args", "inputs", "backend", "attrs", "axis", "$axis", "shapes", "t", "outShape", "$inputs", "identity", "reals", "real", "imags", "imag", "realConcated", "imagConcated", "result", "complex", "r", "i", "inputs2D", "shape", "reshape", "inputsValShapes", "simplyConcat", "outVals", "concatImpl", "finalOutShape", "outInfo", "concatConfig", "pack", "args", "inputs", "backend", "attrs", "axis", "expandDims", "shape", "dtype", "t", "intermediateTensorInfos", "expandedTensors", "expandedT", "result", "concat", "packConfig", "import_tfjs_core", "range", "args", "backend", "attrs", "start", "stop", "dtype", "step", "values", "rangeImpl", "rangeConfig", "import_tfjs_core", "import_tfjs_core", "realDivImpl", "createSimpleBinaryKernelImpl", "a", "b", "div", "binaryKernelFunc", "realDivConfig", "import_tfjs_core", "sum", "args", "inputs", "backend", "attrs", "x", "axis", "keepDims", "assertNotComplex", "$x", "cast", "identity", "xRank", "axes", "permutation", "reductionAxes", "permutedX", "transpose", "outShape", "reduceShape", "resultDtype", "result", "zeros", "reduceSize", "vals", "aVals", "i", "offset", "j", "newShape", "oldResult", "reshape", "sumConfig", "mean", "args", "inputs", "backend", "attrs", "x", "axis", "keepDims", "axes", "reduceShape", "reduceSize", "toDispose", "reduceSizeScalar", "$x", "cast", "res", "div", "result", "sum", "t", "meanConfig", "import_tfjs_core", "batchMatMul", "args", "inputs", "backend", "attrs", "b", "transposeA", "transposeB", "assertNotComplex", "aRank", "bRank", "innerShapeA", "innerShapeB", "outerShapeA", "outerShapeB", "outerDimsA", "outerDimsB", "batchDimA", "batchDimB", "outShape", "a3dShape", "b3dShape", "a3d", "reshape", "b3d", "sharedDim", "leftDim", "rightDim", "batchDim", "a3dValues", "b3dValues", "a3dStrides", "b3dStrides", "aBatch", "aOuterStep", "aInnerStep", "bInnerStep", "bOuterStep", "bBatch", "size", "result", "resVals", "blockSize", "bi", "batchIndexA", "batchIndexB", "i0", "iBlock", "j0", "jBlock", "k0", "kBlock", "i", "j", "sum", "k", "aVal", "bVal", "batchMatMulConfig", "import_tfjs_core", "import_tfjs_core", "max", "args", "inputs", "backend", "attrs", "x", "reductionIndices", "keepDims", "cpuBackend", "xShape", "xRank", "origAxes", "axes", "permutedAxes", "xVals", "newShape", "i", "transposeImpl", "assertNotComplex", "maxOutShape", "reduceShape", "reduceSize", "result", "maxImpl", "dataId", "outShape", "softmax", "args", "inputs", "backend", "attrs", "logits", "dim", "logitsRank", "$dim", "axes", "maxLogit", "max", "expandedShape", "maxLogitReshaped", "reshape", "a", "sub", "b", "exp", "sumExp", "sum", "sumReshaped", "result", "div", "softmaxConfig", "import_tfjs_core", "p", "a1", "a2", "a3", "a4", "a5", "erf", "unaryKernelFunc", "xi", "sign", "v", "t", "erfConfig", "import_tfjs_core", "tile", "args", "inputs", "backend", "attrs", "x", "reps", "assertNotComplex", "outBuf", "tileImpl", "tileConfig", "import_tfjs_core", "squareConfig", "inputs", "backend", "x", "cpuBackend", "assertNotComplex", "values", "newValues", "value", "castConfig", "gatherV2Config", "expandDimsConfig", "stridedSliceConfig", "reshapeConfig", "packConfig", "subConfig", "multiplyConfig", "addConfig", "rangeConfig", "meanConfig", "squaredDifferenceConfig", "rsqrtConfig", "prodConfig", "concatConfig", "batchMatMulConfig", "transposeConfig", "softmaxConfig", "erfConfig", "tileConfig", "sumConfig", "minimumConfig", "maximumConfig", "realDivConfig", "squareConfig", "identityConfig", "c", "path", "fs", "createNodeFileSystemIOHandler", "modelJsonPath", "dir", "modelJson", "modelTopology", "weightsManifest", "weightSpecs", "manifest", "shardPath", "fullPath", "weightData", "TfjsEmbedder", "_TfjsEmbedder", "benchmarkDir", "modelPath", "ioHandler", "oldLog", "oldWarn", "BertTokenizer", "e", "text", "tokenized", "extractData", "tensor", "data", "x", "inputIdsData", "attentionMaskData", "tokenTypeIdsData", "inputIds", "attentionMask", "tokenTypeIds", "result", "appendFileSync", "path", "MODERN_WEB_LOG_FILE", "logToolResult", "toolName", "result", "logDir", "logPath", "path", "MODERN_WEB_LOG_FILE", "logEntry", "appendFileSync", "err", "cachedVectors", "dotProduct", "a", "b", "i", "calculateNorm", "v", "sum", "val", "searchUseCases", "query", "limit", "minSimilarity", "embedder", "queryVector", "TfjsEmbedder", "queryNorm", "VECTORS_FILE", "path", "fs", "compressed", "jsonContent", "zlib", "item", "resultsMap", "sim", "existing", "results", "limitedResults", "r", "logToolResult"]
}
