{ "version": 3, "sources": ["../src/helpers.ts", "../src/config.ts", "../src/sysinfo.ts", "../node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js", "../node_modules/.pnpm/node-fetch@2.6.1/node_modules/node-fetch/browser.js", "../node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/alea.js", "../node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor128.js", "../node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorwow.js", "../node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorshift7.js", "../node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor4096.js", "../node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/tychei.js", "(disabled):crypto", "../node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/seedrandom.js", "../node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/index.js", "../node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js", "../node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js", "../node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js", "../node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js", "../node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js", "../node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js", "../node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js", "../node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js", "../node_modules/.pnpm/string_decoder@1.1.1/node_modules/string_decoder/lib/string_decoder.js", "(disabled):path", "(disabled):worker_threads", "(disabled):perf_hooks", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/backends/backend.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/util_base.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/environment.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/global_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/kernel_names.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/kernel_registry.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/hash_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/profiler.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/tape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/tensor_format.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/tensor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/tensor_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/types.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/engine.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/device_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/flags.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/tensor_util_env.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/operation.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/complex.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tensor_ops_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tensor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/types.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/io_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/router_registry.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/indexed_db.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/local_storage.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/model_management.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/platforms/platform_browser.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/platforms/platform_node.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/buffer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/cast.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/clone.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/print.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/base_side_effects.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/io.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/browser_files.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/progress.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/weights_loader.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/http.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/io/passthrough.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/math.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/mat_mul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/one_hot.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/transpose.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/confusion_matrix.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/browser.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tensor3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/gather_nd_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/scatter_nd_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/slice_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/serialization.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/test_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/version.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/globals.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/add.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/floorDiv.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/div.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/mul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/abs.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/acos.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/acosh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/add_n.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/all.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/any.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/arg_max.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/arg_min.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/asin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/asinh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/atan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/atan2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/atanh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/reshape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/avg_pool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/concat.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sigmoid.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/slice.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tanh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/basic_lstm_cell.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/batch_to_space_nd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/batchnorm_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/batchnorm.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/batchnorm2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/batchnorm3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/batchnorm4d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/bincount.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/broadcast_to.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/ceil.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/clip_by_value.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/concat_1d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/concat_2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/concat_3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/concat_4d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv1d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv2d_backprop_input.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv2d_transpose.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv3d_backprop_input.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv3d_transpose.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/cos.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/cosh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/cumsum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/dense_bincount.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/depth_to_space.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/diag.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/dilation2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/broadcast_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/equal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/where.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/zeros_like.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/div_no_nan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/dot.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/einsum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/elu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/erf.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/exp.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/expand_dims.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/expm1.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tile.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/eye.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/fill.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/floor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/gather.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/greater.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/greater_equal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/imag.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/is_finite.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/is_inf.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/is_nan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/leaky_relu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/less.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/less_equal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/linspace.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/local_response_normalization.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/log.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/log1p.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/neg.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/softplus.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/log_sigmoid.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/max.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sub.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/log_softmax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/axis_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/log_sum_exp.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/logical_and.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/logical_not.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/logical_or.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/logical_xor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/max_pool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/max_pool_3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/max_pool_with_argmax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/maximum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/mean.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/zeros.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/ones.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/meshgrid.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/min.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/minimum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/mirror_pad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/mod.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/square.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/moments.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/multi_rnn_cell.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/multinomial.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/not_equal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/ones_like.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/outer_product.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/pad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/pad1d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/pad2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/pad3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/pad4d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/space_to_batch_nd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/pool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/pow.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/prelu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/prod.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/rand.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/rand_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/random_gamma.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/random_normal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/random_uniform.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/range.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/real.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/reciprocal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/relu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/relu6.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/reverse.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/reverse_1d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/reverse_2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/reverse_3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/reverse_4d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/round.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/rsqrt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/scalar.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/selu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/separable_conv2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/setdiff1d_async.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sign.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sinh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/slice1d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/slice2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/slice3d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/slice4d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/softmax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/spectral/fft.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/spectral/ifft.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/spectral/irfft.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/split.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/spectral/rfft.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sqrt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/squared_difference.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/squeeze.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/stack.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/step.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/strided_slice.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tensor1d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tensor2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tensor4d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tensor5d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/tensor6d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/topk.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/truncated_normal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/unique.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/unsorted_segment_sum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/unstack.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/variable.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/backends/where_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/where_async.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/boolean_mask.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/norm.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/moving_average.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/scatter_nd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sparse_to_dense_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sparse_to_dense.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/gather_nd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/dropout_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/dropout.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/signal_ops_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/in_top_k.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/fused_ops.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv2d_backprop_filter.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/fused_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/fused/conv2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d_native_backprop_filter.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d_native_backprop_input.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/fused/depthwise_conv2d.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/fused/mat_mul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/signal/hamming_window.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/signal/hann_window.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/signal/frame.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/signal/stft.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/crop_and_resize.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/flip_left_right.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/rotate_with_offset.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/nonmax_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/backends/non_max_suppression_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/backends/non_max_suppression_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_async.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_with_score.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_with_score_async.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_padded.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_padded_async.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/resize_bilinear.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/resize_nearest_neighbor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/threshold.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/image/transform.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/linalg/band_part.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/linalg/gram_schmidt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/linalg/qr.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/loss_ops_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/compute_weighted_loss.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/absolute_difference.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/cosine_distance.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/hinge_loss.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/huber_loss.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/log_loss.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/mean_squared_error.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/sigmoid_cross_entropy.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/losses/softmax_cross_entropy.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_fill_empty_rows.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_reshape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_segment_mean.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/sparse/sparse_segment_sum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/string/string_n_grams.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/string/string_split.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/string/string_to_hash_bucket_fast.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/ops.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/optimizer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/adadelta_optimizer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/adagrad_optimizer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/adam_optimizer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/adamax_optimizer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/sgd_optimizer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/momentum_optimizer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/rmsprop_optimizer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/optimizers/optimizer_constructors.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/train.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/browser_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/backends/backend_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/concat_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/reduce_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/rotate_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/array_ops_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/selu_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/erf_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/log.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/backends/complex_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/backends/einsum_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/split_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/segment_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/backends/kernel_impls.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/base.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/index.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Abs_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Acos_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Acosh_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Add_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/AddN_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/ArgMax_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/ArgMin_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Asin_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Asinh_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Atan2_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Atan_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Atanh_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_3d_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/AvgPool3D_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/AvgPool_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/BatchMatMul_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/BatchToSpaceND_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/BroadcastTo_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Cast_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Ceil_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/ClipByValue_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/ComplexAbs_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Concat_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Conv2D_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Conv2DBackpropInput_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/conv3d_backprop_filter.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Conv3D_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Cos_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Cosh_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Cumsum_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/DepthwiseConv2dNative_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Dilation2D_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Elu_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Erf_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Exp_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/ExpandDims_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Expm1_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Floor_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/FloorDiv_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/FusedBatchNorm_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/GatherV2_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/GreaterEqual_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Identity_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/IsFinite_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/IsInf_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/IsNan_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/LeakyRelu_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Log1p_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Log_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/LogSoftmax_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/local_response_normalization_backprop.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/LRN_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/min_max_grad_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Max_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Maximum_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/max_pool_3d_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/MaxPool3D_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/ops/max_pool_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/MaxPool_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Mean_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Min_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Minimum_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/MirrorPad_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Mod_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Multiply_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Neg_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/OneHot_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/OnesLike_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Pack_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/PadV2_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Pow_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Prelu_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/RealDiv_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Reciprocal_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Relu6_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Relu_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Reshape_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/ResizeBilinear_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/ResizeNearestNeighbor_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Reverse_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Round_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Rsqrt_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Select_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Selu_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Sigmoid_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Sign_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Sin_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Sinh_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Slice_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Softmax_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Softplus_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/SpaceToBatchND_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/SplitV_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Sqrt_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Square_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/SquaredDifference_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Step_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Sub_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Sum_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Tan_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Tanh_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Tile_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Transpose_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/Unpack_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/UnsortedSegmentSum_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/gradients/ZerosLike_grad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-core/src/register_all_gradients.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/exports_constraints.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/backend/common.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/errors.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/utils/generic_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/constraints.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/exports_initializers.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/keras_format/common.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/common.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/utils/math_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/backend/tfjs_backend.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/keras_format/initializer_config.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/initializers.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/exports_layers.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/backend/state.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/utils/types_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/utils/variable_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/variables.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/engine/topology.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/engine/input_layer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/logs.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/base_callbacks.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/serialization.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/losses.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/metrics.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/optimizers.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/user_defined_metadata.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/utils/layer_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/utils/serialization_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/version.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/engine/executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/engine/container.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/engine/training_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/engine/training_dataset.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/engine/training_tensors.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/engine/training.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/models.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/exports.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/activations.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/regularizers.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/advanced_activations.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/utils/conv_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/convolutional.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/convolutional_depthwise.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/recurrent.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/convolutional_recurrent.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/core.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/embeddings.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/merge.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/noise.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/normalization.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/padding.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/pooling.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/layers/wrappers.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/exports_metrics.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/exports_models.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/exports_regularizers.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/callbacks.ts", "../node_modules/.pnpm/@tensorflow+tfjs-layers@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-layers/src/index.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/data/compiled_api.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/custom_op/register.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/arithmetic.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/basic_math.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/control.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/convolution.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/creation.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/dynamic.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/evaluation.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/graph.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/hash_table.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/image.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/logical.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/matrices.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/normalization.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/reduction.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/slice_join.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/sparse.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/spectral.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/string.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/op_list/transformation.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/operation_mapper.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/custom_op/node_value_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/arithmetic_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/basic_math_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/tensor_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/tensor_array.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/tensor_list.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/control_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/convolution_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/creation_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/dynamic_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/evaluation_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/graph_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/hash_table.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/hash_table_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/image_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/logical_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/matrices_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/normalization_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/reduction_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/slice_join_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/sparse_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/spectral_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/string_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/executors/transformation_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/operations/operation_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/execution_context.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/model_analysis.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/graph_executor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/resource_manager.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/executor/graph_model.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/version.ts", "../node_modules/.pnpm/@tensorflow+tfjs-converter@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-converter/src/index.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/index.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/dataset.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/iterators/lazy_iterator.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/util/deep_map.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/util/deep_clone.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/util/ring_buffer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/util/growing_ring_buffer.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/datasets/text_line_dataset.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/datasets/csv_dataset.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/iterators/microphone_iterator.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/iterators/webcam_iterator.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/datasource.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/iterators/string_iterator.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/iterators/byte_chunk_iterator.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/iterators/file_chunk_iterator.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/iterators/url_chunk_iterator.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/util/source_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/sources/file_data_source.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/sources/url_data_source.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/readers.ts", "../node_modules/.pnpm/@tensorflow+tfjs-data@3.8.0_05bdadccdefc03588ef42dcd00574ff5/node_modules/@tensorflow/tfjs-data/src/version.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/cpu_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/backend_cpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/shared.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Abs.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/utils/binary_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Complex.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/utils/zeros_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Identity.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Real.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cast.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/utils/binary_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Add.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Bincount_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/utils/unary_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/utils/unary_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Ceil.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Concat_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Equal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Exp.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Expm1.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Floor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GatherNd_Impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GatherV2_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Greater.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GreaterEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Less.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LessEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LinSpace_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Log.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Max_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Maximum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Minimum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Multiply.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Neg.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NotEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Transpose_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Transpose.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Prod.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Range_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Rsqrt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Slice.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseFillEmptyRows_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseReshape_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseSegmentReduction_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SquaredDifference.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StridedSlice_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringNGrams_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringSplit_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringToHashBucketFast_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sub.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tile_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/TopK_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Unique_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/version.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/base.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Elu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LeakyRelu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Prelu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Relu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Relu6.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sigmoid.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/utils/fused_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Reshape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BatchMatMul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/_FusedMatMul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Acos.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Acosh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AddN.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/All.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Any.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ArgMax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ArgMin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Asin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Asinh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Atan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Atan2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Atanh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/utils/pool_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPool3D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPool3DGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPoolGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BatchNorm.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BatchToSpaceND.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Bincount.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Clip.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ComplexAbs.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Imag.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Concat.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv2DBackpropFilter.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv2DBackpropInput.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv3D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv3DBackpropFilterV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Conv3DBackpropInputV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cos.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cosh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/CropAndResize.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cumsum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DenseBincount.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DepthToSpace.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNative.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNativeBackpropFilter.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/DepthwiseConv2dNativeBackpropInput.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Diag.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2DBackpropFilter.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2DBackpropInput.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Einsum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/EluGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Erf.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ExpandDims.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RealDiv.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/utils/fft_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FFT.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Fill.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FlipLeftRight.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FloorDiv.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FusedConv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FusedDepthwiseConv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GatherNd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/GatherV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IFFT.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsFinite.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsInf.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsNaN.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LinSpace.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Log1p.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LogicalAnd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LogicalNot.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LogicalOr.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LRN.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LRNGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Max.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPool3D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPool3DGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolWithArgmax_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolWithArgmax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Mean.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Min.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MirrorPad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Mod.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Multinomial.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Softmax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV3.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV4.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV5.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/OneHot.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ZerosLike.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/OnesLike.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Pack.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/PadV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Pow.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Range.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Reciprocal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ResizeBilinear.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ResizeBilinearGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ResizeNearestNeighbor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ResizeNearestNeighborGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Reverse.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RotateWithOffset.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Round.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Scatter_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/ScatterNd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Select.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Selu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sign.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sinh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Softplus.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SpaceToBatchND.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseFillEmptyRows.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseReshape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseSegmentMean.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseSegmentSum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SparseToDense.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SplitV.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sqrt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Square.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Step.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StridedSlice.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringNGrams.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringSplit.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/StringToHashBucketFast.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tanh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tile.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/TopK.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Transform.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Unique.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Unpack.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/UnsortedSegmentSum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/register_all_kernels.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-cpu@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-cpu/src/index.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/webgl_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/canvas_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/tex_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/flags_webgl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/glsl_version.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/shader_compiler_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/decode_matrix_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/decode_matrix_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/encode_float_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/encode_float_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/encode_matrix_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/encode_matrix_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_context.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/shader_compiler.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_math.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/shared.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/packing_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/pack_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/reshape_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/texture_manager.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/unaryop_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/unaryop_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/unpack_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/backend_webgl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/version.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/webgl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/base.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Identity.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Complex.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LeakyRelu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Prelu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/kernel_funcs_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/mulmat_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_complex_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Multiply.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/reshape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Reshape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/mean_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/reduce_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/reduce.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/transpose_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/transpose_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Transpose_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sum_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Transpose.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchMatMul_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/_FusedMatMul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Abs.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Acos.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Acosh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Add.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/addn_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/addn_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AddN.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/All.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Any.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/argminmax_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/argminmax_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/arg_min_max.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ArgMax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ArgMin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Asin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Asinh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Atan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Atan2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Atanh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/pool_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPool3D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/avg_pool_backprop_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPool3DGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPoolGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchMatMul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/batchnorm_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/batchnorm_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchNorm.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/slice_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/slice_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Slice.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchToSpaceND.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Bincount.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NotEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Real.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/int.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cast.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Ceil.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/clip_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/clip_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ClipByValue.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/complex_abs_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ComplexAbs.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/concat_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/concat_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Imag.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Concat_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Concat.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/conv_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/im2col_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv2D_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/conv_backprop_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv2DBackpropFilter.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv2DBackpropInput.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv3D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv3DBackpropFilterV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Conv3DBackpropInputV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cos.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cosh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/crop_and_resize_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/CropAndResize.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/cumsum_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cumsum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DenseBincount.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/depth_to_space_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DepthToSpace.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/conv_gpu_depthwise.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/conv_packed_gpu_depthwise.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNative.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/conv_backprop_gpu_depthwise.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNativeBackpropFilter.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/DepthwiseConv2dNativeBackpropInput.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/diag_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Diag.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/dilation_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Dilation2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Einsum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Elu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/EluGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Equal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Erf.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Exp.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ExpandDims.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Expm1.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/fft_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FFT_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FFT.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/fill_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Fill.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/flip_left_right_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FlipLeftRight.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Floor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FloorDiv.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels_utils/from_pixels_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels_utils/from_pixels_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FusedConv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FusedDepthwiseConv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/gather_nd_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/GatherNd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/gather_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/GatherV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Greater.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/GreaterEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/IFFT.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/IsFinite.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/IsInf.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/IsNaN.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Less.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LessEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LinSpace.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Log.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Log1p.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LogicalAnd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LogicalNot.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LogicalOr.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LRN.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_grad_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/LRNGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Max_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Max.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Maximum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPool3D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/max_pool_backprop_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPool3DGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolWithArgmax_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolWithArgmax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Mean_impl.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Mean.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Min.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Minimum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/mirror_pad_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/mirror_pad_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MirrorPad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Mod.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/multinomial_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/RealDiv.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sub.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Softmax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Multinomial.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Neg.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV3.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV4.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV5.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/onehot_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/OneHot.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ZerosLike.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/OnesLike.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Pack.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/pad_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/pad_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/PadV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Pow.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Prod.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Range.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Reciprocal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Relu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Relu6.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ResizeBilinear.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_backprop_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ResizeBilinearGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/resize_nearest_neighbor_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/resize_nearest_neighbor_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ResizeNearestNeighbor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/resize_nearest_neighbor_backprop_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ResizeNearestNeighborGrad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/reverse_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/reverse_packed_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Reverse.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/rotate_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/RotateWithOffset.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Round.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Rsqrt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/scatter_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/ScatterNd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/select_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Select.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Selu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sigmoid.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sign.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sinh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Softplus.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SpaceToBatchND.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseFillEmptyRows.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseReshape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseSegmentMean.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseSegmentSum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SparseToDense.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SplitV.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sqrt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Square.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SquaredDifference.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Step.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/strided_slice_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StridedSlice.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StringNGrams.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StringSplit.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/StringToHashBucketFast.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Tan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Tanh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/tile_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Tile.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/top_k_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/TopK.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/transform_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Transform.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Unique.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Unpack.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/segment_gpu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/UnsortedSegmentSum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/register_all_kernels.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-webgl@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-webgl/src/index.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/types.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/_FusedMatMul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/unary_kernel.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Abs.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/binary_kernel.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Add.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/AddN.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Identity.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Transpose.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/kernel_utils.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/All.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Any.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/ArgMax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/AvgPool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Reshape.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/BatchMatMul.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernel_utils/shared.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Slice.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/BatchToSpaceND.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Cast.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Ceil.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/ClipByValue.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Concat.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Conv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Conv2DBackpropInput.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Cos.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Cosh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/CropAndResize.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Cumsum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/DepthToSpace.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/DepthwiseConv2dNative.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Equal.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Exp.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/ExpandDims.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Fill.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/FlipLeftRight.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Floor.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/FloorDiv.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/FusedBatchNorm.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/FusedConv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/FusedDepthwiseConv2D.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/GatherNd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/GatherV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Greater.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/GreaterEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/LeakyRelu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Less.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/LessEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Log.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/LogicalAnd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Max.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Maximum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/MaxPool.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Mean.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Min.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Minimum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/MirrorPad.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Multiply.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Neg.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/NonMaxSuppression_util.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/NonMaxSuppressionV3.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/NonMaxSuppressionV4.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/NonMaxSuppressionV5.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/NotEqual.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/OneHot.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/OnesLike.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Pack.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/PadV2.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Pow.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Prelu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Prod.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Range.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/RealDiv.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Relu.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Relu6.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/ResizeBilinear.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Reverse.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/RotateWithOffset.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Round.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Rsqrt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/ScatterNd.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Select.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Sigmoid.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Sin.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Softmax.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/SpaceToBatchND.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/SplitV.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Sqrt.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Square.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/SquaredDifference.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Step.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/StridedSlice.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Sub.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Sum.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Tan.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Tanh.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Tile.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/TopK.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Transform.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/Unpack.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/kernels/ZerosLike.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/register_all_kernels.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/flags_wasm.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/backend_wasm.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.worker.js", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/version.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/base.ts", "../node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.8.0_@tensorflow+tfjs-core@3.8.0/node_modules/@tensorflow/tfjs-backend-wasm/src/index.ts", "../tfjs/tf-browser.ts", "../src/tfjs/backend.ts", "../src/blazeface/box.ts", "../src/blazeface/util.ts", "../src/blazeface/blazeface.ts", "../src/blazeface/coords.ts", "../src/blazeface/facepipeline.ts", "../src/blazeface/facemesh.ts", "../src/faceres/faceres.ts", "../src/emotion/emotion.ts", "../src/posenet/keypoints.ts", "../src/posenet/utils.ts", "../src/posenet/poses.ts", "../src/posenet/posenet.ts", "../src/handpose/box.ts", "../src/handpose/anchors.ts", "../src/handpose/handdetector.ts", "../src/handpose/util.ts", "../src/handpose/handpipeline.ts", "../src/handpose/handpose.ts", "../src/blazepose/annotations.ts", "../src/blazepose/blazepose.ts", "../src/efficientpose/efficientpose.ts", "../src/movenet/movenet.ts", "../src/object/labels.ts", "../src/object/nanodet.ts", "../src/object/centernet.ts", "../src/image/imagefx.js", "../src/image/image.ts", "../src/segmentation/segmentation.ts", "../src/models.ts", "../src/face.ts", "../src/gesture/gesture.ts", "../src/draw/draw.ts", "../src/persons.ts", "../src/interpolate.ts", "../src/sample.ts", "../src/human.ts"], "sourcesContent": ["/**\n * Simple helper functions used accross codebase\n */\n\n// helper function: join two paths\nexport function join(folder: string, file: string): string {\n const separator = folder.endsWith('/') ? '' : '/';\n const skipJoin = file.startsWith('.') || file.startsWith('/') || file.startsWith('http:') || file.startsWith('https:') || file.startsWith('file:');\n const path = skipJoin ? `${file}` : `${folder}${separator}${file}`;\n if (!path.toLocaleLowerCase().includes('.json')) throw new Error(`Human: ModelPath Error: ${path} Expecting JSON file`);\n return path;\n}\n\n// helper function: wrapper around console output\nexport function log(...msg): void {\n const dt = new Date();\n const ts = `${dt.getHours().toString().padStart(2, '0')}:${dt.getMinutes().toString().padStart(2, '0')}:${dt.getSeconds().toString().padStart(2, '0')}.${dt.getMilliseconds().toString().padStart(3, '0')}`;\n // eslint-disable-next-line no-console\n if (msg) console.log(ts, 'Human:', ...msg);\n}\n\n// helper function: gets elapsed time on both browser and nodejs\nexport const now = () => {\n if (typeof performance !== 'undefined') return performance.now();\n return parseInt((Number(process.hrtime.bigint()) / 1000 / 1000).toString());\n};\n\n// helper function: perform deep merge of multiple objects so it allows full inheriance with overrides\nexport function mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === 'object';\n return objects.reduce((prev, obj) => {\n Object.keys(obj || {}).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) prev[key] = pVal.concat(...oVal);\n else if (isObject(pVal) && isObject(oVal)) prev[key] = mergeDeep(pVal, oVal);\n else prev[key] = oVal;\n });\n return prev;\n }, {});\n}\n\n// helper function: return min and max from input array\nexport const minmax = (data) => data.reduce((acc, val) => {\n acc[0] = (acc[0] === undefined || val < acc[0]) ? val : acc[0];\n acc[1] = (acc[1] === undefined || val > acc[1]) ? val : acc[1];\n return acc;\n}, []);\n", "/* eslint-disable indent */\n/* eslint-disable no-multi-spaces */\n\n/**\n * Configuration interface definition for **Human** library\n *\n * Contains all configurable parameters\n * @typedef Config\n */\nexport interface Config {\n /** Backend used for TFJS operations */\n backend: null | '' | 'cpu' | 'wasm' | 'webgl' | 'humangl' | 'tensorflow',\n\n /** Path to *.wasm files if backend is set to `wasm` */\n wasmPath: string,\n\n /** Print debug statements to console */\n debug: boolean,\n\n /** Perform model loading and inference concurrently or sequentially */\n async: boolean,\n\n /** What to use for `human.warmup()`\n * - warmup pre-initializes all models for faster inference but can take significant time on startup\n * - only used for `webgl` and `humangl` backends\n */\n warmup: 'none' | 'face' | 'full' | 'body',\n\n /** Base model path (typically starting with file://, http:// or https://) for all models\n * - individual modelPath values are relative to this path\n */\n modelBasePath: string,\n\n /** Cache sensitivity\n * - values 0..1 where 0.01 means reset cache if input changed more than 1%\n * - set to 0 to disable caching\n */\n cacheSensitivity: number;\n\n /** Cache sensitivity\n * - values 0..1 where 0.01 means reset cache if input changed more than 1%\n * - set to 0 to disable caching\n */\n skipFrame: boolean;\n\n /** Run input through image filters before inference\n * - image filters run with near-zero latency as they are executed on the GPU\n */\n filter: {\n enabled: boolean,\n /** Resize input width\n * - if both width and height are set to 0, there is no resizing\n * - if just one is set, second one is scaled automatically\n * - if both are set, values are used as-is\n */\n width: number,\n /** Resize input height\n * - if both width and height are set to 0, there is no resizing\n * - if just one is set, second one is scaled automatically\n * - if both are set, values are used as-is\n */\n height: number,\n /** Return processed canvas imagedata in result */\n return: boolean,\n /** Flip input as mirror image */\n flip: boolean,\n /** Range: -1 (darken) to 1 (lighten) */\n brightness: number,\n /** Range: -1 (reduce contrast) to 1 (increase contrast) */\n contrast: number,\n /** Range: 0 (no sharpening) to 1 (maximum sharpening) */\n sharpness: number,\n /** Range: 0 (no blur) to N (blur radius in pixels) */\n blur: number\n /** Range: -1 (reduce saturation) to 1 (increase saturation) */\n saturation: number,\n /** Range: 0 (no change) to 360 (hue rotation in degrees) */\n hue: number,\n /** Image negative */\n negative: boolean,\n /** Image sepia colors */\n sepia: boolean,\n /** Image vintage colors */\n vintage: boolean,\n /** Image kodachrome colors */\n kodachrome: boolean,\n /** Image technicolor colors */\n technicolor: boolean,\n /** Image polaroid camera effect */\n polaroid: boolean,\n /** Range: 0 (no pixelate) to N (number of pixels to pixelate) */\n pixelate: number,\n },\n // type definition end\n\n /** Controlls gesture detection */\n gesture: {\n enabled: boolean,\n },\n\n /** Controlls and configures all face-specific options:\n * - face detection, face mesh detection, age, gender, emotion detection and face description\n * Parameters:\n * - enabled: true/false\n * - modelPath: path for each of face models\n * - minConfidence: threshold for discarding a prediction\n * - iouThreshold: ammount of overlap between two detected objects before one object is removed\n * - maxDetected: maximum number of faces detected in the input, should be set to the minimum number for performance\n * - rotation: use calculated rotated face image or just box with rotation as-is, false means higher performance, but incorrect mesh mapping on higher face angles\n * - return: return extracted face as tensor for futher user processing, in which case user is reponsible for manually disposing the tensor\n */\n face: {\n enabled: boolean,\n detector: {\n modelPath: string,\n rotation: boolean,\n maxDetected: number,\n skipFrames: number,\n minConfidence: number,\n iouThreshold: number,\n return: boolean,\n },\n mesh: {\n enabled: boolean,\n modelPath: string,\n },\n iris: {\n enabled: boolean,\n modelPath: string,\n },\n description: {\n enabled: boolean,\n modelPath: string,\n skipFrames: number,\n minConfidence: number,\n },\n emotion: {\n enabled: boolean,\n minConfidence: number,\n skipFrames: number,\n modelPath: string,\n },\n },\n\n /** Controlls and configures all body detection specific options\n * - enabled: true/false\n * - modelPath: body pose model, can be absolute path or relative to modelBasePath\n * - minConfidence: threshold for discarding a prediction\n * - maxDetected: maximum number of people detected in the input, should be set to the minimum number for performance\n */\n body: {\n enabled: boolean,\n modelPath: string,\n maxDetected: number,\n minConfidence: number,\n skipFrames: number,\n },\n\n /** Controlls and configures all hand detection specific options\n * - enabled: true/false\n * - landmarks: detect hand landmarks or just hand boundary box\n * - modelPath: paths for hand detector and hand skeleton models, can be absolute path or relative to modelBasePath\n * - minConfidence: threshold for discarding a prediction\n * - iouThreshold: ammount of overlap between two detected objects before one object is removed\n * - maxDetected: maximum number of hands detected in the input, should be set to the minimum number for performance\n * - rotation: use best-guess rotated hand image or just box with rotation as-is, false means higher performance, but incorrect finger mapping if hand is inverted\n */\n hand: {\n enabled: boolean,\n rotation: boolean,\n skipFrames: number,\n minConfidence: number,\n iouThreshold: number,\n maxDetected: number,\n landmarks: boolean,\n detector: {\n modelPath: string,\n },\n skeleton: {\n modelPath: string,\n },\n },\n\n /** Controlls and configures all object detection specific options\n * - enabled: true/false\n * - modelPath: object detection model, can be absolute path or relative to modelBasePath\n * - minConfidence: minimum score that detection must have to return as valid object\n * - iouThreshold: ammount of overlap between two detected objects before one object is removed\n * - maxDetected: maximum number of detections to return\n */\n object: {\n enabled: boolean,\n modelPath: string,\n minConfidence: number,\n iouThreshold: number,\n maxDetected: number,\n skipFrames: number,\n },\n\n /** Controlls and configures all body segmentation module\n * removes background from input containing person\n * if segmentation is enabled it will run as preprocessing task before any other model\n * alternatively leave it disabled and use it on-demand using human.segmentation method which can\n * remove background or replace it with user-provided background\n *\n * - enabled: true/false\n * - modelPath: object detection model, can be absolute path or relative to modelBasePath\n */\n segmentation: {\n enabled: boolean,\n modelPath: string,\n },\n}\n\nconst config: Config = {\n backend: 'webgl', // select tfjs backend to use, leave empty to use default backend\n // can be 'webgl', 'wasm', 'cpu', or 'humangl' which is a custom version of webgl\n modelBasePath: '../models/', // base path for all models\n wasmPath: '../node_modules/@tensorflow/tfjs-backend-wasm/dist/', // path for wasm binaries, only used for backend: wasm\n debug: true, // print additional status messages to console\n async: true, // execute enabled models in parallel\n warmup: 'full', // what to use for human.warmup(), can be 'none', 'face', 'full'\n // warmup pre-initializes all models for faster inference but can take\n // significant time on startup\n // only used for `webgl` and `humangl` backends\n cacheSensitivity: 0.75, // cache sensitivity\n // values 0..1 where 0.01 means reset cache if input changed more than 1%\n // set to 0 to disable caching\n skipFrame: false, // internal & dynamic\n filter: { // run input through image filters before inference\n // image filters run with near-zero latency as they are executed on the GPU\n enabled: true, // enable image pre-processing filters\n width: 0, // resize input width\n height: 0, // resize input height\n // if both width and height are set to 0, there is no resizing\n // if just one is set, second one is scaled automatically\n // if both are set, values are used as-is\n flip: false, // flip input as mirror image\n return: true, // return processed canvas imagedata in result\n brightness: 0, // range: -1 (darken) to 1 (lighten)\n contrast: 0, // range: -1 (reduce contrast) to 1 (increase contrast)\n sharpness: 0, // range: 0 (no sharpening) to 1 (maximum sharpening)\n blur: 0, // range: 0 (no blur) to N (blur radius in pixels)\n saturation: 0, // range: -1 (reduce saturation) to 1 (increase saturation)\n hue: 0, // range: 0 (no change) to 360 (hue rotation in degrees)\n negative: false, // image negative\n sepia: false, // image sepia colors\n vintage: false, // image vintage colors\n kodachrome: false, // image kodachrome colors\n technicolor: false, // image technicolor colors\n polaroid: false, // image polaroid camera effect\n pixelate: 0, // range: 0 (no pixelate) to N (number of pixels to pixelate)\n },\n\n gesture: {\n enabled: true, // enable gesture recognition based on model results\n },\n\n face: {\n enabled: true, // controls if specified modul is enabled\n // face.enabled is required for all face models:\n // detector, mesh, iris, age, gender, emotion\n // (note: module is not loaded until it is required)\n detector: {\n modelPath: 'blazeface.json', // detector model, can be absolute path or relative to modelBasePath\n rotation: true, // use best-guess rotated face image or just box with rotation as-is\n // false means higher performance, but incorrect mesh mapping if face angle is above 20 degrees\n // this parameter is not valid in nodejs\n maxDetected: 15, // maximum number of faces detected in the input\n // should be set to the minimum number for performance\n skipFrames: 15, // how many max frames to go without re-running the face bounding box detector\n // only used when cacheSensitivity is not zero\n // e.g., if model is running st 25 FPS, we can re-use existing bounding\n // box for updated face analysis as the head probably hasn't moved much\n // in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.2, // threshold for discarding a prediction\n iouThreshold: 0.1, // ammount of overlap between two detected objects before one object is removed\n return: false, // return extracted face as tensor\n // in which case user is reponsible for disposing the tensor\n },\n\n mesh: {\n enabled: true,\n modelPath: 'facemesh.json', // facemesh model, can be absolute path or relative to modelBasePath\n },\n\n iris: {\n enabled: true,\n modelPath: 'iris.json', // face iris model\n // can be either absolute path or relative to modelBasePath\n },\n\n description: {\n enabled: true, // to improve accuracy of face description extraction it is\n // recommended to enable detector.rotation and mesh.enabled\n modelPath: 'faceres.json', // face description model\n // can be either absolute path or relative to modelBasePath\n skipFrames: 11, // how many max frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n minConfidence: 0.1, // threshold for discarding a prediction\n },\n\n emotion: {\n enabled: true,\n minConfidence: 0.1, // threshold for discarding a prediction\n skipFrames: 17, // how max many frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n modelPath: 'emotion.json', // face emotion model, can be absolute path or relative to modelBasePath\n },\n },\n\n body: {\n enabled: true,\n modelPath: 'movenet-lightning.json', // body model, can be absolute path or relative to modelBasePath\n // can be 'posenet', 'blazepose', 'efficientpose', 'movenet-lightning', 'movenet-thunder'\n maxDetected: 1, // maximum number of people detected in the input\n // should be set to the minimum number for performance\n // only valid for posenet as other models detects single pose\n minConfidence: 0.2, // threshold for discarding a prediction\n skipFrames: 1, // how many max frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n},\n\n hand: {\n enabled: true,\n rotation: true, // use best-guess rotated hand image or just box with rotation as-is\n // false means higher performance, but incorrect finger mapping if hand is inverted\n skipFrames: 18, // how many max frames to go without re-running the hand bounding box detector\n // only used when cacheSensitivity is not zero\n // e.g., if model is running st 25 FPS, we can re-use existing bounding\n // box for updated hand skeleton analysis as the hand probably\n // hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.1, // threshold for discarding a prediction\n iouThreshold: 0.1, // ammount of overlap between two detected objects before one object is removed\n maxDetected: 2, // maximum number of hands detected in the input\n // should be set to the minimum number for performance\n landmarks: true, // detect hand landmarks or just hand boundary box\n detector: {\n modelPath: 'handdetect.json', // hand detector model, can be absolute path or relative to modelBasePath\n },\n skeleton: {\n modelPath: 'handskeleton.json', // hand skeleton model, can be absolute path or relative to modelBasePath\n },\n },\n\n object: {\n enabled: false,\n modelPath: 'mb3-centernet.json', // experimental: object detection model, can be absolute path or relative to modelBasePath\n // can be 'mb3-centernet' or 'nanodet'\n minConfidence: 0.2, // threshold for discarding a prediction\n iouThreshold: 0.4, // ammount of overlap between two detected objects before one object is removed\n maxDetected: 10, // maximum number of objects detected in the input\n skipFrames: 19, // how many max frames to go without re-running the detector\n // only used when cacheSensitivity is not zero\n },\n\n segmentation: {\n enabled: false, // controlls and configures all body segmentation module\n // removes background from input containing person\n // if segmentation is enabled it will run as preprocessing task before any other model\n // alternatively leave it disabled and use it on-demand using human.segmentation method which can\n // remove background or replace it with user-provided background\n modelPath: 'selfie.json', // experimental: object detection model, can be absolute path or relative to modelBasePath\n // can be 'selfie' or 'meet'\n },\n};\nexport { config as defaults };\n", "/**\n * Helper function that returns basic system info\n */\nexport function info(): { platform: string, agent: string } {\n let platform;\n let agent;\n if (typeof navigator !== 'undefined') {\n const raw = navigator.userAgent.match(/\\(([^()]+)\\)/g);\n if (raw && raw[0]) {\n const platformMatch = raw[0].match(/\\(([^()]+)\\)/g);\n platform = platformMatch ? platformMatch[0].replace(/\\(|\\)/g, '') : '';\n agent = navigator.userAgent.replace(raw[0], '');\n if (platform[1]) agent = agent.replace(raw[1], '');\n agent = agent.replace(/ /g, ' ');\n }\n } else if (typeof process !== 'undefined') {\n platform = `${process.platform} ${process.arch}`;\n agent = `NodeJS ${process.version}`;\n }\n return { platform, agent };\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", "", "// A port of an algorithm by Johannes Baag\u00F8e <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\u00F8e <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 = data.toString();\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\u00E7ois 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 2014 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 (pool, math) {\n//\n// The following constants are related to IEEE 754 limits.\n//\nvar global = this,\n 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}\nmath['seed' + rngname] = seedrandom;\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}\n\n// End anonymous scope, and pass initial values.\n})(\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\u00F8e.\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\u00E7ois 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", "// A port of an algorithm by Johannes Baag\u00F8e <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\u00F8e <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\u00E7ois 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\u00F8e.\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\u00E7ois 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", "", "", "", "", "\nvar WasmBackendModuleThreadedSimd = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;\n return (\nfunction(WasmBackendModuleThreadedSimd) {\n WasmBackendModuleThreadedSimd = WasmBackendModuleThreadedSimd || {};\n\nfunction GROWABLE_HEAP_I8(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAP8}function GROWABLE_HEAP_U8(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPU8}function GROWABLE_HEAP_I32(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAP32}function GROWABLE_HEAP_U32(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPU32}function GROWABLE_HEAP_F64(){if(wasmMemory.buffer!=buffer){updateGlobalBufferAndViews(wasmMemory.buffer)}return HEAPF64}var Module=typeof WasmBackendModuleThreadedSimd!==\"undefined\"?WasmBackendModuleThreadedSimd:{};var readyPromiseResolve,readyPromiseReject;Module[\"ready\"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram=\"./this.program\";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window===\"object\";ENVIRONMENT_IS_WORKER=typeof importScripts===\"function\";ENVIRONMENT_IS_NODE=typeof process===\"object\"&&typeof process.versions===\"object\"&&typeof process.versions.node===\"string\";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_PTHREAD=Module[\"ENVIRONMENT_IS_PTHREAD\"]||false;if(ENVIRONMENT_IS_PTHREAD){buffer=Module[\"buffer\"]}var scriptDirectory=\"\";function locateFile(path){if(Module[\"locateFile\"]){return Module[\"locateFile\"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require(\"path\").dirname(scriptDirectory)+\"/\"}else{scriptDirectory=__dirname+\"/\"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require(\"fs\");if(!nodePath)nodePath=require(\"path\");filename=nodePath[\"normalize\"](filename);return nodeFS[\"readFileSync\"](filename,binary?null:\"utf8\")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process[\"argv\"].length>1){thisProgram=process[\"argv\"][1].replace(/\\\\/g,\"/\")}arguments_=process[\"argv\"].slice(2);process[\"on\"](\"uncaughtException\",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process[\"on\"](\"unhandledRejection\",abort);quit_=function(status){process[\"exit\"](status)};Module[\"inspect\"]=function(){return\"[Emscripten Module object]\"};var nodeWorkerThreads;try{nodeWorkerThreads=require(\"worker_threads\")}catch(e){console.error('The \"worker_threads\" module is not supported in this node.js build - perhaps a newer version is needed?');throw e}global.Worker=nodeWorkerThreads.Worker}else if(ENVIRONMENT_IS_SHELL){if(typeof read!=\"undefined\"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer===\"function\"){return new Uint8Array(readbuffer(f))}data=read(f,\"binary\");assert(typeof data===\"object\");return data};if(typeof scriptArgs!=\"undefined\"){arguments_=scriptArgs}else if(typeof arguments!=\"undefined\"){arguments_=arguments}if(typeof quit===\"function\"){quit_=function(status){quit(status)}}if(typeof print!==\"undefined\"){if(typeof console===\"undefined\")console={};console.log=print;console.warn=console.error=typeof printErr!==\"undefined\"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!==\"undefined\"&&document.currentScript){scriptDirectory=document.currentScript.src}if(typeof _scriptDir !== \"undefined\" && _scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf(\"blob:\")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf(\"/\")+1)}else{scriptDirectory=\"\"}if(ENVIRONMENT_IS_NODE){read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require(\"fs\");if(!nodePath)nodePath=require(\"path\");filename=nodePath[\"normalize\"](filename);return nodeFS[\"readFileSync\"](filename,binary?null:\"utf8\")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret}}else{read_=function(url){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,false);xhr.responseType=\"arraybuffer\";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,true);xhr.responseType=\"arraybuffer\";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}if(ENVIRONMENT_IS_NODE){if(typeof performance===\"undefined\"){global.performance=require(\"perf_hooks\").performance}}var out=Module[\"print\"]||console.log.bind(console);var err=Module[\"printErr\"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module[\"arguments\"])arguments_=Module[\"arguments\"];if(Module[\"thisProgram\"])thisProgram=Module[\"thisProgram\"];if(Module[\"quit\"])quit_=Module[\"quit\"];var Atomics_load=Atomics.load;var Atomics_store=Atomics.store;var Atomics_compareExchange=Atomics.compareExchange;var wasmBinary;if(Module[\"wasmBinary\"])wasmBinary=Module[\"wasmBinary\"];var noExitRuntime=Module[\"noExitRuntime\"]||true;if(typeof WebAssembly!==\"object\"){abort(\"no native wasm support detected\")}var wasmMemory;var wasmModule;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(\"Assertion failed: \"+text)}}function getCFunc(ident){var func=Module[\"_\"+ident];assert(func,\"Cannot call unknown function \"+ident+\", make sure it is exported\");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={\"string\":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},\"array\":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType===\"string\")return UTF8ToString(ret);if(returnType===\"boolean\")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func.apply(null,cArgs);ret=convertReturnValue(ret);if(stack!==0)stackRestore(stack);return ret}function cwrap(ident,returnType,argTypes,opts){argTypes=argTypes||[];var numericArgs=argTypes.every(function(type){return type===\"number\"});var numericRet=returnType!==\"string\";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return function(){return ccall(ident,returnType,argTypes,arguments,opts)}}function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var str=\"\";while(!(idx>=endIdx)){var u0=heap[idx++];if(!u0)return str;if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(GROWABLE_HEAP_U8(),ptr,maxBytesToRead):\"\"}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,GROWABLE_HEAP_U8(),outPtr,maxBytesToWrite)}function lengthBytesUTF8(str){var len=0;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127)++len;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else len+=4}return len}function writeArrayToMemory(array,buffer){GROWABLE_HEAP_I8().set(array,buffer)}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module[\"HEAP8\"]=HEAP8=new Int8Array(buf);Module[\"HEAP16\"]=HEAP16=new Int16Array(buf);Module[\"HEAP32\"]=HEAP32=new Int32Array(buf);Module[\"HEAPU8\"]=HEAPU8=new Uint8Array(buf);Module[\"HEAPU16\"]=HEAPU16=new Uint16Array(buf);Module[\"HEAPU32\"]=HEAPU32=new Uint32Array(buf);Module[\"HEAPF32\"]=HEAPF32=new Float32Array(buf);Module[\"HEAPF64\"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module[\"INITIAL_MEMORY\"]||16777216;if(ENVIRONMENT_IS_PTHREAD){wasmMemory=Module[\"wasmMemory\"];buffer=Module[\"buffer\"]}else{if(Module[\"wasmMemory\"]){wasmMemory=Module[\"wasmMemory\"]}else{wasmMemory=new WebAssembly.Memory({\"initial\":INITIAL_MEMORY/65536,\"maximum\":2147483648/65536,\"shared\":true});if(!(wasmMemory.buffer instanceof SharedArrayBuffer)){err(\"requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag\");if(ENVIRONMENT_IS_NODE){console.log(\"(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)\")}throw Error(\"bad memory\")}}}if(wasmMemory){buffer=wasmMemory.buffer}INITIAL_MEMORY=buffer.byteLength;updateGlobalBufferAndViews(buffer);var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;if(!ENVIRONMENT_IS_PTHREAD)__ATINIT__.push({func:function(){___wasm_call_ctors()}});function preRun(){if(ENVIRONMENT_IS_PTHREAD)return;if(Module[\"preRun\"]){if(typeof Module[\"preRun\"]==\"function\")Module[\"preRun\"]=[Module[\"preRun\"]];while(Module[\"preRun\"].length){addOnPreRun(Module[\"preRun\"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(ENVIRONMENT_IS_PTHREAD)return;callRuntimeCallbacks(__ATINIT__)}function preMain(){if(ENVIRONMENT_IS_PTHREAD)return;callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){if(ENVIRONMENT_IS_PTHREAD)return;runtimeExited=true}function postRun(){if(ENVIRONMENT_IS_PTHREAD)return;if(Module[\"postRun\"]){if(typeof Module[\"postRun\"]==\"function\")Module[\"postRun\"]=[Module[\"postRun\"]];while(Module[\"postRun\"].length){addOnPostRun(Module[\"postRun\"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){assert(!ENVIRONMENT_IS_PTHREAD,\"addRunDependency cannot be used in a pthread worker\");runDependencies++;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module[\"preloadedImages\"]={};Module[\"preloadedAudios\"]={};function abort(what){if(Module[\"onAbort\"]){Module[\"onAbort\"](what)}if(ENVIRONMENT_IS_PTHREAD)console.error(\"Pthread aborting at \"+(new Error).stack);what+=\"\";err(what);ABORT=true;EXITSTATUS=1;what=\"abort(\"+what+\"). Build with -s ASSERTIONS=1 for more info.\";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix=\"data:application/octet-stream;base64,\";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix=\"file://\";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile=\"tfjs-backend-wasm-threaded-simd.wasm\";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw\"both async and sync fetching of the wasm failed\"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch===\"function\"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:\"same-origin\"}).then(function(response){if(!response[\"ok\"]){throw\"failed to load wasm binary file at '\"+wasmBinaryFile+\"'\"}return response[\"arrayBuffer\"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={\"a\":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module[\"asm\"]=exports;wasmTable=Module[\"asm\"][\"F\"];wasmModule=module;if(!ENVIRONMENT_IS_PTHREAD){var numWorkersToLoad=PThread.unusedWorkers.length;PThread.unusedWorkers.forEach(function(w){PThread.loadWasmModuleToWorker(w,function(){if(!--numWorkersToLoad)removeRunDependency(\"wasm-instantiate\")})})}}if(!ENVIRONMENT_IS_PTHREAD){addRunDependency(\"wasm-instantiate\")}function receiveInstantiatedSource(output){receiveInstance(output[\"instance\"],output[\"module\"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err(\"failed to asynchronously prepare wasm: \"+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming===\"function\"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch===\"function\"){return fetch(wasmBinaryFile,{credentials:\"same-origin\"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err(\"wasm streaming compile failed: \"+reason);err(\"falling back to ArrayBuffer instantiation\");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module[\"instantiateWasm\"]){try{var exports=Module[\"instantiateWasm\"](info,receiveInstance);return exports}catch(e){err(\"Module.instantiateWasm callback failed with error: \"+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}var ASM_CONSTS={9832:function(){throw\"Canceled!\"},9850:function($0,$1){setTimeout(function(){__emscripten_do_dispatch_to_thread($0,$1)},0)}};function initPthreadsJS(){PThread.initRuntime()}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback==\"function\"){callback(Module);continue}var func=callback.func;if(typeof func===\"number\"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function _emscripten_futex_wake(addr,count){if(addr<=0||addr>GROWABLE_HEAP_I8().length||addr&3!=0||count<0)return-28;if(count==0)return 0;if(count>=2147483647)count=Infinity;var mainThreadWaitAddress=Atomics.load(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2);var mainThreadWoken=0;if(mainThreadWaitAddress==addr){var loadedAddr=Atomics.compareExchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,mainThreadWaitAddress,0);if(loadedAddr==mainThreadWaitAddress){--count;mainThreadWoken=1;if(count<=0)return 1}}var ret=Atomics.notify(GROWABLE_HEAP_I32(),addr>>2,count);if(ret>=0)return ret+mainThreadWoken;throw\"Atomics.notify returned an unexpected value \"+ret}Module[\"_emscripten_futex_wake\"]=_emscripten_futex_wake;function killThread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw\"Internal Error! killThread() can only ever be called from main application thread!\";if(!pthread_ptr)throw\"Internal Error! Null pthread_ptr in killThread!\";GROWABLE_HEAP_I32()[pthread_ptr+12>>2]=0;var pthread=PThread.pthreads[pthread_ptr];pthread.worker.terminate();PThread.freeThreadData(pthread);PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(pthread.worker),1);pthread.worker.pthread=undefined}function cancelThread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw\"Internal Error! cancelThread() can only ever be called from main application thread!\";if(!pthread_ptr)throw\"Internal Error! Null pthread_ptr in cancelThread!\";var pthread=PThread.pthreads[pthread_ptr];pthread.worker.postMessage({\"cmd\":\"cancel\"})}function cleanupThread(pthread_ptr){if(ENVIRONMENT_IS_PTHREAD)throw\"Internal Error! cleanupThread() can only ever be called from main application thread!\";if(!pthread_ptr)throw\"Internal Error! Null pthread_ptr in cleanupThread!\";var pthread=PThread.pthreads[pthread_ptr];if(pthread){GROWABLE_HEAP_I32()[pthread_ptr+12>>2]=0;var worker=pthread.worker;PThread.returnWorkerToPool(worker)}}var PThread={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){var pthreadPoolSize=Math.min(4,Math.max(1,(navigator.hardwareConcurrency||1)/2));for(var i=0;i<pthreadPoolSize;++i){PThread.allocateUnusedWorker()}},initRuntime:function(){var tb=_malloc(228);for(var i=0;i<228/4;++i)GROWABLE_HEAP_U32()[tb/4+i]=0;GROWABLE_HEAP_I32()[tb+12>>2]=tb;var headPtr=tb+152;GROWABLE_HEAP_I32()[headPtr>>2]=headPtr;var tlsMemory=_malloc(512);for(var i=0;i<128;++i)GROWABLE_HEAP_U32()[tlsMemory/4+i]=0;Atomics.store(GROWABLE_HEAP_U32(),tb+100>>2,tlsMemory);Atomics.store(GROWABLE_HEAP_U32(),tb+40>>2,tb);__emscripten_thread_init(tb,!ENVIRONMENT_IS_WORKER,1);_emscripten_register_main_browser_thread_id(tb)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){while(PThread.threadExitHandlers.length>0){PThread.threadExitHandlers.pop()()}if(ENVIRONMENT_IS_PTHREAD&&_pthread_self())___pthread_tsd_run_dtors()},runExitHandlersAndDeinitThread:function(tb,exitCode){Atomics.store(GROWABLE_HEAP_U32(),tb+56>>2,1);Atomics.store(GROWABLE_HEAP_U32(),tb+60>>2,0);PThread.runExitHandlers();Atomics.store(GROWABLE_HEAP_U32(),tb+4>>2,exitCode);Atomics.store(GROWABLE_HEAP_U32(),tb+0>>2,1);_emscripten_futex_wake(tb+0,2147483647);__emscripten_thread_init(0,0,0)},threadExit:function(exitCode){var tb=_pthread_self();if(tb){PThread.runExitHandlersAndDeinitThread(tb,exitCode);if(ENVIRONMENT_IS_PTHREAD){postMessage({\"cmd\":\"exit\"})}}},threadCancel:function(){PThread.runExitHandlersAndDeinitThread(_pthread_self(),-1);postMessage({\"cmd\":\"cancelDone\"})},terminateAllThreads:function(){for(var t in PThread.pthreads){var pthread=PThread.pthreads[t];if(pthread&&pthread.worker){PThread.returnWorkerToPool(pthread.worker)}}PThread.pthreads={};for(var i=0;i<PThread.unusedWorkers.length;++i){var worker=PThread.unusedWorkers[i];worker.terminate()}PThread.unusedWorkers=[];for(var i=0;i<PThread.runningWorkers.length;++i){var worker=PThread.runningWorkers[i];var pthread=worker.pthread;PThread.freeThreadData(pthread);worker.terminate()}PThread.runningWorkers=[]},freeThreadData:function(pthread){if(!pthread)return;if(pthread.threadInfoStruct){var tlsMemory=GROWABLE_HEAP_I32()[pthread.threadInfoStruct+100>>2];GROWABLE_HEAP_I32()[pthread.threadInfoStruct+100>>2]=0;_free(tlsMemory);_free(pthread.threadInfoStruct)}pthread.threadInfoStruct=0;if(pthread.allocatedOwnStack&&pthread.stackBase)_free(pthread.stackBase);pthread.stackBase=0;if(pthread.worker)pthread.worker.pthread=null},returnWorkerToPool:function(worker){PThread.runWithoutMainThreadQueuedCalls(function(){delete PThread.pthreads[worker.pthread.threadInfoStruct];PThread.unusedWorkers.push(worker);PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker),1);PThread.freeThreadData(worker.pthread);worker.pthread=undefined})},runWithoutMainThreadQueuedCalls:function(func){GROWABLE_HEAP_I32()[__emscripten_allow_main_runtime_queued_calls>>2]=0;try{func()}finally{GROWABLE_HEAP_I32()[__emscripten_allow_main_runtime_queued_calls>>2]=1}},receiveObjectTransfer:function(data){},loadWasmModuleToWorker:function(worker,onFinishedLoading){worker.onmessage=function(e){var d=e[\"data\"];var cmd=d[\"cmd\"];if(worker.pthread)PThread.currentProxiedOperationCallerThread=worker.pthread.threadInfoStruct;if(d[\"targetThread\"]&&d[\"targetThread\"]!=_pthread_self()){var thread=PThread.pthreads[d.targetThread];if(thread){thread.worker.postMessage(e.data,d[\"transferList\"])}else{console.error('Internal error! Worker sent a message \"'+cmd+'\" to target pthread '+d[\"targetThread\"]+\", but that thread no longer exists!\")}PThread.currentProxiedOperationCallerThread=undefined;return}if(cmd===\"processQueuedMainThreadWork\"){_emscripten_main_thread_process_queued_calls()}else if(cmd===\"spawnThread\"){spawnThread(e.data)}else if(cmd===\"cleanupThread\"){cleanupThread(d[\"thread\"])}else if(cmd===\"killThread\"){killThread(d[\"thread\"])}else if(cmd===\"cancelThread\"){cancelThread(d[\"thread\"])}else if(cmd===\"loaded\"){worker.loaded=true;if(onFinishedLoading)onFinishedLoading(worker);if(worker.runPthread){worker.runPthread();delete worker.runPthread}}else if(cmd===\"print\"){out(\"Thread \"+d[\"threadId\"]+\": \"+d[\"text\"])}else if(cmd===\"printErr\"){err(\"Thread \"+d[\"threadId\"]+\": \"+d[\"text\"])}else if(cmd===\"alert\"){alert(\"Thread \"+d[\"threadId\"]+\": \"+d[\"text\"])}else if(cmd===\"exit\"){var detached=worker.pthread&&Atomics.load(GROWABLE_HEAP_U32(),worker.pthread.threadInfoStruct+64>>2);if(detached){PThread.returnWorkerToPool(worker)}}else if(cmd===\"exitProcess\"){try{exit(d[\"returnCode\"])}catch(e){if(e instanceof ExitStatus)return;throw e}}else if(cmd===\"cancelDone\"){PThread.returnWorkerToPool(worker)}else if(cmd===\"objectTransfer\"){PThread.receiveObjectTransfer(e.data)}else if(e.data.target===\"setimmediate\"){worker.postMessage(e.data)}else{err(\"worker sent an unknown command \"+cmd)}PThread.currentProxiedOperationCallerThread=undefined};worker.onerror=function(e){err(\"pthread sent an error! \"+e.filename+\":\"+e.lineno+\": \"+e.message)};if(ENVIRONMENT_IS_NODE){worker.on(\"message\",function(data){worker.onmessage({data:data})});worker.on(\"error\",function(data){worker.onerror(data)});worker.on(\"exit\",function(data){})}worker.postMessage({\"cmd\":\"load\",\"urlOrBlob\":Module[\"mainScriptUrlOrBlob\"]||_scriptDir,\"wasmMemory\":wasmMemory,\"wasmModule\":wasmModule})},allocateUnusedWorker:function(){var pthreadMainJs=locateFile(\"tfjs-backend-wasm-threaded-simd.worker.js\");PThread.unusedWorkers.push(new Worker(pthreadMainJs))},getNewWorker:function(){if(PThread.unusedWorkers.length==0){PThread.allocateUnusedWorker();PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0])}if(PThread.unusedWorkers.length>0)return PThread.unusedWorkers.pop();else return null},busySpinWait:function(msecs){var t=performance.now()+msecs;while(performance.now()<t){}}};function establishStackSpace(stackTop,stackMax){_emscripten_stack_set_limits(stackTop,stackMax);stackRestore(stackTop)}Module[\"establishStackSpace\"]=establishStackSpace;function getNoExitRuntime(){return noExitRuntime}Module[\"getNoExitRuntime\"]=getNoExitRuntime;function invokeEntryPoint(ptr,arg){return wasmTable.get(ptr)(arg)}Module[\"invokeEntryPoint\"]=invokeEntryPoint;function ___assert_fail(condition,filename,line,func){abort(\"Assertion failed: \"+UTF8ToString(condition)+\", at: \"+[filename?UTF8ToString(filename):\"unknown filename\",line,func?UTF8ToString(func):\"unknown function\"])}function ___call_main(argc,argv){var returnCode=_main(argc,argv)}var _emscripten_get_now;if(ENVIRONMENT_IS_NODE){_emscripten_get_now=function(){var t=process[\"hrtime\"]();return t[0]*1e3+t[1]/1e6}}else if(ENVIRONMENT_IS_PTHREAD){_emscripten_get_now=function(){return performance.now()-Module[\"__performance_now_clock_drift\"]}}else if(typeof dateNow!==\"undefined\"){_emscripten_get_now=dateNow}else _emscripten_get_now=function(){return performance.now()};function setErrNo(value){GROWABLE_HEAP_I32()[___errno_location()>>2]=value;return value}function _atexit(func,arg){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(1,1,func,arg)}function __emscripten_notify_thread_queue(targetThreadId,mainThreadId){if(targetThreadId==mainThreadId){postMessage({\"cmd\":\"processQueuedMainThreadWork\"})}else if(ENVIRONMENT_IS_PTHREAD){postMessage({\"targetThread\":targetThreadId,\"cmd\":\"processThreadQueue\"})}else{var pthread=PThread.pthreads[targetThreadId];var worker=pthread&&pthread.worker;if(!worker){return}worker.postMessage({\"cmd\":\"processThreadQueue\"})}return 1}function _abort(){abort()}function _emscripten_asm_const_int(code,sigPtr,argbuf){var args=readAsmConstArgs(sigPtr,argbuf);return ASM_CONSTS[code].apply(null,args)}function _emscripten_conditional_set_current_thread_status(expectedStatus,newStatus){}function _emscripten_futex_wait(addr,val,timeout){if(addr<=0||addr>GROWABLE_HEAP_I8().length||addr&3!=0)return-28;if(!ENVIRONMENT_IS_WEB){var ret=Atomics.wait(GROWABLE_HEAP_I32(),addr>>2,val,timeout);if(ret===\"timed-out\")return-73;if(ret===\"not-equal\")return-6;if(ret===\"ok\")return 0;throw\"Atomics.wait returned an unexpected value \"+ret}else{if(Atomics.load(GROWABLE_HEAP_I32(),addr>>2)!=val){return-6}var tNow=performance.now();var tEnd=tNow+timeout;var lastAddr=Atomics.exchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,addr);while(1){tNow=performance.now();if(tNow>tEnd){lastAddr=Atomics.exchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,0);return-73}lastAddr=Atomics.exchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,0);if(lastAddr==0){break}_emscripten_main_thread_process_queued_calls();if(Atomics.load(GROWABLE_HEAP_I32(),addr>>2)!=val){return-6}lastAddr=Atomics.exchange(GROWABLE_HEAP_I32(),__emscripten_main_thread_futex>>2,addr)}return 0}}function _emscripten_memcpy_big(dest,src,num){GROWABLE_HEAP_U8().copyWithin(dest,src,src+num)}function _emscripten_num_logical_cores(){if(ENVIRONMENT_IS_NODE)return require(\"os\").cpus().length;return navigator[\"hardwareConcurrency\"]}function _emscripten_proxy_to_main_thread_js(index,sync){var numCallArgs=arguments.length-2;var stack=stackSave();var serializedNumCallArgs=numCallArgs;var args=stackAlloc(serializedNumCallArgs*8);var b=args>>3;for(var i=0;i<numCallArgs;i++){var arg=arguments[2+i];GROWABLE_HEAP_F64()[b+i]=arg}var ret=_emscripten_run_in_main_runtime_thread_js(index,serializedNumCallArgs,args,sync);stackRestore(stack);return ret}var _emscripten_receive_on_main_thread_js_callArgs=[];var readAsmConstArgsArray=[];function readAsmConstArgs(sigPtr,buf){readAsmConstArgsArray.length=0;var ch;buf>>=2;while(ch=GROWABLE_HEAP_U8()[sigPtr++]){var double=ch<105;if(double&&buf&1)buf++;readAsmConstArgsArray.push(double?GROWABLE_HEAP_F64()[buf++>>1]:GROWABLE_HEAP_I32()[buf]);++buf}return readAsmConstArgsArray}function _emscripten_receive_on_main_thread_js(index,numCallArgs,args){_emscripten_receive_on_main_thread_js_callArgs.length=numCallArgs;var b=args>>3;for(var i=0;i<numCallArgs;i++){_emscripten_receive_on_main_thread_js_callArgs[i]=GROWABLE_HEAP_F64()[b+i]}var isEmAsmConst=index<0;var func=!isEmAsmConst?proxiedFunctionTable[index]:ASM_CONSTS[-index-1];return func.apply(null,_emscripten_receive_on_main_thread_js_callArgs)}function _emscripten_get_heap_size(){return GROWABLE_HEAP_U8().length}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=_emscripten_get_heap_size();if(requestedSize<=oldSize){return false}var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var JSEvents={inEventHandler:0,removeAllEventListeners:function(){for(var i=JSEvents.eventHandlers.length-1;i>=0;--i){JSEvents._removeHandler(i)}JSEvents.eventHandlers=[];JSEvents.deferredCalls=[]},registerRemoveEventListeners:function(){if(!JSEvents.removeEventListenersRegistered){__ATEXIT__.push(JSEvents.removeAllEventListeners);JSEvents.removeEventListenersRegistered=true}},deferredCalls:[],deferCall:function(targetFunction,precedence,argsList){function arraysHaveEqualContent(arrA,arrB){if(arrA.length!=arrB.length)return false;for(var i in arrA){if(arrA[i]!=arrB[i])return false}return true}for(var i in JSEvents.deferredCalls){var call=JSEvents.deferredCalls[i];if(call.targetFunction==targetFunction&&arraysHaveEqualContent(call.argsList,argsList)){return}}JSEvents.deferredCalls.push({targetFunction:targetFunction,precedence:precedence,argsList:argsList});JSEvents.deferredCalls.sort(function(x,y){return x.precedence<y.precedence})},removeDeferredCalls:function(targetFunction){for(var i=0;i<JSEvents.deferredCalls.length;++i){if(JSEvents.deferredCalls[i].targetFunction==targetFunction){JSEvents.deferredCalls.splice(i,1);--i}}},canPerformEventHandlerRequests:function(){return JSEvents.inEventHandler&&JSEvents.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(!JSEvents.canPerformEventHandlerRequests()){return}for(var i=0;i<JSEvents.deferredCalls.length;++i){var call=JSEvents.deferredCalls[i];JSEvents.deferredCalls.splice(i,1);--i;call.targetFunction.apply(null,call.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(target,eventTypeString){for(var i=0;i<JSEvents.eventHandlers.length;++i){if(JSEvents.eventHandlers[i].target==target&&(!eventTypeString||eventTypeString==JSEvents.eventHandlers[i].eventTypeString)){JSEvents._removeHandler(i--)}}},_removeHandler:function(i){var h=JSEvents.eventHandlers[i];h.target.removeEventListener(h.eventTypeString,h.eventListenerFunc,h.useCapture);JSEvents.eventHandlers.splice(i,1)},registerOrRemoveHandler:function(eventHandler){var jsEventHandler=function jsEventHandler(event){++JSEvents.inEventHandler;JSEvents.currentEventHandler=eventHandler;JSEvents.runDeferredCalls();eventHandler.handlerFunc(event);JSEvents.runDeferredCalls();--JSEvents.inEventHandler};if(eventHandler.callbackfunc){eventHandler.eventListenerFunc=jsEventHandler;eventHandler.target.addEventListener(eventHandler.eventTypeString,jsEventHandler,eventHandler.useCapture);JSEvents.eventHandlers.push(eventHandler);JSEvents.registerRemoveEventListeners()}else{for(var i=0;i<JSEvents.eventHandlers.length;++i){if(JSEvents.eventHandlers[i].target==eventHandler.target&&JSEvents.eventHandlers[i].eventTypeString==eventHandler.eventTypeString){JSEvents._removeHandler(i--)}}}},queueEventHandlerOnThread_iiii:function(targetThread,eventHandlerFunc,eventTypeId,eventData,userData){var stackTop=stackSave();var varargs=stackAlloc(12);GROWABLE_HEAP_I32()[varargs>>2]=eventTypeId;GROWABLE_HEAP_I32()[varargs+4>>2]=eventData;GROWABLE_HEAP_I32()[varargs+8>>2]=userData;__emscripten_call_on_thread(0,targetThread,637534208,eventHandlerFunc,eventData,varargs);stackRestore(stackTop)},getTargetThreadForEventCallback:function(targetThread){switch(targetThread){case 1:return 0;case 2:return PThread.currentProxiedOperationCallerThread;default:return targetThread}},getNodeNameForTarget:function(target){if(!target)return\"\";if(target==window)return\"#window\";if(target==screen)return\"#screen\";return target&&target.nodeName?target.nodeName:\"\"},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function stringToNewUTF8(jsString){var length=lengthBytesUTF8(jsString)+1;var cString=_malloc(length);stringToUTF8(jsString,cString,length);return cString}function _emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread,targetCanvas,width,height){var stackTop=stackSave();var varargs=stackAlloc(12);var targetCanvasPtr=0;if(targetCanvas){targetCanvasPtr=stringToNewUTF8(targetCanvas)}GROWABLE_HEAP_I32()[varargs>>2]=targetCanvasPtr;GROWABLE_HEAP_I32()[varargs+4>>2]=width;GROWABLE_HEAP_I32()[varargs+8>>2]=height;__emscripten_call_on_thread(0,targetThread,657457152,0,targetCanvasPtr,varargs);stackRestore(stackTop)}function _emscripten_set_offscreencanvas_size_on_target_thread(targetThread,targetCanvas,width,height){targetCanvas=targetCanvas?UTF8ToString(targetCanvas):\"\";_emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread,targetCanvas,width,height)}function maybeCStringToJsString(cString){return cString>2?UTF8ToString(cString):cString}var specialHTMLTargets=[0,typeof document!==\"undefined\"?document:0,typeof window!==\"undefined\"?window:0];function findEventTarget(target){target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||(typeof document!==\"undefined\"?document.querySelector(target):undefined);return domElement}function findCanvasEventTarget(target){return findEventTarget(target)}function _emscripten_set_canvas_element_size_calling_thread(target,width,height){var canvas=findCanvasEventTarget(target);if(!canvas)return-4;if(canvas.canvasSharedPtr){GROWABLE_HEAP_I32()[canvas.canvasSharedPtr>>2]=width;GROWABLE_HEAP_I32()[canvas.canvasSharedPtr+4>>2]=height}if(canvas.offscreenCanvas||!canvas.controlTransferredOffscreen){if(canvas.offscreenCanvas)canvas=canvas.offscreenCanvas;var autoResizeViewport=false;if(canvas.GLctxObject&&canvas.GLctxObject.GLctx){var prevViewport=canvas.GLctxObject.GLctx.getParameter(2978);autoResizeViewport=prevViewport[0]===0&&prevViewport[1]===0&&prevViewport[2]===canvas.width&&prevViewport[3]===canvas.height}canvas.width=width;canvas.height=height;if(autoResizeViewport){canvas.GLctxObject.GLctx.viewport(0,0,width,height)}}else if(canvas.canvasSharedPtr){var targetThread=GROWABLE_HEAP_I32()[canvas.canvasSharedPtr+8>>2];_emscripten_set_offscreencanvas_size_on_target_thread(targetThread,target,width,height);return 1}else{return-4}return 0}function _emscripten_set_canvas_element_size_main_thread(target,width,height){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(2,1,target,width,height);return _emscripten_set_canvas_element_size_calling_thread(target,width,height)}function _emscripten_set_canvas_element_size(target,width,height){var canvas=findCanvasEventTarget(target);if(canvas){return _emscripten_set_canvas_element_size_calling_thread(target,width,height)}else{return _emscripten_set_canvas_element_size_main_thread(target,width,height)}}function _emscripten_set_current_thread_status(newStatus){}function _emscripten_set_thread_name(threadId,name){}function __webgl_enable_ANGLE_instanced_arrays(ctx){var ext=ctx.getExtension(\"ANGLE_instanced_arrays\");if(ext){ctx[\"vertexAttribDivisor\"]=function(index,divisor){ext[\"vertexAttribDivisorANGLE\"](index,divisor)};ctx[\"drawArraysInstanced\"]=function(mode,first,count,primcount){ext[\"drawArraysInstancedANGLE\"](mode,first,count,primcount)};ctx[\"drawElementsInstanced\"]=function(mode,count,type,indices,primcount){ext[\"drawElementsInstancedANGLE\"](mode,count,type,indices,primcount)};return 1}}function __webgl_enable_OES_vertex_array_object(ctx){var ext=ctx.getExtension(\"OES_vertex_array_object\");if(ext){ctx[\"createVertexArray\"]=function(){return ext[\"createVertexArrayOES\"]()};ctx[\"deleteVertexArray\"]=function(vao){ext[\"deleteVertexArrayOES\"](vao)};ctx[\"bindVertexArray\"]=function(vao){ext[\"bindVertexArrayOES\"](vao)};ctx[\"isVertexArray\"]=function(vao){return ext[\"isVertexArrayOES\"](vao)};return 1}}function __webgl_enable_WEBGL_draw_buffers(ctx){var ext=ctx.getExtension(\"WEBGL_draw_buffers\");if(ext){ctx[\"drawBuffers\"]=function(n,bufs){ext[\"drawBuffersWEBGL\"](n,bufs)};return 1}}function __webgl_enable_WEBGL_multi_draw(ctx){return!!(ctx.multiDrawWebgl=ctx.getExtension(\"WEBGL_multi_draw\"))}var GL={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function recordError(errorCode){if(!GL.lastError){GL.lastError=errorCode}},getNewId:function(table){var ret=GL.counter++;for(var i=table.length;i<ret;i++){table[i]=null}return ret},getSource:function(shader,count,string,length){var source=\"\";for(var i=0;i<count;++i){var len=length?GROWABLE_HEAP_I32()[length+i*4>>2]:-1;source+=UTF8ToString(GROWABLE_HEAP_I32()[string+i*4>>2],len<0?undefined:len)}return source},createContext:function(canvas,webGLContextAttributes){var ctx=canvas.getContext(\"webgl\",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:function(ctx,webGLContextAttributes){var handle=_malloc(8);GROWABLE_HEAP_I32()[handle+4>>2]=_pthread_self();var context={handle:handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault===\"undefined\"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}return handle},makeContextCurrent:function(contextHandle){GL.currentContext=GL.contexts[contextHandle];Module.ctx=GLctx=GL.currentContext&&GL.currentContext.GLctx;return!(contextHandle&&!GLctx)},getContext:function(contextHandle){return GL.contexts[contextHandle]},deleteContext:function(contextHandle){if(GL.currentContext===GL.contexts[contextHandle])GL.currentContext=null;if(typeof JSEvents===\"object\")JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas);if(GL.contexts[contextHandle]&&GL.contexts[contextHandle].GLctx.canvas)GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined;_free(GL.contexts[contextHandle].handle);GL.contexts[contextHandle]=null},initExtensions:function(context){if(!context)context=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;__webgl_enable_ANGLE_instanced_arrays(GLctx);__webgl_enable_OES_vertex_array_object(GLctx);__webgl_enable_WEBGL_draw_buffers(GLctx);GLctx.disjointTimerQueryExt=GLctx.getExtension(\"EXT_disjoint_timer_query\");__webgl_enable_WEBGL_multi_draw(GLctx);var exts=GLctx.getSupportedExtensions()||[];exts.forEach(function(ext){if(ext.indexOf(\"lose_context\")<0&&ext.indexOf(\"debug\")<0){GLctx.getExtension(ext)}})},populateUniformTable:function(program){var p=GL.programs[program];var ptable=GL.programInfos[program]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1};var utable=ptable.uniforms;var numUniforms=GLctx.getProgramParameter(p,35718);for(var i=0;i<numUniforms;++i){var u=GLctx.getActiveUniform(p,i);var name=u.name;ptable.maxUniformLength=Math.max(ptable.maxUniformLength,name.length+1);if(name.slice(-1)==\"]\"){name=name.slice(0,name.lastIndexOf(\"[\"))}var loc=GLctx.getUniformLocation(p,name);if(loc){var id=GL.getNewId(GL.uniforms);utable[name]=[u.size,id];GL.uniforms[id]=loc;for(var j=1;j<u.size;++j){var n=name+\"[\"+j+\"]\";loc=GLctx.getUniformLocation(p,n);id=GL.getNewId(GL.uniforms);GL.uniforms[id]=loc}}}}};var __emscripten_webgl_power_preferences=[\"default\",\"low-power\",\"high-performance\"];function _emscripten_webgl_do_create_context(target,attributes){var a=attributes>>2;var powerPreference=GROWABLE_HEAP_I32()[a+(24>>2)];var contextAttributes={\"alpha\":!!GROWABLE_HEAP_I32()[a+(0>>2)],\"depth\":!!GROWABLE_HEAP_I32()[a+(4>>2)],\"stencil\":!!GROWABLE_HEAP_I32()[a+(8>>2)],\"antialias\":!!GROWABLE_HEAP_I32()[a+(12>>2)],\"premultipliedAlpha\":!!GROWABLE_HEAP_I32()[a+(16>>2)],\"preserveDrawingBuffer\":!!GROWABLE_HEAP_I32()[a+(20>>2)],\"powerPreference\":__emscripten_webgl_power_preferences[powerPreference],\"failIfMajorPerformanceCaveat\":!!GROWABLE_HEAP_I32()[a+(28>>2)],majorVersion:GROWABLE_HEAP_I32()[a+(32>>2)],minorVersion:GROWABLE_HEAP_I32()[a+(36>>2)],enableExtensionsByDefault:GROWABLE_HEAP_I32()[a+(40>>2)],explicitSwapControl:GROWABLE_HEAP_I32()[a+(44>>2)],proxyContextToMainThread:GROWABLE_HEAP_I32()[a+(48>>2)],renderViaOffscreenBackBuffer:GROWABLE_HEAP_I32()[a+(52>>2)]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle}function _emscripten_webgl_create_context(a0,a1){return _emscripten_webgl_do_create_context(a0,a1)}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=GROWABLE_HEAP_I32()[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(3,1,fd);return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(4,1,fd,offset_low,offset_high,whence,newOffset)}function _fd_write(fd,iov,iovcnt,pnum){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(5,1,fd,iov,iovcnt,pnum);var num=0;for(var i=0;i<iovcnt;i++){var ptr=GROWABLE_HEAP_I32()[iov+i*8>>2];var len=GROWABLE_HEAP_I32()[iov+(i*8+4)>>2];for(var j=0;j<len;j++){SYSCALLS.printChar(fd,GROWABLE_HEAP_U8()[ptr+j])}num+=len}GROWABLE_HEAP_I32()[pnum>>2]=num;return 0}function _pthread_cleanup_pop(execute){var routine=PThread.threadExitHandlers.pop();if(execute)routine()}function _pthread_cleanup_push(routine,arg){PThread.threadExitHandlers.push(function(){wasmTable.get(routine)(arg)})}function spawnThread(threadParams){if(ENVIRONMENT_IS_PTHREAD)throw\"Internal Error! spawnThread() can only ever be called from main application thread!\";var worker=PThread.getNewWorker();if(worker.pthread!==undefined)throw\"Internal error!\";if(!threadParams.pthread_ptr)throw\"Internal error, no pthread ptr!\";PThread.runningWorkers.push(worker);var tlsMemory=_malloc(128*4);for(var i=0;i<128;++i){GROWABLE_HEAP_I32()[tlsMemory+i*4>>2]=0}var stackHigh=threadParams.stackBase+threadParams.stackSize;var pthread=PThread.pthreads[threadParams.pthread_ptr]={worker:worker,stackBase:threadParams.stackBase,stackSize:threadParams.stackSize,allocatedOwnStack:threadParams.allocatedOwnStack,threadInfoStruct:threadParams.pthread_ptr};var tis=pthread.threadInfoStruct>>2;Atomics.store(GROWABLE_HEAP_U32(),tis+(64>>2),threadParams.detached);Atomics.store(GROWABLE_HEAP_U32(),tis+(100>>2),tlsMemory);Atomics.store(GROWABLE_HEAP_U32(),tis+(40>>2),pthread.threadInfoStruct);Atomics.store(GROWABLE_HEAP_U32(),tis+(80>>2),threadParams.stackSize);Atomics.store(GROWABLE_HEAP_U32(),tis+(76>>2),stackHigh);Atomics.store(GROWABLE_HEAP_U32(),tis+(104>>2),threadParams.stackSize);Atomics.store(GROWABLE_HEAP_U32(),tis+(104+8>>2),stackHigh);Atomics.store(GROWABLE_HEAP_U32(),tis+(104+12>>2),threadParams.detached);var global_libc=_emscripten_get_global_libc();var global_locale=global_libc+40;Atomics.store(GROWABLE_HEAP_U32(),tis+(172>>2),global_locale);worker.pthread=pthread;var msg={\"cmd\":\"run\",\"start_routine\":threadParams.startRoutine,\"arg\":threadParams.arg,\"threadInfoStruct\":threadParams.pthread_ptr,\"stackBase\":threadParams.stackBase,\"stackSize\":threadParams.stackSize};worker.runPthread=function(){msg.time=performance.now();worker.postMessage(msg,threadParams.transferList)};if(worker.loaded){worker.runPthread();delete worker.runPthread}}function _pthread_create(pthread_ptr,attr,start_routine,arg){if(typeof SharedArrayBuffer===\"undefined\"){err(\"Current environment does not support SharedArrayBuffer, pthreads are not available!\");return 6}if(!pthread_ptr){err(\"pthread_create called with a null thread pointer!\");return 28}var transferList=[];var error=0;if(ENVIRONMENT_IS_PTHREAD&&(transferList.length===0||error)){return _emscripten_sync_run_in_main_thread_4(687865856,pthread_ptr,attr,start_routine,arg)}if(error)return error;var stackSize=0;var stackBase=0;var detached=0;if(attr&&attr!=-1){stackSize=GROWABLE_HEAP_I32()[attr>>2];stackSize+=81920;stackBase=GROWABLE_HEAP_I32()[attr+8>>2];detached=GROWABLE_HEAP_I32()[attr+12>>2]!==0}else{stackSize=2097152}var allocatedOwnStack=stackBase==0;if(allocatedOwnStack){stackBase=_memalign(16,stackSize)}else{stackBase-=stackSize;assert(stackBase>0)}var threadInfoStruct=_malloc(228);for(var i=0;i<228>>2;++i)GROWABLE_HEAP_U32()[(threadInfoStruct>>2)+i]=0;GROWABLE_HEAP_I32()[pthread_ptr>>2]=threadInfoStruct;GROWABLE_HEAP_I32()[threadInfoStruct+12>>2]=threadInfoStruct;var headPtr=threadInfoStruct+152;GROWABLE_HEAP_I32()[headPtr>>2]=headPtr;var threadParams={stackBase:stackBase,stackSize:stackSize,allocatedOwnStack:allocatedOwnStack,detached:detached,startRoutine:start_routine,pthread_ptr:threadInfoStruct,arg:arg,transferList:transferList};if(ENVIRONMENT_IS_PTHREAD){threadParams.cmd=\"spawnThread\";postMessage(threadParams,transferList)}else{spawnThread(threadParams)}return 0}function _sysconf(name){if(ENVIRONMENT_IS_PTHREAD)return _emscripten_proxy_to_main_thread_js(6,1,name);switch(name){case 30:return 16384;case 85:var maxHeapSize=2147483648;return maxHeapSize/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:{if(typeof navigator===\"object\")return navigator[\"hardwareConcurrency\"]||1;return 1}}setErrNo(28);return-1}if(!ENVIRONMENT_IS_PTHREAD)PThread.initMainThreadBlock();var GLctx;var proxiedFunctionTable=[null,_atexit,_emscripten_set_canvas_element_size_main_thread,_fd_close,_fd_seek,_fd_write,_sysconf];var asmLibraryArg={\"e\":___assert_fail,\"r\":___call_main,\"x\":__emscripten_notify_thread_queue,\"b\":_abort,\"y\":_emscripten_asm_const_int,\"j\":_emscripten_conditional_set_current_thread_status,\"c\":_emscripten_futex_wait,\"d\":_emscripten_futex_wake,\"f\":_emscripten_get_now,\"p\":_emscripten_memcpy_big,\"z\":_emscripten_num_logical_cores,\"u\":_emscripten_receive_on_main_thread_js,\"q\":_emscripten_resize_heap,\"v\":_emscripten_set_canvas_element_size,\"i\":_emscripten_set_current_thread_status,\"t\":_emscripten_set_thread_name,\"w\":_emscripten_webgl_create_context,\"m\":_fd_close,\"n\":_fd_seek,\"g\":_fd_write,\"o\":initPthreadsJS,\"a\":wasmMemory||Module[\"wasmMemory\"],\"k\":_pthread_cleanup_pop,\"l\":_pthread_cleanup_push,\"h\":_pthread_create,\"s\":_sysconf};var asm=createWasm();var ___wasm_call_ctors=Module[\"___wasm_call_ctors\"]=function(){return(___wasm_call_ctors=Module[\"___wasm_call_ctors\"]=Module[\"asm\"][\"A\"]).apply(null,arguments)};var _init=Module[\"_init\"]=function(){return(_init=Module[\"_init\"]=Module[\"asm\"][\"B\"]).apply(null,arguments)};var _register_tensor=Module[\"_register_tensor\"]=function(){return(_register_tensor=Module[\"_register_tensor\"]=Module[\"asm\"][\"C\"]).apply(null,arguments)};var _dispose_data=Module[\"_dispose_data\"]=function(){return(_dispose_data=Module[\"_dispose_data\"]=Module[\"asm\"][\"D\"]).apply(null,arguments)};var _dispose=Module[\"_dispose\"]=function(){return(_dispose=Module[\"_dispose\"]=Module[\"asm\"][\"E\"]).apply(null,arguments)};var _Abs=Module[\"_Abs\"]=function(){return(_Abs=Module[\"_Abs\"]=Module[\"asm\"][\"G\"]).apply(null,arguments)};var _Add=Module[\"_Add\"]=function(){return(_Add=Module[\"_Add\"]=Module[\"asm\"][\"H\"]).apply(null,arguments)};var _AddN=Module[\"_AddN\"]=function(){return(_AddN=Module[\"_AddN\"]=Module[\"asm\"][\"I\"]).apply(null,arguments)};var _All=Module[\"_All\"]=function(){return(_All=Module[\"_All\"]=Module[\"asm\"][\"J\"]).apply(null,arguments)};var _Any=Module[\"_Any\"]=function(){return(_Any=Module[\"_Any\"]=Module[\"asm\"][\"K\"]).apply(null,arguments)};var _ArgMax=Module[\"_ArgMax\"]=function(){return(_ArgMax=Module[\"_ArgMax\"]=Module[\"asm\"][\"L\"]).apply(null,arguments)};var _AvgPool=Module[\"_AvgPool\"]=function(){return(_AvgPool=Module[\"_AvgPool\"]=Module[\"asm\"][\"M\"]).apply(null,arguments)};var _BatchMatMul=Module[\"_BatchMatMul\"]=function(){return(_BatchMatMul=Module[\"_BatchMatMul\"]=Module[\"asm\"][\"N\"]).apply(null,arguments)};var _Ceil=Module[\"_Ceil\"]=function(){return(_Ceil=Module[\"_Ceil\"]=Module[\"asm\"][\"O\"]).apply(null,arguments)};var _ClipByValue=Module[\"_ClipByValue\"]=function(){return(_ClipByValue=Module[\"_ClipByValue\"]=Module[\"asm\"][\"P\"]).apply(null,arguments)};var _Conv2D=Module[\"_Conv2D\"]=function(){return(_Conv2D=Module[\"_Conv2D\"]=Module[\"asm\"][\"Q\"]).apply(null,arguments)};var _Conv2DBackpropInput=Module[\"_Conv2DBackpropInput\"]=function(){return(_Conv2DBackpropInput=Module[\"_Conv2DBackpropInput\"]=Module[\"asm\"][\"R\"]).apply(null,arguments)};var _Cos=Module[\"_Cos\"]=function(){return(_Cos=Module[\"_Cos\"]=Module[\"asm\"][\"S\"]).apply(null,arguments)};var _Cosh=Module[\"_Cosh\"]=function(){return(_Cosh=Module[\"_Cosh\"]=Module[\"asm\"][\"T\"]).apply(null,arguments)};var _CropAndResize=Module[\"_CropAndResize\"]=function(){return(_CropAndResize=Module[\"_CropAndResize\"]=Module[\"asm\"][\"U\"]).apply(null,arguments)};var _Cumsum=Module[\"_Cumsum\"]=function(){return(_Cumsum=Module[\"_Cumsum\"]=Module[\"asm\"][\"V\"]).apply(null,arguments)};var _DepthToSpace=Module[\"_DepthToSpace\"]=function(){return(_DepthToSpace=Module[\"_DepthToSpace\"]=Module[\"asm\"][\"W\"]).apply(null,arguments)};var _DepthwiseConv2dNative=Module[\"_DepthwiseConv2dNative\"]=function(){return(_DepthwiseConv2dNative=Module[\"_DepthwiseConv2dNative\"]=Module[\"asm\"][\"X\"]).apply(null,arguments)};var _Equal=Module[\"_Equal\"]=function(){return(_Equal=Module[\"_Equal\"]=Module[\"asm\"][\"Y\"]).apply(null,arguments)};var _Exp=Module[\"_Exp\"]=function(){return(_Exp=Module[\"_Exp\"]=Module[\"asm\"][\"Z\"]).apply(null,arguments)};var _FlipLeftRight=Module[\"_FlipLeftRight\"]=function(){return(_FlipLeftRight=Module[\"_FlipLeftRight\"]=Module[\"asm\"][\"_\"]).apply(null,arguments)};var _Floor=Module[\"_Floor\"]=function(){return(_Floor=Module[\"_Floor\"]=Module[\"asm\"][\"$\"]).apply(null,arguments)};var _FloorDiv=Module[\"_FloorDiv\"]=function(){return(_FloorDiv=Module[\"_FloorDiv\"]=Module[\"asm\"][\"aa\"]).apply(null,arguments)};var _FusedBatchNorm=Module[\"_FusedBatchNorm\"]=function(){return(_FusedBatchNorm=Module[\"_FusedBatchNorm\"]=Module[\"asm\"][\"ba\"]).apply(null,arguments)};var _FusedConv2D=Module[\"_FusedConv2D\"]=function(){return(_FusedConv2D=Module[\"_FusedConv2D\"]=Module[\"asm\"][\"ca\"]).apply(null,arguments)};var _FusedDepthwiseConv2D=Module[\"_FusedDepthwiseConv2D\"]=function(){return(_FusedDepthwiseConv2D=Module[\"_FusedDepthwiseConv2D\"]=Module[\"asm\"][\"da\"]).apply(null,arguments)};var _Gather=Module[\"_Gather\"]=function(){return(_Gather=Module[\"_Gather\"]=Module[\"asm\"][\"ea\"]).apply(null,arguments)};var _GatherNd=Module[\"_GatherNd\"]=function(){return(_GatherNd=Module[\"_GatherNd\"]=Module[\"asm\"][\"fa\"]).apply(null,arguments)};var _Greater=Module[\"_Greater\"]=function(){return(_Greater=Module[\"_Greater\"]=Module[\"asm\"][\"ga\"]).apply(null,arguments)};var _GreaterEqual=Module[\"_GreaterEqual\"]=function(){return(_GreaterEqual=Module[\"_GreaterEqual\"]=Module[\"asm\"][\"ha\"]).apply(null,arguments)};var _LeakyRelu=Module[\"_LeakyRelu\"]=function(){return(_LeakyRelu=Module[\"_LeakyRelu\"]=Module[\"asm\"][\"ia\"]).apply(null,arguments)};var _Less=Module[\"_Less\"]=function(){return(_Less=Module[\"_Less\"]=Module[\"asm\"][\"ja\"]).apply(null,arguments)};var _LessEqual=Module[\"_LessEqual\"]=function(){return(_LessEqual=Module[\"_LessEqual\"]=Module[\"asm\"][\"ka\"]).apply(null,arguments)};var _Log=Module[\"_Log\"]=function(){return(_Log=Module[\"_Log\"]=Module[\"asm\"][\"la\"]).apply(null,arguments)};var _LogicalAnd=Module[\"_LogicalAnd\"]=function(){return(_LogicalAnd=Module[\"_LogicalAnd\"]=Module[\"asm\"][\"ma\"]).apply(null,arguments)};var _Max=Module[\"_Max\"]=function(){return(_Max=Module[\"_Max\"]=Module[\"asm\"][\"na\"]).apply(null,arguments)};var _MaxPool=Module[\"_MaxPool\"]=function(){return(_MaxPool=Module[\"_MaxPool\"]=Module[\"asm\"][\"oa\"]).apply(null,arguments)};var _Maximum=Module[\"_Maximum\"]=function(){return(_Maximum=Module[\"_Maximum\"]=Module[\"asm\"][\"pa\"]).apply(null,arguments)};var _Mean=Module[\"_Mean\"]=function(){return(_Mean=Module[\"_Mean\"]=Module[\"asm\"][\"qa\"]).apply(null,arguments)};var _Min=Module[\"_Min\"]=function(){return(_Min=Module[\"_Min\"]=Module[\"asm\"][\"ra\"]).apply(null,arguments)};var _Minimum=Module[\"_Minimum\"]=function(){return(_Minimum=Module[\"_Minimum\"]=Module[\"asm\"][\"sa\"]).apply(null,arguments)};var _MirrorPad=Module[\"_MirrorPad\"]=function(){return(_MirrorPad=Module[\"_MirrorPad\"]=Module[\"asm\"][\"ta\"]).apply(null,arguments)};var _Multiply=Module[\"_Multiply\"]=function(){return(_Multiply=Module[\"_Multiply\"]=Module[\"asm\"][\"ua\"]).apply(null,arguments)};var _Neg=Module[\"_Neg\"]=function(){return(_Neg=Module[\"_Neg\"]=Module[\"asm\"][\"va\"]).apply(null,arguments)};var _NonMaxSuppressionV3=Module[\"_NonMaxSuppressionV3\"]=function(){return(_NonMaxSuppressionV3=Module[\"_NonMaxSuppressionV3\"]=Module[\"asm\"][\"wa\"]).apply(null,arguments)};var _NonMaxSuppressionV4=Module[\"_NonMaxSuppressionV4\"]=function(){return(_NonMaxSuppressionV4=Module[\"_NonMaxSuppressionV4\"]=Module[\"asm\"][\"xa\"]).apply(null,arguments)};var _NonMaxSuppressionV5=Module[\"_NonMaxSuppressionV5\"]=function(){return(_NonMaxSuppressionV5=Module[\"_NonMaxSuppressionV5\"]=Module[\"asm\"][\"ya\"]).apply(null,arguments)};var _NotEqual=Module[\"_NotEqual\"]=function(){return(_NotEqual=Module[\"_NotEqual\"]=Module[\"asm\"][\"za\"]).apply(null,arguments)};var _OneHot=Module[\"_OneHot\"]=function(){return(_OneHot=Module[\"_OneHot\"]=Module[\"asm\"][\"Aa\"]).apply(null,arguments)};var _PadV2=Module[\"_PadV2\"]=function(){return(_PadV2=Module[\"_PadV2\"]=Module[\"asm\"][\"Ba\"]).apply(null,arguments)};var _Pow=Module[\"_Pow\"]=function(){return(_Pow=Module[\"_Pow\"]=Module[\"asm\"][\"Ca\"]).apply(null,arguments)};var _Prelu=Module[\"_Prelu\"]=function(){return(_Prelu=Module[\"_Prelu\"]=Module[\"asm\"][\"Da\"]).apply(null,arguments)};var _Prod=Module[\"_Prod\"]=function(){return(_Prod=Module[\"_Prod\"]=Module[\"asm\"][\"Ea\"]).apply(null,arguments)};var _RealDiv=Module[\"_RealDiv\"]=function(){return(_RealDiv=Module[\"_RealDiv\"]=Module[\"asm\"][\"Fa\"]).apply(null,arguments)};var _Relu=Module[\"_Relu\"]=function(){return(_Relu=Module[\"_Relu\"]=Module[\"asm\"][\"Ga\"]).apply(null,arguments)};var _Relu6=Module[\"_Relu6\"]=function(){return(_Relu6=Module[\"_Relu6\"]=Module[\"asm\"][\"Ha\"]).apply(null,arguments)};var _ResizeBilinear=Module[\"_ResizeBilinear\"]=function(){return(_ResizeBilinear=Module[\"_ResizeBilinear\"]=Module[\"asm\"][\"Ia\"]).apply(null,arguments)};var _Reverse=Module[\"_Reverse\"]=function(){return(_Reverse=Module[\"_Reverse\"]=Module[\"asm\"][\"Ja\"]).apply(null,arguments)};var _RotateWithOffset=Module[\"_RotateWithOffset\"]=function(){return(_RotateWithOffset=Module[\"_RotateWithOffset\"]=Module[\"asm\"][\"Ka\"]).apply(null,arguments)};var _Round=Module[\"_Round\"]=function(){return(_Round=Module[\"_Round\"]=Module[\"asm\"][\"La\"]).apply(null,arguments)};var _Rsqrt=Module[\"_Rsqrt\"]=function(){return(_Rsqrt=Module[\"_Rsqrt\"]=Module[\"asm\"][\"Ma\"]).apply(null,arguments)};var _ScatterNd=Module[\"_ScatterNd\"]=function(){return(_ScatterNd=Module[\"_ScatterNd\"]=Module[\"asm\"][\"Na\"]).apply(null,arguments)};var _SelectV2=Module[\"_SelectV2\"]=function(){return(_SelectV2=Module[\"_SelectV2\"]=Module[\"asm\"][\"Oa\"]).apply(null,arguments)};var _Sigmoid=Module[\"_Sigmoid\"]=function(){return(_Sigmoid=Module[\"_Sigmoid\"]=Module[\"asm\"][\"Pa\"]).apply(null,arguments)};var _Sin=Module[\"_Sin\"]=function(){return(_Sin=Module[\"_Sin\"]=Module[\"asm\"][\"Qa\"]).apply(null,arguments)};var _Softmax=Module[\"_Softmax\"]=function(){return(_Softmax=Module[\"_Softmax\"]=Module[\"asm\"][\"Ra\"]).apply(null,arguments)};var _Sqrt=Module[\"_Sqrt\"]=function(){return(_Sqrt=Module[\"_Sqrt\"]=Module[\"asm\"][\"Sa\"]).apply(null,arguments)};var _Square=Module[\"_Square\"]=function(){return(_Square=Module[\"_Square\"]=Module[\"asm\"][\"Ta\"]).apply(null,arguments)};var _SquaredDifference=Module[\"_SquaredDifference\"]=function(){return(_SquaredDifference=Module[\"_SquaredDifference\"]=Module[\"asm\"][\"Ua\"]).apply(null,arguments)};var _Step=Module[\"_Step\"]=function(){return(_Step=Module[\"_Step\"]=Module[\"asm\"][\"Va\"]).apply(null,arguments)};var _StridedSlice=Module[\"_StridedSlice\"]=function(){return(_StridedSlice=Module[\"_StridedSlice\"]=Module[\"asm\"][\"Wa\"]).apply(null,arguments)};var _Sub=Module[\"_Sub\"]=function(){return(_Sub=Module[\"_Sub\"]=Module[\"asm\"][\"Xa\"]).apply(null,arguments)};var _Sum=Module[\"_Sum\"]=function(){return(_Sum=Module[\"_Sum\"]=Module[\"asm\"][\"Ya\"]).apply(null,arguments)};var _Tan=Module[\"_Tan\"]=function(){return(_Tan=Module[\"_Tan\"]=Module[\"asm\"][\"Za\"]).apply(null,arguments)};var _Tanh=Module[\"_Tanh\"]=function(){return(_Tanh=Module[\"_Tanh\"]=Module[\"asm\"][\"_a\"]).apply(null,arguments)};var _Tile=Module[\"_Tile\"]=function(){return(_Tile=Module[\"_Tile\"]=Module[\"asm\"][\"$a\"]).apply(null,arguments)};var _TopK=Module[\"_TopK\"]=function(){return(_TopK=Module[\"_TopK\"]=Module[\"asm\"][\"ab\"]).apply(null,arguments)};var _Transform=Module[\"_Transform\"]=function(){return(_Transform=Module[\"_Transform\"]=Module[\"asm\"][\"bb\"]).apply(null,arguments)};var _Transpose=Module[\"_Transpose\"]=function(){return(_Transpose=Module[\"_Transpose\"]=Module[\"asm\"][\"cb\"]).apply(null,arguments)};var __FusedMatMul=Module[\"__FusedMatMul\"]=function(){return(__FusedMatMul=Module[\"__FusedMatMul\"]=Module[\"asm\"][\"db\"]).apply(null,arguments)};var _malloc=Module[\"_malloc\"]=function(){return(_malloc=Module[\"_malloc\"]=Module[\"asm\"][\"eb\"]).apply(null,arguments)};var _free=Module[\"_free\"]=function(){return(_free=Module[\"_free\"]=Module[\"asm\"][\"fb\"]).apply(null,arguments)};var ___errno_location=Module[\"___errno_location\"]=function(){return(___errno_location=Module[\"___errno_location\"]=Module[\"asm\"][\"gb\"]).apply(null,arguments)};var _emscripten_get_global_libc=Module[\"_emscripten_get_global_libc\"]=function(){return(_emscripten_get_global_libc=Module[\"_emscripten_get_global_libc\"]=Module[\"asm\"][\"hb\"]).apply(null,arguments)};var _pthread_self=Module[\"_pthread_self\"]=function(){return(_pthread_self=Module[\"_pthread_self\"]=Module[\"asm\"][\"ib\"]).apply(null,arguments)};var ___pthread_tsd_run_dtors=Module[\"___pthread_tsd_run_dtors\"]=function(){return(___pthread_tsd_run_dtors=Module[\"___pthread_tsd_run_dtors\"]=Module[\"asm\"][\"jb\"]).apply(null,arguments)};var _emscripten_main_thread_process_queued_calls=Module[\"_emscripten_main_thread_process_queued_calls\"]=function(){return(_emscripten_main_thread_process_queued_calls=Module[\"_emscripten_main_thread_process_queued_calls\"]=Module[\"asm\"][\"kb\"]).apply(null,arguments)};var _emscripten_current_thread_process_queued_calls=Module[\"_emscripten_current_thread_process_queued_calls\"]=function(){return(_emscripten_current_thread_process_queued_calls=Module[\"_emscripten_current_thread_process_queued_calls\"]=Module[\"asm\"][\"lb\"]).apply(null,arguments)};var _emscripten_register_main_browser_thread_id=Module[\"_emscripten_register_main_browser_thread_id\"]=function(){return(_emscripten_register_main_browser_thread_id=Module[\"_emscripten_register_main_browser_thread_id\"]=Module[\"asm\"][\"mb\"]).apply(null,arguments)};var __emscripten_do_dispatch_to_thread=Module[\"__emscripten_do_dispatch_to_thread\"]=function(){return(__emscripten_do_dispatch_to_thread=Module[\"__emscripten_do_dispatch_to_thread\"]=Module[\"asm\"][\"nb\"]).apply(null,arguments)};var _emscripten_sync_run_in_main_thread_4=Module[\"_emscripten_sync_run_in_main_thread_4\"]=function(){return(_emscripten_sync_run_in_main_thread_4=Module[\"_emscripten_sync_run_in_main_thread_4\"]=Module[\"asm\"][\"ob\"]).apply(null,arguments)};var _emscripten_run_in_main_runtime_thread_js=Module[\"_emscripten_run_in_main_runtime_thread_js\"]=function(){return(_emscripten_run_in_main_runtime_thread_js=Module[\"_emscripten_run_in_main_runtime_thread_js\"]=Module[\"asm\"][\"pb\"]).apply(null,arguments)};var __emscripten_call_on_thread=Module[\"__emscripten_call_on_thread\"]=function(){return(__emscripten_call_on_thread=Module[\"__emscripten_call_on_thread\"]=Module[\"asm\"][\"qb\"]).apply(null,arguments)};var _emscripten_tls_init=Module[\"_emscripten_tls_init\"]=function(){return(_emscripten_tls_init=Module[\"_emscripten_tls_init\"]=Module[\"asm\"][\"rb\"]).apply(null,arguments)};var __emscripten_thread_init=Module[\"__emscripten_thread_init\"]=function(){return(__emscripten_thread_init=Module[\"__emscripten_thread_init\"]=Module[\"asm\"][\"sb\"]).apply(null,arguments)};var stackSave=Module[\"stackSave\"]=function(){return(stackSave=Module[\"stackSave\"]=Module[\"asm\"][\"tb\"]).apply(null,arguments)};var stackRestore=Module[\"stackRestore\"]=function(){return(stackRestore=Module[\"stackRestore\"]=Module[\"asm\"][\"ub\"]).apply(null,arguments)};var stackAlloc=Module[\"stackAlloc\"]=function(){return(stackAlloc=Module[\"stackAlloc\"]=Module[\"asm\"][\"vb\"]).apply(null,arguments)};var _emscripten_stack_set_limits=Module[\"_emscripten_stack_set_limits\"]=function(){return(_emscripten_stack_set_limits=Module[\"_emscripten_stack_set_limits\"]=Module[\"asm\"][\"wb\"]).apply(null,arguments)};var _memalign=Module[\"_memalign\"]=function(){return(_memalign=Module[\"_memalign\"]=Module[\"asm\"][\"xb\"]).apply(null,arguments)};var __emscripten_allow_main_runtime_queued_calls=Module[\"__emscripten_allow_main_runtime_queued_calls\"]=9824;var __emscripten_main_thread_futex=Module[\"__emscripten_main_thread_futex\"]=11448;Module[\"cwrap\"]=cwrap;Module[\"PThread\"]=PThread;Module[\"PThread\"]=PThread;Module[\"wasmMemory\"]=wasmMemory;Module[\"ExitStatus\"]=ExitStatus;var calledRun;function ExitStatus(status){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+status+\")\";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}if(ENVIRONMENT_IS_PTHREAD){readyPromiseResolve(Module);initRuntime();postMessage({\"cmd\":\"loaded\"});return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module[\"calledRun\"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module[\"onRuntimeInitialized\"])Module[\"onRuntimeInitialized\"]();postRun()}if(Module[\"setStatus\"]){Module[\"setStatus\"](\"Running...\");setTimeout(function(){setTimeout(function(){Module[\"setStatus\"](\"\")},1);doRun()},1)}else{doRun()}}Module[\"run\"]=run;function exit(status,implicit){if(implicit&&noExitRuntime&&status===0){return}if(!implicit){if(ENVIRONMENT_IS_PTHREAD){postMessage({\"cmd\":\"exitProcess\",\"returnCode\":status});throw new ExitStatus(status)}else{}}if(noExitRuntime){}else{PThread.terminateAllThreads();EXITSTATUS=status;exitRuntime();if(Module[\"onExit\"])Module[\"onExit\"](status);ABORT=true}quit_(status,new ExitStatus(status))}if(Module[\"preInit\"]){if(typeof Module[\"preInit\"]==\"function\")Module[\"preInit\"]=[Module[\"preInit\"]];while(Module[\"preInit\"].length>0){Module[\"preInit\"].pop()()}}if(ENVIRONMENT_IS_PTHREAD){noExitRuntime=false;PThread.initWorker()}run();\n\n\n return WasmBackendModuleThreadedSimd.ready\n}\n);\n})();\nif (typeof exports === 'object' && typeof module === 'object')\n module.exports = WasmBackendModuleThreadedSimd;\nelse if (typeof define === 'function' && define['amd'])\n define([], function() { return WasmBackendModuleThreadedSimd; });\nelse if (typeof exports === 'object')\n exports[\"WasmBackendModuleThreadedSimd\"] = WasmBackendModuleThreadedSimd;\n", "\nvar WasmBackendModule = (function() {\n var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;\n if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;\n return (\nfunction(WasmBackendModule) {\n WasmBackendModule = WasmBackendModule || {};\n\nvar Module=typeof WasmBackendModule!==\"undefined\"?WasmBackendModule:{};var readyPromiseResolve,readyPromiseReject;Module[\"ready\"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var arguments_=[];var thisProgram=\"./this.program\";var quit_=function(status,toThrow){throw toThrow};var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window===\"object\";ENVIRONMENT_IS_WORKER=typeof importScripts===\"function\";ENVIRONMENT_IS_NODE=typeof process===\"object\"&&typeof process.versions===\"object\"&&typeof process.versions.node===\"string\";ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;var scriptDirectory=\"\";function locateFile(path){if(Module[\"locateFile\"]){return Module[\"locateFile\"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;var nodeFS;var nodePath;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require(\"path\").dirname(scriptDirectory)+\"/\"}else{scriptDirectory=__dirname+\"/\"}read_=function shell_read(filename,binary){if(!nodeFS)nodeFS=require(\"fs\");if(!nodePath)nodePath=require(\"path\");filename=nodePath[\"normalize\"](filename);return nodeFS[\"readFileSync\"](filename,binary?null:\"utf8\")};readBinary=function readBinary(filename){var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};if(process[\"argv\"].length>1){thisProgram=process[\"argv\"][1].replace(/\\\\/g,\"/\")}arguments_=process[\"argv\"].slice(2);process[\"on\"](\"uncaughtException\",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process[\"on\"](\"unhandledRejection\",abort);quit_=function(status){process[\"exit\"](status)};Module[\"inspect\"]=function(){return\"[Emscripten Module object]\"}}else if(ENVIRONMENT_IS_SHELL){if(typeof read!=\"undefined\"){read_=function shell_read(f){return read(f)}}readBinary=function readBinary(f){var data;if(typeof readbuffer===\"function\"){return new Uint8Array(readbuffer(f))}data=read(f,\"binary\");assert(typeof data===\"object\");return data};if(typeof scriptArgs!=\"undefined\"){arguments_=scriptArgs}else if(typeof arguments!=\"undefined\"){arguments_=arguments}if(typeof quit===\"function\"){quit_=function(status){quit(status)}}if(typeof print!==\"undefined\"){if(typeof console===\"undefined\")console={};console.log=print;console.warn=console.error=typeof printErr!==\"undefined\"?printErr:print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!==\"undefined\"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf(\"blob:\")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.lastIndexOf(\"/\")+1)}else{scriptDirectory=\"\"}{read_=function(url){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,false);xhr.send(null);return xhr.responseText};if(ENVIRONMENT_IS_WORKER){readBinary=function(url){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,false);xhr.responseType=\"arraybuffer\";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=function(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open(\"GET\",url,true);xhr.responseType=\"arraybuffer\";xhr.onload=function(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}onerror()};xhr.onerror=onerror;xhr.send(null)}}setWindowTitle=function(title){document.title=title}}else{}var out=Module[\"print\"]||console.log.bind(console);var err=Module[\"printErr\"]||console.warn.bind(console);for(key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=null;if(Module[\"arguments\"])arguments_=Module[\"arguments\"];if(Module[\"thisProgram\"])thisProgram=Module[\"thisProgram\"];if(Module[\"quit\"])quit_=Module[\"quit\"];var wasmBinary;if(Module[\"wasmBinary\"])wasmBinary=Module[\"wasmBinary\"];var noExitRuntime=Module[\"noExitRuntime\"]||true;if(typeof WebAssembly!==\"object\"){abort(\"no native wasm support detected\")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(\"Assertion failed: \"+text)}}function getCFunc(ident){var func=Module[\"_\"+ident];assert(func,\"Cannot call unknown function \"+ident+\", make sure it is exported\");return func}function ccall(ident,returnType,argTypes,args,opts){var toC={\"string\":function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){var len=(str.length<<2)+1;ret=stackAlloc(len);stringToUTF8(str,ret,len)}return ret},\"array\":function(arr){var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType===\"string\")return UTF8ToString(ret);if(returnType===\"boolean\")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func.apply(null,cArgs);ret=convertReturnValue(ret);if(stack!==0)stackRestore(stack);return ret}function cwrap(ident,returnType,argTypes,opts){argTypes=argTypes||[];var numericArgs=argTypes.every(function(type){return type===\"number\"});var numericRet=returnType!==\"string\";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return function(){return ccall(ident,returnType,argTypes,arguments,opts)}}var UTF8Decoder=typeof TextDecoder!==\"undefined\"?new TextDecoder(\"utf8\"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str=\"\";while(idx<endPtr){var u0=heap[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):\"\"}function stringToUTF8Array(str,heap,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}}heap[outIdx]=0;return outIdx-startIdx}function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}function writeArrayToMemory(array,buffer){HEAP8.set(array,buffer)}function alignUp(x,multiple){if(x%multiple>0){x+=multiple-x%multiple}return x}var buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferAndViews(buf){buffer=buf;Module[\"HEAP8\"]=HEAP8=new Int8Array(buf);Module[\"HEAP16\"]=HEAP16=new Int16Array(buf);Module[\"HEAP32\"]=HEAP32=new Int32Array(buf);Module[\"HEAPU8\"]=HEAPU8=new Uint8Array(buf);Module[\"HEAPU16\"]=HEAPU16=new Uint16Array(buf);Module[\"HEAPU32\"]=HEAPU32=new Uint32Array(buf);Module[\"HEAPF32\"]=HEAPF32=new Float32Array(buf);Module[\"HEAPF64\"]=HEAPF64=new Float64Array(buf)}var INITIAL_MEMORY=Module[\"INITIAL_MEMORY\"]||16777216;var wasmTable;var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;__ATINIT__.push({func:function(){___wasm_call_ctors()}});function preRun(){if(Module[\"preRun\"]){if(typeof Module[\"preRun\"]==\"function\")Module[\"preRun\"]=[Module[\"preRun\"]];while(Module[\"preRun\"].length){addOnPreRun(Module[\"preRun\"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module[\"postRun\"]){if(typeof Module[\"postRun\"]==\"function\")Module[\"postRun\"]=[Module[\"postRun\"]];while(Module[\"postRun\"].length){addOnPostRun(Module[\"postRun\"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}}function removeRunDependency(id){runDependencies--;if(Module[\"monitorRunDependencies\"]){Module[\"monitorRunDependencies\"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module[\"preloadedImages\"]={};Module[\"preloadedAudios\"]={};function abort(what){if(Module[\"onAbort\"]){Module[\"onAbort\"](what)}what+=\"\";err(what);ABORT=true;EXITSTATUS=1;what=\"abort(\"+what+\"). Build with -s ASSERTIONS=1 for more info.\";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}function hasPrefix(str,prefix){return String.prototype.startsWith?str.startsWith(prefix):str.indexOf(prefix)===0}var dataURIPrefix=\"data:application/octet-stream;base64,\";function isDataURI(filename){return hasPrefix(filename,dataURIPrefix)}var fileURIPrefix=\"file://\";function isFileURI(filename){return hasPrefix(filename,fileURIPrefix)}var wasmBinaryFile=\"tfjs-backend-wasm.wasm\";if(!isDataURI(wasmBinaryFile)){wasmBinaryFile=locateFile(wasmBinaryFile)}function getBinary(file){try{if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}else{throw\"both async and sync fetching of the wasm failed\"}}catch(err){abort(err)}}function getBinaryPromise(){if(!wasmBinary&&(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)){if(typeof fetch===\"function\"&&!isFileURI(wasmBinaryFile)){return fetch(wasmBinaryFile,{credentials:\"same-origin\"}).then(function(response){if(!response[\"ok\"]){throw\"failed to load wasm binary file at '\"+wasmBinaryFile+\"'\"}return response[\"arrayBuffer\"]()}).catch(function(){return getBinary(wasmBinaryFile)})}else{if(readAsync){return new Promise(function(resolve,reject){readAsync(wasmBinaryFile,function(response){resolve(new Uint8Array(response))},reject)})}}}return Promise.resolve().then(function(){return getBinary(wasmBinaryFile)})}function createWasm(){var info={\"a\":asmLibraryArg};function receiveInstance(instance,module){var exports=instance.exports;Module[\"asm\"]=exports;wasmMemory=Module[\"asm\"][\"i\"];updateGlobalBufferAndViews(wasmMemory.buffer);wasmTable=Module[\"asm\"][\"o\"];removeRunDependency(\"wasm-instantiate\")}addRunDependency(\"wasm-instantiate\");function receiveInstantiatedSource(output){receiveInstance(output[\"instance\"])}function instantiateArrayBuffer(receiver){return getBinaryPromise().then(function(binary){return WebAssembly.instantiate(binary,info)}).then(receiver,function(reason){err(\"failed to asynchronously prepare wasm: \"+reason);abort(reason)})}function instantiateAsync(){if(!wasmBinary&&typeof WebAssembly.instantiateStreaming===\"function\"&&!isDataURI(wasmBinaryFile)&&!isFileURI(wasmBinaryFile)&&typeof fetch===\"function\"){return fetch(wasmBinaryFile,{credentials:\"same-origin\"}).then(function(response){var result=WebAssembly.instantiateStreaming(response,info);return result.then(receiveInstantiatedSource,function(reason){err(\"wasm streaming compile failed: \"+reason);err(\"falling back to ArrayBuffer instantiation\");return instantiateArrayBuffer(receiveInstantiatedSource)})})}else{return instantiateArrayBuffer(receiveInstantiatedSource)}}if(Module[\"instantiateWasm\"]){try{var exports=Module[\"instantiateWasm\"](info,receiveInstance);return exports}catch(e){err(\"Module.instantiateWasm callback failed with error: \"+e);return false}}instantiateAsync().catch(readyPromiseReject);return{}}function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback==\"function\"){callback(Module);continue}var func=callback.func;if(typeof func===\"number\"){if(callback.arg===undefined){wasmTable.get(func)()}else{wasmTable.get(func)(callback.arg)}}else{func(callback.arg===undefined?null:callback.arg)}}}function _abort(){abort()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.copyWithin(dest,src,src+num)}function _emscripten_get_heap_size(){return HEAPU8.length}function emscripten_realloc_buffer(size){try{wasmMemory.grow(size-buffer.byteLength+65535>>>16);updateGlobalBufferAndViews(wasmMemory.buffer);return 1}catch(e){}}function _emscripten_resize_heap(requestedSize){var oldSize=_emscripten_get_heap_size();var maxHeapSize=2147483648;if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=emscripten_realloc_buffer(newSize);if(replacement){return true}}return false}var SYSCALLS={mappings:{},buffers:[null,[],[]],printChar:function(stream,curr){var buffer=SYSCALLS.buffers[stream];if(curr===0||curr===10){(stream===1?out:err)(UTF8ArrayToString(buffer,0));buffer.length=0}else{buffer.push(curr)}},varargs:undefined,get:function(){SYSCALLS.varargs+=4;var ret=HEAP32[SYSCALLS.varargs-4>>2];return ret},getStr:function(ptr){var ret=UTF8ToString(ptr);return ret},get64:function(low,high){return low}};function _fd_close(fd){return 0}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){}function _fd_write(fd,iov,iovcnt,pnum){var num=0;for(var i=0;i<iovcnt;i++){var ptr=HEAP32[iov+i*8>>2];var len=HEAP32[iov+(i*8+4)>>2];for(var j=0;j<len;j++){SYSCALLS.printChar(fd,HEAPU8[ptr+j])}num+=len}HEAP32[pnum>>2]=num;return 0}function _pthread_create(){return 6}function setErrNo(value){HEAP32[___errno_location()>>2]=value;return value}function _sysconf(name){switch(name){case 30:return 16384;case 85:var maxHeapSize=2147483648;return maxHeapSize/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:{if(typeof navigator===\"object\")return navigator[\"hardwareConcurrency\"]||1;return 1}}setErrNo(28);return-1}var asmLibraryArg={\"a\":_abort,\"d\":_emscripten_memcpy_big,\"e\":_emscripten_resize_heap,\"f\":_fd_close,\"c\":_fd_seek,\"b\":_fd_write,\"g\":_pthread_create,\"h\":_sysconf};var asm=createWasm();var ___wasm_call_ctors=Module[\"___wasm_call_ctors\"]=function(){return(___wasm_call_ctors=Module[\"___wasm_call_ctors\"]=Module[\"asm\"][\"j\"]).apply(null,arguments)};var _init=Module[\"_init\"]=function(){return(_init=Module[\"_init\"]=Module[\"asm\"][\"k\"]).apply(null,arguments)};var _register_tensor=Module[\"_register_tensor\"]=function(){return(_register_tensor=Module[\"_register_tensor\"]=Module[\"asm\"][\"l\"]).apply(null,arguments)};var _dispose_data=Module[\"_dispose_data\"]=function(){return(_dispose_data=Module[\"_dispose_data\"]=Module[\"asm\"][\"m\"]).apply(null,arguments)};var _dispose=Module[\"_dispose\"]=function(){return(_dispose=Module[\"_dispose\"]=Module[\"asm\"][\"n\"]).apply(null,arguments)};var _Abs=Module[\"_Abs\"]=function(){return(_Abs=Module[\"_Abs\"]=Module[\"asm\"][\"p\"]).apply(null,arguments)};var _Add=Module[\"_Add\"]=function(){return(_Add=Module[\"_Add\"]=Module[\"asm\"][\"q\"]).apply(null,arguments)};var _AddN=Module[\"_AddN\"]=function(){return(_AddN=Module[\"_AddN\"]=Module[\"asm\"][\"r\"]).apply(null,arguments)};var _All=Module[\"_All\"]=function(){return(_All=Module[\"_All\"]=Module[\"asm\"][\"s\"]).apply(null,arguments)};var _Any=Module[\"_Any\"]=function(){return(_Any=Module[\"_Any\"]=Module[\"asm\"][\"t\"]).apply(null,arguments)};var _ArgMax=Module[\"_ArgMax\"]=function(){return(_ArgMax=Module[\"_ArgMax\"]=Module[\"asm\"][\"u\"]).apply(null,arguments)};var _AvgPool=Module[\"_AvgPool\"]=function(){return(_AvgPool=Module[\"_AvgPool\"]=Module[\"asm\"][\"v\"]).apply(null,arguments)};var _BatchMatMul=Module[\"_BatchMatMul\"]=function(){return(_BatchMatMul=Module[\"_BatchMatMul\"]=Module[\"asm\"][\"w\"]).apply(null,arguments)};var _Ceil=Module[\"_Ceil\"]=function(){return(_Ceil=Module[\"_Ceil\"]=Module[\"asm\"][\"x\"]).apply(null,arguments)};var _ClipByValue=Module[\"_ClipByValue\"]=function(){return(_ClipByValue=Module[\"_ClipByValue\"]=Module[\"asm\"][\"y\"]).apply(null,arguments)};var _Conv2D=Module[\"_Conv2D\"]=function(){return(_Conv2D=Module[\"_Conv2D\"]=Module[\"asm\"][\"z\"]).apply(null,arguments)};var _Conv2DBackpropInput=Module[\"_Conv2DBackpropInput\"]=function(){return(_Conv2DBackpropInput=Module[\"_Conv2DBackpropInput\"]=Module[\"asm\"][\"A\"]).apply(null,arguments)};var _Cos=Module[\"_Cos\"]=function(){return(_Cos=Module[\"_Cos\"]=Module[\"asm\"][\"B\"]).apply(null,arguments)};var _Cosh=Module[\"_Cosh\"]=function(){return(_Cosh=Module[\"_Cosh\"]=Module[\"asm\"][\"C\"]).apply(null,arguments)};var _CropAndResize=Module[\"_CropAndResize\"]=function(){return(_CropAndResize=Module[\"_CropAndResize\"]=Module[\"asm\"][\"D\"]).apply(null,arguments)};var _Cumsum=Module[\"_Cumsum\"]=function(){return(_Cumsum=Module[\"_Cumsum\"]=Module[\"asm\"][\"E\"]).apply(null,arguments)};var _DepthToSpace=Module[\"_DepthToSpace\"]=function(){return(_DepthToSpace=Module[\"_DepthToSpace\"]=Module[\"asm\"][\"F\"]).apply(null,arguments)};var _DepthwiseConv2dNative=Module[\"_DepthwiseConv2dNative\"]=function(){return(_DepthwiseConv2dNative=Module[\"_DepthwiseConv2dNative\"]=Module[\"asm\"][\"G\"]).apply(null,arguments)};var _Equal=Module[\"_Equal\"]=function(){return(_Equal=Module[\"_Equal\"]=Module[\"asm\"][\"H\"]).apply(null,arguments)};var _Exp=Module[\"_Exp\"]=function(){return(_Exp=Module[\"_Exp\"]=Module[\"asm\"][\"I\"]).apply(null,arguments)};var _FlipLeftRight=Module[\"_FlipLeftRight\"]=function(){return(_FlipLeftRight=Module[\"_FlipLeftRight\"]=Module[\"asm\"][\"J\"]).apply(null,arguments)};var _Floor=Module[\"_Floor\"]=function(){return(_Floor=Module[\"_Floor\"]=Module[\"asm\"][\"K\"]).apply(null,arguments)};var _FloorDiv=Module[\"_FloorDiv\"]=function(){return(_FloorDiv=Module[\"_FloorDiv\"]=Module[\"asm\"][\"L\"]).apply(null,arguments)};var _FusedBatchNorm=Module[\"_FusedBatchNorm\"]=function(){return(_FusedBatchNorm=Module[\"_FusedBatchNorm\"]=Module[\"asm\"][\"M\"]).apply(null,arguments)};var _FusedConv2D=Module[\"_FusedConv2D\"]=function(){return(_FusedConv2D=Module[\"_FusedConv2D\"]=Module[\"asm\"][\"N\"]).apply(null,arguments)};var _FusedDepthwiseConv2D=Module[\"_FusedDepthwiseConv2D\"]=function(){return(_FusedDepthwiseConv2D=Module[\"_FusedDepthwiseConv2D\"]=Module[\"asm\"][\"O\"]).apply(null,arguments)};var _Gather=Module[\"_Gather\"]=function(){return(_Gather=Module[\"_Gather\"]=Module[\"asm\"][\"P\"]).apply(null,arguments)};var _GatherNd=Module[\"_GatherNd\"]=function(){return(_GatherNd=Module[\"_GatherNd\"]=Module[\"asm\"][\"Q\"]).apply(null,arguments)};var _Greater=Module[\"_Greater\"]=function(){return(_Greater=Module[\"_Greater\"]=Module[\"asm\"][\"R\"]).apply(null,arguments)};var _GreaterEqual=Module[\"_GreaterEqual\"]=function(){return(_GreaterEqual=Module[\"_GreaterEqual\"]=Module[\"asm\"][\"S\"]).apply(null,arguments)};var _LeakyRelu=Module[\"_LeakyRelu\"]=function(){return(_LeakyRelu=Module[\"_LeakyRelu\"]=Module[\"asm\"][\"T\"]).apply(null,arguments)};var _Less=Module[\"_Less\"]=function(){return(_Less=Module[\"_Less\"]=Module[\"asm\"][\"U\"]).apply(null,arguments)};var _LessEqual=Module[\"_LessEqual\"]=function(){return(_LessEqual=Module[\"_LessEqual\"]=Module[\"asm\"][\"V\"]).apply(null,arguments)};var _Log=Module[\"_Log\"]=function(){return(_Log=Module[\"_Log\"]=Module[\"asm\"][\"W\"]).apply(null,arguments)};var _LogicalAnd=Module[\"_LogicalAnd\"]=function(){return(_LogicalAnd=Module[\"_LogicalAnd\"]=Module[\"asm\"][\"X\"]).apply(null,arguments)};var _Max=Module[\"_Max\"]=function(){return(_Max=Module[\"_Max\"]=Module[\"asm\"][\"Y\"]).apply(null,arguments)};var _MaxPool=Module[\"_MaxPool\"]=function(){return(_MaxPool=Module[\"_MaxPool\"]=Module[\"asm\"][\"Z\"]).apply(null,arguments)};var _Maximum=Module[\"_Maximum\"]=function(){return(_Maximum=Module[\"_Maximum\"]=Module[\"asm\"][\"_\"]).apply(null,arguments)};var _Mean=Module[\"_Mean\"]=function(){return(_Mean=Module[\"_Mean\"]=Module[\"asm\"][\"$\"]).apply(null,arguments)};var _Min=Module[\"_Min\"]=function(){return(_Min=Module[\"_Min\"]=Module[\"asm\"][\"aa\"]).apply(null,arguments)};var _Minimum=Module[\"_Minimum\"]=function(){return(_Minimum=Module[\"_Minimum\"]=Module[\"asm\"][\"ba\"]).apply(null,arguments)};var _MirrorPad=Module[\"_MirrorPad\"]=function(){return(_MirrorPad=Module[\"_MirrorPad\"]=Module[\"asm\"][\"ca\"]).apply(null,arguments)};var _Multiply=Module[\"_Multiply\"]=function(){return(_Multiply=Module[\"_Multiply\"]=Module[\"asm\"][\"da\"]).apply(null,arguments)};var _Neg=Module[\"_Neg\"]=function(){return(_Neg=Module[\"_Neg\"]=Module[\"asm\"][\"ea\"]).apply(null,arguments)};var _NonMaxSuppressionV3=Module[\"_NonMaxSuppressionV3\"]=function(){return(_NonMaxSuppressionV3=Module[\"_NonMaxSuppressionV3\"]=Module[\"asm\"][\"fa\"]).apply(null,arguments)};var _NonMaxSuppressionV4=Module[\"_NonMaxSuppressionV4\"]=function(){return(_NonMaxSuppressionV4=Module[\"_NonMaxSuppressionV4\"]=Module[\"asm\"][\"ga\"]).apply(null,arguments)};var _NonMaxSuppressionV5=Module[\"_NonMaxSuppressionV5\"]=function(){return(_NonMaxSuppressionV5=Module[\"_NonMaxSuppressionV5\"]=Module[\"asm\"][\"ha\"]).apply(null,arguments)};var _NotEqual=Module[\"_NotEqual\"]=function(){return(_NotEqual=Module[\"_NotEqual\"]=Module[\"asm\"][\"ia\"]).apply(null,arguments)};var _OneHot=Module[\"_OneHot\"]=function(){return(_OneHot=Module[\"_OneHot\"]=Module[\"asm\"][\"ja\"]).apply(null,arguments)};var _PadV2=Module[\"_PadV2\"]=function(){return(_PadV2=Module[\"_PadV2\"]=Module[\"asm\"][\"ka\"]).apply(null,arguments)};var _Pow=Module[\"_Pow\"]=function(){return(_Pow=Module[\"_Pow\"]=Module[\"asm\"][\"la\"]).apply(null,arguments)};var _Prelu=Module[\"_Prelu\"]=function(){return(_Prelu=Module[\"_Prelu\"]=Module[\"asm\"][\"ma\"]).apply(null,arguments)};var _Prod=Module[\"_Prod\"]=function(){return(_Prod=Module[\"_Prod\"]=Module[\"asm\"][\"na\"]).apply(null,arguments)};var _RealDiv=Module[\"_RealDiv\"]=function(){return(_RealDiv=Module[\"_RealDiv\"]=Module[\"asm\"][\"oa\"]).apply(null,arguments)};var _Relu=Module[\"_Relu\"]=function(){return(_Relu=Module[\"_Relu\"]=Module[\"asm\"][\"pa\"]).apply(null,arguments)};var _Relu6=Module[\"_Relu6\"]=function(){return(_Relu6=Module[\"_Relu6\"]=Module[\"asm\"][\"qa\"]).apply(null,arguments)};var _ResizeBilinear=Module[\"_ResizeBilinear\"]=function(){return(_ResizeBilinear=Module[\"_ResizeBilinear\"]=Module[\"asm\"][\"ra\"]).apply(null,arguments)};var _Reverse=Module[\"_Reverse\"]=function(){return(_Reverse=Module[\"_Reverse\"]=Module[\"asm\"][\"sa\"]).apply(null,arguments)};var _RotateWithOffset=Module[\"_RotateWithOffset\"]=function(){return(_RotateWithOffset=Module[\"_RotateWithOffset\"]=Module[\"asm\"][\"ta\"]).apply(null,arguments)};var _Round=Module[\"_Round\"]=function(){return(_Round=Module[\"_Round\"]=Module[\"asm\"][\"ua\"]).apply(null,arguments)};var _Rsqrt=Module[\"_Rsqrt\"]=function(){return(_Rsqrt=Module[\"_Rsqrt\"]=Module[\"asm\"][\"va\"]).apply(null,arguments)};var _ScatterNd=Module[\"_ScatterNd\"]=function(){return(_ScatterNd=Module[\"_ScatterNd\"]=Module[\"asm\"][\"wa\"]).apply(null,arguments)};var _SelectV2=Module[\"_SelectV2\"]=function(){return(_SelectV2=Module[\"_SelectV2\"]=Module[\"asm\"][\"xa\"]).apply(null,arguments)};var _Sigmoid=Module[\"_Sigmoid\"]=function(){return(_Sigmoid=Module[\"_Sigmoid\"]=Module[\"asm\"][\"ya\"]).apply(null,arguments)};var _Sin=Module[\"_Sin\"]=function(){return(_Sin=Module[\"_Sin\"]=Module[\"asm\"][\"za\"]).apply(null,arguments)};var _Softmax=Module[\"_Softmax\"]=function(){return(_Softmax=Module[\"_Softmax\"]=Module[\"asm\"][\"Aa\"]).apply(null,arguments)};var _Sqrt=Module[\"_Sqrt\"]=function(){return(_Sqrt=Module[\"_Sqrt\"]=Module[\"asm\"][\"Ba\"]).apply(null,arguments)};var _Square=Module[\"_Square\"]=function(){return(_Square=Module[\"_Square\"]=Module[\"asm\"][\"Ca\"]).apply(null,arguments)};var _SquaredDifference=Module[\"_SquaredDifference\"]=function(){return(_SquaredDifference=Module[\"_SquaredDifference\"]=Module[\"asm\"][\"Da\"]).apply(null,arguments)};var _Step=Module[\"_Step\"]=function(){return(_Step=Module[\"_Step\"]=Module[\"asm\"][\"Ea\"]).apply(null,arguments)};var _StridedSlice=Module[\"_StridedSlice\"]=function(){return(_StridedSlice=Module[\"_StridedSlice\"]=Module[\"asm\"][\"Fa\"]).apply(null,arguments)};var _Sub=Module[\"_Sub\"]=function(){return(_Sub=Module[\"_Sub\"]=Module[\"asm\"][\"Ga\"]).apply(null,arguments)};var _Sum=Module[\"_Sum\"]=function(){return(_Sum=Module[\"_Sum\"]=Module[\"asm\"][\"Ha\"]).apply(null,arguments)};var _Tan=Module[\"_Tan\"]=function(){return(_Tan=Module[\"_Tan\"]=Module[\"asm\"][\"Ia\"]).apply(null,arguments)};var _Tanh=Module[\"_Tanh\"]=function(){return(_Tanh=Module[\"_Tanh\"]=Module[\"asm\"][\"Ja\"]).apply(null,arguments)};var _Tile=Module[\"_Tile\"]=function(){return(_Tile=Module[\"_Tile\"]=Module[\"asm\"][\"Ka\"]).apply(null,arguments)};var _TopK=Module[\"_TopK\"]=function(){return(_TopK=Module[\"_TopK\"]=Module[\"asm\"][\"La\"]).apply(null,arguments)};var _Transform=Module[\"_Transform\"]=function(){return(_Transform=Module[\"_Transform\"]=Module[\"asm\"][\"Ma\"]).apply(null,arguments)};var _Transpose=Module[\"_Transpose\"]=function(){return(_Transpose=Module[\"_Transpose\"]=Module[\"asm\"][\"Na\"]).apply(null,arguments)};var __FusedMatMul=Module[\"__FusedMatMul\"]=function(){return(__FusedMatMul=Module[\"__FusedMatMul\"]=Module[\"asm\"][\"Oa\"]).apply(null,arguments)};var _malloc=Module[\"_malloc\"]=function(){return(_malloc=Module[\"_malloc\"]=Module[\"asm\"][\"Pa\"]).apply(null,arguments)};var _free=Module[\"_free\"]=function(){return(_free=Module[\"_free\"]=Module[\"asm\"][\"Qa\"]).apply(null,arguments)};var ___errno_location=Module[\"___errno_location\"]=function(){return(___errno_location=Module[\"___errno_location\"]=Module[\"asm\"][\"Ra\"]).apply(null,arguments)};var stackSave=Module[\"stackSave\"]=function(){return(stackSave=Module[\"stackSave\"]=Module[\"asm\"][\"Sa\"]).apply(null,arguments)};var stackRestore=Module[\"stackRestore\"]=function(){return(stackRestore=Module[\"stackRestore\"]=Module[\"asm\"][\"Ta\"]).apply(null,arguments)};var stackAlloc=Module[\"stackAlloc\"]=function(){return(stackAlloc=Module[\"stackAlloc\"]=Module[\"asm\"][\"Ua\"]).apply(null,arguments)};Module[\"cwrap\"]=cwrap;var calledRun;function ExitStatus(status){this.name=\"ExitStatus\";this.message=\"Program terminated with exit(\"+status+\")\";this.status=status}dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(args){args=args||arguments_;if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module[\"calledRun\"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);if(Module[\"onRuntimeInitialized\"])Module[\"onRuntimeInitialized\"]();postRun()}if(Module[\"setStatus\"]){Module[\"setStatus\"](\"Running...\");setTimeout(function(){setTimeout(function(){Module[\"setStatus\"](\"\")},1);doRun()},1)}else{doRun()}}Module[\"run\"]=run;if(Module[\"preInit\"]){if(typeof Module[\"preInit\"]==\"function\")Module[\"preInit\"]=[Module[\"preInit\"]];while(Module[\"preInit\"].length>0){Module[\"preInit\"].pop()()}}run();\n\n\n return WasmBackendModule.ready\n}\n);\n})();\nif (typeof exports === 'object' && typeof module === 'object')\n module.exports = WasmBackendModule;\nelse if (typeof define === 'function' && define['amd'])\n define([], function() { return WasmBackendModule; });\nelse if (typeof exports === 'object')\n exports[\"WasmBackendModule\"] = WasmBackendModule;\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, DataId} from '../tensor';\nimport {BackendValues, DataType} 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 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 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 {DataType, DataTypeMap, FlatVector, NumericDataType, RecursiveArray, TensorLike, TypedArray} 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// 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 (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {\n for (let i = 0; i < arr.length; ++i) {\n flatten(arr[i], result, skipTypedArray);\n }\n } else {\n result.push(arr as T);\n }\n return result;\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 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 indicies 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 indicies 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): 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 setTimeout(tryFn, nextBackoff);\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 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 return values as DataTypeMap[D];\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 isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array {\n return a instanceof Float32Array || a instanceof Int32Array ||\n a instanceof Uint8Array;\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 is\n * not possible since it depends on the encoding of the html page that serves\n * 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): DataType {\n if (Array.isArray(values)) {\n return inferDtype(values[0]);\n }\n if (values instanceof Float32Array) {\n return 'float32';\n } else if (values instanceof Int32Array || values instanceof Uint8Array) {\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 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 tensor/multidimentional\n * 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) {\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 patch\n // the async calls, so it is possible the obj (patched) is comparing to a\n // 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;\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 console.warn(\n `Platform ${this.platformName} has already been set. ` +\n `Overwriting the platform with ${platform}.`);\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 the\n // environment is initialized before flags get registered.\n if (this.urlFlags[flagName] != null) {\n const flagValue = this.urlFlags[flagName];\n console.warn(\n `Setting feature override from URL ${flagName}: ${flagValue}.`);\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 as number | boolean;\n\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 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 value = value.toLowerCase();\n if (value === 'true' || value === 'false') {\n return value === 'true';\n } else if (`${+ value}` === value) {\n return +value;\n }\n throw new Error(\n `Could not parse value flag value ${value} for flag ${flagName}.`);\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, TensorInfo} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {DataType, 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 BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick<NamedTensorInfoMap, 'x'>;\nexport interface BroadCastToAttrs {\n shape: number[];\n inputShape: number[]; // for gradient\n}\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 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 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 LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick<NamedTensorInfoMap, 'logits'>;\nexport interface LogSoftmaxAttrs {\n axis: number;\n}\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 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}\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 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 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 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 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 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';\n\nimport {getGlobal} from './global_util';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {DataType, RecursiveArray} from './types';\n\nconst kernelRegistry =\n getGlobal('kernelRegistry', () => new Map<string, KernelConfig>());\nconst gradRegistry =\n getGlobal('gradRegistry', () => new Map<string, GradConfig>());\n\nexport type DataId = object;\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\n/** Holds metadata for a given tensor. */\nexport interface TensorInfo {\n dataId: DataId;\n shape: number[];\n dtype: DataType;\n}\n\nexport interface NamedTensorInfoMap {\n [name: string]: TensorInfo;\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 console.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 console.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, backendName: string) {\n return `${backendName}_${kernelName}`;\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 {BackendValues, DataType, 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 = base.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://unpkg.com/@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", "/**\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 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] = '[' + 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\nimport {getGlobal} from './global_util';\nimport {tensorToString} from './tensor_format';\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 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}\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/**\n * We wrap data id since we use weak map to avoid memory leaks.\n * Since we have our own memory management, we have a reference counter\n * mapping a tensor to its data, so there is always a pointer (even if that\n * data is otherwise garbage collectable).\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/\n * Global_Objects/WeakMap\n */\nexport type DataId = object; // object instead of {} to force non-primitive.\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> {\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\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 * 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 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}\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 becase 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}\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 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 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 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';\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 * @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, TensorInfo} from './kernel_registry';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataId, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\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 console.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 suceeded. 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 console.warn(\n `Initialization of backend ${backendName} failed`);\n console.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 console.warn(`Initialization of backend ${backendName} failed`);\n console.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, {x} as {} 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 {} as NamedTensorMap,\n // tslint:disable-next-line: no-unnecessary-type-assertion\n attrs as {} 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 const {dataId, shape, dtype} = outInfo as TensorInfo;\n return this.makeTensorFromDataId(dataId, shape, dtype);\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 */\n makeTensorFromDataId(\n dataId: DataId, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n dtype = dtype || 'float32';\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 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 {} 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 {} 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\nexport function isMobile(nav?: Navigator): boolean {\n if (nav || _isNavigatorDefined()) {\n if (!nav) {\n nav = navigator;\n }\n if (nav.product === 'ReactNative') {\n return true;\n }\n\n // tslint:disable-next-line:no-any\n const a = nav.userAgent || nav.vendor || (window as any).opera;\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/**\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', () => true);\n\n/** Whether the backend needs to wrap input to imageBitmap. */\nENV.registerFlag('WRAP_TO_IMAGEBITMAP', () => 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 {Tensor} from './tensor';\nimport {DataType, TensorLike} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\n\nexport function inferShape(val: TensorLike, dtype?: DataType): number[] {\n let firstElem: typeof val = val;\n\n if (isTypedArray(val)) {\n return dtype === 'string' ? [] : [val.length];\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 Tensor) {\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 {} as NamedTensorMap);\n}\n\nexport const complex = 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 {TensorLike, TypedArray} 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, shape: number[], inferredShape: number[],\n dtype?: DataType): Tensor {\n if (dtype == null) {\n dtype = inferDtype(values);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `Cannot construct a complex64 tensor directly. ` +\n `Please use tf.complex(real, imag).`);\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 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} 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 * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`. If the values are strings,\n * they will be encoded as utf-8 and kept as `Uint8Array[]`.\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, shape?: ShapeMap[R], dtype?: DataType): Tensor<R> {\n const inferredShape = inferShape(values, dtype);\n return makeTensor(values, shape, inferredShape, 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\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\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 for all weight values concatenated in the order specified\n * by `weightSpecs`.\n */\n weightData?: 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/**\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/**\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 * 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?: Function;\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/**\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, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\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 buffer A flat ArrayBuffer carrying the binary values of the tensors\n * concatenated in the order specified in `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 buffer: ArrayBuffer, specs: WeightsManifestEntry[]): NamedTensorMap {\n // TODO(adarob, cais): Support quantization.\n const out: NamedTensorMap = {};\n let float16Decode: (buffer: Uint16Array) => Float32Array | undefined;\n let offset = 0;\n for (const spec of specs) {\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\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 byteBuffer =\n buffer.slice(offset, offset + size * quantizationSizeFactor);\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 if (float16Decode === undefined) {\n float16Decode = getFloat16Decoder();\n }\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 buffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n offset += NUM_BYTES_STRING_LENGTH;\n const bytes = new Uint8Array(buffer.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 const byteBuffer = buffer.slice(offset, offset + size * dtypeFactor);\n\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 out[name] = complex(realTensor, imageTensor);\n realTensor.dispose();\n imageTensor.dispose();\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * dtypeFactor;\n }\n if (dtype !== 'complex64') {\n out[name] = tensor(values, shape, dtype);\n }\n }\n return out;\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);\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 A number of array buffers to concatenate.\n * @returns Result of concatenating `buffers` in order.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]): ArrayBuffer {\n if (buffers.length === 1) {\n return buffers[0];\n }\n\n let totalByteLength = 0;\n buffers.forEach((buffer: ArrayBuffer) => {\n totalByteLength += buffer.byteLength;\n });\n\n const temp = new Uint8Array(totalByteLength);\n let offset = 0;\n buffers.forEach((buffer: ArrayBuffer) => {\n temp.set(new Uint8Array(buffer), offset);\n offset += buffer.byteLength;\n });\n return temp.buffer;\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.trainingConfig != null) {\n result.trainingConfig = artifacts.trainingConfig;\n }\n return result;\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 */ ArrayBuffer\n ]>): Promise<ModelArtifacts> {\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 const [weightSpecs, weightData] =\n await loadWeights(modelJSON.weightsManifest);\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\n return modelArtifacts;\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 modelArtifacts.weightData.byteLength,\n };\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';\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 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 const putInfoRequest =\n infoStore.put({modelPath: this.modelPath, modelArtifactsInfo});\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 const putModelRequest = modelStore.put({\n modelPath: this.modelPath,\n modelArtifacts,\n modelArtifactsInfo\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` (sublcass 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 {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 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(modelArtifacts.weightData));\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 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.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 = this.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(this.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 reigstered 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';\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 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\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';\n\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}\n\nif (env().get('IS_NODE')) {\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const cast = 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 {} as NamedTensorMap);\n}\n\nexport const clone = 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 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, encodeWeights, getModelArtifactsForJSON, getModelArtifactsInfoForJSON} from './io_utils';\nimport {fromMemory, withSaveHandler} from './passthrough';\nimport {getLoadHandlers, getSaveHandlers, registerLoadRouter, registerSaveRouter} from './router_registry';\nimport {IOHandler, LoadHandler, LoadOptions, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, OnProgressCallback, RequestDetails, SaveConfig, SaveHandler, SaveResult, TrainingConfig, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeights, weightsLoaderFactory} from './weights_loader';\n\nexport {copyModel, listModels, moveModel, removeModel} from './model_management';\nexport {\n browserFiles,\n browserHTTPRequest,\n concatenateArrayBuffers,\n decodeWeights,\n encodeWeights,\n fromMemory,\n getLoadHandlers,\n getModelArtifactsForJSON,\n getModelArtifactsInfoForJSON,\n getSaveHandlers,\n http,\n IOHandler,\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 WeightGroup,\n weightsLoaderFactory,\n WeightsManifestConfig,\n WeightsManifestEntry,\n withSaveHandler\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, concatenateArrayBuffers, getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelJSON, SaveResult, WeightsManifestConfig, WeightsManifestEntry} from './types';\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 const weightsURL = window.URL.createObjectURL(new Blob(\n [modelArtifacts.weightData], {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 */ ArrayBuffer\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, concatenateArrayBuffers(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(\n promises: Array<Promise<{}|void>>, 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<{}>) => {\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<{}|void>>): 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 {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\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 let groupBytes = 0;\n for (let i = 0; i < numBuffers; i++) {\n groupBytes += buffers[bufferIndexOffset + i].byteLength;\n }\n\n // Create a buffer for the whole group.\n const groupBuffer = new ArrayBuffer(groupBytes);\n const groupByteBuffer = new Uint8Array(groupBuffer);\n let groupBufferOffset = 0;\n for (let i = 0; i < numBuffers; i++) {\n const buffer = new Uint8Array(buffers[bufferIndexOffset + i]);\n groupByteBuffer.set(buffer, groupBufferOffset);\n groupBufferOffset += buffer.byteLength;\n }\n\n const weightsEntries = groupWeightsToFetch[i];\n weightsEntries.forEach(weightsEntry => {\n const byteBuffer = groupBuffer.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 {concatenateArrayBuffers, getModelArtifactsForJSON, getModelArtifactsInfoForJSON, getModelJSONForModelArtifacts} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, LoadOptions, ModelArtifacts, ModelJSON, OnProgressCallback, SaveResult, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeightsAsArrayBuffer} 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: Function;\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 onProgress: OnProgressCallback;\n\n constructor(path: string, loadOptions?: LoadOptions) {\n if (loadOptions == null) {\n loadOptions = {};\n }\n this.weightPathPrefix = loadOptions.weightPathPrefix;\n this.onProgress = loadOptions.onProgress;\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 }\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 init.body.append(\n 'model.weights.bin',\n new Blob([modelArtifacts.weightData], {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 /**\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 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 getModelArtifactsForJSON(\n modelJSON, (weightsManifest) => this.loadWeights(weightsManifest));\n }\n\n private async loadWeights(weightsManifest: WeightsManifestConfig):\n Promise<[WeightsManifestEntry[], ArrayBuffer]> {\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 weightSpecs = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\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\n const buffers = await loadWeightsAsArrayBuffer(fetchURLs, {\n requestInit: this.requestInit,\n fetchFunc: this.fetch,\n onProgress: this.onProgress\n });\n return [weightSpecs, concatenateArrayBuffers(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 requst,\n * this particular server reconsistutes 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, ModelArtifacts, SaveResult, TrainingConfig, WeightsManifestEntry} from './types';\n\nclass PassthroughLoader implements IOHandler {\n constructor(private readonly modelArtifacts?: ModelArtifacts) {}\n\n async load(): Promise<ModelArtifacts> {\n return this.modelArtifacts;\n }\n}\n\nclass PassthroughSaver implements IOHandler {\n constructor(\n private readonly saveHandler:\n (artifacts: ModelArtifacts) => Promise<SaveResult>) {}\n\n async save(modelArtifacts: ModelArtifacts) {\n return this.saveHandler(modelArtifacts);\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.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs.\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?: ArrayBuffer, trainingConfig?: TrainingConfig): IOHandler {\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 * `SaveResult`.\n */\nexport function withSaveHandler(\n saveHandler: (artifacts: ModelArtifacts) =>\n Promise<SaveResult>): IOHandler {\n return new PassthroughSaver(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/**\n * Exports under the tf.math.* namespace.\n */\n\nimport {confusionMatrix} from './ops/confusion_matrix';\n\nexport {confusionMatrix};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const matMul = 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 {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 {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 *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`.\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 *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(\n indices: Tensor|TensorLike, depth: number, onValue = 1,\n offValue = 0): 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 = {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 = 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 {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';\n\nimport {op} from './operation';\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 *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_<T extends Tensor>(x: T|TensorLike, perm?: number[]): 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 return ENGINE.runKernel(\n Transpose, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const transpose = 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 {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 = op({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 {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 {PixelData, TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\nimport {tensor3d} from './tensor3d';\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\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 * @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 (isVideo) {\n const HAVE_CURRENT_DATA_READY_STATE = 2;\n if (isVideo &&\n (pixels as HTMLVideoElement).readyState <\n HAVE_CURRENT_DATA_READY_STATE) {\n throw new Error(\n 'The video element has not loaded data yet. Please wait for ' +\n '`loadeddata` event on the <video> element.');\n }\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 {} as NamedTensorMap,\n attrs as {} 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 fromPixels2DContext = document.createElement('canvas').getContext('2d');\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\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 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 [height, width] = $img.shape.slice(0, 2);\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 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 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\nexport const fromPixels = 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 */\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 */\nimport {TensorInfo} from '../kernel_registry';\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 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 '../kernel_registry';\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 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 {TensorInfo} from '../kernel_registry';\nimport * as util from '../util';\n\nexport type SliceInfo = {\n nonStrided: boolean,\n $begin: number[],\n $end: number[],\n $strides: number[],\n size: number[],\n newShape: number[],\n outShape: 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\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 // make a copy because it may be modified further down.\n let $begin = begin.slice();\n let $end = end.slice();\n let $strides = strides;\n\n if (strides == null) {\n $strides = new Array($begin.length);\n }\n\n const ellipsisAxes = maskToAxes(ellipsisMask);\n if (ellipsisAxes.length > 1) {\n throw new Error('Multiple ellipses in slice is not allowed.');\n }\n\n if (ellipsisMask !== 0 && newAxisMask !== 0) {\n throw new Error(\n 'Using both ellipsisMask and newAxisMask is not yet supported.');\n }\n\n if (ellipsisMask !== 0 && shrinkAxisMask !== 0) {\n throw new Error(\n 'Using both ellipsisMask and shrinkAxisMask is not yet supported.');\n }\n\n const numInterpolatedAxes = xShape.length - $begin.length;\n\n // Expand the dims of x based on the newAxisMask.\n const expandAxes = maskToAxes(newAxisMask);\n const newShape = xShape.slice();\n expandAxes.forEach(axis => {\n $begin[axis] = 0;\n $end[axis] = 1;\n newShape.splice(axis, 0, 1);\n });\n\n const {\n begin: normalizedBegin,\n end: normalizedEnd,\n strides: normalizedStrides\n } =\n getNormalizedAxes(\n newShape, ellipsisAxes, numInterpolatedAxes, $begin, $end, $strides,\n beginMask, endMask, ellipsisMask);\n $begin = normalizedBegin;\n $end = normalizedEnd;\n $strides = normalizedStrides;\n\n const shrinkAxes = maskToAxes(shrinkAxisMask);\n // Adjust the ends based on the shrink mask.\n shrinkAxes.forEach(axis => {\n $end[axis] = $begin[axis] + 1;\n $strides[axis] = 1;\n });\n\n // Figure out the output shape.\n const size = computeOutShape($begin, $end, $strides);\n // Remove the axes based on shrinkMask.\n const outShape = size.filter((_, axis) => shrinkAxes.indexOf(axis) === -1);\n\n const nonStrided = $strides.every(v => v === 1);\n\n return {nonStrided, $begin, $end, $strides, size, newShape, outShape};\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 {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 * 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:\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 * ```\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 *\n * @doc {heading: 'Models', subheading: 'Serialization', ignoreCI: true}\n */\nexport function registerClass<T extends Serializable>(\n cls: SerializableConstructor<T>) {\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 SerializationMap.register(cls);\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 {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}\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}\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}\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 & Jasmine don't like comparing ArrayBuffers directly. Wrapping in\n // a Float32Array solves this issue.\n expect(new Float32Array(actual)).toEqual(new Float32Array(expected));\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", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.8.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 {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 \u2264 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 {} as NamedTensorMap);\n}\n\nexport const add = 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 {} as NamedTensorMap);\n}\n\nexport const floorDiv = 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, inputs as {} as NamedTensorMap, attrs) as T;\n}\n\nexport const div = 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 {} as NamedTensorMap);\n}\nexport const mul = 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 {} as NamedTensorMap);\n } else {\n const inputs: AbsInputs = {x: $x};\n return ENGINE.runKernel(Abs, inputs as {} as NamedTensorMap);\n }\n}\n\nexport const abs = 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 {} as NamedTensorMap);\n}\nexport const acos = 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 {} as NamedTensorMap);\n}\nexport const acosh = 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 {} as NamedTensorMap);\n}\n\nexport const addN = 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 an\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const all = 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 an\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\n// tslint:disable-next-line:variable-name\nexport const any = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const argMax = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const argMin = 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 {} as NamedTensorMap);\n}\nexport const asin = 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 {} as NamedTensorMap);\n}\nexport const asinh = 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 {} as NamedTensorMap);\n}\nexport const atan = 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 {} as NamedTensorMap);\n}\n\nexport const atan2 = 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 {} as NamedTensorMap);\n}\nexport const atanh = 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\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], fieldSize: number,\n outChannels: number, stride: number, zeroPad?: number,\n roundingMode?: 'floor'|'round'|'ceil'): [number, number, number, number] {\n if (zeroPad == null) {\n zeroPad = computeDefaultPad(inShape, fieldSize, stride);\n }\n const inputDepth = inShape[0];\n const inputRows = inShape[1];\n const inputCols = inShape[2];\n\n const outputDepths =\n round((inputDepth - fieldSize + 2 * zeroPad) / stride + 1, roundingMode);\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 [outputDepths, outputRows, outputCols, outChannels];\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 (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], filterDepth, 1, strideDepth, pad,\n 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 if (pad === 'valid') {\n padInfo = {\n top: 0,\n bottom: 0,\n left: 0,\n right: 0,\n front: 0,\n back: 0,\n type: 'VALID'\n };\n outDepth = Math.ceil((inDepth - filterDepth + 1) / strideDepth);\n outHeight = Math.ceil((inHeight - filterHeight + 1) / strideHeight);\n outWidth = Math.ceil((inWidth - filterWidth + 1) / strideWidth);\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\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 * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\nexport const reshape = 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 */\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\n if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in avgPool: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n const inputs: AvgPoolInputs = {x: x4D};\n\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 {} as NamedTensorMap,\n attrs as {} 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 = 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 {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\n if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in avgPool3d: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n const inputs: AvgPool3DInputs = {x: x5D};\n\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 {} as NamedTensorMap,\n attrs as {} 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 = 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 concate 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 {} as NamedTensorMap, attr as {} as NamedAttrMap);\n}\n\nexport const concat = op({concat_});\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');\n\n const inputs: SigmoidInputs = {x: $x};\n\n return ENGINE.runKernel(Sigmoid, inputs as {} as NamedTensorMap);\n}\nexport const sigmoid = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const slice = 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');\n\n const inputs: TanhInputs = {x: $x};\n\n return ENGINE.runKernel(Tanh, inputs as {} as NamedTensorMap);\n}\nexport const tanh = 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 = 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const batchToSpaceND = 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 an `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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor<R>;\n\n return reshape(res, $x.shape);\n}\n\nexport const batchNorm = 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 = 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 = 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 = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const bincount = op({bincount_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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';\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 is 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 if (shape.some(d => !(d > 0) || d % 1 !== 0)) {\n throw new Error(`broadcastTo(): Invalid broadcast shape [${shape}].`);\n }\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 {} as NamedTensorMap, attrs as unknown as NamedAttrMap);\n}\n\nexport const broadcastTo = 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');\n\n const inputs: CeilInputs = {x: $x};\n return ENGINE.runKernel(Ceil, inputs as {} as NamedTensorMap);\n}\nexport const ceil = op({ceil_});\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';\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 const inputs: ClipByValueInputs = {x: $x};\n const attrs: ClipByValueAttrs = {clipValueMin, clipValueMax};\n\n return ENGINE.runKernel(\n ClipByValue, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const clipByValue = 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 = 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 = 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 = 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 = 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');\n const $filter = convertToTensor(filter, 'filter', 'conv2d');\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 if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in conv2d: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\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\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 {} as NamedTensorMap,\n attrs as {} 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 = 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 if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in conv1d: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\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 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 = 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 if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in conv2dDerInput: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n const inputs: Conv2DBackpropInputInputs = {dy: dy4D, filter};\n\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 {} as NamedTensorMap,\n attrs as {} 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 = 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 = 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} 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\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 {} as NamedTensorMap,\n attrs as {} 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 = 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 {} as NamedTensorMap,\n attrs as {} 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 = 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 = 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.\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');\n\n const inputs: CosInputs = {x: $x};\n\n return ENGINE.runKernel(Cos, inputs as {} as NamedTensorMap);\n}\nexport const cos = 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.\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');\n const inputs: CoshInputs = {x: $x};\n\n return ENGINE.runKernel(Cosh, inputs as {} as NamedTensorMap);\n}\nexport const cosh = op({cosh_});\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const cumsum = 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const denseBincount = 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') 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 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const depthToSpace = 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 {ExplicitPadding} 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|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');\n const $filter = convertToTensor(filter, 'filter', 'depthwiseConv2d');\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 util.assert(\n x4D.shape[3] === $filter.shape[2],\n () => `Error in depthwiseConv2d: number of input channels ` +\n `(${x4D.shape[3]}) must match the inChannels dimension in ` +\n `filter ${$filter.shape[2]}.`);\n\n if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in depthwiseConv2d: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\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 {} as NamedTensorMap,\n attrs as {} 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 = 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 a 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.tensor1d([1, 2, 3, 4, 5, 6, 6, 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 {} as NamedTensorMap);\n}\n\nexport const diag = 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, inChannels]`. 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 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 {} as NamedTensorMap,\n attrs as {} 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 = 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 result: number[] = [];\n const l = Math.max(shapeA.length, shapeB.length);\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.unshift(b);\n } else if (b === 1) {\n result.unshift(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.unshift(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 {} as NamedTensorMap);\n}\n\nexport const equal = 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 {} as NamedTensorMap);\n}\n\nexport const where = 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 {} as NamedTensorMap);\n}\nexport const zerosLike = 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 = 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 = 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 suppoted.\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const einsum = 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 ? e ^ x - 1 : 0`.\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');\n\n const inputs: EluInputs = {x: $x};\n\n return ENGINE.runKernel(Elu, inputs as {} as NamedTensorMap);\n}\n\nexport const elu = op({elu_});\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 gause 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 {} as NamedTensorMap);\n}\nexport const erf = op({erf_});\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 {} as NamedTensorMap);\n}\nexport const exp = 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 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const expandDims = 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 {} as NamedTensorMap);\n}\nexport const expm1 = 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 a.tile([2])\n * ```\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.tile([1, 2]).print(); // or a.tile([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 = 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 = op({eye_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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';\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 * 'float'.\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 const attrs: FillAttrs = {shape, value, dtype};\n\n return ENGINE.runKernel(Fill, {}, attrs as {} 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 {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');\n\n const inputs: FloorInputs = {x: $x};\n return ENGINE.runKernel(Floor, inputs as {} as NamedTensorMap);\n}\nexport const floor = 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 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const gather = 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 {} as NamedTensorMap);\n}\n\nexport const greater = 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 {} as NamedTensorMap);\n}\n\nexport const greaterEqual = 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 {} as NamedTensorMap);\n}\n\nexport const imag = 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 {} as NamedTensorMap);\n}\nexport const isFinite = 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 {} as NamedTensorMap);\n}\nexport const isInf = 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 * RReturns 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 {} as NamedTensorMap);\n}\nexport const isNaN = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const leakyRelu = 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 {} as NamedTensorMap);\n}\n\nexport const less = 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 {} as NamedTensorMap);\n}\n\nexport const lessEqual = 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 {} 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 {} as NamedTensorMap,\n attrs as {} 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 = 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');\n\n const inputs: LogInputs = {x: $x};\n return ENGINE.runKernel(Log, inputs as {} as NamedTensorMap);\n}\nexport const log = 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 {} as NamedTensorMap);\n}\nexport const log1p = 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 passsed 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 tensor.\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 {} as NamedTensorMap);\n}\nexport const neg = 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 {} as NamedTensorMap);\n}\nexport const softplus = 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 = 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 */\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 an\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const max = op({max_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 {} as NamedTensorMap);\n}\n\nexport const sub = op({sub_});\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const sum = op({sum_});\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 {} as NamedTensorMap,\n // attrs as {} as NamedAttrMap);\n}\n\nexport const logSoftmax = op({logSoftmax_});\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 \u00A0 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 {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 = 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 {} as NamedTensorMap);\n}\n\nexport const logicalAnd = 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 {} as NamedTensorMap);\n}\n\nexport const logicalNot = 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 {} as NamedTensorMap);\n}\nexport const logicalOr = 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 = op({logicalXor_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in maxPool: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n const inputs: MaxPoolInputs = {x: x4D};\n\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 {} as NamedTensorMap,\n attrs as {} 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 = 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 {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 if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in maxPool3d: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n const inputs: MaxPool3DInputs = {x: x5D};\n\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 {} as NamedTensorMap,\n attrs as {} 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 = 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor[];\n\n return {result: result[0], indexes: result[1]};\n}\n\nexport const maxPoolWithArgmax = 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 {} as NamedTensorMap);\n}\n\nexport const maximum = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const mean = 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 {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 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';\n\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 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 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n}\n\nexport const min = 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 */\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 {} as NamedTensorMap);\n}\n\nexport const minimum = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const mirrorPad = 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 {} as NamedTensorMap);\n}\n\nexport const mod = op({mod_});\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 = op({square_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 = 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 = 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 {} as NamedTensorMap,\n attrs as {} 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 = 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 {} as NamedTensorMap);\n}\n\nexport const notEqual = op({notEqual_});\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 {} as NamedTensorMap);\n}\n\nexport const onesLike = 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 = 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 = 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 = 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 = 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 = 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 = 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const spaceToBatchND = 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 *\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 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 () => maxPool(convertedX, windowShape, strides, convertedPad);\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 = 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 */\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 {} as NamedTensorMap);\n}\n\nexport const pow = op({pow_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {} as NamedTensorMap);\n}\n\nexport const prelu = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const prod = op({prod_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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';\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 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 = op({rand_});\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';\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 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 = 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';\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 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 = op({randomNormal_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 *\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 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 = op({randomUniform_});\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 is half-open interval meaning it includes start, but\n * excludes stop. Decrementing ranges and negative step values are also\n * supported.sv\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 */, attrs as {} 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 {} as NamedTensorMap);\n}\n\nexport const real = 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 {} as NamedTensorMap);\n}\nexport const reciprocal = 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 {} as NamedTensorMap);\n}\n\nexport const relu = 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 {} as NamedTensorMap);\n}\n\nexport const relu6 = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const reverse = 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 = 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 = 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 = 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 = 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 {} as NamedTensorMap);\n}\n\nexport const round = 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');\n\n const inputs: RsqrtInputs = {x: $x};\n\n return ENGINE.runKernel(Rsqrt, inputs as {} as NamedTensorMap);\n}\nexport const rsqrt = op({rsqrt_});\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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) : 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 {} as NamedTensorMap);\n}\n\nexport const selu = 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 = 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 {} as NamedTensorMap);\n}\nexport const sign = 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');\n\n const inputs: SinInputs = {x: $x};\n\n return ENGINE.runKernel(Sin, inputs as {} as NamedTensorMap);\n}\nexport const sin = 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 {} as NamedTensorMap);\n}\nexport const sinh = 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 = 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 = 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 = 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 = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const softmax = 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 {} as NamedTensorMap);\n}\n\nexport const fft = 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 {} as NamedTensorMap);\n}\n\nexport const ifft = 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 = 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 {} as NamedTensorMap,\n attr as {} as NamedAttrMap) as {} as T[];\n}\n\nexport const split = 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 = op({rfft_});\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');\n\n const inputs: SqrtInputs = {x: $x};\n\n return ENGINE.runKernel(Sqrt, inputs as {} as NamedTensorMap);\n}\nexport const sqrt = op({sqrt_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 = 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');\n return reshape($x, squeezeShape($x.shape, axis).newShape) as T;\n}\n\nexport const squeeze = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const stack = 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 * x`\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.\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\nexport const step = 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const stridedSlice = 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');\n\n const inputs: TanInputs = {x: $x};\n\n return ENGINE.runKernel(Tan, inputs as {} as NamedTensorMap);\n}\nexport const tan = 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 {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 */\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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n\n return {values, indices} as {values: T, indices: T};\n}\n\nexport const topk = 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';\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 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 = 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as [T, Tensor1D];\n return {values, indices};\n}\n\nexport const unique = 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const unsortedSegmentSum = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const unstack = op({unstack_});\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 {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 a 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 have 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 = op({norm_});\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 = 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';\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 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor<R>;\n}\n\nexport const scatterND = 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';\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 const $sparseIndices =\n convertToTensor(sparseIndices, 'sparseIndices', 'sparseToDense', 'int32');\n const $sparseValues =\n convertToTensor(sparseValues, 'sparseValues', 'sparseToDense');\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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n}\n\nexport const sparseToDense = 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 an 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 {} as NamedTensorMap);\n}\n\nexport const gatherND = 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 = 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 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in conv2dDerFilter: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor4D;\n}\n\nexport const conv2DBackpropFilter = 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 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');\n const $filter = convertToTensor(filter, 'filter', 'conv2d');\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 if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in fused conv2d: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n util.assert(\n x4D.shape[3] === $filter.shape[2],\n () => `Error in conv2d: depth of input (${x4D.shape[3]}) 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 dataFormat === 'NHWC',\n () => `Error in conv2d: got dataFormat of ${\n dataFormat} but only NHWC is currently supported.`);\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 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 conv2d');\n }\n\n const grad = (dy: Tensor4D, saved: Tensor[]) => {\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 {} as NamedTensorMap,\n attrs as {} 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 {} as NamedTensorMap,\n attrs as {} 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 = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap) as\n 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, inputs as {} as NamedTensorMap,\n attrs as {} 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';\n\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');\n const $filter = convertToTensor(filter, 'filter', 'depthwiseConv2d');\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\n if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in fused depthwiseConv2d: pad must be an integer when ` +\n `using dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\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 {} as NamedTensorMap,\n attrs as {} 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 {} as NamedTensorMap,\n attrs as {} 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 = 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_<T extends Tensor>({\n a,\n b,\n transposeA = false,\n transposeB = false,\n bias,\n activation = 'linear',\n preluActivationWeights,\n leakyreluAlpha,\n}: {\n a: T|TensorLike,\n b: T|TensorLike,\n transposeA?: boolean,\n transposeB?: boolean,\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 = unfusedMatMul(a, b, transposeA, transposeB);\n if (bias != null) {\n result = add(result, bias);\n }\n\n return applyActivation(\n result, activation, preluActivationWeights, leakyreluAlpha) as\n T;\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 $a.rank >= 2 && $b.rank >= 2 && $a.rank === $b.rank,\n () => `Error in fused matMul: inputs must have the same rank of at ` +\n `least 2, got ranks ${$a.rank} and ${$b.rank}.`);\n\n util.assert(\n util.arraysEqual(outerDimsA, outerDimsB),\n () => `Error in fused matMul: outer dimensions (${outerDimsA}) and (` +\n `${outerDimsB}) of Tensors with shapes ${$a.shape} and ` +\n `${$b.shape} must match.`);\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 outShape = $a.shape.slice(0, -2).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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n save([a3D, b3D, res]);\n\n return {value: reshape(res, outShape), gradFunc: grad};\n });\n return customOp(a3D, b3D) as T;\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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as T;\n\n save([a3D, b3D, res, $bias]);\n\n return {value: reshape(res, outShape), gradFunc: grad};\n });\n\n return customOpWithBias(a3D, b3D, $bias) as T;\n }\n }\n\n export const matMul = 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 {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 = 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 = 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 An 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 = 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 = 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n return res as Tensor4D;\n}\n\nexport const cropAndResize = 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 {} as NamedTensorMap, {});\n return res as Tensor4D;\n}\n\nexport const flipLeftRight = op({flipLeftRight_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap);\n return res as Tensor4D;\n}\n\nexport const rotateWithOffset = 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';\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 * @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 = convertToTensor(boxes, 'boxes', 'nonMaxSuppression');\n const $scores = convertToTensor(scores, 'scores', 'nonMaxSuppression');\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 = 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 boxe 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 (c.f.\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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor[];\n\n return {selectedIndices: result[0], selectedScores: result[1]};\n}\n\nexport const nonMaxSuppressionWithScore = 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 (c.f.\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 Defalts 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 {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor[];\n\n return {selectedIndices: result[0], validOutputs: result[1]};\n}\n\nexport const nonMaxSuppressionPadded = 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 Defalts 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 {} as NamedTensorMap,\n attrs as {} 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 = 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 assumes pixels are of\n * half the actual dimensions, and yields 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 {} as NamedTensorMap,\n attrs as {} 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 = 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 = 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 {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const transform = 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 {Tensor} from '../../tensor';\nimport {convertToTensor} from '../../tensor_util_env';\nimport {TensorLike} from '../../types';\nimport {assert} from '../../util';\n\nimport {greaterEqual} from '../greater_equal';\nimport {lessEqual} from '../less_equal';\nimport {logicalAnd} from '../logical_and';\nimport {op} from '../operation';\nimport {range} from '../range';\nimport {reshape} from '../reshape';\nimport {scalar} from '../scalar';\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, numUpper: number): T {\n assert(\n numLower % 1 === 0,\n () => `bandPart(): numLower must be an integer, got ${numLower}.`);\n assert(\n numUpper % 1 === 0,\n () => `bandPart(): numUpper must be an integer, got ${numUpper}.`);\n\n const $a = convertToTensor(a, 'a', 'bandPart');\n\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 if (!(numLower <= M)) {\n throw new Error(\n `bandPart(): numLower (${numLower})` +\n ` must not be greater than the number of rows (${M}).`);\n }\n if (!(numUpper <= N)) {\n throw new Error(\n `bandPart(): numUpper (${numUpper})` +\n ` must not be greater than the number of columns (${N}).`);\n }\n\n if (numLower < 0) {\n numLower = M;\n }\n if (numUpper < 0) {\n numUpper = N;\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 = logicalAnd(\n lessEqual(ij, scalar(+numLower, 'int32')),\n greaterEqual(ij, scalar(-numUpper, 'int32')));\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 = 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('Othogonalized:');\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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = convertToTensor(indices, 'indices', 'sparseFillEmptyRows');\n const $values = convertToTensor(values, 'values', 'sparseFillEmptyRows');\n const $denseShape =\n convertToTensor(denseShape, 'denseShape', 'sparseFillEmptyRows');\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 = 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');\n const $inputShape =\n convertToTensor(inputShape, 'inputShape', 'sparseReshape');\n const $newShape = convertToTensor(newShape, 'newShape', 'sparseReshape');\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 = 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 = convertToTensor(indices, 'indices', 'sparseSegmentMean');\n const $segmentIds =\n convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentMean');\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 = 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 segment.\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 = convertToTensor(indices, 'indices', 'sparseSegmentSum');\n const $segmentIds =\n convertToTensor(segmentIds, 'segmentIds', 'sparseSegmentSum');\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 = 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 = 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 = 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 = op({stringToHashBucketFast_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {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 {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 {equal} from './equal';\nexport {erf} from './erf';\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 {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 {rand} from './rand';\nexport {randomGamma} from './random_gamma';\nexport {randomNormal} from './random_normal';\nexport {randomUniform} from './random_uniform';\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 {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 {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 './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 {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 resizeNearestNeighbor,\n resizeBilinear,\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';\n// tslint:disable-next-line:variable-name\nconst string = {\n stringNGrams,\n stringSplit,\n stringToHashBucketFast\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 {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, registerClass, 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 className = 'Adadelta'; // Name matters for Python compatibility.\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 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 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 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 fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate'], config['rho'], config['epsilon']);\n }\n}\nregisterClass(AdadeltaOptimizer);\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, registerClass, 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 className = 'Adagrad'; // Note: Name matters for Python compatibility.\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 dispose(): void {\n if (this.accumulatedGrads != null) {\n dispose(this.accumulatedGrads.map(v => v.variable));\n }\n }\n\n 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 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 fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate'], config['initialAccumulatorValue']);\n }\n}\nregisterClass(AdagradOptimizer);\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, registerClass, 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 className = 'Adam'; // Note: Name matters for Python compatibility.\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 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 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 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 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}\nregisterClass(AdamOptimizer);\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, registerClass, 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 className = 'Adamax'; // Note: Name matters for Python compatbility.\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 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 async getWeights(): Promise<NamedTensor[]> {\n throw new Error('getWeights() is not implemented for Adamax yet.');\n }\n\n 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 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}\nregisterClass(AdamaxOptimizer);\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, registerClass, 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 className = 'SGD'; // Note: Name matters for Python compatibility.\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 dispose() {\n this.c.dispose();\n }\n\n async getWeights(): Promise<NamedTensor[]> {\n return [await this.saveIterations()];\n }\n\n 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 fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(config['learningRate']);\n }\n}\nregisterClass(SGDOptimizer);\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, registerClass, 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 static className = 'Momentum'; // Name matters for Python compatibility.\n private m: Scalar;\n private accumulations: OptimizerVariable[] = [];\n\n constructor(\n protected learningRate: number, private momentum: number,\n private useNesterov = false) {\n super(learningRate);\n this.m = scalar(this.momentum);\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.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 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 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 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 getConfig(): ConfigDict {\n return {\n 'learningRate': this.learningRate,\n 'momentum': this.momentum,\n 'useNesterov': this.useNesterov\n };\n }\n\n /** @nocollapse */\n static fromConfig<T extends Serializable>(\n cls: SerializableConstructor<T>, config: ConfigDict): T {\n return new cls(\n config['learningRate'], config['momentum'], config['useNesterov']);\n }\n}\nregisterClass(MomentumOptimizer);\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, registerClass, 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 className = 'RMSProp'; // Note: Name matters for Python compatibility.\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 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 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 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 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}\nregisterClass(RMSPropOptimizer);\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\n// So typings can propagate.\nimport {AdadeltaOptimizer} from './optimizers/adadelta_optimizer';\nimport {AdagradOptimizer} from './optimizers/adagrad_optimizer';\nimport {AdamOptimizer} from './optimizers/adam_optimizer';\nimport {AdamaxOptimizer} from './optimizers/adamax_optimizer';\nimport {MomentumOptimizer} from './optimizers/momentum_optimizer';\nimport {OptimizerConstructors} from './optimizers/optimizer_constructors';\nimport {RMSPropOptimizer} from './optimizers/rmsprop_optimizer';\nimport {SGDOptimizer} from './optimizers/sgd_optimizer';\n\n// tslint:disable-next-line:no-unused-expression\n[MomentumOptimizer, SGDOptimizer, AdadeltaOptimizer, AdagradOptimizer,\n RMSPropOptimizer, AdamaxOptimizer, AdamOptimizer];\n\nexport const train = {\n sgd: OptimizerConstructors.sgd,\n momentum: OptimizerConstructors.momentum,\n adadelta: OptimizerConstructors.adadelta,\n adagrad: OptimizerConstructors.adagrad,\n rmsprop: OptimizerConstructors.rmsprop,\n adamax: OptimizerConstructors.adamax,\n adam: OptimizerConstructors.adam\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\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 resolve 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 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/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';\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 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 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 {env} from './environment';\n\nexport function warn(...msg: Array<{}>): void {\n if (!env().getBool('IS_TEST')) {\n console.warn(...msg);\n }\n}\n\nexport function log(...msg: Array<{}>): void {\n if (!env().getBool('IS_TEST')) {\n console.log(...msg);\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 {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 comple 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 consituent 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 '../kernel_registry';\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 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 '../kernel_registry';\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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// base.ts is tfjs-core without auto registration of things like flags,\n// gradients, chained ops or the opHandler. See base_side_effects.ts for parts\n// tfjs core that are required side effects.\n\n/**\n * @fileoverview\n * @suppress {partialAlias} Optimization disabled due to passing the module\n * object into a function below:\n *\n * import * as ops from './ops/ops';\n * setOpHandler(ops);\n */\n\n// Serialization.\nimport * as io from './io/io';\nimport * as math from './math';\nimport * as browser from './ops/browser';\nimport * as gather_util from './ops/gather_nd_util';\nimport * as scatter_util from './ops/scatter_nd_util';\nimport * as slice_util from './ops/slice_util';\nimport * as serialization from './serialization';\nimport * as tensor_util from './tensor_util';\nimport * as test_util from './test_util';\nimport * as util from './util';\nimport {version} from './version';\n\nexport {InferenceModel, MetaGraph, MetaGraphInfo, ModelPredictConfig, ModelTensorInfo, SavedModelTensorInfo, SignatureDef, SignatureDefEntry, SignatureDefInfo} from './model_types';\n// Optimizers.\nexport {AdadeltaOptimizer} from './optimizers/adadelta_optimizer';\nexport {AdagradOptimizer} from './optimizers/adagrad_optimizer';\nexport {AdamOptimizer} from './optimizers/adam_optimizer';\nexport {AdamaxOptimizer} from './optimizers/adamax_optimizer';\nexport {MomentumOptimizer} from './optimizers/momentum_optimizer';\nexport {Optimizer} from './optimizers/optimizer';\nexport {RMSPropOptimizer} from './optimizers/rmsprop_optimizer';\nexport {SGDOptimizer} from './optimizers/sgd_optimizer';\nexport {Scalar, Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D, Tensor5D, TensorBuffer, Variable} from './tensor';\nexport {GradSaveFunc, NamedTensorMap, TensorContainer, TensorContainerArray, TensorContainerObject} from './tensor_types';\nexport {BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, PixelData, Rank, RecursiveArray, ScalarLike, ShapeMap, sumOutType, TensorLike, TypedArray, upcastType} from './types';\n\nexport * from './ops/ops';\nexport {Reduction} from './ops/loss_ops_utils';\n\nexport * from './train';\nexport * from './globals';\nexport * from './kernel_registry';\nexport {customGrad, grad, grads, valueAndGrad, valueAndGrads, variableGrads} from './gradients';\n\nexport {TimingInfo, MemoryInfo, ForwardFunc} from './engine';\nexport {Environment, env, ENV} from './environment';\nexport {Platform} from './platforms/platform';\n\nexport {version as version_core};\n\n// Top-level method exports.\nexport {nextFrame} from './browser_util';\n\n// Second level exports.\nimport * as backend_util from './backends/backend_util';\nimport * as device_util from './device_util';\nexport {\n browser,\n io,\n math,\n serialization,\n test_util,\n util,\n backend_util,\n tensor_util,\n slice_util,\n gather_util,\n scatter_util,\n device_util\n};\n\nimport * as kernel_impls from './backends/kernel_impls';\nexport {kernel_impls};\n// Backend specific.\nexport {KernelBackend, BackendTimingInfo, DataMover, DataStorage} from './backends/backend';\n\n// Export all kernel names / info.\nexport * from './kernel_names';\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// All exports from this package should be in base.\nexport * from './base';\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Abs} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {mul} from '../ops/mul';\nimport {step} from '../ops/step';\nimport {Tensor} from '../tensor';\n\nexport const absGradConfig: GradConfig = {\n kernelName: Abs,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => mul(dy, step(cast(x, 'float32'), -1))};\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 {Acos} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {neg} from '../ops/neg';\nimport {scalar} from '../ops/scalar';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {Tensor} from '../tensor';\n\nexport const acosGradConfig: GradConfig = {\n kernelName: Acos,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {\n x: () => {\n const a = square(cast(x, 'float32'));\n const b = sqrt(sub(scalar(1), a));\n return neg(div(dy, b));\n }\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 */\n\nimport {Acosh} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {Tensor} from '../tensor';\n\nexport const acoshGradConfig: GradConfig = {\n kernelName: Acosh,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {\n x: () => {\n const a = sqrt(sub(square(cast(x, 'float32')), 1));\n return div(dy, a);\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 {Add} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport * as broadcast_util from '../ops/broadcast_util';\nimport {reshape} from '../ops/reshape';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const addGradConfig: GradConfig = {\n kernelName: Add,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const outShape =\n broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);\n\n const derA = () => {\n let res = dy;\n const reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, a.shape);\n };\n const derB = () => {\n let res = dy;\n const reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, b.shape);\n };\n\n return {a: derA, b: derB};\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 {AddN} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {Tensor} from '../tensor';\n\nexport const addNGradConfig: GradConfig = {\n kernelName: AddN,\n saveAllInputs: true,\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const ders: {[key: string]: () => Tensor} = {};\n saved.forEach((_, i) => {\n ders[i] = () => dy.clone();\n });\n return ders;\n }\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 {ArgMax} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const argMaxGradConfig: GradConfig = {\n kernelName: ArgMax,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => zerosLike(x)};\n }\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 {ArgMin} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const argMinGradConfig: GradConfig = {\n kernelName: ArgMin,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => zerosLike(x)};\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 {Asin} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {scalar} from '../ops/scalar';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {Tensor} from '../tensor';\n\nexport const asinGradConfig: GradConfig = {\n kernelName: Asin,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => div(dy, sqrt(sub(scalar(1), square(cast(x, 'float32')))))};\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 {Asinh} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {add} from '../ops/add';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {scalar} from '../ops/scalar';\nimport {sqrt} from '../ops/sqrt';\nimport {square} from '../ops/square';\nimport {Tensor} from '../tensor';\n\nexport const asinhGradConfig: GradConfig = {\n kernelName: Asinh,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {\n x: () => {\n const a = sqrt(add(scalar(1), square(cast(x, 'float32'))));\n return div(dy, a);\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 */\n\nimport {Atan2} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {add} from '../ops/add';\nimport {assertAndGetBroadcastShape, getReductionAxes} from '../ops/broadcast_util';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {neg} from '../ops/neg';\nimport {reshape} from '../ops/reshape';\nimport {square} from '../ops/square';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const atan2GradConfig: GradConfig = {\n kernelName: Atan2,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const outShape = assertAndGetBroadcastShape(a.shape, b.shape);\n\n const derA = () => {\n const d = add(square(a), square(b));\n let res = mul(dy, div(b, d));\n const reduceAxes = getReductionAxes(a.shape, outShape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, a.shape);\n };\n const derB = () => {\n const d = add(square(a), square(b));\n let res = neg(mul(dy, div(a, d)));\n const reduceAxes = getReductionAxes(b.shape, outShape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, b.shape);\n };\n return {a: derA, b: derB};\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 {Atan} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {add} from '../ops/add';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {square} from '../ops/square';\nimport {Tensor} from '../tensor';\n\nexport const atanGradConfig: GradConfig = {\n kernelName: Atan,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {x: () => div(dy, add(square(cast(x, 'float32')), 1))};\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 {Atanh} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {scalar} from '../ops/scalar';\nimport {Tensor} from '../tensor';\n\nexport const atanhGradConfig: GradConfig = {\n kernelName: Atanh,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {x: () => div(dy, sub(scalar(1), square(cast(x, 'float32'))))};\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 {AvgPool3DGrad, AvgPool3DGradAttrs, AvgPool3DGradInputs} 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 {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the backprop of a 3d avg pool.\n *\n * @param dy The dy error, of rank 5 of shape\n * [batchSize, depth, height, width, channels].\n * assumed.\n * @param input The original input image, of rank 5 or rank4 of shape\n * [batchSize, depth, height, width, channels].\n * @param filterSize The filter size:\n * `[filterDepth, filterHeight, filterWidth]`.\n * `filterSize` is a single number,\n * then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n * `[strideDepth, strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == 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 dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction avgPool3dGrad_<T extends Tensor4D|Tensor5D>(\n dy: T|TensorLike, input: T|TensorLike,\n filterSize: [number, number, number]|number,\n strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $dy = convertToTensor(dy, 'dy', 'avgPool3dGrad');\n const $input = convertToTensor(input, 'input', 'avgPool3dGrad');\n\n let dy5D = $dy as Tensor5D;\n let input5D = $input as Tensor5D;\n let reshapedTo5D = false;\n\n if ($input.rank === 4) {\n reshapedTo5D = true;\n dy5D = reshape(\n $dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);\n input5D = reshape($input, [\n 1, $input.shape[0], $input.shape[1], $input.shape[2], $input.shape[3]\n ]);\n }\n\n util.assert(\n dy5D.rank === 5,\n () => `Error in avgPool3dGrad: dy must be rank 5 but got rank ` +\n `${dy5D.rank}.`);\n util.assert(\n input5D.rank === 5,\n () => `Error in avgPool3dGrad: input must be rank 5 but got rank ` +\n `${input5D.rank}.`);\n\n if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in avgPool3dGrad: pad must be an integer when ` +\n `using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n const inputs: AvgPool3DGradInputs = {dy: dy5D, input: input5D};\n\n const attrs: AvgPool3DGradAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n AvgPool3DGrad, inputs as {} as NamedTensorMap,\n attrs as {} 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 avgPool3dGrad = op({avgPool3dGrad_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AvgPool3D, AvgPool3DAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {avgPool3dGrad} from '../ops/avg_pool_3d_grad';\nimport {Tensor, Tensor5D} from '../tensor';\n\nexport const avgPool3DGradConfig: GradConfig = {\n kernelName: AvgPool3D,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved as [Tensor5D];\n const {filterSize, strides, pad, dimRoundingMode} =\n attrs as {} as AvgPool3DAttrs;\n\n return {\n x: () => avgPool3dGrad(\n dy as Tensor5D, x, filterSize, strides, pad, dimRoundingMode)\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 {AvgPoolGrad, AvgPoolGradAttrs, AvgPoolGradInputs} 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 {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the backprop of an 2D avg pool.\n *\n * @param dy The dy error, of rank 4 or rank 3 of shape\n * [batchSize, height, width, channels]. If rank 3, batch of 1 is\n * assumed.\n * @param input The input image, of rank 4 or rank 3 of shape\n * [batchSize, height, width, channels]. If rank 3, batch of 1 is\n * 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 used in the forward prop of the op.\n * 'same', 'valid', 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 */\nfunction avgPoolGrad_<T extends Tensor3D|Tensor4D>(\n dy: T|TensorLike, input: T|TensorLike, filterSize: [number, number]|number,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding): T {\n const $dy = convertToTensor(dy, 'dy', 'avgPoolGrad');\n const $input = convertToTensor(input, 'input', 'avgPoolGrad');\n\n util.assert(\n $input.rank === $dy.rank,\n () => `Rank of input (${$input.rank}) does not match rank of dy (${\n $dy.rank})`);\n\n let input4D = $input as Tensor4D;\n let dy4D = $dy as Tensor4D;\n let reshapedTo4D = false;\n\n if ($input.rank === 3) {\n reshapedTo4D = true;\n input4D =\n reshape($input, [1, $input.shape[0], $input.shape[1], $input.shape[2]]);\n dy4D = reshape($dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2]]);\n }\n\n util.assert(\n dy4D.rank === 4,\n () => `Error in avgPoolGrad: dy must be rank 4 but got rank ` +\n `${dy4D.rank}.`);\n util.assert(\n input4D.rank === 4,\n () => `Error in avgPoolGrad: input must be rank 4 but got rank ` +\n `${input4D.rank}.`);\n\n const inputs: AvgPoolGradInputs = {dy: dy4D, input: input4D};\n\n const attrs: AvgPoolGradAttrs = {filterSize, strides, pad};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n AvgPoolGrad, inputs as {} as NamedTensorMap,\n attrs as {} 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 avgPoolGrad = op({avgPoolGrad_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {AvgPool, AvgPoolAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {avgPoolGrad} from '../ops/avg_pool_grad';\nimport {Tensor, Tensor4D} from '../tensor';\n\nexport const avgPoolGradConfig: GradConfig = {\n kernelName: AvgPool,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved as [Tensor4D];\n const {filterSize, strides, pad} = attrs as {} as AvgPoolAttrs;\n return {x: () => avgPoolGrad(dy as Tensor4D, x, filterSize, strides, pad)};\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 {BatchMatMul, BatchMatMulAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {matMul} from '../ops/mat_mul';\nimport {Tensor} from '../tensor';\n\nexport const batchMatMulGradConfig: GradConfig = {\n kernelName: BatchMatMul,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [a, b] = saved;\n\n const {transposeA, transposeB} = attrs as {} as BatchMatMulAttrs;\n\n if (!transposeA && !transposeB) {\n return {\n a: () => matMul(dy, b, false, true),\n b: () => matMul(a, dy, true, false)\n };\n } else if (!transposeA && transposeB) {\n return {\n a: () => matMul(dy, b, false, false),\n b: () => matMul(dy, a, true, false)\n };\n } else if (transposeA && !transposeB) {\n return {\n a: () => matMul(b, dy, false, true),\n b: () => matMul(a, dy, false, false)\n };\n } else {\n return {\n a: () => matMul(b, dy, true, true),\n b: () => matMul(dy, a, true, true)\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 */\n\nimport {BatchToSpaceND, BatchToSpaceNDAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {spaceToBatchND} from '../ops/space_to_batch_nd';\nimport {Tensor} from '../tensor';\n\nexport const batchToSpaceNDGradConfig: GradConfig = {\n kernelName: BatchToSpaceND,\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const {blockShape, crops} = attrs as {} as BatchToSpaceNDAttrs;\n return {x: () => spaceToBatchND(dy, blockShape, crops)};\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 {BroadcastTo, BroadCastToAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const broadcastToGradConfig: GradConfig = {\n kernelName: BroadcastTo,\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const broadCastToAttrs: BroadCastToAttrs =\n attrs as unknown as BroadCastToAttrs;\n\n const inputShape = broadCastToAttrs.inputShape;\n const outputShape = broadCastToAttrs.shape;\n\n const reps: number[] = Array.from(outputShape);\n for (let i = inputShape.length - 1; i >= 0; i--) {\n if (inputShape[i] === outputShape[i]) {\n reps[i] = 1;\n } else if (inputShape[i] !== 1) {\n throw new Error(`broadcastTo(): [${\n inputShape}] cannot be broadcast to [${outputShape}].`);\n }\n }\n const axes: number[] = [];\n for (let i = 0; i < reps.length; i++) {\n if (reps[i] > 1) {\n axes.push(i);\n }\n }\n\n return {x: () => sum(dy, axes, true /* keepDims */)};\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 {Cast} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {Tensor} from '../tensor';\n\nexport const castGradConfig: GradConfig = {\n kernelName: Cast,\n gradFunc: (dy: Tensor) => {\n return {x: () => dy.clone()};\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 {Ceil} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const ceilGradConfig: GradConfig = {\n kernelName: Ceil,\n gradFunc: (dy: Tensor) => {\n // TODO(manrajgrover): Return null for gradients when backprop supports it.\n return {x: () => zerosLike(dy)};\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 {ClipByValue, ClipByValueAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {greaterEqual} from '../ops/greater_equal';\nimport {lessEqual} from '../ops/less_equal';\nimport {logicalAnd} from '../ops/logical_and';\nimport {where} from '../ops/where';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const clipByValueGradConfig: GradConfig = {\n kernelName: ClipByValue,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved;\n const {clipValueMin, clipValueMax} = attrs as {} as ClipByValueAttrs;\n return {\n x: () => where(\n logicalAnd(greaterEqual(x, clipValueMin), lessEqual(x, clipValueMax)),\n dy, zerosLike(dy)),\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 {ComplexAbs} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {absGradConfig} from './Abs_grad';\n\nexport const complexAbsGradConfig: GradConfig = {\n kernelName: ComplexAbs,\n inputsToSave: ['x'],\n gradFunc: absGradConfig.gradFunc,\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 {Concat, ConcatAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {split} from '../ops/split';\nimport {Tensor} from '../tensor';\nimport {parseAxisParam} from '../util';\n\nexport const concatGradConfig: GradConfig = {\n kernelName: Concat,\n saveAllInputs: true,\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const shapes = saved.map(t => t.shape);\n const {axis} = attrs as {} as ConcatAttrs;\n const $axis = parseAxisParam(axis, saved[0].shape)[0];\n const sizeSplits = shapes.map(s => s[$axis]);\n const derTensors = split(dy, sizeSplits, $axis);\n return derTensors.map(t => () => t) as {};\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 {Conv2D, Conv2DAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {conv2DBackpropFilter} from '../ops/conv2d_backprop_filter';\nimport {conv2DBackpropInput} from '../ops/conv2d_backprop_input';\nimport * as conv_util from '../ops/conv_util';\nimport {Tensor, Tensor4D} from '../tensor';\nimport * as util from '../util';\n\nexport const conv2DGradConfig: GradConfig = {\n kernelName: Conv2D,\n inputsToSave: ['x', 'filter'],\n gradFunc: (dy: Tensor4D, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x4D, $filter] = saved as [Tensor4D, Tensor4D];\n const {dilations, strides, pad, dataFormat} = attrs as {} as Conv2DAttrs;\n\n util.assert(\n conv_util.tupleValuesAreOne(dilations),\n () => 'Error in gradient of conv2D: dilation rates greater than 1 ' +\n `are not yet supported in gradients. Got dilations '${dilations}'`);\n\n return {\n x: () =>\n conv2DBackpropInput(x4D.shape, dy, $filter, strides, pad, dataFormat),\n filter: () =>\n conv2DBackpropFilter(x4D, dy, $filter.shape, strides, pad, dataFormat)\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 {Conv2DBackpropInput, Conv2DBackpropInputAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {conv2d} from '../ops/conv2d';\nimport {conv2DBackpropFilter} from '../ops/conv2d_backprop_filter';\nimport {Tensor, Tensor4D} from '../tensor';\n\nexport const conv2DBackpropInputGradConfig: GradConfig = {\n kernelName: Conv2DBackpropInput,\n inputsToSave: ['dy', 'filter'],\n gradFunc: (ddx: Tensor4D, saved: Tensor[], attrs: NamedAttrMap) => {\n const [dy, filter] = saved as [Tensor4D, Tensor4D];\n\n const {strides, pad, dataFormat, dimRoundingMode} =\n attrs as {} as Conv2DBackpropInputAttrs;\n\n return {\n dy: () => conv2d(\n ddx, filter, strides, pad, dataFormat, 1 /* dilations */,\n dimRoundingMode),\n filter: () => conv2DBackpropFilter(\n ddx, dy, filter.shape, strides, pad, dataFormat, dimRoundingMode)\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 {ENGINE} from '../engine';\nimport {Conv3DBackpropFilterV2, Conv3DBackpropFilterV2Attrs, Conv3DBackpropFilterV2Inputs} 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 filter of a 3D convolution.\n *\n * @param x The input tensor, of rank 5 or rank 4 of shape\n * [batch, depth, height, width, inChannels]. If rank 4, batch of 1 is\n * assumed.\n * @param dy The dy image, of rank 5 or rank 4, of shape\n * [batch, depth, height, width, outDepth]. If rank 4, batch of 1 is\n * assumed.\n * @param filterShape The shape of the filter, length 5,\n * [filterDepth, filterHeight, filterWidth, inDepth, outDepth].\n * @param strides The strides of the convolution: [strideDepth, 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 */\nfunction conv3DBackpropFilter_<T extends Tensor4D|Tensor5D>(\n x: T, dy: T, filterShape: [number, number, number, number, number],\n strides: [number, number, number]|number, pad: 'valid'|'same'): Tensor5D {\n let x5D = x as Tensor5D;\n if (x.rank === 4) {\n x5D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2], x.shape[3]]);\n }\n let dy5D = dy as Tensor5D;\n if (dy5D.rank === 4) {\n dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);\n }\n util.assert(\n x5D.rank === 5,\n () => `Error in conv3dDerFilter: input must be rank 5, but got shape ` +\n `${x5D.shape}.`);\n util.assert(\n dy5D.rank === 5,\n () => `Error in conv3dDerFilter: dy must be rank 5, but got shape ` +\n `${dy5D.shape}.`);\n util.assert(\n filterShape.length === 5,\n () => `Error in conv3dDerFilter: filterShape must be length 5, but got ` +\n `${filterShape}.`);\n util.assert(\n x5D.shape[4] === filterShape[3],\n () => `Error in conv3dDerFilter: depth of input ${x5D.shape[4]}) must ` +\n `match input depth in filter (${filterShape[3]}.`);\n util.assert(\n dy5D.shape[4] === filterShape[4],\n () => `Error in conv3dDerFilter: depth of dy (${dy5D.shape[4]}) must ` +\n `match output depth for filter (${filterShape[4]}).`);\n\n const inputs: Conv3DBackpropFilterV2Inputs = {x: x5D, dy: dy5D};\n\n const attrs: Conv3DBackpropFilterV2Attrs = {strides, pad, filterShape};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n Conv3DBackpropFilterV2, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor5D;\n}\n\nexport const conv3DBackpropFilter = op({conv3DBackpropFilter_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 {Conv3D, Conv3DAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {conv3DBackpropFilter} from '../ops/conv3d_backprop_filter';\nimport {conv3DBackpropInput} from '../ops/conv3d_backprop_input';\nimport {tupleValuesAreOne} from '../ops/conv_util';\nimport {Tensor, Tensor5D} from '../tensor';\nimport * as util from '../util';\n\nexport const conv3DGradConfig: GradConfig = {\n kernelName: Conv3D,\n inputsToSave: ['x', 'filter'],\n gradFunc: (dy: Tensor5D, saved: Tensor[], attrs: NamedAttrMap) => {\n const {dilations, strides, pad} = attrs as {} as Conv3DAttrs;\n util.assert(\n tupleValuesAreOne(dilations),\n () =>\n 'Error in gradient of conv3D: dilation rates greater than 1 are ' +\n `not yet supported in gradients. Got dilations '${dilations}'`);\n\n const [x5D, $filter] = saved;\n\n return {\n x: () => conv3DBackpropInput(\n (x5D as Tensor5D).shape, dy, $filter as Tensor5D, strides, pad),\n filter: () => conv3DBackpropFilter(\n x5D as Tensor5D, dy, ($filter as Tensor5D).shape, strides, 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 {Cos} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {mul} from '../ops/mul';\nimport {neg} from '../ops/neg';\nimport {sin} from '../ops/sin';\nimport {Tensor} from '../tensor';\n\nexport const cosGradConfig: GradConfig = {\n kernelName: Cos,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {x: () => mul(neg(sin(cast(x, 'float32'))), dy)};\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 {Cosh} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {mul} from '../ops/mul';\nimport {sinh} from '../ops/sinh';\nimport {Tensor} from '../tensor';\n\nexport const coshGradConfig: GradConfig = {\n kernelName: Cosh,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {x: () => mul(sinh(cast(x, 'float32')), dy)};\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 {Cumsum, CumsumAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {getAxesPermutation} from '../ops/axis_util';\nimport {cumsum} from '../ops/cumsum';\nimport {transpose} from '../ops/transpose';\nimport {Tensor} from '../tensor';\n\nexport const cumsumGradConfig: GradConfig = {\n kernelName: Cumsum,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved;\n const {axis, exclusive, reverse}: CumsumAttrs = attrs as {} as CumsumAttrs;\n\n return {\n x: () => {\n const permutation = getAxesPermutation([axis], x.rank);\n\n let out = cumsum(dy, axis, exclusive, !reverse);\n\n if (permutation != null) {\n out = transpose(out, permutation);\n }\n\n return out;\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 {DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport * as conv_util from '../ops/conv_util';\nimport {depthwiseConv2dNativeBackpropFilter} from '../ops/depthwise_conv2d_native_backprop_filter';\nimport {depthwiseConv2dNativeBackpropInput} from '../ops/depthwise_conv2d_native_backprop_input';\nimport {Tensor, Tensor4D} from '../tensor';\nimport * as util from '../util';\n\nexport const depthwiseConv2dNativeGradConfig: GradConfig = {\n kernelName: DepthwiseConv2dNative,\n inputsToSave: ['x', 'filter'],\n gradFunc: (dy: Tensor4D, saved: Tensor[], attrs: NamedAttrMap) => {\n const {dilations, strides, pad, dimRoundingMode} =\n attrs as {} as DepthwiseConv2dNativeAttrs;\n\n const $dilations = dilations == null ? [1, 1] : dilations;\n\n util.assert(\n conv_util.tupleValuesAreOne($dilations),\n () => 'Error in gradient of depthwiseConv2dNative: dilation rates ' +\n `greater than 1 are not yet supported. Got dilations ` +\n `'${$dilations}'`);\n\n const [x, filter] = saved as [Tensor4D, Tensor4D];\n\n util.assert(\n x.rank === 4,\n () => `Error in gradient of depthwiseConv2dNative: input must be ` +\n `rank 4, but got rank ${x.rank}.`);\n util.assert(\n filter.rank === 4,\n () => `Error in gradient of depthwiseConv2dNative: filter must be ` +\n `rank 4, but got rank ${filter.rank}.`);\n util.assert(\n x.shape[3] === filter.shape[2],\n () => `Error in gradient of depthwiseConv2d: number of input ` +\n `channels (${x.shape[3]}) must match the inChannels dimension ` +\n `in filter ${filter.shape[2]}.`);\n\n util.assert(\n conv_util.eitherStridesOrDilationsAreOne(strides, $dilations),\n () => 'Error in gradient of depthwiseConv2d: Either strides or ' +\n `dilations must be 1. Got strides ${strides} and dilations ` +\n `'${$dilations}'.`);\n\n if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () =>\n `Error in depthwiseConv2d: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n return {\n x: () => depthwiseConv2dNativeBackpropInput(\n x.shape, dy, filter, strides, pad, dilations, dimRoundingMode),\n filter: () => depthwiseConv2dNativeBackpropFilter(\n x, dy, filter.shape, strides, pad, dilations, dimRoundingMode),\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 {ENGINE} from '../engine';\nimport {Dilation2D, Dilation2DBackpropFilter, Dilation2DBackpropFilterInputs, Dilation2DBackpropInput, Dilation2DBackpropInputInputs} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor3D, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nexport const dilation2dGradConfig: GradConfig = {\n kernelName: Dilation2D,\n inputsToSave: ['x', 'filter'],\n gradFunc: (dy: Tensor4D, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x, filter] = saved as [Tensor4D, Tensor3D];\n\n const inputInputs: Dilation2DBackpropInputInputs = {x, filter, dy};\n const filterInputs: Dilation2DBackpropFilterInputs = {x, filter, dy};\n\n return {\n x: () => ENGINE.runKernel(\n Dilation2DBackpropInput, inputInputs as {} as NamedTensorMap, attrs),\n filter: () => ENGINE.runKernel(\n Dilation2DBackpropFilter, filterInputs as {} as NamedTensorMap, attrs)\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 {ENGINE} from '../engine';\nimport {Elu, EluGrad, EluGradInputs} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nexport const eluGradConfig: GradConfig = {\n kernelName: Elu,\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [y] = saved;\n\n const inputs: EluGradInputs = {dy, y};\n\n return {x: () => ENGINE.runKernel(EluGrad, inputs as {} as NamedTensorMap)};\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 {Erf} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {exp} from '../ops/exp';\nimport {mul} from '../ops/mul';\nimport {neg} from '../ops/neg';\nimport {square} from '../ops/square';\nimport {Tensor} from '../tensor';\n\nexport const erfGradConfig: GradConfig = {\n kernelName: Erf,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n const a = mul(exp(neg(square(x))), 2 / Math.sqrt(Math.PI));\n return {x: () => mul(dy, a)};\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 {Exp} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {mul} from '../ops/mul';\nimport {Tensor} from '../tensor';\n\nexport const expGradConfig: GradConfig = {\n kernelName: Exp,\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [y] = saved;\n return {x: () => mul(dy, 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 {ExpandDims} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {reshape} from '../ops/reshape';\nimport {Tensor} from '../tensor';\n\nexport const expandDimsGradConfig: GradConfig = {\n kernelName: ExpandDims,\n inputsToSave: ['input'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [input] = saved;\n return {input: () => reshape(dy, input.shape)};\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 {Expm1} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {exp} from '../ops/exp';\nimport {mul} from '../ops/mul';\nimport {Tensor} from '../tensor';\n\nexport const expm1GradConfig: GradConfig = {\n kernelName: Expm1,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => mul(dy, exp(x))};\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 {Floor} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const floorGradConfig: GradConfig = {\n kernelName: Floor,\n gradFunc: (dy: Tensor) => {\n return {x: () => zerosLike(dy)};\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 {FloorDiv} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {assertAndGetBroadcastShape, getReductionAxes} from '../ops/broadcast_util';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {neg} from '../ops/neg';\nimport {reshape} from '../ops/reshape';\nimport {square} from '../ops/square';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const floorDivGradConfig: GradConfig = {\n kernelName: FloorDiv,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const outShape = assertAndGetBroadcastShape(a.shape, b.shape);\n\n const derA = () => {\n const res = div(dy, cast(b, 'float32'));\n const reduceAxes = getReductionAxes(a.shape, outShape);\n if (reduceAxes.length > 0) {\n return reshape(sum(res, reduceAxes), a.shape);\n }\n return res;\n };\n const derB = () => {\n let res = mul(dy, cast(a, 'float32'));\n const reduceAxes = getReductionAxes(b.shape, outShape);\n if (reduceAxes.length > 0) {\n res = reshape(sum(res, reduceAxes), b.shape);\n }\n const tmp = square(b);\n return neg(div(res, cast(tmp, 'float32')));\n };\n return {a: derA, b: derB};\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 {FusedBatchNorm, FusedBatchNormAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {add} from '../ops/add';\nimport {getReductionAxes} from '../ops/broadcast_util';\nimport {mul} from '../ops/mul';\nimport {reshape} from '../ops/reshape';\nimport {rsqrt} from '../ops/rsqrt';\nimport {scalar} from '../ops/scalar';\nimport {sub} from '../ops/sub';\nimport {sum} from '../ops/sum';\nimport {tile} from '../ops/tile';\nimport {Tensor} from '../tensor';\nimport {Rank, ShapeMap} from '../types';\n\nexport const fusedBatchNormGradConfig: GradConfig = {\n kernelName: FusedBatchNorm,\n inputsToSave: ['x', 'mean', 'variance', 'scale'],\n gradFunc: <R extends Rank>(\n dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const {varianceEpsilon} = attrs as {} as FusedBatchNormAttrs;\n const [x, mean, variance, scale] = saved;\n\n const scaleValue = scale == null ? scalar(1) : scale;\n const reductionAxes = getReductionAxes(mean.shape, x.shape);\n const tileShape: number[] = [];\n if (mean.rank === 1) {\n for (let i = 0; i < x.shape.length - 1; ++i) {\n tileShape.push(x.shape[i]);\n }\n tileShape.push(1);\n }\n\n const xMinusMean = sub(x, mean);\n const dyTimesScaleValue = mul(dy, scaleValue);\n const oneOverSqrtVariance = rsqrt(add(variance, scalar(varianceEpsilon)));\n const minusHalfRCube = mul(\n mul(mul(oneOverSqrtVariance, oneOverSqrtVariance), oneOverSqrtVariance),\n scalar(-0.5));\n\n const derX = () => {\n if (mean.rank === 1) {\n return reshape(\n mul(mul(dy,\n tile(\n reshape(oneOverSqrtVariance, [1, 1, 1, mean.shape[0]]),\n tileShape)),\n scaleValue),\n x.shape);\n } else {\n return reshape(mul(mul(dy, oneOverSqrtVariance), scaleValue), x.shape);\n }\n };\n const derMean = () => {\n let meanDer =\n mul(mul(oneOverSqrtVariance, scalar(-1)), dyTimesScaleValue);\n if (mean.rank === 1) {\n meanDer = sum(meanDer, reductionAxes);\n }\n return reshape(meanDer, mean.shape as ShapeMap[R]);\n };\n const derVariance = () => {\n let varianceDer = mul(mul(minusHalfRCube, xMinusMean), dyTimesScaleValue);\n\n if (mean.rank === 1) {\n varianceDer = sum(varianceDer, reductionAxes);\n }\n return reshape(varianceDer, mean.shape as ShapeMap[R]);\n };\n const derScale = () => {\n const xMinusMean2TimesRsqrt = mul(xMinusMean, oneOverSqrtVariance);\n\n let scaleDer = mul(dy, xMinusMean2TimesRsqrt);\n if (mean.rank === 1) {\n scaleDer = sum(scaleDer, reductionAxes);\n }\n return reshape(scaleDer, mean.shape as ShapeMap[R]);\n };\n const derOffset = () => {\n let offsetDer = dy;\n if (mean.rank === 1) {\n offsetDer = sum(offsetDer, reductionAxes);\n }\n return reshape(offsetDer, mean.shape as ShapeMap[R]);\n };\n\n return {\n x: derX,\n mean: derMean,\n variance: derVariance,\n scale: derScale,\n offset: derOffset\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 {GatherV2, GatherV2Attrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {getUndoAxesPermutation} from '../ops/axis_util';\nimport {reshape} from '../ops/reshape';\nimport {transpose} from '../ops/transpose';\nimport {unsortedSegmentSum} from '../ops/unsorted_segment_sum';\nimport {Tensor, Tensor1D} from '../tensor';\nimport {parseAxisParam} from '../util';\n\nexport const gatherGradConfig: GradConfig = {\n kernelName: GatherV2,\n inputsToSave: ['x', 'indices'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x, indices] = saved;\n const {axis} = attrs as {} as GatherV2Attrs;\n\n const parsedAxis = parseAxisParam(axis, x.shape)[0];\n\n const derX = () => {\n const paramsShape = x.shape;\n const indicesSize = indices.size;\n\n const outerShape = paramsShape.slice(0, parsedAxis);\n const outerDims = outerShape.length;\n const innerShape = paramsShape.slice(axis, paramsShape.length).slice(1);\n const innerDims = innerShape.length;\n\n const outerAxesIndices = arrayRange(0, outerDims);\n const innerAxesIndices =\n arrayRange(outerDims + 1, outerDims + 1 + innerDims);\n\n const valuesShape = arrayConcat([outerShape, [indicesSize], innerShape]);\n\n const values = reshape(dy, valuesShape);\n const reshapedIndices = reshape(indices, [indicesSize]);\n\n const transposeDims =\n arrayConcat([[outerDims], outerAxesIndices, innerAxesIndices]);\n const valuesTranspose = transpose(values, transposeDims);\n let paramsGrad = unsortedSegmentSum(\n valuesTranspose, reshapedIndices as Tensor1D, x.shape[parsedAxis]);\n\n const invertTransposeDims = getUndoAxesPermutation(transposeDims);\n paramsGrad = transpose(paramsGrad, invertTransposeDims);\n\n return paramsGrad;\n };\n return {x: derX, indices: () => indices};\n }\n};\n\nfunction arrayRange(start: number, stop: number): number[] {\n const result = [];\n for (let i = start; i < stop; ++i) {\n result.push(i);\n }\n return result;\n}\n\nfunction arrayConcat(arrays: number[][]): number[] {\n const result = [];\n for (let i = 0; i < arrays.length; ++i) {\n for (let j = 0; j < arrays[i].length; ++j) {\n result.push(arrays[i][j]);\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 {GreaterEqual} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const greaterEqualGradConfig: GradConfig = {\n kernelName: GreaterEqual,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n return {a: () => zerosLike(a), b: () => zerosLike(b)};\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 {Identity} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {Tensor} from '../tensor';\n\nexport const identityGradConfig: GradConfig = {\n kernelName: Identity,\n gradFunc: (dy: Tensor) => {\n return {x: () => cast(dy, 'float32')};\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 {IsFinite} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const isFiniteGradConfig: GradConfig = {\n kernelName: IsFinite,\n gradFunc: (dy: Tensor) => {\n // TODO(nsthorat): Let gradients be null for cases where we want to stop\n // backpropgation.\n return {x: () => zerosLike(dy)};\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 {IsInf} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const isInfGradConfig: GradConfig = {\n kernelName: IsInf,\n gradFunc: (dy: Tensor) => {\n // TODO(nsthorat): Let gradients be null for cases where we want to stop\n // backpropgation.\n return {x: () => zerosLike(dy)};\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 {IsNan} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const isNanGradConfig: GradConfig = {\n kernelName: IsNan,\n gradFunc: (dy: Tensor) => {\n // TODO(nsthorat): Let gradients be null for cases where we want to stop\n // backpropgation.\n return {x: () => zerosLike(dy)};\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 {LeakyRelu, LeakyReluAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {greater} from '../ops/greater';\nimport {mul} from '../ops/mul';\nimport {where} from '../ops/where';\nimport {Tensor} from '../tensor';\n\nexport const leakyReluGradConfig: GradConfig = {\n kernelName: LeakyRelu,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved;\n const {alpha} = attrs as {} as LeakyReluAttrs;\n const mask = greater(x, 0);\n\n // Returns `gradients * (features > 0) + alpha * gradients * (features <=\n // 0)`.\n return {x: () => where(mask, dy, mul(dy, alpha))};\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 {Log1p} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {add} from '../ops/add';\nimport {div} from '../ops/div';\nimport {Tensor} from '../tensor';\n\nexport const log1pGradConfig: GradConfig = {\n kernelName: Log1p,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => div(dy, add(x, 1))};\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 {Log} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {Tensor} from '../tensor';\n\nexport const logGradConfig: GradConfig = {\n kernelName: Log,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => div(dy, cast(x, 'float32'))};\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 {LogSoftmax, LogSoftmaxAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {exp} from '../ops/exp';\nimport {mul} from '../ops/mul';\nimport {sub} from '../ops/sub';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const logSoftmaxGradConfig: GradConfig = {\n kernelName: LogSoftmax,\n inputsToSave: [],\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [value] = saved;\n const {axis} = attrs as {} as LogSoftmaxAttrs;\n return {\n logits: () => {\n const keepDims = true;\n const softmax = exp(value);\n return sub(dy, mul(sum(dy, axis, keepDims), softmax));\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 */\n\nimport {ENGINE} from '../engine';\nimport {LRNGrad, LRNGradAttrs, LRNGradInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nimport {op} from './operation';\n\nfunction localResponseNormalizationBackprop_<T extends Tensor4D>(\n x: T, y: T, dy: T, depthRadius = 5, bias = 1, alpha = 1, beta = 0.5): T {\n const inputs: LRNGradInputs = {x, y, dy};\n\n const attrs: LRNGradAttrs = {depthRadius, bias, alpha, beta};\n\n return ENGINE.runKernel(\n LRNGrad, inputs as {} as NamedTensorMap, attrs as {} as NamedAttrMap);\n}\n\nexport const localResponseNormalizationBackprop =\n op({localResponseNormalizationBackprop_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 {LRN, LRNAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {localResponseNormalizationBackprop} from '../ops/local_response_normalization_backprop';\nimport {Tensor, Tensor4D} from '../tensor';\n\nexport const lrnGradConfig: GradConfig = {\n kernelName: LRN,\n inputsToSave: ['x'],\n outputsToSave: [true],\n gradFunc: (dy: Tensor4D, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x, y] = saved as [Tensor4D, Tensor4D];\n const {depthRadius, bias, alpha, beta} = attrs as {} as LRNAttrs;\n\n return {\n x: () => localResponseNormalizationBackprop(\n x, y, dy, depthRadius, bias, alpha, beta)\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 * as axis_util from '../ops/axis_util';\nimport {cast} from '../ops/cast';\nimport {equal} from '../ops/equal';\nimport {mul} from '../ops/mul';\nimport {reshape} from '../ops/reshape';\nimport {Tensor} from '../tensor';\n\n/**\n * Gradient helper function for the min and max operations.\n */\nexport function gradForMinAndMax<T extends Tensor>(\n dy: T, y: T, xOrig: Tensor, origAxes: number[]) {\n if (y.rank < xOrig.rank) {\n y = reshape(y, axis_util.expandShapeToKeepDim(y.shape, origAxes)) as T;\n }\n if (dy.rank < xOrig.rank) {\n dy = reshape(dy, axis_util.expandShapeToKeepDim(dy.shape, origAxes)) as T;\n }\n return {\n x: () => {\n const dx = mul(dy, cast(equal(xOrig, y), dy.dtype));\n return dx;\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 {Max, MaxAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport * as util from '../util';\n\nimport {gradForMinAndMax} from './min_max_grad_util';\n\nexport const maxGradConfig: GradConfig = {\n kernelName: Max,\n inputsToSave: ['x'],\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const maxAttrs: MaxAttrs = attrs as {} as MaxAttrs;\n const {reductionIndices} = maxAttrs;\n const x = saved[0];\n const y = saved[1];\n const origAxes = util.parseAxisParam(reductionIndices, x.shape);\n const maxGrad = gradForMinAndMax(dy, y, x, origAxes);\n return {\n x: () => {\n return maxGrad['x']();\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 */\n\nimport {Maximum} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {greaterEqual} from '../ops/greater_equal';\nimport {less} from '../ops/less';\nimport {mul} from '../ops/mul';\nimport {Tensor} from '../tensor';\n\nexport const maximumGradConfig: GradConfig = {\n kernelName: Maximum,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const derA = () => mul(dy, cast(greaterEqual(a, b), 'float32'));\n const derB = () => mul(dy, cast(less(a, b), 'float32'));\n return {a: derA, b: derB};\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 {MaxPool3DGrad, MaxPool3DGradAttrs, MaxPool3DGradInputs} 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 {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the backprop of a 3d max pool.\n *\n * @param dy The dy error, of rank 5 of shape\n * [batchSize, depth, height, width, channels].\n * assumed.\n * @param input The original input image, of rank 5 or rank 4 of shape\n * [batchSize, depth, height, width, channels].\n * @param output The original output image, of rank 5 of shape\n * [batchSize, outDepth, outHeight, outWidth, channels].\n * @param filterSize The filter size:\n * `[filterDepth, filterHeight, filterWidth]`.\n * `filterSize` is a single number,\n * then `filterDepth == filterHeight == filterWidth`.\n * @param strides The strides of the pooling:\n * `[strideDepth, strideHeight, strideWidth]`. If\n * `strides` is a single number, then `strideHeight == 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 dimRoundingMode A string from: 'ceil', 'round', 'floor'. If none is\n * provided, it will default to truncate.\n */\nfunction maxPool3dGrad_<T extends Tensor4D|Tensor5D>(\n dy: T|TensorLike, input: T|TensorLike, output: T|TensorLike,\n filterSize: [number, number, number]|number,\n strides: [number, number, number]|number, pad: 'valid'|'same'|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n const $dy = convertToTensor(dy, 'dy', 'maxPool3dGrad');\n const $input = convertToTensor(input, 'input', 'maxPool3dGrad');\n const $output = convertToTensor(output, 'output', 'maxPool3dGrad');\n\n let dy5D = $dy as Tensor5D;\n let input5D = $input as Tensor5D;\n let output5D = $output as Tensor5D;\n let reshapedTo5D = false;\n\n if ($input.rank === 4) {\n reshapedTo5D = true;\n dy5D = reshape(\n $dy, [1, $dy.shape[0], $dy.shape[1], $dy.shape[2], $dy.shape[3]]);\n input5D = reshape($input, [\n 1, $input.shape[0], $input.shape[1], $input.shape[2], $input.shape[3]\n ]);\n output5D = reshape($output, [\n 1, $output.shape[0], $output.shape[1], $output.shape[2], $output.shape[3]\n ]);\n }\n\n util.assert(\n dy5D.rank === 5,\n () => `Error in maxPool3dGrad: dy must be rank 5 but got rank ` +\n `${dy5D.rank}.`);\n util.assert(\n input5D.rank === 5,\n () => `Error in maxPool3dGrad: input must be rank 5 but got rank ` +\n `${input5D.rank}.`);\n util.assert(\n output5D.rank === 5,\n () => `Error in maxPool3dGrad: output must be rank 5 but got rank ` +\n `${output5D.rank}.`);\n if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in maxPool3dGrad: pad must be an integer when ` +\n `using, dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n const inputs:\n MaxPool3DGradInputs = {dy: dy5D, input: input5D, output: output5D};\n\n const attrs: MaxPool3DGradAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n const res = ENGINE.runKernel(\n MaxPool3DGrad, inputs as {} as NamedTensorMap,\n attrs as {} 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 maxPool3dGrad = op({maxPool3dGrad_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {MaxPool3D, MaxPool3DAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {maxPool3dGrad} from '../ops/max_pool_3d_grad';\nimport {Tensor, Tensor5D} from '../tensor';\n\nexport const maxPool3DGradConfig: GradConfig = {\n kernelName: MaxPool3D,\n inputsToSave: ['x'],\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x, y] = saved as [Tensor5D, Tensor5D];\n const {filterSize, strides, pad, dimRoundingMode} =\n attrs as {} as MaxPool3DAttrs;\n\n return {\n x: () => maxPool3dGrad(\n dy as Tensor5D, x, y, filterSize, strides, pad, dimRoundingMode)\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 {MaxPoolGrad, MaxPoolGradAttrs, MaxPoolGradInputs} 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 {ExplicitPadding} from './conv_util';\nimport {op} from './operation';\n\n/**\n * Computes the backprop of a 2D max pool.\n *\n * @param dy The dy error, of rank 4 or rank 3 of shape\n * [batchSize, height, width, channels]. If rank 3, batch of 1 is\n * assumed.\n * @param input The original input image, of rank 4, of shape\n * [batchSize, height, width, channels].\n * @param output The original output image, of rank 4, of shape\n * [batchSize, outHeight, outWidth, channels].\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 used in the forward prop of the op.\n * 'same', 'valid', 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 maxPoolGrad_(\n dy: Tensor4D|TensorLike, input: Tensor4D|TensorLike,\n output: Tensor4D|TensorLike, filterSize: [number, number]|number,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): Tensor4D {\n const $dy = convertToTensor(dy, 'dy', 'maxPoolGrad');\n const $input = convertToTensor(input, 'input', 'maxPoolGrad');\n const $output = convertToTensor(output, 'output', 'maxPoolGrad');\n\n util.assert(\n $input.rank === $dy.rank,\n () => `Rank of input (${$input.rank}) does not match rank of dy ` +\n `(${$dy.rank})`);\n\n util.assert(\n $dy.rank === 4,\n () => `Error in maxPoolGrad: dy must be rank 4 but got rank ` +\n `${$dy.rank}.`);\n util.assert(\n $input.rank === 4,\n () => `Error in maxPoolGrad: input must be rank 4 but got rank ` +\n `${$input.rank}.`);\n if (dimRoundingMode != null) {\n util.assert(\n util.isInt(pad as number),\n () => `Error in maxPoolGrad: pad must be an integer when using, ` +\n `dimRoundingMode ${dimRoundingMode} but got pad ${pad}.`);\n }\n\n const inputs: MaxPoolGradInputs = {dy: $dy, input: $input, output: $output};\n\n const attrs: MaxPoolGradAttrs = {filterSize, strides, pad, dimRoundingMode};\n\n // tslint:disable-next-line: no-unnecessary-type-assertion\n return ENGINE.runKernel(\n MaxPoolGrad, inputs as {} as NamedTensorMap,\n attrs as {} as NamedAttrMap) as Tensor4D;\n}\n\nexport const maxPoolGrad = op({maxPoolGrad_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {MaxPool, MaxPoolAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {maxPoolGrad} from '../ops/max_pool_grad';\nimport {Tensor, Tensor4D} from '../tensor';\n\nexport const maxPoolGradConfig: GradConfig = {\n kernelName: MaxPool,\n inputsToSave: ['x'],\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x, y] = saved as [Tensor4D, Tensor4D];\n const {filterSize, strides, pad} = attrs as {} as MaxPoolAttrs;\n\n return {\n x: () => maxPoolGrad(dy as Tensor4D, x, y, filterSize, strides, 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 {Mean, MeanAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {computeOutAndReduceShapes} from '../ops/axis_util';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {ones} from '../ops/ones';\nimport {reshape} from '../ops/reshape';\nimport {Tensor} from '../tensor';\nimport * as util from '../util';\n\nexport const meanGradConfig: GradConfig = {\n kernelName: Mean,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved;\n const {axis} = attrs as {} as MeanAttrs;\n const axes = util.parseAxisParam(axis, x.shape);\n const shapes = computeOutAndReduceShapes(x.shape, axes);\n const reduceShape = shapes[1];\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const derX = () => {\n const expandedDyShape = x.shape.slice();\n axes.forEach(axis => {\n expandedDyShape[axis] = 1;\n });\n const expandedDy = reshape(dy, expandedDyShape);\n const res = div(mul(expandedDy, ones(x.shape, 'float32')), reduceSize);\n return res;\n };\n\n return {x: derX};\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 {Min, MinAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport * as util from '../util';\n\nimport {gradForMinAndMax} from './min_max_grad_util';\n\nexport const minGradConfig: GradConfig = {\n kernelName: Min,\n inputsToSave: ['x'],\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const minAttrs: MinAttrs = attrs as {} as MinAttrs;\n const {axis} = minAttrs;\n const [x, y] = saved;\n const origAxes = util.parseAxisParam(axis, x.shape);\n const minGrad = gradForMinAndMax(dy, y, x, origAxes);\n return {\n x: () => {\n return minGrad['x']();\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 */\n\nimport {Minimum} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {greater} from '../ops/greater';\nimport {lessEqual} from '../ops/less_equal';\nimport {mul} from '../ops/mul';\nimport {Tensor} from '../tensor';\n\nexport const minimumGradConfig: GradConfig = {\n kernelName: Minimum,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const derA = () => mul(dy, cast(lessEqual(a, b), 'float32'));\n const derB = () => mul(dy, cast(greater(a, b), 'float32'));\n return {a: derA, b: derB};\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 {MirrorPad, MirrorPadAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {slice} from '../ops/slice';\nimport {Tensor} from '../tensor';\n\nexport const mirrorPadGradConfig: GradConfig = {\n kernelName: MirrorPad,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n // Pad introduces values around the original tensor, so the gradient\n // slices the original shape out of the gradient.\n const x = saved[0];\n const {paddings} = attrs as unknown as MirrorPadAttrs;\n const begin = paddings.map(p => p[0]);\n return {x: () => slice(dy, begin, x.shape)};\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 {Mod} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {assertAndGetBroadcastShape, getReductionAxes} from '../ops/broadcast_util';\nimport {div} from '../ops/div';\nimport {floor} from '../ops/floor';\nimport {mul} from '../ops/mul';\nimport {neg} from '../ops/neg';\nimport {reshape} from '../ops/reshape';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const modGradConfig: GradConfig = {\n kernelName: Mod,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const outShape = assertAndGetBroadcastShape(a.shape, b.shape);\n\n const derA = () => {\n const reduceAxes = getReductionAxes(a.shape, outShape);\n if (reduceAxes.length > 0) {\n return reshape(sum(dy, reduceAxes), a.shape);\n }\n return dy;\n };\n const derB = () => {\n const res = mul(dy, neg(floor(div(a, b))));\n const reduceAxes = getReductionAxes(b.shape, outShape);\n if (reduceAxes.length > 0) {\n return reshape(sum(res, reduceAxes), b.shape);\n }\n return res;\n };\n return {a: derA, b: derB};\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 {Multiply} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {assertAndGetBroadcastShape, getReductionAxes} from '../ops/broadcast_util';\nimport {cast} from '../ops/cast';\nimport {mul} from '../ops/mul';\nimport {reshape} from '../ops/reshape';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const multiplyGradConfig: GradConfig = {\n kernelName: Multiply,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const outShape = assertAndGetBroadcastShape(a.shape, b.shape);\n\n const derA = () => {\n const res = mul(dy, cast(b, 'float32'));\n const reduceAxes = getReductionAxes(a.shape, outShape);\n if (reduceAxes.length > 0) {\n return reshape(sum(res, reduceAxes), a.shape);\n }\n return res;\n };\n const derB = () => {\n const res = mul(dy, cast(a, 'float32'));\n const reduceAxes = getReductionAxes(b.shape, outShape);\n if (reduceAxes.length > 0) {\n return reshape(sum(res, reduceAxes), b.shape);\n }\n return res;\n };\n return {a: derA, b: derB};\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 {Neg} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {neg} from '../ops/neg';\nimport {Tensor} from '../tensor';\n\nexport const negGradConfig: GradConfig = {\n kernelName: Neg,\n gradFunc: (dy: Tensor) => {\n return {x: () => neg(dy)};\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 {OneHot} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zeros} from '../ops/zeros';\nimport {Tensor} from '../tensor';\n\nexport const oneHotGradConfig: GradConfig = {\n kernelName: OneHot,\n inputsToSave: ['indices'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const indices = saved[0];\n return {indices: () => zeros(indices.shape, 'float32')};\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 {OnesLike} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const onesLikeGradConfig: GradConfig = {\n kernelName: OnesLike,\n gradFunc: (dy: Tensor) => {\n return {x: () => zerosLike(dy)};\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 {Pack, PackAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {unstack} from '../ops/unstack';\nimport {Tensor} from '../tensor';\n\nexport const packGradConfig: GradConfig = {\n kernelName: Pack,\n saveAllInputs: true,\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const {axis} = attrs as {} as PackAttrs;\n const derTensors = unstack(dy, axis);\n return derTensors.map(t => () => t) as {};\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 {PadV2, PadV2Attrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {slice} from '../ops/slice';\nimport {Tensor} from '../tensor';\n\nexport const padV2GradConfig: GradConfig = {\n kernelName: PadV2,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n // Pad introduces values around the original tensor, so the gradient\n // slices the original shape out of the gradient.\n const x = saved[0];\n const {paddings} = attrs as unknown as PadV2Attrs;\n const begin = paddings.map(p => p[0]);\n return {x: () => slice(dy, begin, x.shape)};\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 {Pow} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport * as broadcast_util from '../ops/broadcast_util';\nimport {cast} from '../ops/cast';\nimport {greater} from '../ops/greater';\nimport {log} from '../ops/log';\nimport {mul} from '../ops/mul';\nimport {pow} from '../ops/pow';\nimport {reshape} from '../ops/reshape';\nimport {scalar} from '../ops/scalar';\nimport {sub} from '../ops/sub';\nimport {sum} from '../ops/sum';\nimport {where} from '../ops/where';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const powGradConfig: GradConfig = {\n kernelName: Pow,\n inputsToSave: ['a', 'b'],\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b, y] = saved;\n const base = a;\n const exp = b;\n const outShape =\n broadcast_util.assertAndGetBroadcastShape(base.shape, exp.shape);\n\n const derBase = () => {\n const expFloat = cast(exp, 'float32');\n let res = mul(dy, mul(expFloat, pow(base, sub(expFloat, scalar(1)))));\n const reduceAxes = broadcast_util.getReductionAxes(base.shape, outShape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, base.shape);\n };\n const derExp = () => {\n const condition = greater(base, 0);\n const logBase = where(condition, log(base), zerosLike(base));\n let res = mul(dy, mul(y, logBase));\n const reduceAxes = broadcast_util.getReductionAxes(exp.shape, outShape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, exp.shape);\n };\n return {a: derBase, b: derExp};\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 {Prelu} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {getReductionAxes} from '../ops/broadcast_util';\nimport {greater} from '../ops/greater';\nimport {mul} from '../ops/mul';\nimport {reshape} from '../ops/reshape';\nimport {sum} from '../ops/sum';\nimport {where} from '../ops/where';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const preluGradConfig: GradConfig = {\n kernelName: Prelu,\n inputsToSave: ['x', 'alpha'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x, alpha] = saved;\n const mask = greater(x, 0);\n\n return {\n x: () => where(mask, dy, mul(dy, alpha)),\n alpha: () => {\n let res = where(mask, zerosLike(dy), mul(dy, x));\n const reduceAxes = getReductionAxes(alpha.shape, dy.shape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, alpha.shape);\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 */\n\nimport {RealDiv} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport * as broadcast_util from '../ops/broadcast_util';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {neg} from '../ops/neg';\nimport {reshape} from '../ops/reshape';\nimport {square} from '../ops/square';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const divGradConfig: GradConfig = {\n kernelName: RealDiv,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const outShape =\n broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);\n const derA = () => {\n const res = div(dy, cast(b, 'float32'));\n const reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);\n if (reduceAxes.length > 0) {\n return reshape(sum(res, reduceAxes), a.shape);\n }\n return res;\n };\n const derB = () => {\n let res = mul(dy, cast(a, 'float32'));\n const reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);\n if (reduceAxes.length > 0) {\n res = reshape(sum(res, reduceAxes), b.shape);\n }\n const tmp = square(b);\n return neg(div(res, cast(tmp, 'float32')));\n };\n return {a: derA, b: derB};\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 {Reciprocal} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {div} from '../ops/div';\nimport {neg} from '../ops/neg';\nimport {square} from '../ops/square';\nimport {Tensor} from '../tensor';\n\nexport const reciprocalGradConfig: GradConfig = {\n kernelName: Reciprocal,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => div(dy, neg(square(x)))};\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 {Relu6} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {lessEqual} from '../ops/less_equal';\nimport {mul} from '../ops/mul';\nimport {step} from '../ops/step';\nimport {Tensor} from '../tensor';\n\nexport const relu6GradConfig: GradConfig = {\n kernelName: Relu6,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n const mask = mul(lessEqual(x, 6), step(x));\n\n return {x: () => mul(dy, cast(mask, 'float32'))};\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 {Relu} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {mul} from '../ops/mul';\nimport {step} from '../ops/step';\nimport {Tensor} from '../tensor';\n\nexport const reluGradConfig: GradConfig = {\n kernelName: Relu,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => mul(dy, cast(step(x), 'float32'))};\n }\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 {Reshape} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {reshape} from '../ops/reshape';\nimport {Tensor} from '../tensor';\n\nexport const reshapeGradConfig: GradConfig = {\n kernelName: Reshape,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => reshape(dy, x.shape)};\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 {ENGINE} from '../engine';\nimport {ResizeBilinear, ResizeBilinearGrad, ResizeBilinearGradInputs} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nexport const resizeBilinearGradConfig: GradConfig = {\n kernelName: ResizeBilinear,\n inputsToSave: ['images'],\n gradFunc: (dy: Tensor4D, saved: Tensor[], attrs: NamedAttrMap) => {\n const [images] = saved;\n\n const inputs: ResizeBilinearGradInputs = {dy, images};\n const imagesDer = () =>\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n ResizeBilinearGrad, inputs as {} as NamedTensorMap, attrs) as\n Tensor4D;\n\n return {images: imagesDer};\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 {ENGINE} from '../engine';\nimport {ResizeNearestNeighbor, ResizeNearestNeighborGrad, ResizeNearestNeighborGradInputs} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor4D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\n\nexport const resizeNearestNeighborGradConfig: GradConfig = {\n kernelName: ResizeNearestNeighbor,\n inputsToSave: ['images'],\n gradFunc: (dy: Tensor4D, saved: Tensor[], attrs: NamedAttrMap) => {\n const [images] = saved;\n\n const inputs: ResizeNearestNeighborGradInputs = {dy, images};\n const imagesDer = () =>\n // tslint:disable-next-line: no-unnecessary-type-assertion\n ENGINE.runKernel(\n ResizeNearestNeighborGrad, inputs as {} as NamedTensorMap, attrs) as\n Tensor4D;\n\n return {images: imagesDer};\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 {Reverse, ReverseAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {reverse} from '../ops/reverse';\nimport {Tensor} from '../tensor';\nimport {parseAxisParam} from '../util';\n\nexport const reverseGradConfig: GradConfig = {\n kernelName: Reverse,\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const {dims} = attrs as {} as ReverseAttrs;\n const axes = parseAxisParam(dims, dy.shape);\n return {x: () => reverse(dy, axes)};\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 {Round} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const roundGradConfig: GradConfig = {\n kernelName: Round,\n gradFunc: (dy: Tensor) => {\n // TODO(nsthorat): Let gradients be null for cases where we want to stop\n // backpropgation.\n return {x: () => zerosLike(dy)};\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 {Rsqrt} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {neg} from '../ops/neg';\nimport {pow} from '../ops/pow';\nimport {Tensor} from '../tensor';\n\nexport const rsqrtGradConfig: GradConfig = {\n kernelName: Rsqrt,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => neg(div(dy, mul(pow(x, 1.5), 2)))};\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 {Select} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {logicalNot} from '../ops/logical_not';\nimport {mul} from '../ops/mul';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const selectGradConfig: GradConfig = {\n kernelName: Select,\n inputsToSave: ['condition'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [condition] = saved;\n return {\n // TODO(julianoks): Return null for condition gradient\n // when backprop supports it.\n condition: () => cast(zerosLike(condition), 'float32'),\n t: () => mul(dy, cast(condition, dy.dtype)),\n e: () => mul(dy, cast(logicalNot(condition), dy.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 */\nimport {Selu} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {exp} from '../ops/exp';\nimport {greater} from '../ops/greater';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {SELU_SCALE, SELU_SCALEALPHA} from '../ops/selu_util';\nimport {where} from '../ops/where';\nimport {Tensor} from '../tensor';\n\nexport const seluGradConfig: GradConfig = {\n kernelName: Selu,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {\n x: () => {\n const mask = greater(x, scalar(0));\n\n const scaleAlpha = scalar(SELU_SCALEALPHA);\n const scale = scalar(SELU_SCALE);\n\n const greaterThanZeroDer = mul(dy, scale);\n const lessEqualZeroDer =\n mul(mul(dy, scaleAlpha), exp(cast(x, 'float32')));\n\n return where(mask, greaterThanZeroDer, lessEqualZeroDer);\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 */\n\nimport {Sigmoid} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {sub} from '../ops/sub';\nimport {Tensor} from '../tensor';\n\nexport const sigmoidGradConfig: GradConfig = {\n kernelName: Sigmoid,\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [y] = saved;\n\n return {x: () => mul(dy, mul(y, sub(scalar(1), 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 {Sign} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const signGradConfig: GradConfig = {\n kernelName: Sign,\n gradFunc: (dy: Tensor) => {\n return {x: () => zerosLike(dy)};\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 {Sin} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {cos} from '../ops/cos';\nimport {mul} from '../ops/mul';\nimport {Tensor} from '../tensor';\n\nexport const sinGradConfig: GradConfig = {\n kernelName: Sin,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => mul(cos(cast(x, 'float32')), dy)};\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 {Sinh} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {cosh} from '../ops/cosh';\nimport {mul} from '../ops/mul';\nimport {Tensor} from '../tensor';\n\nexport const sinhGradConfig: GradConfig = {\n kernelName: Sinh,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {x: () => mul(cosh(cast(x, 'float32')), dy)};\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 {Slice, SliceAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {pad} from '../ops/pad';\nimport {parseSliceParams} from '../ops/slice_util';\nimport {Tensor} from '../tensor';\n\nexport const sliceGradConfig: GradConfig = {\n kernelName: Slice,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved;\n const {begin, size} = attrs as {} as SliceAttrs;\n\n const inputShape = x.shape;\n const [begin_, size_] = parseSliceParams(x, begin, size);\n\n // Create an Nx2 padding where the first column represents how many\n // zeros are prepended (at start) for each dimension, and the second\n // column indicates how many zeros are appended (at end).\n\n // The number of zeros to append is the shape of the input\n // elementwise-subtracted by both the begin vector and sizes vector.\n const paddings: Array<[number, number]> = [];\n for (let i = 0; i < dy.rank; i++) {\n paddings.push([begin_[i], inputShape[i] - begin_[i] - size_[i]]);\n }\n return {x: () => pad(dy, paddings)};\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 {Softmax, SoftmaxAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {mul} from '../ops/mul';\nimport {sub} from '../ops/sub';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const softmaxGradConfig: GradConfig = {\n kernelName: Softmax,\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [y] = saved;\n const {dim} = attrs as {} as SoftmaxAttrs;\n const keepDims = true;\n\n const dyTimesY = mul(dy, y);\n return {\n logits: () => sub(dyTimesY, mul(sum(dyTimesY, [dim], keepDims), y))\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 {Softplus} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {mul} from '../ops/mul';\nimport {sigmoid} from '../ops/sigmoid';\nimport {Tensor} from '../tensor';\n\nexport const softplusGradConfig: GradConfig = {\n kernelName: Softplus,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {x: () => mul(dy, sigmoid(x))};\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 {SpaceToBatchND, SpaceToBatchNDAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {batchToSpaceND} from '../ops/batch_to_space_nd';\nimport {Tensor} from '../tensor';\n\nexport const spaceToBatchNDGradConfig: GradConfig = {\n kernelName: SpaceToBatchND,\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const {blockShape, paddings} = attrs as {} as SpaceToBatchNDAttrs;\n return {x: () => batchToSpaceND(dy, blockShape, paddings)};\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 {SplitV, SplitVAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {concat} from '../ops/concat';\nimport {Tensor} from '../tensor';\n\nexport const splitVGradConfig: GradConfig = {\n kernelName: SplitV,\n gradFunc: (dy: Tensor[], saved: Tensor[], attrs: NamedAttrMap) => {\n const {axis} = attrs as {} as SplitVAttrs;\n\n return {x: () => concat(dy, axis)};\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 {Sqrt} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {div} from '../ops/div';\nimport {mul} from '../ops/mul';\nimport {sqrt} from '../ops/sqrt';\nimport {Tensor} from '../tensor';\n\nexport const sqrtGradConfig: GradConfig = {\n kernelName: Sqrt,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {x: () => div(dy, mul(sqrt(cast(x, 'float32')), 2))};\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 {Square} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cast} from '../ops/cast';\nimport {mul} from '../ops/mul';\nimport {Tensor} from '../tensor';\n\nexport const squareGradConfig: GradConfig = {\n kernelName: Square,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n return {x: () => mul(dy, mul(cast(x, 'float32'), 2))};\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 {SquaredDifference} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {sub} from '../ops/sub';\nimport {Tensor} from '../tensor';\n\nexport const squaredDifferenceGradConfig: GradConfig = {\n kernelName: SquaredDifference,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const two = scalar(2);\n const derA = () => mul(dy, mul(two, sub(a, b)));\n const derB = () => mul(dy, mul(two, sub(b, a)));\n return {a: derA, b: derB};\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 {Step} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const stepGradConfig: GradConfig = {\n kernelName: Step,\n gradFunc: (dy: Tensor) => {\n // TODO(manrajgrover): Return null for gradients when backprop supports\n // it.\n return {x: () => zerosLike(dy)};\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 {Sub} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport * as broadcast_util from '../ops/broadcast_util';\nimport {neg} from '../ops/neg';\nimport {reshape} from '../ops/reshape';\nimport {sum} from '../ops/sum';\nimport {Tensor} from '../tensor';\n\nexport const subGradConfig: GradConfig = {\n kernelName: Sub,\n inputsToSave: ['a', 'b'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [a, b] = saved;\n const outShape =\n broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);\n\n const derA = () => {\n let res = dy;\n const reduceAxes = broadcast_util.getReductionAxes(a.shape, outShape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(res, a.shape);\n };\n const derB = () => {\n let res = dy;\n const reduceAxes = broadcast_util.getReductionAxes(b.shape, outShape);\n if (reduceAxes.length > 0) {\n res = sum(res, reduceAxes);\n }\n return reshape(neg(res), b.shape);\n };\n\n return {a: derA, b: derB};\n }\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 {Sum, SumAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {mul} from '../ops/mul';\nimport {ones} from '../ops/ones';\nimport {reshape} from '../ops/reshape';\nimport {Tensor} from '../tensor';\nimport {parseAxisParam} from '../util';\n\nexport const sumGradConfig: GradConfig = {\n kernelName: Sum,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved;\n const expandedDyShape = x.shape.slice();\n const {axis} = attrs as {} as SumAttrs;\n\n const axes = parseAxisParam(axis, x.shape);\n axes.forEach(axis => {\n expandedDyShape[axis] = 1;\n });\n const expandedDy = reshape(dy, expandedDyShape);\n const derX = mul(expandedDy, ones(x.shape, 'float32'));\n\n return {x: () => derX};\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 {Tan} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {cos} from '../ops/cos';\nimport {div} from '../ops/div';\nimport {square} from '../ops/square';\nimport {Tensor} from '../tensor';\n\nexport const tanGradConfig: GradConfig = {\n kernelName: Tan,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [x] = saved;\n\n return {x: () => div(dy, square(cos(x)))};\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 {Tanh} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {mul} from '../ops/mul';\nimport {scalar} from '../ops/scalar';\nimport {square} from '../ops/square';\nimport {sub} from '../ops/sub';\nimport {Tensor} from '../tensor';\n\nexport const tanhGradConfig: GradConfig = {\n kernelName: Tanh,\n outputsToSave: [true],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [y] = saved;\n\n return {x: () => mul(sub(scalar(1), square(y)), dy)};\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 {Tile, TileAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {add} from '../ops/add';\nimport {slice} from '../ops/slice';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const tileGradConfig: GradConfig = {\n kernelName: Tile,\n inputsToSave: ['x'],\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const [x] = saved;\n const {reps} = attrs as unknown as TileAttrs;\n\n const derX = () => {\n let xGrad = zerosLike(x);\n // TODO(cais): Maybe reduce memory footprint by avoiding repeated\n // slicing.\n if (x.rank === 1) {\n for (let i = 0; i < reps[0]; ++i) {\n xGrad = add(xGrad, slice(dy, [i * x.shape[0]], [x.shape[0]]));\n }\n } else if (x.rank === 2) {\n for (let i = 0; i < reps[0]; ++i) {\n for (let j = 0; j < reps[1]; ++j) {\n xGrad = add(xGrad, slice(dy, [i * x.shape[0], j * x.shape[1]], [\n x.shape[0], x.shape[1]\n ]));\n }\n }\n } else if (x.rank === 3) {\n for (let i = 0; i < reps[0]; ++i) {\n for (let j = 0; j < reps[1]; ++j) {\n for (let k = 0; k < reps[2]; ++k) {\n xGrad =\n add(xGrad,\n slice(\n dy, [i * x.shape[0], j * x.shape[1], k * x.shape[2]],\n [x.shape[0], x.shape[1], x.shape[2]]));\n }\n }\n }\n } else if (x.rank === 4) {\n for (let i = 0; i < reps[0]; ++i) {\n for (let j = 0; j < reps[1]; ++j) {\n for (let k = 0; k < reps[2]; ++k) {\n for (let l = 0; l < reps[3]; ++l) {\n xGrad =\n add(xGrad,\n slice(\n dy,\n [\n i * x.shape[0], j * x.shape[1], k * x.shape[2],\n l * x.shape[3]\n ],\n [x.shape[0], x.shape[1], x.shape[2], x.shape[3]]));\n }\n }\n }\n }\n } else {\n throw new Error(\n `Gradient for tile operation is not implemented for rank-` +\n `${x.rank} tensors yet.`);\n }\n return xGrad;\n };\n return {x: derX};\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 {Transpose, TransposeAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport * as axis_util from '../ops/axis_util';\nimport {transpose} from '../ops/transpose';\nimport {Tensor} from '../tensor';\n\nexport const transposeGradConfig: GradConfig = {\n kernelName: Transpose,\n gradFunc: (dy: Tensor, saved: Tensor[], attrs: NamedAttrMap) => {\n const transposeAttrs: TransposeAttrs = attrs as {} as TransposeAttrs;\n const {perm} = transposeAttrs;\n const undoPerm = axis_util.getUndoAxesPermutation(perm);\n return {x: () => transpose(dy, undoPerm)};\n }\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 {Unpack, UnpackAttrs} from '../kernel_names';\nimport {GradConfig, NamedAttrMap} from '../kernel_registry';\nimport {stack} from '../ops/stack';\nimport {Tensor} from '../tensor';\n\nexport const unpackGradConfig: GradConfig = {\n kernelName: Unpack,\n gradFunc: (dy: Tensor[], saved: Tensor[], attrs: NamedAttrMap) => {\n const unpackAttrs: UnpackAttrs = attrs as {} as UnpackAttrs;\n const {axis} = unpackAttrs;\n return {value: () => stack(dy, axis)};\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 {UnsortedSegmentSum} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {expandDims} from '../ops/expand_dims';\nimport {gather} from '../ops/gather';\nimport {greaterEqual} from '../ops/greater_equal';\nimport {logicalAnd} from '../ops/logical_and';\nimport {maximum} from '../ops/maximum';\nimport {ones} from '../ops/ones';\nimport {scalar} from '../ops/scalar';\nimport {where} from '../ops/where';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor, Tensor1D} from '../tensor';\n\nexport const unsortedSegmentSumGradConfig: GradConfig = {\n kernelName: UnsortedSegmentSum,\n inputsToSave: ['segmentIds'],\n gradFunc: (dy: Tensor, saved: Tensor[]) => {\n const [segmentIds] = saved;\n\n const derX = () => {\n return gatherDropNegatives(dy, segmentIds as Tensor1D);\n };\n return {x: derX};\n }\n};\n\nfunction gatherDropNegatives<T extends Tensor>(x: T, indices: Tensor1D) {\n // Helper function for unsorted segment ops. Gathers params for\n // positive segment ids and gathers 0 for inputs with negative segment id.\n // Mirrors _GatherDropNegatives from tensorflow/python/ops/math_grad.py\n const zeroClippedIndices = maximum(indices, zerosLike(indices));\n const gathered = gather(x, zeroClippedIndices as Tensor1D);\n let isPositive = greaterEqual(indices, scalar(0, 'int32'));\n const numIters = gathered.rank - isPositive.rank;\n for (let i = 0; i < numIters; ++i) {\n isPositive = expandDims(isPositive, i + 1);\n }\n isPositive = logicalAnd(isPositive, ones(gathered.shape, 'bool'));\n const zeroSlice = zerosLike(gathered);\n return where(isPositive, gathered, zeroSlice);\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 {ZerosLike} from '../kernel_names';\nimport {GradConfig} from '../kernel_registry';\nimport {zerosLike} from '../ops/zeros_like';\nimport {Tensor} from '../tensor';\n\nexport const zerosLikeGradConfig: GradConfig = {\n kernelName: ZerosLike,\n gradFunc: (dy: Tensor) => {\n return {x: () => zerosLike(dy)};\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 {absGradConfig} from './gradients/Abs_grad';\nimport {acosGradConfig} from './gradients/Acos_grad';\nimport {acoshGradConfig} from './gradients/Acosh_grad';\nimport {addGradConfig} from './gradients/Add_grad';\nimport {addNGradConfig} from './gradients/AddN_grad';\nimport {argMaxGradConfig} from './gradients/ArgMax_grad';\nimport {argMinGradConfig} from './gradients/ArgMin_grad';\nimport {asinGradConfig} from './gradients/Asin_grad';\nimport {asinhGradConfig} from './gradients/Asinh_grad';\nimport {atan2GradConfig} from './gradients/Atan2_grad';\nimport {atanGradConfig} from './gradients/Atan_grad';\nimport {atanhGradConfig} from './gradients/Atanh_grad';\nimport {avgPool3DGradConfig} from './gradients/AvgPool3D_grad';\nimport {avgPoolGradConfig} from './gradients/AvgPool_grad';\nimport {batchMatMulGradConfig} from './gradients/BatchMatMul_grad';\nimport {batchToSpaceNDGradConfig} from './gradients/BatchToSpaceND_grad';\nimport {broadcastToGradConfig} from './gradients/BroadcastTo_grad';\nimport {castGradConfig} from './gradients/Cast_grad';\nimport {ceilGradConfig} from './gradients/Ceil_grad';\nimport {clipByValueGradConfig} from './gradients/ClipByValue_grad';\nimport {complexAbsGradConfig} from './gradients/ComplexAbs_grad';\nimport {concatGradConfig} from './gradients/Concat_grad';\nimport {conv2DGradConfig} from './gradients/Conv2D_grad';\nimport {conv2DBackpropInputGradConfig} from './gradients/Conv2DBackpropInput_grad';\nimport {conv3DGradConfig} from './gradients/Conv3D_grad';\nimport {cosGradConfig} from './gradients/Cos_grad';\nimport {coshGradConfig} from './gradients/Cosh_grad';\nimport {cumsumGradConfig} from './gradients/Cumsum_grad';\nimport {depthwiseConv2dNativeGradConfig} from './gradients/DepthwiseConv2dNative_grad';\nimport {dilation2dGradConfig} from './gradients/Dilation2D_grad';\nimport {eluGradConfig} from './gradients/Elu_grad';\nimport {erfGradConfig} from './gradients/Erf_grad';\nimport {expGradConfig} from './gradients/Exp_grad';\nimport {expandDimsGradConfig} from './gradients/ExpandDims_grad';\nimport {expm1GradConfig} from './gradients/Expm1_grad';\nimport {floorGradConfig} from './gradients/Floor_grad';\nimport {floorDivGradConfig} from './gradients/FloorDiv_grad';\nimport {fusedBatchNormGradConfig} from './gradients/FusedBatchNorm_grad';\nimport {gatherGradConfig} from './gradients/GatherV2_grad';\nimport {greaterEqualGradConfig} from './gradients/GreaterEqual_grad';\nimport {identityGradConfig} from './gradients/Identity_grad';\nimport {isFiniteGradConfig} from './gradients/IsFinite_grad';\nimport {isInfGradConfig} from './gradients/IsInf_grad';\nimport {isNanGradConfig} from './gradients/IsNan_grad';\nimport {leakyReluGradConfig} from './gradients/LeakyRelu_grad';\nimport {log1pGradConfig} from './gradients/Log1p_grad';\nimport {logGradConfig} from './gradients/Log_grad';\nimport {logSoftmaxGradConfig} from './gradients/LogSoftmax_grad';\nimport {lrnGradConfig} from './gradients/LRN_grad';\nimport {maxGradConfig} from './gradients/Max_grad';\nimport {maximumGradConfig} from './gradients/Maximum_grad';\nimport {maxPool3DGradConfig} from './gradients/MaxPool3D_grad';\nimport {maxPoolGradConfig} from './gradients/MaxPool_grad';\nimport {meanGradConfig} from './gradients/Mean_grad';\nimport {minGradConfig} from './gradients/Min_grad';\nimport {minimumGradConfig} from './gradients/Minimum_grad';\nimport {mirrorPadGradConfig} from './gradients/MirrorPad_grad';\nimport {modGradConfig} from './gradients/Mod_grad';\nimport {multiplyGradConfig} from './gradients/Multiply_grad';\nimport {negGradConfig} from './gradients/Neg_grad';\nimport {oneHotGradConfig} from './gradients/OneHot_grad';\nimport {onesLikeGradConfig} from './gradients/OnesLike_grad';\nimport {packGradConfig} from './gradients/Pack_grad';\nimport {padV2GradConfig} from './gradients/PadV2_grad';\nimport {powGradConfig} from './gradients/Pow_grad';\nimport {preluGradConfig} from './gradients/Prelu_grad';\nimport {divGradConfig} from './gradients/RealDiv_grad';\nimport {reciprocalGradConfig} from './gradients/Reciprocal_grad';\nimport {relu6GradConfig} from './gradients/Relu6_grad';\nimport {reluGradConfig} from './gradients/Relu_grad';\nimport {reshapeGradConfig} from './gradients/Reshape_grad';\nimport {resizeBilinearGradConfig} from './gradients/ResizeBilinear_grad';\nimport {resizeNearestNeighborGradConfig} from './gradients/ResizeNearestNeighbor_grad';\nimport {reverseGradConfig} from './gradients/Reverse_grad';\nimport {roundGradConfig} from './gradients/Round_grad';\nimport {rsqrtGradConfig} from './gradients/Rsqrt_grad';\nimport {selectGradConfig} from './gradients/Select_grad';\nimport {seluGradConfig} from './gradients/Selu_grad';\nimport {sigmoidGradConfig} from './gradients/Sigmoid_grad';\nimport {signGradConfig} from './gradients/Sign_grad';\nimport {sinGradConfig} from './gradients/Sin_grad';\nimport {sinhGradConfig} from './gradients/Sinh_grad';\nimport {sliceGradConfig} from './gradients/Slice_grad';\nimport {softmaxGradConfig} from './gradients/Softmax_grad';\nimport {softplusGradConfig} from './gradients/Softplus_grad';\nimport {spaceToBatchNDGradConfig} from './gradients/SpaceToBatchND_grad';\nimport {splitVGradConfig} from './gradients/SplitV_grad';\nimport {sqrtGradConfig} from './gradients/Sqrt_grad';\nimport {squareGradConfig} from './gradients/Square_grad';\nimport {squaredDifferenceGradConfig} from './gradients/SquaredDifference_grad';\nimport {stepGradConfig} from './gradients/Step_grad';\nimport {subGradConfig} from './gradients/Sub_grad';\nimport {sumGradConfig} from './gradients/Sum_grad';\nimport {tanGradConfig} from './gradients/Tan_grad';\nimport {tanhGradConfig} from './gradients/Tanh_grad';\nimport {tileGradConfig} from './gradients/Tile_grad';\nimport {transposeGradConfig} from './gradients/Transpose_grad';\nimport {unpackGradConfig} from './gradients/Unpack_grad';\nimport {unsortedSegmentSumGradConfig} from './gradients/UnsortedSegmentSum_grad';\nimport {zerosLikeGradConfig} from './gradients/ZerosLike_grad';\nimport {GradConfig} from './kernel_registry';\nimport {registerGradient} from './kernel_registry';\n\n// Export all kernel configs here so that the package can auto register them\nconst gradConfigs: GradConfig[] = [\n absGradConfig,\n acosGradConfig,\n acoshGradConfig,\n addGradConfig,\n addNGradConfig,\n argMaxGradConfig,\n argMinGradConfig,\n asinGradConfig,\n asinhGradConfig,\n atan2GradConfig,\n atanGradConfig,\n atanhGradConfig,\n avgPool3DGradConfig,\n avgPoolGradConfig,\n batchMatMulGradConfig,\n batchToSpaceNDGradConfig,\n broadcastToGradConfig,\n castGradConfig,\n ceilGradConfig,\n clipByValueGradConfig,\n complexAbsGradConfig,\n concatGradConfig,\n conv2DBackpropInputGradConfig,\n conv2DGradConfig,\n conv3DGradConfig,\n cosGradConfig,\n coshGradConfig,\n cumsumGradConfig,\n depthwiseConv2dNativeGradConfig,\n dilation2dGradConfig,\n divGradConfig,\n eluGradConfig,\n erfGradConfig,\n expGradConfig,\n expandDimsGradConfig,\n expm1GradConfig,\n floorDivGradConfig,\n floorGradConfig,\n fusedBatchNormGradConfig,\n gatherGradConfig,\n greaterEqualGradConfig,\n identityGradConfig,\n isFiniteGradConfig,\n isInfGradConfig,\n isNanGradConfig,\n leakyReluGradConfig,\n log1pGradConfig,\n logGradConfig,\n logSoftmaxGradConfig,\n lrnGradConfig,\n maxGradConfig,\n maxGradConfig,\n maximumGradConfig,\n maxPool3DGradConfig,\n maxPoolGradConfig,\n meanGradConfig,\n minGradConfig,\n minimumGradConfig,\n mirrorPadGradConfig,\n modGradConfig,\n multiplyGradConfig,\n negGradConfig,\n oneHotGradConfig,\n onesLikeGradConfig,\n packGradConfig,\n padV2GradConfig,\n padV2GradConfig,\n powGradConfig,\n preluGradConfig,\n reciprocalGradConfig,\n relu6GradConfig,\n reluGradConfig,\n reshapeGradConfig,\n resizeBilinearGradConfig,\n resizeNearestNeighborGradConfig,\n reverseGradConfig,\n roundGradConfig,\n rsqrtGradConfig,\n selectGradConfig,\n seluGradConfig,\n sigmoidGradConfig,\n signGradConfig,\n sinGradConfig,\n sinhGradConfig,\n sliceGradConfig,\n softmaxGradConfig,\n softplusGradConfig,\n spaceToBatchNDGradConfig,\n spaceToBatchNDGradConfig,\n splitVGradConfig,\n splitVGradConfig,\n sqrtGradConfig,\n squaredDifferenceGradConfig,\n squareGradConfig,\n stepGradConfig,\n subGradConfig,\n sumGradConfig,\n tanGradConfig,\n tanhGradConfig,\n tileGradConfig,\n transposeGradConfig,\n unpackGradConfig,\n unsortedSegmentSumGradConfig,\n zerosLikeGradConfig\n];\n\nfor (const gradientConfig of gradConfigs) {\n registerGradient(gradientConfig);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n// tslint:disable-next-line:max-line-length\nimport {Constraint, MaxNorm, MaxNormArgs, MinMaxNorm, MinMaxNormArgs, NonNeg, UnitNorm, UnitNormArgs} from './constraints';\n\n/**\n * MaxNorm weight constraint.\n *\n * Constrains the weights incident to each hidden unit\n * to have a norm less than or equal to a desired value.\n *\n * References\n * - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting\n * Srivastava, Hinton, et al.\n * 2014](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf)\n *\n * @doc {heading: 'Constraints',namespace: 'constraints'}\n */\nexport function maxNorm(args: MaxNormArgs): Constraint {\n return new MaxNorm(args);\n}\n\n/**\n * Constrains the weights incident to each hidden unit to have unit norm.\n *\n * @doc {heading: 'Constraints', namespace: 'constraints'}\n */\nexport function unitNorm(args: UnitNormArgs): Constraint {\n return new UnitNorm(args);\n}\n\n/**\n * Constains the weight to be non-negative.\n *\n * @doc {heading: 'Constraints', namespace: 'constraints'}\n */\nexport function nonNeg(): Constraint {\n return new NonNeg();\n}\n\n/** @doc {heading: 'Constraints', namespace: 'constraints'} */\nexport function minMaxNorm(config: MinMaxNormArgs): Constraint {\n return new MinMaxNorm(config);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {backend} from '@tensorflow/tfjs-core';\nimport {DataFormat} from '../keras_format/common';\n\nlet _epsilon: number;\n\n/**\n * Returns the value of the fuzz factor used in numeric expressions.\n */\nexport function epsilon() {\n if (_epsilon == null) {\n _epsilon = backend().epsilon();\n }\n return _epsilon;\n}\n\n/**\n * Sets the value of the fuzz factor used in numeric expressions.\n * @param e New value of epsilon.\n */\nexport function setEpsilon(e: number) {\n _epsilon = e;\n}\n\n/**\n * Returns the default image data format convention.\n */\nexport function imageDataFormat(): DataFormat {\n return 'channelsLast';\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Explicit error types.\n *\n * See the following link for more information about why the code includes\n * calls to setPrototypeOf:\n *\n * https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n */\n// tslint:enable\n\n/**\n * Equivalent of Python's AttributeError.\n */\nexport class AttributeError extends Error {\n constructor(message?: string) {\n super(message);\n // Set the prototype explicitly.\n Object.setPrototypeOf(this, AttributeError.prototype);\n }\n}\n\n/**\n * Equivalent of Python's RuntimeError.\n */\nexport class RuntimeError extends Error {\n constructor(message?: string) {\n super(message);\n // Set the prototype explicitly.\n Object.setPrototypeOf(this, RuntimeError.prototype);\n }\n}\n\n/**\n * Equivalent of Python's ValueError.\n */\nexport class ValueError extends Error {\n constructor(message?: string) {\n super(message);\n // Set the prototype explicitly.\n Object.setPrototypeOf(this, ValueError.prototype);\n }\n}\n\n/**\n * Equivalent of Python's NotImplementedError.\n */\nexport class NotImplementedError extends Error {\n constructor(message?: string) {\n super(message);\n // Set the prototype explicitly.\n Object.setPrototypeOf(this, NotImplementedError.prototype);\n }\n}\n\n/**\n * Equivalent of Python's AssertionError.\n */\nexport class AssertionError extends Error {\n constructor(message?: string) {\n super(message);\n // Set the prototype explicitly.\n Object.setPrototypeOf(this, AssertionError.prototype);\n }\n}\n\n/**\n * Equivalent of Python's IndexError.\n */\nexport class IndexError extends Error {\n constructor(message?: string) {\n super(message);\n // Set the prototype explicitly.\n Object.setPrototypeOf(this, IndexError.prototype);\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: utils/generic_utils.py */\n\nimport {DataType, fused, serialization, util} from '@tensorflow/tfjs-core';\n\nimport {AssertionError, ValueError} from '../errors';\n\n// tslint:enable\n\n/**\n * If `value` is an Array, equivalent to Python's `value * numValues`.\n * If `value` is not an Array, equivalent to Python's `[value] * numValues`\n */\n// tslint:disable-next-line:no-any\nexport function pyListRepeat(value: any, numValues: number): any[] {\n if (Array.isArray(value)) {\n // tslint:disable-next-line:no-any\n let newArray: any[] = [];\n for (let i = 0; i < numValues; i++) {\n newArray = newArray.concat(value);\n }\n return newArray;\n } else {\n const newArray = new Array(numValues);\n newArray.fill(value);\n return newArray;\n }\n}\n\nexport function assert(val: boolean, message?: string): void {\n if (!val) {\n throw new AssertionError(message);\n }\n}\n\n/**\n * Count the number of elements of the `array` that are equal to `reference`.\n */\nexport function count<T>(array: T[], refernce: T) {\n let counter = 0;\n for (const item of array) {\n if (item === refernce) {\n counter++;\n }\n }\n return counter;\n}\n\n/**\n * If an array is of length 1, just return the first element. Otherwise, return\n * the full array.\n * @param tensors\n */\nexport function singletonOrArray<T>(xs: T[]): T|T[] {\n if (xs.length === 1) {\n return xs[0];\n }\n return xs;\n}\n\n/**\n * Normalizes a list/tensor into a list.\n *\n * If a tensor is passed, we return\n * a list of size 1 containing the tensor.\n *\n * @param x target object to be normalized.\n */\n// tslint:disable-next-line:no-any\nexport function toList(x: any): any[] {\n if (Array.isArray(x)) {\n return x;\n }\n return [x];\n}\n\n/**\n * Generate a UID for a list\n */\n// tslint:disable-next-line:no-any\nexport function objectListUid(objs: any|any[]): string {\n const objectList = toList(objs);\n let retVal = '';\n for (const obj of objectList) {\n if (obj.id == null) {\n throw new ValueError(\n `Object ${obj} passed to objectListUid without an id`);\n }\n if (retVal !== '') {\n retVal = retVal + ', ';\n }\n retVal = `${retVal}${Math.abs(obj.id)}`;\n }\n return retVal;\n}\n/**\n * Converts string to snake-case.\n * @param name\n */\nexport function toSnakeCase(name: string): string {\n const intermediate = name.replace(/(.)([A-Z][a-z0-9]+)/g, '$1_$2');\n const insecure =\n intermediate.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();\n /*\n If the class is private the name starts with \"_\" which is not secure\n for creating scopes. We prefix the name with \"private\" in this case.\n */\n if (insecure[0] !== '_') {\n return insecure;\n }\n return 'private' + insecure;\n}\n\nexport function toCamelCase(identifier: string): string {\n // quick return for empty string or single character strings\n if (identifier.length <= 1) {\n return identifier;\n }\n // Check for the underscore indicating snake_case\n if (identifier.indexOf('_') === -1) {\n return identifier;\n }\n return identifier.replace(/[_]+(\\w|$)/g, (m, p1) => p1.toUpperCase());\n}\n\n// tslint:disable-next-line:no-any\nlet _GLOBAL_CUSTOM_OBJECTS = {} as {[objName: string]: any};\n\nexport function serializeKerasObject(instance: serialization.Serializable):\n serialization.ConfigDictValue {\n if (instance === null || instance === undefined) {\n return null;\n }\n const dict: serialization.ConfigDictValue = {};\n dict['className'] = instance.getClassName();\n dict['config'] = instance.getConfig();\n return dict;\n}\n\n/**\n * Replace ndarray-style scalar objects in serialization objects with numbers.\n *\n * Background: In some versions of tf.keras, certain scalar values in the HDF5\n * model save file can be serialized as: `{'type': 'ndarray', 'value': num}`,\n * where in `num` is a plain number. This method converts such serialization\n * to a `number`.\n *\n * @param config The keras-format serialization object to be processed\n * (in place).\n */\nfunction convertNDArrayScalarsInConfig(config: serialization.ConfigDictValue):\n void {\n if (config == null || typeof config !== 'object') {\n return;\n } else if (Array.isArray(config)) {\n config.forEach(configItem => convertNDArrayScalarsInConfig(configItem));\n } else {\n const fields = Object.keys(config);\n for (const field of fields) {\n const value = config[field];\n if (value != null && typeof value === 'object') {\n if (!Array.isArray(value) && value['type'] === 'ndarray' &&\n typeof value['value'] === 'number') {\n config[field] = value['value'];\n } else {\n convertNDArrayScalarsInConfig(value as serialization.ConfigDict);\n }\n }\n }\n }\n}\n\n/**\n * Deserialize a saved Keras Object\n * @param identifier either a string ID or a saved Keras dictionary\n * @param moduleObjects a list of Python class names to object constructors\n * @param customObjects a list of Python class names to object constructors\n * @param printableModuleName debug text for the object being reconstituted\n * @param fastWeightInit Optional flag to use fast weight initialization\n * during deserialization. This is applicable to cases in which\n * the initialization will be immediately overwritten by loaded weight\n * values. Default: `false`.\n * @returns a TensorFlow.js Layers object\n */\n// tslint:disable:no-any\nexport function deserializeKerasObject(\n identifier: string|serialization.ConfigDict,\n moduleObjects = {} as {[objName: string]: any},\n customObjects = {} as {[objName: string]: any},\n printableModuleName = 'object', fastWeightInit = false): any {\n // tslint:enable\n if (typeof identifier === 'string') {\n const functionName = identifier;\n let fn;\n if (functionName in customObjects) {\n fn = customObjects[functionName];\n } else if (functionName in _GLOBAL_CUSTOM_OBJECTS) {\n fn = _GLOBAL_CUSTOM_OBJECTS[functionName];\n } else {\n fn = moduleObjects[functionName];\n if (fn == null) {\n throw new ValueError(\n `Unknown ${printableModuleName}: ${identifier}. ` +\n `This may be due to one of the following reasons:\\n` +\n `1. The ${printableModuleName} is defined in Python, in which ` +\n `case it needs to be ported to TensorFlow.js or your JavaScript ` +\n `code.\\n` +\n `2. The custom ${printableModuleName} is defined in JavaScript, ` +\n `but is not registered properly with ` +\n `tf.serialization.registerClass().`);\n // TODO(cais): Add link to tutorial page on custom layers.\n }\n }\n return fn;\n } else {\n // In this case we are dealing with a Keras config dictionary.\n const config = identifier;\n if (config['className'] == null || config['config'] == null) {\n throw new ValueError(\n `${printableModuleName}: Improper config format: ` +\n `${JSON.stringify(config)}.\\n` +\n `'className' and 'config' must set.`);\n }\n const className = config['className'] as string;\n let cls, fromConfig;\n if (className in customObjects) {\n [cls, fromConfig] = customObjects[className];\n } else if (className in _GLOBAL_CUSTOM_OBJECTS) {\n [cls, fromConfig] = _GLOBAL_CUSTOM_OBJECTS['className'];\n } else if (className in moduleObjects) {\n [cls, fromConfig] = moduleObjects[className];\n }\n if (cls == null) {\n throw new ValueError(\n `Unknown ${printableModuleName}: ${className}. ` +\n `This may be due to one of the following reasons:\\n` +\n `1. The ${printableModuleName} is defined in Python, in which ` +\n `case it needs to be ported to TensorFlow.js or your JavaScript ` +\n `code.\\n` +\n `2. The custom ${printableModuleName} is defined in JavaScript, ` +\n `but is not registered properly with ` +\n `tf.serialization.registerClass().`);\n // TODO(cais): Add link to tutorial page on custom layers.\n }\n if (fromConfig != null) {\n // Porting notes: Instead of checking to see whether fromConfig accepts\n // customObjects, we create a customObjects dictionary and tack it on to\n // config['config'] as config['config'].customObjects. Objects can use it,\n // if they want.\n\n // tslint:disable-next-line:no-any\n const customObjectsCombined = {} as {[objName: string]: any};\n for (const key of Object.keys(_GLOBAL_CUSTOM_OBJECTS)) {\n customObjectsCombined[key] = _GLOBAL_CUSTOM_OBJECTS[key];\n }\n for (const key of Object.keys(customObjects)) {\n customObjectsCombined[key] = customObjects[key];\n }\n // Add the customObjects to config\n const nestedConfig = config['config'] as serialization.ConfigDict;\n nestedConfig['customObjects'] = customObjectsCombined;\n\n const backupCustomObjects = {..._GLOBAL_CUSTOM_OBJECTS};\n for (const key of Object.keys(customObjects)) {\n _GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key];\n }\n convertNDArrayScalarsInConfig(config['config']);\n const returnObj =\n fromConfig(cls, config['config'], customObjects, fastWeightInit);\n _GLOBAL_CUSTOM_OBJECTS = {...backupCustomObjects};\n\n return returnObj;\n } else {\n // Then `cls` may be a function returning a class.\n // In this case by convention `config` holds\n // the kwargs of the function.\n const backupCustomObjects = {..._GLOBAL_CUSTOM_OBJECTS};\n for (const key of Object.keys(customObjects)) {\n _GLOBAL_CUSTOM_OBJECTS[key] = customObjects[key];\n }\n // In python this is **config['config'], for tfjs-layers we require\n // classes that use this fall-through construction method to take\n // a config interface that mimics the expansion of named parameters.\n const returnObj = new cls(config['config']);\n _GLOBAL_CUSTOM_OBJECTS = {...backupCustomObjects};\n return returnObj;\n }\n }\n}\n\n/**\n * Compares two numbers for sorting.\n * @param a\n * @param b\n */\nexport function numberCompare(a: number, b: number) {\n return (a < b) ? -1 : ((a > b) ? 1 : 0);\n}\n\n/**\n * Comparison of two numbers for reverse sorting.\n * @param a\n * @param b\n */\nexport function reverseNumberCompare(a: number, b: number) {\n return -1 * numberCompare(a, b);\n}\n\n/**\n * Convert a string into the corresponding DType.\n * @param dtype\n * @returns An instance of DType.\n */\nexport function stringToDType(dtype: string): DataType {\n switch (dtype) {\n case 'float32':\n return 'float32';\n default:\n throw new ValueError(`Invalid dtype: ${dtype}`);\n }\n}\n\n/**\n * Test the element-by-element equality of two Arrays of strings.\n * @param xs First array of strings.\n * @param ys Second array of strings.\n * @returns Wether the two arrays are all equal, element by element.\n */\nexport function stringsEqual(xs: string[], ys: string[]): boolean {\n if (xs == null || ys == null) {\n return xs === ys;\n }\n if (xs.length !== ys.length) {\n return false;\n }\n for (let i = 0; i < xs.length; ++i) {\n if (xs[i] !== ys[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Get the unique elements of an array.\n * @param xs Array.\n * @returns An Array consisting of the unique elements in `xs`.\n */\nexport function unique<T>(xs: T[]): T[] {\n if (xs == null) {\n return xs;\n }\n const out: T[] = [];\n // TODO(cais): Maybe improve performance by sorting.\n for (const x of xs) {\n if (out.indexOf(x) === -1) {\n out.push(x);\n }\n }\n return out;\n}\n\n/**\n * Determine if an Object is empty (i.e., does not have own properties).\n * @param obj Object\n * @returns Whether the Object is empty.\n * @throws ValueError: If object is `null` or `undefined`.\n */\nexport function isObjectEmpty(obj: {}): boolean {\n if (obj == null) {\n throw new ValueError(`Invalid value in obj: ${JSON.stringify(obj)}`);\n }\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Helper function used to build type union/enum run-time checkers.\n * @param values The list of allowed values.\n * @param label A string name for the type\n * @param value The value to test.\n * @throws ValueError: If the value is not in values nor `undefined`/`null`.\n */\nexport function checkStringTypeUnionValue(\n values: string[], label: string, value: string): void {\n if (value == null) {\n return;\n }\n if (values.indexOf(value) < 0) {\n throw new ValueError(`${value} is not a valid ${label}. Valid values are ${\n values} or null/undefined.`);\n }\n}\n\n/**\n * Helper function for verifying the types of inputs.\n *\n * Ensures that the elements of `x` are all of type `expectedType`.\n * Also verifies that the length of `x` is within bounds.\n *\n * @param x Object to test.\n * @param expectedType The string expected type of all of the elements in the\n * Array.\n * @param minLength Return false if x.length is less than this.\n * @param maxLength Return false if x.length is greater than this.\n * @returns true if and only if `x` is an `Array<expectedType>` with\n * length >= `minLength` and <= `maxLength`.\n */\n// tslint:disable:no-any\nexport function checkArrayTypeAndLength(\n x: any, expectedType: string, minLength = 0,\n maxLength = Infinity): boolean {\n assert(minLength >= 0);\n assert(maxLength >= minLength);\n return (\n Array.isArray(x) && x.length >= minLength && x.length <= maxLength &&\n x.every(e => typeof e === expectedType));\n}\n// tslint:enable:no-any\n\n/**\n * Assert that a value or an array of value are positive integer.\n *\n * @param value The value being asserted on. May be a single number or an array\n * of numbers.\n * @param name Name of the value, used to make the error message.\n */\nexport function assertPositiveInteger(value: number|number[], name: string) {\n if (Array.isArray(value)) {\n util.assert(\n value.length > 0, () => `${name} is unexpectedly an empty array.`);\n value.forEach(\n (v, i) => assertPositiveInteger(v, `element ${i + 1} of ${name}`));\n } else {\n util.assert(\n Number.isInteger(value) && value > 0,\n () => `Expected ${name} to be a positive integer, but got ` +\n `${formatAsFriendlyString(value)}.`);\n }\n}\n\n/**\n * Format a value into a display-friendly, human-readable fashion.\n *\n * - `null` is formatted as `'null'`\n * - Strings are formated with flanking pair of quotes.\n * - Arrays are formatted with flanking pair of square brackets.\n *\n * @param value The value to display.\n * @return Formatted string.\n */\n// tslint:disable-next-line:no-any\nexport function formatAsFriendlyString(value: any): string {\n if (value === null) {\n return 'null';\n } else if (Array.isArray(value)) {\n return '[' + value.map(v => formatAsFriendlyString(v)).join(',') + ']';\n } else if (typeof value === 'string') {\n return `\"${value}\"`;\n } else {\n return `${value}`;\n }\n}\n\n/**\n * Returns a function `f2` (decorator) which wraps the original function\n * `f`. `f2` guarantees that `f` can be called at most once\n * every `waitMs` ms. If `f2` is called more often, it will return\n * the last returned result of `f`.\n *\n * @param f The original function `f` to wrap.\n * @param waitMs The time between two consecutive calls to `f` in ms.\n */\nexport function debounce<T>(\n f: (...args: Array<{}>) => T, waitMs: number): (...args: Array<{}>) => T {\n let lastTime = util.now();\n let lastResult: T;\n const f2 = (...args: Array<{}>) => {\n const now = util.now();\n if (now - lastTime < waitMs) {\n return lastResult;\n }\n lastTime = now;\n lastResult = f(...args);\n return lastResult;\n };\n return f2;\n}\n\n/**\n * Returns the fusable activation given a layers identifier.\n *\n * @param activationName The layers identifier string.\n * @return The name of the fusable activation.\n */\nexport function mapActivationToFusedKernel(activationName: string):\n fused.Activation {\n if (activationName === 'relu') {\n return 'relu';\n }\n if (activationName === 'linear') {\n return 'linear';\n }\n if (activationName === 'elu') {\n return 'elu';\n }\n return null;\n}\n\ntype PossibleValues = Array<Array<boolean|string|number>>;\n\n/**\n * Returns the cartesian product of sets of values.\n * This works the same as itertools.product in Python.\n *\n * Example:\n *\n * filters = [128, 256, 512]\n * paddings = ['same', 'valid']\n *\n * product = [ [128, 'same'], [128, 'valid'], [256, 'same'], [256, 'valid'],\n * [512, 'same'], [512, 'valid']]\n *\n * @param arrayOfValues List/array of values.\n * @return The cartesian product.\n */\nexport function getCartesianProductOfValues(...arrayOfValues: PossibleValues):\n PossibleValues {\n assert(arrayOfValues.length > 0, 'arrayOfValues is empty');\n\n for (const values of arrayOfValues) {\n assert(Array.isArray(values), 'one of the values is not an array');\n assert(values.length > 0, 'one of the values is empty');\n }\n\n return arrayOfValues.reduce((products, values) => {\n if (products.length === 0) {\n return values.map(value => [value]);\n }\n\n return values\n .map(value => {\n return products.map((prevValue) => [...prevValue, value]);\n })\n .reduce((flattenedProduct, unflattenedProduct) => {\n return flattenedProduct.concat(unflattenedProduct);\n }, []);\n }, [] as PossibleValues);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: keras/contraints.py */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {serialization, Tensor, tidy} from '@tensorflow/tfjs-core';\nimport {epsilon} from './backend/common';\nimport {deserializeKerasObject, serializeKerasObject} from './utils/generic_utils';\n\n/**\n * Helper function used by many of the Constraints to find the L2Norms.\n */\nfunction calcL2Norms(w: Tensor, axis: number): Tensor {\n return tidy(() => tfc.sqrt(tfc.sum(tfc.mul(w, w), axis, true)));\n}\n\n/**\n * Base class for functions that impose constraints on weight values\n *\n * @doc {\n * heading: 'Constraints',\n * subheading: 'Classes',\n * namespace: 'constraints'\n * }\n */\nexport abstract class Constraint extends serialization.Serializable {\n /* Porting note: was __call__, apply chosen to match other similar choices */\n abstract apply(w: Tensor): Tensor;\n getConfig(): serialization.ConfigDict {\n return {};\n }\n}\n\nexport interface MaxNormArgs {\n /**\n * Maximum norm for incoming weights\n */\n maxValue?: number;\n /**\n * Axis along which to calculate norms.\n *\n * For instance, in a `Dense` layer the weight matrix\n * has shape `[inputDim, outputDim]`,\n * set `axis` to `0` to constrain each weight vector\n * of length `[inputDim,]`.\n * In a `Conv2D` layer with `dataFormat=\"channels_last\"`,\n * the weight tensor has shape\n * `[rows, cols, inputDepth, outputDepth]`,\n * set `axis` to `[0, 1, 2]`\n * to constrain the weights of each filter tensor of size\n * `[rows, cols, inputDepth]`.\n */\n axis?: number;\n}\n\nexport class MaxNorm extends Constraint {\n /** @nocollapse */\n static readonly className = 'MaxNorm';\n private maxValue: number;\n private axis: number;\n private readonly defaultMaxValue = 2;\n private readonly defaultAxis = 0;\n\n constructor(args: MaxNormArgs) {\n super();\n this.maxValue =\n args.maxValue != null ? args.maxValue : this.defaultMaxValue;\n this.axis = args.axis != null ? args.axis : this.defaultAxis;\n }\n\n apply(w: Tensor): Tensor {\n return tidy(() => {\n const norms = calcL2Norms(w, this.axis);\n const desired = tfc.clipByValue(norms, 0, this.maxValue);\n return tfc.mul(w, tfc.div(desired, tfc.add(epsilon(), norms)));\n });\n }\n\n getConfig(): serialization.ConfigDict {\n return {maxValue: this.maxValue, axis: this.axis};\n }\n}\nserialization.registerClass(MaxNorm);\n\nexport interface UnitNormArgs {\n /**\n * Axis along which to calculate norms.\n *\n * For instance, in a `Dense` layer the weight matrix\n * has shape `[inputDim, outputDim]`,\n * set `axis` to `0` to constrain each weight vector\n * of length `[inputDim,]`.\n * In a `Conv2D` layer with `dataFormat=\"channels_last\"`,\n * the weight tensor has shape\n * [rows, cols, inputDepth, outputDepth]`,\n * set `axis` to `[0, 1, 2]`\n * to constrain the weights of each filter tensor of size\n * `[rows, cols, inputDepth]`.\n */\n axis?: number;\n}\n\nexport class UnitNorm extends Constraint {\n /** @nocollapse */\n static readonly className = 'UnitNorm';\n private axis: number;\n private readonly defaultAxis = 0;\n constructor(args: UnitNormArgs) {\n super();\n this.axis = args.axis != null ? args.axis : this.defaultAxis;\n }\n\n apply(w: Tensor): Tensor {\n return tidy(\n () => tfc.div(w, tfc.add(epsilon(), calcL2Norms(w, this.axis))));\n }\n\n getConfig(): serialization.ConfigDict {\n return {axis: this.axis};\n }\n}\nserialization.registerClass(UnitNorm);\n\nexport class NonNeg extends Constraint {\n /** @nocollapse */\n static readonly className = 'NonNeg';\n\n apply(w: Tensor): Tensor {\n return tfc.relu(w);\n }\n}\nserialization.registerClass(NonNeg);\n\nexport interface MinMaxNormArgs {\n /**\n * Minimum norm for incoming weights\n */\n minValue?: number;\n /**\n * Maximum norm for incoming weights\n */\n maxValue?: number;\n /**\n * Axis along which to calculate norms.\n * For instance, in a `Dense` layer the weight matrix\n * has shape `[inputDim, outputDim]`,\n * set `axis` to `0` to constrain each weight vector\n * of length `[inputDim,]`.\n * In a `Conv2D` layer with `dataFormat=\"channels_last\"`,\n * the weight tensor has shape\n * `[rows, cols, inputDepth, outputDepth]`,\n * set `axis` to `[0, 1, 2]`\n * to constrain the weights of each filter tensor of size\n * `[rows, cols, inputDepth]`.\n */\n axis?: number;\n /**\n * Rate for enforcing the constraint: weights will be rescaled to yield:\n * `(1 - rate) * norm + rate * norm.clip(minValue, maxValue)`.\n * Effectively, this means that rate=1.0 stands for strict\n * enforcement of the constraint, while rate<1.0 means that\n * weights will be rescaled at each step to slowly move\n * towards a value inside the desired interval.\n */\n rate?: number;\n}\n\nexport class MinMaxNorm extends Constraint {\n /** @nocollapse */\n static readonly className = 'MinMaxNorm';\n private minValue: number;\n private maxValue: number;\n private rate: number;\n private axis: number;\n private readonly defaultMinValue = 0.0;\n private readonly defaultMaxValue = 1.0;\n private readonly defaultRate = 1.0;\n private readonly defaultAxis = 0;\n\n constructor(args: MinMaxNormArgs) {\n super();\n this.minValue =\n args.minValue != null ? args.minValue : this.defaultMinValue;\n this.maxValue =\n args.maxValue != null ? args.maxValue : this.defaultMaxValue;\n this.rate = args.rate != null ? args.rate : this.defaultRate;\n this.axis = args.axis != null ? args.axis : this.defaultAxis;\n }\n\n apply(w: Tensor): Tensor {\n return tidy(() => {\n const norms = calcL2Norms(w, this.axis);\n const desired = tfc.add(\n tfc.mul(\n this.rate, tfc.clipByValue(norms, this.minValue, this.maxValue)),\n tfc.mul(1.0 - this.rate, norms));\n return tfc.mul(w, tfc.div(desired, tfc.add(epsilon(), norms)));\n });\n }\n\n getConfig(): serialization.ConfigDict {\n return {\n minValue: this.minValue,\n maxValue: this.maxValue,\n rate: this.rate,\n axis: this.axis\n };\n }\n}\nserialization.registerClass(MinMaxNorm);\n\n/** @docinline */\nexport type ConstraintIdentifier =\n 'maxNorm'|'minMaxNorm'|'nonNeg'|'unitNorm'|string;\n\n// Maps the JavaScript-like identifier keys to the corresponding registry\n// symbols.\nexport const CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP:\n {[identifier in ConstraintIdentifier]: string} = {\n 'maxNorm': 'MaxNorm',\n 'minMaxNorm': 'MinMaxNorm',\n 'nonNeg': 'NonNeg',\n 'unitNorm': 'UnitNorm'\n };\n\nexport function serializeConstraint(constraint: Constraint):\n serialization.ConfigDictValue {\n return serializeKerasObject(constraint);\n}\n\nexport function deserializeConstraint(\n config: serialization.ConfigDict,\n customObjects: serialization.ConfigDict = {}): Constraint {\n return deserializeKerasObject(\n config, serialization.SerializationMap.getMap().classNameMap,\n customObjects, 'constraint');\n}\n\nexport function getConstraint(identifier: ConstraintIdentifier|\n serialization.ConfigDict|Constraint): Constraint {\n if (identifier == null) {\n return null;\n }\n if (typeof identifier === 'string') {\n const className = identifier in CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP ?\n CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] :\n identifier;\n const config = {className, config: {}};\n return deserializeConstraint(config);\n } else if (identifier instanceof Constraint) {\n return identifier;\n } else {\n return deserializeConstraint(identifier);\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n// tslint:disable-next-line:max-line-length\nimport {Constant, ConstantArgs, GlorotNormal, GlorotUniform, HeNormal, HeUniform, Identity, IdentityArgs, Initializer, LeCunNormal, LeCunUniform, Ones, Orthogonal, OrthogonalArgs, RandomNormal, RandomNormalArgs, RandomUniform, RandomUniformArgs, SeedOnlyInitializerArgs, TruncatedNormal, TruncatedNormalArgs, VarianceScaling, VarianceScalingArgs, Zeros} from './initializers';\n\n/**\n * Initializer that generates tensors initialized to 0.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function zeros(): Zeros {\n return new Zeros();\n}\n\n/**\n * Initializer that generates tensors initialized to 1.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function ones(): Initializer {\n return new Ones();\n}\n\n/**\n * Initializer that generates values initialized to some constant.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function constant(args: ConstantArgs): Initializer {\n return new Constant(args);\n}\n\n/**\n * Initializer that generates random values initialized to a uniform\n * distribution.\n *\n * Values will be distributed uniformly between the configured minval and\n * maxval.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function randomUniform(args: RandomUniformArgs): Initializer {\n return new RandomUniform(args);\n}\n\n/**\n * Initializer that generates random values initialized to a normal\n * distribution.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function randomNormal(args: RandomNormalArgs): Initializer {\n return new RandomNormal(args);\n}\n\n/**\n * Initializer that generates random values initialized to a truncated normal.\n * distribution.\n *\n * These values are similar to values from a `RandomNormal` except that values\n * more than two standard deviations from the mean are discarded and re-drawn.\n * This is the recommended initializer for neural network weights and filters.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function truncatedNormal(args: TruncatedNormalArgs): Initializer {\n return new TruncatedNormal(args);\n}\n\n/**\n * Initializer that generates the identity matrix.\n * Only use for square 2D matrices.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function identity(args: IdentityArgs): Initializer {\n return new Identity(args);\n}\n\n/**\n * Initializer capable of adapting its scale to the shape of weights.\n * With distribution=NORMAL, samples are drawn from a truncated normal\n * distribution centered on zero, with `stddev = sqrt(scale / n)` where n is:\n * - number of input units in the weight tensor, if mode = FAN_IN.\n * - number of output units, if mode = FAN_OUT.\n * - average of the numbers of input and output units, if mode = FAN_AVG.\n * With distribution=UNIFORM,\n * samples are drawn from a uniform distribution\n * within [-limit, limit], with `limit = sqrt(3 * scale / n)`.\n *\n * @doc {heading: 'Initializers',namespace: 'initializers'}\n */\nexport function varianceScaling(config: VarianceScalingArgs): Initializer {\n return new VarianceScaling(config);\n}\n\n/**\n * Glorot uniform initializer, also called Xavier uniform initializer.\n * It draws samples from a uniform distribution within [-limit, limit]\n * where `limit` is `sqrt(6 / (fan_in + fan_out))`\n * where `fan_in` is the number of input units in the weight tensor\n * and `fan_out` is the number of output units in the weight tensor\n *\n * Reference:\n * Glorot & Bengio, AISTATS 2010\n * http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function glorotUniform(args: SeedOnlyInitializerArgs): Initializer {\n return new GlorotUniform(args);\n}\n\n/**\n * Glorot normal initializer, also called Xavier normal initializer.\n * It draws samples from a truncated normal distribution centered on 0\n * with `stddev = sqrt(2 / (fan_in + fan_out))`\n * where `fan_in` is the number of input units in the weight tensor\n * and `fan_out` is the number of output units in the weight tensor.\n *\n * Reference:\n * Glorot & Bengio, AISTATS 2010\n * http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function glorotNormal(args: SeedOnlyInitializerArgs): Initializer {\n return new GlorotNormal(args);\n}\n\n/**\n * He normal initializer.\n *\n * It draws samples from a truncated normal distribution centered on 0\n * with `stddev = sqrt(2 / fanIn)`\n * where `fanIn` is the number of input units in the weight tensor.\n *\n * Reference:\n * He et al., http://arxiv.org/abs/1502.01852\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function heNormal(args: SeedOnlyInitializerArgs): Initializer {\n return new HeNormal(args);\n}\n\n/**\n * He uniform initializer.\n *\n * It draws samples from a uniform distribution within [-limit, limit]\n * where `limit` is `sqrt(6 / fan_in)`\n * where `fanIn` is the number of input units in the weight tensor.\n *\n * Reference:\n * He et al., http://arxiv.org/abs/1502.01852\n *\n * @doc {heading: 'Initializers',namespace: 'initializers'}\n */\nexport function heUniform(args: SeedOnlyInitializerArgs): Initializer {\n return new HeUniform(args);\n}\n\n/**\n * LeCun normal initializer.\n *\n * It draws samples from a truncated normal distribution centered on 0\n * with `stddev = sqrt(1 / fanIn)`\n * where `fanIn` is the number of input units in the weight tensor.\n *\n * References:\n * [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)\n * [Efficient Backprop](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function leCunNormal(args: SeedOnlyInitializerArgs): Initializer {\n return new LeCunNormal(args);\n}\n\n/**\n * LeCun uniform initializer.\n *\n * It draws samples from a uniform distribution in the interval\n * `[-limit, limit]` with `limit = sqrt(3 / fanIn)`,\n * where `fanIn` is the number of input units in the weight tensor.\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function leCunUniform(args: SeedOnlyInitializerArgs): Initializer {\n return new LeCunUniform(args);\n}\n\n/**\n * Initializer that generates a random orthogonal matrix.\n *\n * Reference:\n * [Saxe et al., http://arxiv.org/abs/1312.6120](http://arxiv.org/abs/1312.6120)\n *\n * @doc {heading: 'Initializers', namespace: 'initializers'}\n */\nexport function orthogonal(args: OrthogonalArgs): Initializer {\n return new Orthogonal(args);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n// TODO(huan): add layer-specific input shape types (see: https://github.com/tensorflow/tfjs-layers/pull/492)\n/** @docalias (null | number)[] */\nexport type Shape = Array<null | number>;\n\n// The tfjs-core version of DataType must stay synced with this.\nexport type DataType = 'float32'|'int32'|'bool'|'complex64'|'string';\n\n// TODO(soergel): Move the CamelCase versions back out of keras_format\n// e.g. to src/common.ts. Maybe even duplicate *all* of these to be pedantic?\n/** @docinline */\nexport type DataFormat = 'channelsFirst'|'channelsLast';\nexport const VALID_DATA_FORMAT_VALUES = ['channelsFirst', 'channelsLast'];\n\nexport type InterpolationFormat = 'nearest'|'bilinear';\nexport const VALID_INTERPOLATION_FORMAT_VALUES = ['nearest', 'bilinear'];\n// These constants have a snake vs. camel distinction.\nexport type DataFormatSerialization = 'channels_first'|'channels_last';\n\n/** @docinline */\nexport type PaddingMode = 'valid'|'same'|'causal';\nexport const VALID_PADDING_MODE_VALUES = ['valid', 'same', 'causal'];\n\n/** @docinline */\nexport type PoolMode = 'max'|'avg';\nexport const VALID_POOL_MODE_VALUES = ['max', 'avg'];\n\n/** @docinline */\nexport type BidirectionalMergeMode = 'sum'|'mul'|'concat'|'ave';\nexport const VALID_BIDIRECTIONAL_MERGE_MODES = ['sum', 'mul', 'concat', 'ave'];\n\n/** @docinline */\nexport type SampleWeightMode = 'temporal';\nexport const VALID_SAMPLE_WEIGHT_MODES = ['temporal'];\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Common functions for TensorFlow.js Layers.\n */\nimport {VALID_DATA_FORMAT_VALUES, VALID_INTERPOLATION_FORMAT_VALUES, VALID_PADDING_MODE_VALUES, VALID_POOL_MODE_VALUES} from './keras_format/common';\nimport {checkStringTypeUnionValue} from './utils/generic_utils';\n\n// A map from the requested scoped name of a Tensor to the number of Tensors\n// wanting that name so far. This allows enforcing name uniqueness by appending\n// an incrementing index, e.g. scope/name, scope/name_1, scope/name_2, etc.\nconst nameMap: Map<string, number> = new Map<string, number>();\n\nexport function checkDataFormat(value?: string): void {\n checkStringTypeUnionValue(VALID_DATA_FORMAT_VALUES, 'DataFormat', value);\n}\n\nexport function checkInterpolationFormat(value?: string): void {\n checkStringTypeUnionValue(\n VALID_INTERPOLATION_FORMAT_VALUES, 'InterpolationFormat', value);\n}\n\nexport function checkPaddingMode(value?: string): void {\n checkStringTypeUnionValue(VALID_PADDING_MODE_VALUES, 'PaddingMode', value);\n}\n\nexport function checkPoolMode(value?: string): void {\n checkStringTypeUnionValue(VALID_POOL_MODE_VALUES, 'PoolMode', value);\n}\n\nconst _nameScopeStack: string[] = [];\nconst _nameScopeDivider = '/';\n\n/**\n * Enter namescope, which can be nested.\n */\nexport function nameScope<T>(name: string, fn: () => T): T {\n _nameScopeStack.push(name);\n try {\n const val: T = fn();\n _nameScopeStack.pop();\n return val;\n } catch (e) {\n _nameScopeStack.pop();\n throw e;\n }\n}\n\n/**\n * Get the current namescope as a flat, concatenated string.\n */\nfunction currentNameScopePrefix(): string {\n if (_nameScopeStack.length === 0) {\n return '';\n } else {\n return _nameScopeStack.join(_nameScopeDivider) + _nameScopeDivider;\n }\n}\n\n/**\n * Get the name a Tensor (or Variable) would have if not uniqueified.\n * @param tensorName\n * @return Scoped name string.\n */\nexport function getScopedTensorName(tensorName: string): string {\n if (!isValidTensorName(tensorName)) {\n throw new Error('Not a valid tensor name: \\'' + tensorName + '\\'');\n }\n return currentNameScopePrefix() + tensorName;\n}\n\n/**\n * Get unique names for Tensors and Variables.\n * @param scopedName The fully-qualified name of the Tensor, i.e. as produced by\n * `getScopedTensorName()`.\n * @return A unique version of the given fully scoped name.\n * If this is the first time that the scoped name is seen in this session,\n * then the given `scopedName` is returned unaltered. If the same name is\n * seen again (producing a collision), an incrementing suffix is added to the\n * end of the name, so it takes the form 'scope/name_1', 'scope/name_2', etc.\n */\nexport function getUniqueTensorName(scopedName: string): string {\n if (!isValidTensorName(scopedName)) {\n throw new Error('Not a valid tensor name: \\'' + scopedName + '\\'');\n }\n if (!nameMap.has(scopedName)) {\n nameMap.set(scopedName, 0);\n }\n const index = nameMap.get(scopedName);\n nameMap.set(scopedName, nameMap.get(scopedName) + 1);\n\n if (index > 0) {\n const result = `${scopedName}_${index}`;\n // Mark the composed name as used in case someone wants\n // to call getUniqueTensorName(\"name_1\").\n nameMap.set(result, 1);\n return result;\n } else {\n return scopedName;\n }\n}\n\nconst tensorNameRegex = new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\\._\\/]*$/);\n\n/**\n * Determine whether a string is a valid tensor name.\n * @param name\n * @returns A Boolean indicating whether `name` is a valid tensor name.\n */\nexport function isValidTensorName(name: string): boolean {\n return !!name.match(tensorNameRegex);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Math utility functions.\n *\n * This file contains some frequently used math function that operates on\n * number[] or Float32Array and return a number. Many of these functions are\n * not-so-thick wrappers around TF.js Core functions. But they offer the\n * convenience of\n * 1) not having to convert the inputs into Tensors,\n * 2) not having to convert the returned Tensors to numbers.\n */\n\nimport {ValueError} from '../errors';\n\nexport type ArrayTypes = Uint8Array|Int32Array|Float32Array;\n\n/**\n * Determine if a number is an integer.\n */\nexport function isInteger(x: number): boolean {\n return x === parseInt(x.toString(), 10);\n}\n\n/**\n * Calculate the product of an array of numbers.\n * @param array The array to calculate the product over.\n * @param begin Beginning index, inclusive.\n * @param end Ending index, exclusive.\n * @return The product.\n */\nexport function arrayProd(\n array: number[]|ArrayTypes, begin?: number, end?: number): number {\n if (begin == null) {\n begin = 0;\n }\n if (end == null) {\n end = array.length;\n }\n\n let prod = 1;\n for (let i = begin; i < end; ++i) {\n prod *= array[i];\n }\n return prod;\n}\n\n/**\n * Compute minimum value.\n * @param array\n * @return minimum value.\n */\nexport function min(array: number[]|Float32Array): number {\n // same behavior as tf.min()\n if (array.length === 0) {\n return Number.NaN;\n }\n let min = Number.POSITIVE_INFINITY;\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n if (value < min) {\n min = value;\n }\n }\n return min;\n}\n\n/**\n * Compute maximum value.\n * @param array\n * @return maximum value\n */\nexport function max(array: number[]|Float32Array): number {\n // same behavior as tf.max()\n if (array.length === 0) {\n return Number.NaN;\n }\n let max = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n if (value > max) {\n max = value;\n }\n }\n return max;\n}\n\n/**\n * Compute sum of array.\n * @param array\n * @return The sum.\n */\nexport function sum(array: number[]|Float32Array): number {\n let sum = 0;\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n sum += value;\n }\n return sum;\n}\n\n/**\n * Compute mean of array.\n * @param array\n * @return The mean.\n */\nexport function mean(array: number[]|Float32Array): number {\n return sum(array) / array.length;\n}\n\n/**\n * Compute variance of array.\n * @param array\n * @return The variance.\n */\nexport function variance(array: number[]|Float32Array): number {\n const meanValue = mean(array);\n const demeaned = array.map((value: number) => value - meanValue);\n let sumSquare = 0;\n for (let i = 0; i < demeaned.length; i++) {\n const value = demeaned[i];\n sumSquare += value * value;\n }\n return sumSquare / array.length;\n}\n\n/**\n * Compute median of array.\n * @param array\n * @return The median value.\n */\nexport function median(array: number[]|Float32Array): number {\n const arraySorted = array.slice().sort((a, b) => a - b);\n const lowIdx = Math.floor((arraySorted.length - 1) / 2);\n const highIdx = Math.ceil((arraySorted.length - 1) / 2);\n if (lowIdx === highIdx) {\n return arraySorted[lowIdx];\n }\n return (arraySorted[lowIdx] + arraySorted[highIdx]) / 2;\n}\n\n/**\n * Generate an array of integers in [begin, end).\n * @param begin Beginning integer, inclusive.\n * @param end Ending integer, exclusive.\n * @returns Range array.\n * @throws ValueError, iff `end` < `begin`.\n */\nexport function range(begin: number, end: number): number[] {\n if (end < begin) {\n throw new ValueError(`end (${end}) < begin (${begin}) is forbidden.`);\n }\n const out: number[] = [];\n for (let i = begin; i < end; ++i) {\n out.push(i);\n }\n return out;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * deeplearn.js backend.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {onesLike as coreOnesLike, scalar, Tensor, Tensor1D, tensor1d, Tensor2D, Tensor3D, Tensor4D, Tensor5D, tidy, where, zerosLike as coreZerosLike} from '@tensorflow/tfjs-core';\nimport {checkDataFormat} from '../common';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {DataFormat, Shape} from '../keras_format/common';\nimport {HasShape} from '../types';\nimport * as math_utils from '../utils/math_utils';\n\nimport {imageDataFormat} from './common';\n\n// tslint:enable\n\n/* Setting and getting backend from deeplearn.js. */\n\n// Default deeplearn.js backend is WebGL (GPU).\nlet backend: 'cpu'|'webgl' = 'webgl';\n\nexport function setBackend(requestedBackend: 'cpu'|'webgl') {\n tfc.setBackend(requestedBackend);\n backend = requestedBackend;\n}\n\nexport function getBackend(): 'cpu'|'webgl' {\n return backend;\n}\n\n/**\n * Indicates whether the backend is operating symbolically.\n *\n * This function will be used to determine how to interpret user code. If\n * it returns true, calls to the backend construct a symbolic graph; if\n * it returns false, calls to the backend execute immediately.\n */\nexport function isBackendSymbolic(): boolean {\n return false;\n}\n\n/**\n * Get the number of elements in a Tensor.\n * @param x The Tensor.\n * @return Number of elements in `x`.\n */\nexport function countParams(x: HasShape): number {\n const shape = x.shape;\n if (shape.length > 0) {\n return shape.reduce((a: number, b: number) => a * b);\n } else {\n // Scalar.\n return 1;\n }\n}\n\n/**\n * Casts a tensor to a different dtype and returns it.\n * @param x Input tensor.\n * @param dtype String: 'float32'|'int32'|'bool'.\n * @returns Tensor of the specified `dtype`.\n */\nexport function cast(x: Tensor, dtype: tfc.DataType): Tensor {\n return tfc.cast(x, dtype);\n}\n\n/**\n * Adds a 1-sized dimension at index \"axis\".\n * @param x Input tensor.\n * @param axis Position where to add the new axis.\n * @returns Result of the dimension expansion.\n */\nexport function expandDims(x: Tensor, axis = -1): Tensor {\n const outShape = x.shape.slice();\n if (axis < 0) {\n axis = outShape.length + axis + 1;\n }\n outShape.splice(axis, 0, 1);\n return tfc.reshape(x, outShape);\n}\n\n/**\n * Repeats a 2D tensor.\n *\n * If `x` has shape `[samples, dim]` and `n` is 2, for example, the output\n * will have shape `[samples, 2, dim]`.\n *\n * @param x Input tensor.\n * @param n Integer, number of times to repeat.\n * @returns The result of the repeat operation.\n * @throws ValueError: If input tensor is not 2D.\n */\nexport function repeat(x: Tensor, n: number): Tensor {\n return tidy(() => {\n if (x.shape.length !== 2) {\n throw new ValueError(\n `repeat() expects a rank-2 tensor, but received a ` +\n `rank-${x.shape.length} tensor.`);\n }\n const y = expandDims(x, 1);\n return tile(y, [1, n, 1]);\n });\n}\n\n/**\n * Flatten a Tensor into 1D.\n * @param x Input tensor.\n * @return The result of the flattening `x`.\n */\nexport function flatten(x: Tensor): Tensor {\n const newShape = [math_utils.arrayProd(x.shape)];\n return tfc.reshape(x, newShape);\n}\n\n/**\n * Turn a nD tensor into a 2D tensor with same 0th dimension.\n * In other words, it flattens each data samples of a batch.\n *\n * @param x The tensor to flatten. The rank of this tensor is required to be 2\n * or higher.\n * @return The result of the flattening.\n */\nexport function batchFlatten(x: Tensor): Tensor {\n if (x.rank <= 1) {\n throw new ValueError(\n `batchFlatten requires a minimum rank of 2. Got rank: ${x.rank}.`);\n }\n const newShape = [x.shape[0], math_utils.arrayProd(x.shape, 1)];\n return tfc.reshape(x, newShape);\n}\n\n/**\n * Do slicing along the first axis.\n * @param array input `tf.Tensor`.\n * @param start starting index, inclusive.\n * @param size size of the slice along the first axis.\n * @returns result of the slicing.\n * @throws ValueError: If `array` is of an unsupported subtype of `tf.Tensor`.\n */\nexport function sliceAlongFirstAxis(\n array: Tensor, start: number, size: number): Tensor {\n return tidy(() => {\n switch (array.rank) {\n case 1:\n return tfc.slice1d(array as Tensor1D, start, size);\n case 2:\n return tfc.slice2d(\n array as Tensor2D, [start, 0], [size, array.shape[1]]);\n case 3:\n return tfc.slice3d(\n array as Tensor3D, [start, 0, 0],\n [size, array.shape[1], array.shape[2]]);\n case 4:\n return tfc.slice4d(\n array as Tensor4D, [start, 0, 0, 0],\n [size, array.shape[1], array.shape[2], array.shape[3]]);\n case 5:\n return tfc.slice(array as Tensor5D, [start, 0, 0, 0, 0], [\n size, array.shape[1], array.shape[2], array.shape[3], array.shape[4]\n ]);\n case 6:\n return tfc.slice(array, [start, 0, 0, 0, 0, 0], [\n size, array.shape[1], array.shape[2], array.shape[3], array.shape[4],\n array.shape[5]\n ]);\n default:\n throw new ValueError(\n `sliceAlongFirstAxis() received an unsupported tensor rank: ` +\n `${array.rank}`);\n }\n });\n}\n\n/**\n * Do slicing along the last axis.\n * @param array input `tf.Tensor`.\n * @param start starting index, inclusive.\n * @param size size of the slice along the last axis.\n * @returns result of the slicing.\n * @throws ValueError: If `array` is of an unsupported subtype of `tf.Tensor`.\n */\nexport function sliceAlongLastAxis(\n array: Tensor, start: number, size: number): Tensor {\n return tidy(() => {\n switch (array.rank) {\n case 1:\n return tfc.slice1d(array as Tensor1D, start, size);\n case 2:\n return tfc.slice2d(\n array as Tensor2D, [0, start], [array.shape[0], size]);\n case 3:\n return tfc.slice3d(\n array as Tensor3D, [0, 0, start],\n [array.shape[0], array.shape[1], size]);\n case 4:\n return tfc.slice4d(\n array as Tensor4D, [0, 0, 0, start],\n [array.shape[0], array.shape[1], array.shape[2], size]);\n default:\n throw new ValueError(\n `sliceAlongLastAxis() received an unsupported tensor rank: ` +\n `${array.rank}`);\n }\n });\n}\n\n/**\n * Do slicing along the sepcified axis.\n * @param array input `tf.Tensor`.\n * @param start starting index, inclusive.\n * @param size of the slice along the chosen axis.\n * @param choose an axis.\n * @returns result of the slicing.\n * @throws ValueError: If `array` is of an unsupported subtype of `tf.Tensor`.\n */\nexport function sliceAlongAxis(\n array: Tensor, start: number, size: number, axis: number): Tensor {\n return tidy(() => {\n switch (array.rank) {\n case 1:\n return tfc.slice1d(array as Tensor1D, start, size);\n case 2:\n switch (axis) {\n case 1:\n return sliceAlongFirstAxis(array, start, size);\n case 2:\n return sliceAlongLastAxis(array, start, size);\n default:\n throw new ValueError(\n `The axis is not within the rank of the tensor ` +\n `${axis}`);\n }\n case 3:\n switch (axis) {\n case 1:\n return sliceAlongFirstAxis(array, start, size);\n case 2:\n return tfc.slice3d(\n array as Tensor3D, [0, start, 0],\n [array.shape[0], size, array.shape[2]]);\n case 3:\n return sliceAlongLastAxis(array, start, size);\n default:\n throw new ValueError(\n `The axis is not within the rank of the tensor ` +\n `${axis}`);\n }\n case 4:\n switch (axis) {\n case 1:\n return sliceAlongFirstAxis(array, start, size);\n case 2:\n return tfc.slice4d(\n array as Tensor4D, [0, start, 0, 0],\n [array.shape[0], size, array.shape[2], array.shape[3]]);\n case 3:\n return tfc.slice4d(\n array as Tensor4D, [0, 0, start, 0],\n [array.shape[0], array.shape[1], size, array.shape[3]]);\n case 4:\n return sliceAlongLastAxis(array, start, size);\n default:\n throw new ValueError(\n `The axis is not within the rank of the tensor ` +\n `${axis}`);\n }\n default:\n throw new ValueError(\n `sliceAlongLastAxis() received an unsupported tensor rank: ` +\n `${array.rank}`);\n }\n });\n}\n\n/**\n * Concatenates a list of tensors alongside the specified axis.\n * @param tensors `Array` of tensors to concatenate.\n * @param axis Concatenation axis.\n * @returns The result of the concatenation.\n */\nexport function concatenate(tensors: Tensor[], axis = -1): Tensor {\n let rank: number;\n if (axis < 0) {\n rank = tensors[0].rank;\n if (rank !== 0) {\n axis = rank;\n } else {\n axis = 0;\n }\n }\n if (axis === tensors[0].rank) {\n // Porting Note: This is necessary because tfc.concat() requires axis to be\n // in the interval [-rank, rank).\n axis = -1;\n }\n // Porting Note: Sparse concat is not supported yet.\n return tfc.concat(tensors, axis);\n}\n\n/**\n * Concatenate two arrays along the first dimension.\n * @param a The 1st `tf.Tensor` to concatenate.\n * @param b The 2nd `tf.Tensor` to concatenate.\n * @returns Result of the concatenation.\n * @throws ValueError: If `a` is of an unsupported subtype of `tf.Tensor`.\n */\nexport function concatAlongFirstAxis(a: Tensor, b: Tensor): Tensor {\n switch (a.rank) {\n case 1:\n return tfc.concat1d([a as Tensor1D, b as Tensor1D]);\n case 2:\n return tfc.concat2d([a as Tensor2D, b as Tensor2D], 0);\n case 3:\n return tfc.concat3d([a as Tensor3D, b as Tensor3D], 0);\n case 4:\n return tfc.concat4d([a as Tensor4D, b as Tensor4D], 0);\n default:\n throw new ValueError(\n `concatAlongFirstAxis() received an unsupported ` +\n `tensor rank: ${a.rank}`);\n }\n}\n\n/**\n * Creates a tensor by tiling `x` by `n`.\n * @param x A tensor.\n * @param n An Array of integers or a single integer. If an Array, the length\n * must be the same as the number of dimensions in `x`. If a single integer,\n * it will be treated as an Array of length 1.\n */\nexport function tile(x: Tensor, n: number|number[]): Tensor {\n if (!Array.isArray(n)) {\n n = [n];\n }\n if (x.rank !== n.length) {\n throw new ValueError(\n `The length of input n (${n.length}) does not match ` +\n `the number of dimensions in input x (${x.rank})`);\n }\n return tfc.tile(x, n);\n}\n\n/* Creation of random tensors. */\n\n/**\n * Get a tensor with normal distribution of values.\n *\n * @param shape Shape of the tensor.\n * @param mean mean value of the normal distribution.\n * @param stddev standard deviation of the normal distribution.\n * @param dtype\n * @param seed\n * @return The normal tensor.\n */\nexport function randomNormal(\n shape: Shape, mean = 0.0, stddev = 1.0, dtype?: 'float32'|'int32',\n seed?: number): Tensor {\n return tfc.randomNormal(shape, mean, stddev, dtype, seed);\n}\n\n/* Linear Algebra */\n\n/**\n * Multiply two tensors and returns the result as a tensor.\n *\n * For 2D tensors, this is equivalent to matrix multiplication (matMul).\n * For tensors of higher ranks, it follows the Theano behavior,\n * (e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`). From the Theano documentation:\n *\n * For N dimensions it is a sum product over the last axis of x and the\n * second-to-last of y:\n *\n * @param a A tensor of at least rank 2.\n * @param b A tensor of at least rank 2.\n * @param activation (optional) A string identifying the activation\n * function.\n * @return Result of the dot operation.\n */\nexport function dot(\n a: Tensor, b: Tensor, activation?: tfc.fused.Activation,\n bias?: Tensor): Tensor {\n if ((a.rank < 2) || (b.rank < 2)) {\n throw new NotImplementedError(\n `dot requires both inputs to be rank >= 2` +\n ` but got x shape = ${a.shape} and y shape = ${b.shape}`);\n }\n if (b.rank >= 3) {\n const xLastDim = a.shape.slice(-1)[0];\n const ySecondLastDim = b.shape.slice(-2)[0];\n if (xLastDim !== ySecondLastDim) {\n throw new NotImplementedError(\n `If rank y >= 3, then the second last dim` +\n ` of y must equal the last dim of x but got x shape = ${\n a.shape} and ` +\n ` y shape = ${b.shape}`);\n }\n }\n // Handle basic 2D x 2D case.\n if ((a.rank === 2) && (b.rank === 2)) {\n const transposeA = false;\n const transposeB = false;\n // tfc.fused.matMul only fuses certain activation functions. Unsupported\n // activation functions are treated as 'linear' activations, which is\n // equivalent to a no-op.\n return tfc.fused.matMul({\n a,\n b: b as Tensor2D,\n transposeA,\n transposeB,\n bias: bias ? reshapeBias(a.rank, bias, imageDataFormat()) : null,\n activation\n });\n } else {\n // Reshape x into the analogous 2D Tensor.\n const aFirstDims = a.shape.slice(); // Holds all but the last dim of x.\n const aLastDim = aFirstDims.pop();\n a = tfc.reshape(a, [-1, aLastDim]);\n\n // Reshape y into the analogous 2D Tensor, and keep track of the\n // required dimensions to reproduce the output shape.\n const bShape = b.shape.slice();\n const bLastDim = bShape.pop();\n const ySecondLastDim = bShape.pop();\n const yOtherDims = [...bShape, bLastDim];\n // permutation should be like [r-2, 0, 1, 2, ... r-4, r-3, r-1]\n // where r is the rank of y.\n const perm = Array.from({length: b.rank}, (_, i) => {\n if (i === 0) {\n return b.rank - 2;\n } else if (i <= b.rank - 2) {\n return i - 1;\n }\n return i;\n });\n b = tfc.reshape(tfc.transpose(b, perm), [ySecondLastDim, -1]);\n\n // Multiply x and y as 2D Tensors, and then reshape back to original.\n const outputShape = [...aFirstDims, ...yOtherDims];\n const transposeA = false;\n const transposeB = false;\n return tfc.reshape(\n tfc.fused.matMul({\n a,\n b,\n transposeA,\n transposeB,\n bias: bias ? reshapeBias(a.rank, bias, imageDataFormat()) : null,\n activation\n }),\n outputShape);\n }\n}\n\n/**\n * Compute the sign Tensor of an input Tensor.\n *\n * Elements of the input `tf.Tensor` that are === 0 are mapped to 0.\n * Elements of the input `tf.Tensor` that are > 0 are mapped to 1.\n * Elements of the input `tf.Tensor` that are < 0 are mapped to -1.\n *\n * @param x Input `tf.Tensor`.\n * @return The sign `tf.Tensor`.\n */\nexport function sign(x: Tensor): Tensor {\n // TODO(cais): Move to the core.\n return tidy(() => {\n const zerosLikeX = coreZerosLike(x);\n const onesLikeX = coreOnesLike(x);\n return where(\n tfc.equal(x, zerosLikeX), zerosLikeX,\n where(\n tfc.greater(x, coreZerosLike(x)), onesLikeX,\n tfc.mul(-1, onesLikeX)));\n });\n}\n\n/**\n * Computes the one-hot representation of an integer tensor.\n * @param indices nD integer tensor of shape\n * `(batch_size, dim1, dim2, ... dim(n-1))`\n * @param numClasses Integer, number of classes to consider.\n * @returns (n + 1)D one hot representation of the input\n * with shape `(batch_size, dim1, dim2, ... dim(n-1), num_classes)`\n */\nexport function oneHot(indices: Tensor, numClasses: number): Tensor {\n return tidy(() => {\n if (indices.rank !== 1) {\n throw new Error(\n 'Only 1D one-hot tensors are supported in the ' +\n 'deeplearn backend, at present.');\n }\n indices = tfc.cast(indices, 'int32');\n return tfc.cast(tfc.oneHot(indices as Tensor1D, numClasses), 'float32');\n });\n}\n\n/* Elementary math functions. */\n\n/**\n * Retrieves the elements of indices `indices` in the tensor `reference`.\n * @param reference A tensor.\n * @param indices An integer tensor of indices or an `Array` of integers.\n * @param axis Axis along which to perform the gather operation.\n * @returns The result of the gathering as a tensor.\n */\nexport function gather(\n reference: Tensor, indices: number[]|Tensor1D, axis?: number): Tensor {\n return tidy(() => {\n if (Array.isArray(indices)) {\n indices = tensor1d(indices, 'int32');\n } else {\n indices = tfc.cast(indices, 'int32');\n }\n return tfc.gather(reference, indices, axis);\n });\n}\n\n/**\n * Element-wise square.\n * @param x Input tensor.\n * @return element-wise x^2\n */\nexport function square(x: Tensor): Tensor {\n return tfc.mul(x, x);\n}\n\n/**\n * Element-wise exponentiation.\n *\n * Porting Note: In PyKeras, `a` (the exponent) is a Python integer, which\n * takes advatnage of the backend's (e.g., TensorFlow's) automatic\n * conversion to tensor. Here we allow `a` to be either a number or a tensor.\n *\n * @param x The base tensor.\n * @param a The exponent, tensor or number. If a number, it is rounded to the\n * nearest integer and converted to a tensor.\n * @returns A tensor of the same shape as `x`.\n */\nexport function pow(x: Tensor, a: Tensor|number): Tensor {\n return tidy(() => {\n if (typeof (a) === 'number') {\n a = scalar(Math.round(a), 'int32');\n }\n if (a.dtype !== 'int32') {\n throw new NotImplementedError(\n `Non-int32 dtype (${a.dtype}) is not supported by pow() yet`);\n }\n return tfc.pow(x, a);\n });\n}\n\n/**\n * Reshapes bias tensor according to rank of x.\n */\nfunction reshapeBias(xRank: number, bias: Tensor, dataFormat: string) {\n const biasShape = bias.shape;\n\n if (bias.rank !== 1 && bias.rank !== xRank) {\n throw new ValueError(\n `Unexpected bias dimensions: ${bias.rank}` +\n `; expected it to be 1 or ${xRank}`);\n }\n\n if (xRank === 5) {\n if (dataFormat === 'channelsFirst') {\n if (biasShape.length === 1) {\n return tfc.reshape(bias, [1, biasShape[0], 1, 1, 1]);\n } else {\n return tfc.reshape(\n bias, [1, biasShape[3], biasShape[0], biasShape[1], biasShape[2]]);\n }\n } else if (dataFormat === 'channelsLast') {\n if (biasShape.length === 1) {\n return tfc.reshape(bias, [1, 1, 1, 1, biasShape[0]]);\n } else {\n return tfc.reshape(bias, [1].concat(biasShape));\n }\n }\n } else if (xRank === 4) {\n if (dataFormat === 'channelsFirst') {\n if (biasShape.length === 1) {\n return tfc.reshape(bias, [1, biasShape[0], 1, 1]);\n } else {\n return tfc.reshape(bias, [1, biasShape[2], biasShape[0], biasShape[1]]);\n }\n } else if (dataFormat === 'channelsLast') {\n if (biasShape.length === 1) {\n return tfc.reshape(bias, [1, 1, 1, biasShape[0]]);\n } else {\n return tfc.reshape(bias, [1].concat(biasShape));\n }\n }\n } else if (xRank === 3) {\n if (dataFormat === 'channelsFirst') {\n if (biasShape.length === 1) {\n return tfc.reshape(bias, [1, biasShape[0], 1]);\n } else {\n return tfc.reshape(bias, [1, biasShape[1], biasShape[0]]);\n }\n } else if (dataFormat === 'channelsLast') {\n if (biasShape.length === 1) {\n return tfc.reshape(bias, [1, 1, biasShape[0]]);\n } else {\n return tfc.reshape(bias, [1].concat(biasShape));\n }\n }\n } else if (xRank < 3) {\n return bias;\n }\n throw new ValueError(`Unsupported input rank by biasAdd: ${bias.rank}`);\n}\n\n/* Neural-network operations. */\n\n/**\n * Add a bias to a tensor.\n *\n * @param x The tensor to add the bias to.\n * @param bias The bias to add to `x`. Must be 1D or the same rank as `x`.\n * @return Result of the bias adding.\n * @throws ValueError: If the rank of `bias` is incorrect.\n */\nexport function biasAdd(\n x: Tensor, bias: Tensor, dataFormat?: DataFormat): Tensor {\n return tidy(() => {\n if (dataFormat == null) {\n dataFormat = imageDataFormat();\n }\n checkDataFormat(dataFormat);\n\n return tfc.add(x, reshapeBias(x.rank, bias, dataFormat));\n });\n}\n\n/**\n * Exponential linear unit (ELU).\n * @param x A tensor or variable to compute the activation function for.\n * @param alpha: A scalar, a scaling factor for the negative section.\n * @return Output of the ELU operation.\n */\nexport function elu(x: Tensor, alpha = 1): Tensor {\n // TODO(cais): Add support for alpha values other than 1.\n if (alpha !== 1) {\n throw new NotImplementedError(\n `Support for alpha values other than 1 (${alpha}) is not implemented ` +\n `yet.`);\n }\n return tfc.elu(x);\n}\n\n/**\n * Softsign of a tensor.\n *\n * Defined as x / (abs(x) + 1), element-wise.\n *\n * @param x: Input.\n * @returns Output.\n */\nexport function softsign(x: Tensor): Tensor {\n return tidy(() => tfc.div(x, tfc.add(tfc.abs(x), 1)));\n}\n\n/**\n * Sets entries in `x` to zero at random, while scaling the entire tensor.\n *\n * @param x input tensor.\n * @param level fraction of the entries in the tensor that will be set to 0.\n * @param noiseShape shape of randomly generated keep/drop flags, must be\n * broadcastable to the shape of `x`. Optional.\n * @param seed random seed to ensure determinism. Optional.\n * @returns Result of the dropout operation.\n */\nexport function dropout(\n x: Tensor, level: number, noiseShape?: number[], seed?: number): Tensor {\n return tidy(() => tfc.dropout(x, level, noiseShape, seed));\n}\n\n/**\n * Element-wise, segment-wise linear approximation of sigmoid.\n *\n * Returns `0.` if `x < -2.5`, `1.` if `x > 2.5`.\n * In `-2.5 <= x <= 2.5`, returns `0.2 * x + 0.5`.\n *\n * @param x Input tensor.\n * @returns Output tensor.\n */\nexport function hardSigmoid(x: Tensor): Tensor {\n return tidy(() => {\n const y = tfc.add(.5, tfc.mul(.2, x));\n return tfc.clipByValue(y, 0, 1);\n });\n}\n\n/**\n * Invoke `x` in the training phase, and `alt` otherwise.\n *\n * Porting Note: We do not create placeholder tensors for the `training`\n * boolean flag here, because there is no such thing in the TF.js imperative\n * backend.\n *\n * @param x The function to invoke iff `training` is `true`.\n * @param alt The function to invoke iff `training` is `false`.\n * @param training Boolean flag for whether training phase is active.\n * @returns The return value of `x()` if `training` is `true`, or the return\n * value of `alt()` if `training` is `false`.\n */\nexport function inTrainPhase<T>(x: () => T, alt: () => T, training = false): T {\n return training ? x() : alt();\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {BaseSerialization} from './types';\n\n// TODO(soergel): Move the CamelCase versions back out of keras_format\n// e.g. to src/common.ts. Maybe even duplicate *all* of these to be pedantic?\n/** @docinline */\nexport type FanMode = 'fanIn'|'fanOut'|'fanAvg';\nexport const VALID_FAN_MODE_VALUES = ['fanIn', 'fanOut', 'fanAvg'];\n\n// These constants have a snake vs. camel distinction.\nexport type FanModeSerialization = 'fan_in'|'fan_out'|'fan_avg';\n\n/** @docinline */\nexport type Distribution = 'normal'|'uniform'|'truncatedNormal';\nexport const VALID_DISTRIBUTION_VALUES =\n ['normal', 'uniform', 'truncatedNormal'];\n// These constants have a snake vs. camel distinction.\nexport type DistributionSerialization = 'normal'|'uniform'|'truncated_normal';\n\nexport type ZerosSerialization = BaseSerialization<'Zeros', {}>;\n\nexport type OnesSerialization = BaseSerialization<'Ones', {}>;\n\nexport type ConstantConfig = {\n value: number;\n};\n\nexport type ConstantSerialization =\n BaseSerialization<'Constant', ConstantConfig>;\n\nexport type RandomNormalConfig = {\n mean?: number;\n stddev?: number;\n seed?: number;\n};\n\nexport type RandomNormalSerialization =\n BaseSerialization<'RandomNormal', RandomNormalConfig>;\n\nexport type RandomUniformConfig = {\n minval?: number;\n maxval?: number;\n seed?: number;\n};\n\nexport type RandomUniformSerialization =\n BaseSerialization<'RandomUniform', RandomUniformConfig>;\n\nexport type TruncatedNormalConfig = {\n mean?: number;\n stddev?: number;\n seed?: number;\n};\n\nexport type TruncatedNormalSerialization =\n BaseSerialization<'TruncatedNormal', TruncatedNormalConfig>;\n\nexport type VarianceScalingConfig = {\n scale?: number;\n\n mode?: FanModeSerialization;\n distribution?: DistributionSerialization;\n seed?: number;\n};\n\nexport type VarianceScalingSerialization =\n BaseSerialization<'VarianceScaling', VarianceScalingConfig>;\n\nexport type OrthogonalConfig = {\n seed?: number;\n gain?: number;\n};\n\nexport type OrthogonalSerialization =\n BaseSerialization<'Orthogonal', OrthogonalConfig>;\n\nexport type IdentityConfig = {\n gain?: number;\n};\n\nexport type IdentitySerialization =\n BaseSerialization<'Identity', IdentityConfig>;\n\n// Update initializerClassNames below in concert with this.\nexport type InitializerSerialization = ZerosSerialization|OnesSerialization|\n ConstantSerialization|RandomUniformSerialization|RandomNormalSerialization|\n TruncatedNormalSerialization|IdentitySerialization|\n VarianceScalingSerialization|OrthogonalSerialization;\n\nexport type InitializerClassName = InitializerSerialization['class_name'];\n\n// We can't easily extract a string[] from the string union type, but we can\n// recapitulate the list, enforcing at compile time that the values are valid\n// and that we have the right number of them.\n\n/**\n * A string array of valid Initializer class names.\n *\n * This is guaranteed to match the `InitializerClassName` union type.\n */\nexport const initializerClassNames: InitializerClassName[] = [\n 'Zeros', 'Ones', 'Constant', 'RandomNormal', 'RandomUniform',\n 'TruncatedNormal', 'VarianceScaling', 'Orthogonal', 'Identity'\n];\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {DataType, eye, linalg, mul, ones, randomUniform, scalar, serialization, Tensor, Tensor2D, tidy, transpose, truncatedNormal, zeros} from '@tensorflow/tfjs-core';\n\nimport * as K from './backend/tfjs_backend';\nimport {checkDataFormat} from './common';\nimport {NotImplementedError, ValueError} from './errors';\nimport {DataFormat, Shape} from './keras_format/common';\nimport {Distribution, FanMode, VALID_DISTRIBUTION_VALUES, VALID_FAN_MODE_VALUES} from './keras_format/initializer_config';\nimport {checkStringTypeUnionValue, deserializeKerasObject, serializeKerasObject} from './utils/generic_utils';\nimport {arrayProd} from './utils/math_utils';\n\nexport function checkFanMode(value?: string): void {\n checkStringTypeUnionValue(VALID_FAN_MODE_VALUES, 'FanMode', value);\n}\n\nexport function checkDistribution(value?: string): void {\n checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES, 'Distribution', value);\n}\n\n/**\n * Initializer base class.\n *\n * @doc {\n * heading: 'Initializers', subheading: 'Classes', namespace: 'initializers'}\n */\nexport abstract class Initializer extends serialization.Serializable {\n public fromConfigUsesCustomObjects(): boolean {\n return false;\n }\n /**\n * Generate an initial value.\n * @param shape\n * @param dtype\n * @return The init value.\n */\n abstract apply(shape: Shape, dtype?: DataType): Tensor;\n\n getConfig(): serialization.ConfigDict {\n return {};\n }\n}\n\nexport class Zeros extends Initializer {\n /** @nocollapse */\n static className = 'Zeros';\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n return zeros(shape, dtype);\n }\n}\nserialization.registerClass(Zeros);\n\nexport class Ones extends Initializer {\n /** @nocollapse */\n static className = 'Ones';\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n return ones(shape, dtype);\n }\n}\nserialization.registerClass(Ones);\n\nexport interface ConstantArgs {\n /** The value for each element in the variable. */\n value: number;\n}\n\nexport class Constant extends Initializer {\n /** @nocollapse */\n static className = 'Constant';\n private value: number;\n constructor(args: ConstantArgs) {\n super();\n if (typeof args !== 'object') {\n throw new ValueError(\n `Expected argument of type ConstantConfig but got ${args}`);\n }\n if (args.value === undefined) {\n throw new ValueError(`config must have value set but got ${args}`);\n }\n this.value = args.value;\n }\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n return tidy(() => mul(scalar(this.value), ones(shape, dtype)));\n }\n\n getConfig(): serialization.ConfigDict {\n return {\n value: this.value,\n };\n }\n}\nserialization.registerClass(Constant);\n\nexport interface RandomUniformArgs {\n /** Lower bound of the range of random values to generate. */\n minval?: number;\n /** Upper bound of the range of random values to generate. */\n maxval?: number;\n /** Used to seed the random generator. */\n seed?: number;\n}\n\nexport class RandomUniform extends Initializer {\n /** @nocollapse */\n static className = 'RandomUniform';\n readonly DEFAULT_MINVAL = -0.05;\n readonly DEFAULT_MAXVAL = 0.05;\n private minval: number;\n private maxval: number;\n private seed: number;\n\n constructor(args: RandomUniformArgs) {\n super();\n this.minval = args.minval || this.DEFAULT_MINVAL;\n this.maxval = args.maxval || this.DEFAULT_MAXVAL;\n this.seed = args.seed;\n }\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n return randomUniform(shape, this.minval, this.maxval, dtype);\n }\n\n getConfig(): serialization.ConfigDict {\n return {minval: this.minval, maxval: this.maxval, seed: this.seed};\n }\n}\nserialization.registerClass(RandomUniform);\n\nexport interface RandomNormalArgs {\n /** Mean of the random values to generate. */\n mean?: number;\n /** Standard deviation of the random values to generate. */\n stddev?: number;\n /** Used to seed the random generator. */\n seed?: number;\n}\n\nexport class RandomNormal extends Initializer {\n /** @nocollapse */\n static className = 'RandomNormal';\n readonly DEFAULT_MEAN = 0.;\n readonly DEFAULT_STDDEV = 0.05;\n private mean: number;\n private stddev: number;\n private seed: number;\n\n constructor(args: RandomNormalArgs) {\n super();\n this.mean = args.mean || this.DEFAULT_MEAN;\n this.stddev = args.stddev || this.DEFAULT_STDDEV;\n this.seed = args.seed;\n }\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n dtype = dtype || 'float32';\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new NotImplementedError(\n `randomNormal does not support dType ${dtype}.`);\n }\n\n return K.randomNormal(shape, this.mean, this.stddev, dtype, this.seed);\n }\n\n getConfig(): serialization.ConfigDict {\n return {mean: this.mean, stddev: this.stddev, seed: this.seed};\n }\n}\nserialization.registerClass(RandomNormal);\n\nexport interface TruncatedNormalArgs {\n /** Mean of the random values to generate. */\n mean?: number;\n /** Standard deviation of the random values to generate. */\n stddev?: number;\n /** Used to seed the random generator. */\n seed?: number;\n}\n\nexport class TruncatedNormal extends Initializer {\n /** @nocollapse */\n static className = 'TruncatedNormal';\n\n readonly DEFAULT_MEAN = 0.;\n readonly DEFAULT_STDDEV = 0.05;\n private mean: number;\n private stddev: number;\n private seed: number;\n\n constructor(args: TruncatedNormalArgs) {\n super();\n this.mean = args.mean || this.DEFAULT_MEAN;\n this.stddev = args.stddev || this.DEFAULT_STDDEV;\n this.seed = args.seed;\n }\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n dtype = dtype || 'float32';\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new NotImplementedError(\n `truncatedNormal does not support dType ${dtype}.`);\n }\n return truncatedNormal(shape, this.mean, this.stddev, dtype, this.seed);\n }\n\n getConfig(): serialization.ConfigDict {\n return {mean: this.mean, stddev: this.stddev, seed: this.seed};\n }\n}\nserialization.registerClass(TruncatedNormal);\n\nexport interface IdentityArgs {\n /**\n * Multiplicative factor to apply to the identity matrix.\n */\n gain?: number;\n}\n\nexport class Identity extends Initializer {\n /** @nocollapse */\n static className = 'Identity';\n private gain: number;\n constructor(args: IdentityArgs) {\n super();\n this.gain = args.gain != null ? args.gain : 1.0;\n }\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n return tidy(() => {\n if (shape.length !== 2 || shape[0] !== shape[1]) {\n throw new ValueError(\n 'Identity matrix initializer can only be used for' +\n ' 2D square matrices.');\n } else {\n return mul(this.gain, eye(shape[0]));\n }\n });\n }\n\n getConfig(): serialization.ConfigDict {\n return {gain: this.gain};\n }\n}\nserialization.registerClass(Identity);\n\n/**\n * Computes the number of input and output units for a weight shape.\n * @param shape Shape of weight.\n * @param dataFormat data format to use for convolution kernels.\n * Note that all kernels in Keras are standardized on the\n * CHANNEL_LAST ordering (even when inputs are set to CHANNEL_FIRST).\n * @return An length-2 array: fanIn, fanOut.\n */\nfunction computeFans(\n shape: Shape, dataFormat: DataFormat = 'channelsLast'): number[] {\n let fanIn: number;\n let fanOut: number;\n checkDataFormat(dataFormat);\n if (shape.length === 2) {\n fanIn = shape[0];\n fanOut = shape[1];\n } else if ([3, 4, 5].indexOf(shape.length) !== -1) {\n if (dataFormat === 'channelsFirst') {\n const receptiveFieldSize = arrayProd(shape, 2);\n fanIn = shape[1] * receptiveFieldSize;\n fanOut = shape[0] * receptiveFieldSize;\n } else if (dataFormat === 'channelsLast') {\n const receptiveFieldSize = arrayProd(shape, 0, shape.length - 2);\n fanIn = shape[shape.length - 2] * receptiveFieldSize;\n fanOut = shape[shape.length - 1] * receptiveFieldSize;\n }\n } else {\n const shapeProd = arrayProd(shape);\n fanIn = Math.sqrt(shapeProd);\n fanOut = Math.sqrt(shapeProd);\n }\n\n return [fanIn, fanOut];\n}\n\nexport interface VarianceScalingArgs {\n /** Scaling factor (positive float). */\n scale?: number;\n\n /** Fanning mode for inputs and outputs. */\n mode?: FanMode;\n\n /** Probabilistic distribution of the values. */\n distribution?: Distribution;\n\n /** Random number generator seed. */\n seed?: number;\n}\n\nexport class VarianceScaling extends Initializer {\n /** @nocollapse */\n static className = 'VarianceScaling';\n private scale: number;\n private mode: FanMode;\n private distribution: Distribution;\n private seed: number;\n\n /**\n * Constructor of VarianceScaling.\n * @throws ValueError for invalid value in scale.\n */\n constructor(args: VarianceScalingArgs) {\n super();\n if (args.scale < 0.0) {\n throw new ValueError(\n `scale must be a positive float. Got: ${args.scale}`);\n }\n this.scale = args.scale == null ? 1.0 : args.scale;\n this.mode = args.mode == null ? 'fanIn' : args.mode;\n checkFanMode(this.mode);\n this.distribution =\n args.distribution == null ? 'normal' : args.distribution;\n checkDistribution(this.distribution);\n this.seed = args.seed;\n }\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n const fans = computeFans(shape);\n const fanIn = fans[0];\n const fanOut = fans[1];\n let scale = this.scale;\n if (this.mode === 'fanIn') {\n scale /= Math.max(1, fanIn);\n } else if (this.mode === 'fanOut') {\n scale /= Math.max(1, fanOut);\n } else {\n scale /= Math.max(1, (fanIn + fanOut) / 2);\n }\n\n if (this.distribution === 'normal') {\n const stddev = Math.sqrt(scale);\n dtype = dtype || 'float32';\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new NotImplementedError(\n `${this.getClassName()} does not support dType ${dtype}.`);\n }\n return truncatedNormal(shape, 0, stddev, dtype, this.seed);\n } else {\n const limit = Math.sqrt(3 * scale);\n return randomUniform(shape, -limit, limit, dtype);\n }\n }\n\n getConfig(): serialization.ConfigDict {\n return {\n scale: this.scale,\n mode: this.mode,\n distribution: this.distribution,\n seed: this.seed\n };\n }\n}\nserialization.registerClass(VarianceScaling);\n\nexport interface SeedOnlyInitializerArgs {\n /** Random number generator seed. */\n seed?: number;\n}\n\nexport class GlorotUniform extends VarianceScaling {\n /** @nocollapse */\n static className = 'GlorotUniform';\n\n /**\n * Constructor of GlorotUniform\n * @param scale\n * @param mode\n * @param distribution\n * @param seed\n */\n constructor(args?: SeedOnlyInitializerArgs) {\n super({\n scale: 1.0,\n mode: 'fanAvg',\n distribution: 'uniform',\n seed: args == null ? null : args.seed\n });\n }\n\n getClassName(): string {\n // In Python Keras, GlorotUniform is not a class, but a helper method\n // that creates a VarianceScaling object. Use 'VarianceScaling' as\n // class name to be compatible with that.\n return VarianceScaling.className;\n }\n}\nserialization.registerClass(GlorotUniform);\n\nexport class GlorotNormal extends VarianceScaling {\n /** @nocollapse */\n static className = 'GlorotNormal';\n\n /**\n * Constructor of GlorotNormal.\n * @param scale\n * @param mode\n * @param distribution\n * @param seed\n */\n constructor(args?: SeedOnlyInitializerArgs) {\n super({\n scale: 1.0,\n mode: 'fanAvg',\n distribution: 'normal',\n seed: args == null ? null : args.seed\n });\n }\n\n getClassName(): string {\n // In Python Keras, GlorotNormal is not a class, but a helper method\n // that creates a VarianceScaling object. Use 'VarianceScaling' as\n // class name to be compatible with that.\n return VarianceScaling.className;\n }\n}\nserialization.registerClass(GlorotNormal);\n\nexport class HeNormal extends VarianceScaling {\n /** @nocollapse */\n static className = 'HeNormal';\n\n constructor(args?: SeedOnlyInitializerArgs) {\n super({\n scale: 2.0,\n mode: 'fanIn',\n distribution: 'normal',\n seed: args == null ? null : args.seed\n });\n }\n\n getClassName(): string {\n // In Python Keras, HeNormal is not a class, but a helper method\n // that creates a VarianceScaling object. Use 'VarianceScaling' as\n // class name to be compatible with that.\n return VarianceScaling.className;\n }\n}\nserialization.registerClass(HeNormal);\n\nexport class HeUniform extends VarianceScaling {\n /** @nocollapse */\n static className = 'HeUniform';\n\n constructor(args?: SeedOnlyInitializerArgs) {\n super({\n scale: 2.0,\n mode: 'fanIn',\n distribution: 'uniform',\n seed: args == null ? null : args.seed\n });\n }\n\n getClassName(): string {\n // In Python Keras, HeUniform is not a class, but a helper method\n // that creates a VarianceScaling object. Use 'VarianceScaling' as\n // class name to be compatible with that.\n return VarianceScaling.className;\n }\n}\nserialization.registerClass(HeUniform);\n\nexport class LeCunNormal extends VarianceScaling {\n /** @nocollapse */\n static className = 'LeCunNormal';\n\n constructor(args?: SeedOnlyInitializerArgs) {\n super({\n scale: 1.0,\n mode: 'fanIn',\n distribution: 'normal',\n seed: args == null ? null : args.seed\n });\n }\n\n getClassName(): string {\n // In Python Keras, LeCunNormal is not a class, but a helper method\n // that creates a VarianceScaling object. Use 'VarianceScaling' as\n // class name to be compatible with that.\n return VarianceScaling.className;\n }\n}\nserialization.registerClass(LeCunNormal);\n\nexport class LeCunUniform extends VarianceScaling {\n /** @nocollapse */\n static className = 'LeCunNormal';\n\n constructor(args?: SeedOnlyInitializerArgs) {\n super({\n scale: 1.0,\n mode: 'fanIn',\n distribution: 'uniform',\n seed: args == null ? null : args.seed\n });\n }\n\n getClassName(): string {\n // In Python Keras, LeCunUniform is not a class, but a helper method\n // that creates a VarianceScaling object. Use 'VarianceScaling' as\n // class name to be compatible with that.\n return VarianceScaling.className;\n }\n}\nserialization.registerClass(LeCunUniform);\n\nexport interface OrthogonalArgs extends SeedOnlyInitializerArgs {\n /**\n * Multiplicative factor to apply to the orthogonal matrix. Defaults to 1.\n */\n gain?: number;\n}\n\nexport class Orthogonal extends Initializer {\n /** @nocollapse */\n static className = 'Orthogonal';\n readonly DEFAULT_GAIN = 1;\n protected readonly gain: number;\n protected readonly seed: number;\n\n constructor(args?: OrthogonalArgs) {\n super();\n this.gain = args.gain == null ? this.DEFAULT_GAIN : args.gain;\n this.seed = args.seed;\n\n if (this.seed != null) {\n throw new NotImplementedError(\n 'Random seed is not implemented for Orthogonal Initializer yet.');\n }\n }\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n return tidy(() => {\n if (shape.length < 2) {\n throw new NotImplementedError('Shape must be at least 2D.');\n }\n if (shape[0] * shape[1] > 2000) {\n console.warn(\n `Orthogonal initializer is being called on a matrix with more ` +\n `than 2000 (${shape[0] * shape[1]}) elements: ` +\n `Slowness may result.`);\n }\n\n // TODO(cais): Add seed support.\n const normalizedShape =\n shape[0] > shape[1] ? [shape[1], shape[0]] : shape;\n const a = K.randomNormal(normalizedShape, 0, 1, 'float32') as Tensor2D;\n let q = linalg.gramSchmidt(a) as Tensor2D;\n if (shape[0] > shape[1]) {\n q = transpose(q);\n }\n return mul(this.gain, q);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n return {\n gain: this.gain,\n seed: this.seed,\n };\n }\n}\nserialization.registerClass(Orthogonal);\n\n/** @docinline */\nexport type InitializerIdentifier =\n 'constant'|'glorotNormal'|'glorotUniform'|'heNormal'|'heUniform'|'identity'|\n 'leCunNormal'|'leCunUniform'|'ones'|'orthogonal'|'randomNormal'|\n 'randomUniform'|'truncatedNormal'|'varianceScaling'|'zeros'|string;\n\n// Maps the JavaScript-like identifier keys to the corresponding registry\n// symbols.\nexport const INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP:\n {[identifier in InitializerIdentifier]: string} = {\n 'constant': 'Constant',\n 'glorotNormal': 'GlorotNormal',\n 'glorotUniform': 'GlorotUniform',\n 'heNormal': 'HeNormal',\n 'heUniform': 'HeUniform',\n 'identity': 'Identity',\n 'leCunNormal': 'LeCunNormal',\n 'leCunUniform': 'LeCunUniform',\n 'ones': 'Ones',\n 'orthogonal': 'Orthogonal',\n 'randomNormal': 'RandomNormal',\n 'randomUniform': 'RandomUniform',\n 'truncatedNormal': 'TruncatedNormal',\n 'varianceScaling': 'VarianceScaling',\n 'zeros': 'Zeros'\n };\n\nfunction deserializeInitializer(\n config: serialization.ConfigDict,\n customObjects: serialization.ConfigDict = {}): Initializer {\n return deserializeKerasObject(\n config, serialization.SerializationMap.getMap().classNameMap,\n customObjects, 'initializer');\n}\n\nexport function serializeInitializer(initializer: Initializer):\n serialization.ConfigDictValue {\n return serializeKerasObject(initializer);\n}\n\nexport function getInitializer(identifier: InitializerIdentifier|Initializer|\n serialization.ConfigDict): Initializer {\n if (typeof identifier === 'string') {\n const className = identifier in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ?\n INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] :\n identifier;\n /* We have four 'helper' classes for common initializers that\n all get serialized as 'VarianceScaling' and shouldn't go through\n the deserializeInitializer pathway. */\n if (className === 'GlorotNormal') {\n return new GlorotNormal();\n } else if (className === 'GlorotUniform') {\n return new GlorotUniform();\n } else if (className === 'HeNormal') {\n return new HeNormal();\n } else if (className === 'HeUniform') {\n return new HeUniform();\n } else if (className === 'LeCunNormal') {\n return new LeCunNormal();\n } else if (className === 'LeCunUniform') {\n return new LeCunUniform();\n } else {\n const config: serialization.ConfigDict = {};\n config['className'] = className;\n config['config'] = {};\n return deserializeInitializer(config);\n }\n } else if (identifier instanceof Initializer) {\n return identifier;\n } else {\n return deserializeInitializer(identifier);\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {InputLayer, InputLayerArgs} from './engine/input_layer';\nimport {Layer, LayerArgs} from './engine/topology';\nimport {input} from './exports';\nimport {ELU, ELULayerArgs, LeakyReLU, LeakyReLULayerArgs, PReLU, PReLULayerArgs, ReLU, ReLULayerArgs, Softmax, SoftmaxLayerArgs, ThresholdedReLU, ThresholdedReLULayerArgs} from './layers/advanced_activations';\nimport {Conv1D, Conv2D, Conv2DTranspose, Conv3D, ConvLayerArgs, Cropping2D, Cropping2DLayerArgs, SeparableConv2D, SeparableConvLayerArgs, UpSampling2D, UpSampling2DLayerArgs, Conv3DTranspose} from './layers/convolutional';\nimport {DepthwiseConv2D, DepthwiseConv2DLayerArgs} from './layers/convolutional_depthwise';\nimport {ConvLSTM2D, ConvLSTM2DArgs, ConvLSTM2DCell, ConvLSTM2DCellArgs} from './layers/convolutional_recurrent';\nimport {Activation, ActivationLayerArgs, Dense, DenseLayerArgs, Dropout, DropoutLayerArgs, Flatten, FlattenLayerArgs, Masking, MaskingArgs, Permute, PermuteLayerArgs, RepeatVector, RepeatVectorLayerArgs, Reshape, ReshapeLayerArgs, SpatialDropout1D, SpatialDropout1DLayerConfig} from './layers/core';\nimport {Embedding, EmbeddingLayerArgs} from './layers/embeddings';\nimport {Add, Average, Concatenate, ConcatenateLayerArgs, Dot, DotLayerArgs, Maximum, Minimum, Multiply} from './layers/merge';\nimport {AlphaDropout, AlphaDropoutArgs, GaussianDropout, GaussianDropoutArgs, GaussianNoise, GaussianNoiseArgs} from './layers/noise';\nimport {BatchNormalization, BatchNormalizationLayerArgs, LayerNormalization, LayerNormalizationLayerArgs} from './layers/normalization';\nimport {ZeroPadding2D, ZeroPadding2DLayerArgs} from './layers/padding';\nimport {AveragePooling1D, AveragePooling2D, AveragePooling3D, GlobalAveragePooling1D, GlobalAveragePooling2D, GlobalMaxPooling1D, GlobalMaxPooling2D, GlobalPooling2DLayerArgs, MaxPooling1D, MaxPooling2D, MaxPooling3D, Pooling1DLayerArgs, Pooling2DLayerArgs, Pooling3DLayerArgs} from './layers/pooling';\nimport {GRU, GRUCell, GRUCellLayerArgs, GRULayerArgs, LSTM, LSTMCell, LSTMCellLayerArgs, LSTMLayerArgs, RNN, RNNCell, RNNLayerArgs, SimpleRNN, SimpleRNNCell, SimpleRNNCellLayerArgs, SimpleRNNLayerArgs, StackedRNNCells, StackedRNNCellsArgs} from './layers/recurrent';\nimport {Bidirectional, BidirectionalLayerArgs, TimeDistributed, WrapperLayerArgs} from './layers/wrappers';\n\n// TODO(cais): Add doc string to all the public static functions in this\n// class; include exectuable JavaScript code snippets where applicable\n// (b/74074458).\n\n// Input Layer.\n/**\n * An input layer is an entry point into a `tf.LayersModel`.\n *\n * `InputLayer` is generated automatically for `tf.Sequential`` models by\n * specifying the `inputshape` or `batchInputShape` for the first layer. It\n * should not be specified explicitly. However, it can be useful sometimes,\n * e.g., when constructing a sequential model from a subset of another\n * sequential model's layers. Like the code snippet below shows.\n *\n * ```js\n * // Define a model which simply adds two inputs.\n * const model1 = tf.sequential();\n * model1.add(tf.layers.dense({inputShape: [4], units: 3, activation: 'relu'}));\n * model1.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));\n * model1.summary();\n * model1.predict(tf.zeros([1, 4])).print();\n *\n * // Construct another model, reusing the second layer of `model1` while\n * // not using the first layer of `model1`. Note that you cannot add the second\n * // layer of `model` directly as the first layer of the new sequential model,\n * // because doing so will lead to an error related to the fact that the layer\n * // is not an input layer. Instead, you need to create an `inputLayer` and add\n * // it to the new sequential model before adding the reused layer.\n * const model2 = tf.sequential();\n * // Use an inputShape that matches the input shape of `model1`'s second\n * // layer.\n * model2.add(tf.layers.inputLayer({inputShape: [3]}));\n * model2.add(model1.layers[1]);\n * model2.summary();\n * model2.predict(tf.zeros([1, 3])).print();\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Inputs', namespace: 'layers'}\n */\nexport function inputLayer(args: InputLayerArgs) {\n return new InputLayer(args);\n}\n\n// Advanced Activation Layers.\n\n/**\n * Exponetial Linear Unit (ELU).\n *\n * It follows:\n * `f(x) = alpha * (exp(x) - 1.) for x < 0`,\n * `f(x) = x for x >= 0`.\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * References:\n * - [Fast and Accurate Deep Network Learning by Exponential Linear Units\n * (ELUs)](https://arxiv.org/abs/1511.07289v1)\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function elu(args?: ELULayerArgs) {\n return new ELU(args);\n}\n\n/**\n * Rectified Linear Unit activation function.\n *\n * Input shape:\n * Arbitrary. Use the config field `inputShape` (Array of integers, does\n * not include the sample axis) when using this layer as the first layer\n * in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function reLU(args?: ReLULayerArgs) {\n return new ReLU(args);\n}\n\n/**\n * Leaky version of a rectified linear unit.\n *\n * It allows a small gradient when the unit is not active:\n * `f(x) = alpha * x for x < 0.`\n * `f(x) = x for x >= 0.`\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function leakyReLU(args?: LeakyReLULayerArgs) {\n return new LeakyReLU(args);\n}\n\n/**\n * Parameterized version of a leaky rectified linear unit.\n *\n * It follows\n * `f(x) = alpha * x for x < 0.`\n * `f(x) = x for x >= 0.`\n * wherein `alpha` is a trainable weight.\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function prelu(args?: PReLULayerArgs) {\n return new PReLU(args);\n}\n\n/**\n * Softmax activation layer.\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function softmax(args?: SoftmaxLayerArgs) {\n return new Softmax(args);\n}\n\n/**\n * Thresholded Rectified Linear Unit.\n *\n * It follows:\n * `f(x) = x for x > theta`,\n * `f(x) = 0 otherwise`.\n *\n * Input shape:\n * Arbitrary. Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n * Output shape:\n * Same shape as the input.\n *\n * References:\n * - [Zero-Bias Autoencoders and the Benefits of Co-Adapting\n * Features](http://arxiv.org/abs/1402.3337)\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Advanced Activation',\n * namespace: 'layers'\n * }\n */\nexport function thresholdedReLU(args?: ThresholdedReLULayerArgs) {\n return new ThresholdedReLU(args);\n}\n\n// Convolutional Layers.\n\n/**\n * 1D convolution layer (e.g., temporal convolution).\n *\n * This layer creates a convolution kernel that is convolved\n * with the layer input over a single spatial (or temporal) dimension\n * to produce a tensor of outputs.\n *\n * If `use_bias` is True, a bias vector is created and added to the outputs.\n *\n * If `activation` is not `null`, it is applied to the outputs as well.\n *\n * When using this layer as the first layer in a model, provide an\n * `inputShape` argument `Array` or `null`.\n *\n * For example, `inputShape` would be:\n * - `[10, 128]` for sequences of 10 vectors of 128-dimensional vectors\n * - `[null, 128]` for variable-length sequences of 128-dimensional vectors.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function conv1d(args: ConvLayerArgs) {\n return new Conv1D(args);\n}\n\n/**\n * 2D convolution layer (e.g. spatial convolution over images).\n *\n * This layer creates a convolution kernel that is convolved\n * with the layer input to produce a tensor of outputs.\n *\n * If `useBias` is True, a bias vector is created and added to the outputs.\n *\n * If `activation` is not `null`, it is applied to the outputs as well.\n *\n * When using this layer as the first layer in a model,\n * provide the keyword argument `inputShape`\n * (Array of integers, does not include the sample axis),\n * e.g. `inputShape=[128, 128, 3]` for 128x128 RGB pictures\n * in `dataFormat='channelsLast'`.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function conv2d(args: ConvLayerArgs) {\n return new Conv2D(args);\n}\n\n/**\n * Transposed convolutional layer (sometimes called Deconvolution).\n *\n * The need for transposed convolutions generally arises\n * from the desire to use a transformation going in the opposite direction of\n * a normal convolution, i.e., from something that has the shape of the output\n * of some convolution to something that has the shape of its input while\n * maintaining a connectivity pattern that is compatible with said\n * convolution.\n *\n * When using this layer as the first layer in a model, provide the\n * configuration `inputShape` (`Array` of integers, does not include the\n * sample axis), e.g., `inputShape: [128, 128, 3]` for 128x128 RGB pictures in\n * `dataFormat: 'channelsLast'`.\n *\n * Input shape:\n * 4D tensor with shape:\n * `[batch, channels, rows, cols]` if `dataFormat` is `'channelsFirst'`.\n * or 4D tensor with shape\n * `[batch, rows, cols, channels]` if `dataFormat` is `'channelsLast`.\n *\n * Output shape:\n * 4D tensor with shape:\n * `[batch, filters, newRows, newCols]` if `dataFormat` is\n * `'channelsFirst'`. or 4D tensor with shape:\n * `[batch, newRows, newCols, filters]` if `dataFormat` is `'channelsLast'`.\n *\n * References:\n * - [A guide to convolution arithmetic for deep\n * learning](https://arxiv.org/abs/1603.07285v1)\n * - [Deconvolutional\n * Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf)\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function conv2dTranspose(args: ConvLayerArgs) {\n return new Conv2DTranspose(args);\n}\n\n/**\n * 3D convolution layer (e.g. spatial convolution over volumes).\n *\n * This layer creates a convolution kernel that is convolved\n * with the layer input to produce a tensor of outputs.\n *\n * If `useBias` is True, a bias vector is created and added to the outputs.\n *\n * If `activation` is not `null`, it is applied to the outputs as well.\n *\n * When using this layer as the first layer in a model,\n * provide the keyword argument `inputShape`\n * (Array of integers, does not include the sample axis),\n * e.g. `inputShape=[128, 128, 128, 1]` for 128x128x128 grayscale volumes\n * in `dataFormat='channelsLast'`.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function conv3d(args: ConvLayerArgs) {\n return new Conv3D(args);\n}\n\nexport function conv3dTranspose(args: ConvLayerArgs): Layer {\n return new Conv3DTranspose(args);\n}\n\n/**\n * Depthwise separable 2D convolution.\n *\n * Separable convolution consists of first performing\n * a depthwise spatial convolution\n * (which acts on each input channel separately)\n * followed by a pointwise convolution which mixes together the resulting\n * output channels. The `depthMultiplier` argument controls how many\n * output channels are generated per input channel in the depthwise step.\n *\n * Intuitively, separable convolutions can be understood as\n * a way to factorize a convolution kernel into two smaller kernels,\n * or as an extreme version of an Inception block.\n *\n * Input shape:\n * 4D tensor with shape:\n * `[batch, channels, rows, cols]` if data_format='channelsFirst'\n * or 4D tensor with shape:\n * `[batch, rows, cols, channels]` if data_format='channelsLast'.\n *\n * Output shape:\n * 4D tensor with shape:\n * `[batch, filters, newRows, newCols]` if data_format='channelsFirst'\n * or 4D tensor with shape:\n * `[batch, newRows, newCols, filters]` if data_format='channelsLast'.\n * `rows` and `cols` values might have changed due to padding.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function separableConv2d(args: SeparableConvLayerArgs) {\n return new SeparableConv2D(args);\n}\n\n/**\n * Cropping layer for 2D input (e.g., image).\n *\n * This layer can crop an input\n * at the top, bottom, left and right side of an image tensor.\n *\n * Input shape:\n * 4D tensor with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, rows, cols, channels]`\n * - If `data_format` is `\"channels_first\"`:\n * `[batch, channels, rows, cols]`.\n *\n * Output shape:\n * 4D with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, croppedRows, croppedCols, channels]`\n * - If `dataFormat` is `\"channelsFirst\"`:\n * `[batch, channels, croppedRows, croppedCols]`.\n *\n * Examples\n * ```js\n *\n * const model = tf.sequential();\n * model.add(tf.layers.cropping2D({cropping:[[2, 2], [2, 2]],\n * inputShape: [128, 128, 3]}));\n * //now output shape is [batch, 124, 124, 3]\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function cropping2D(args: Cropping2DLayerArgs) {\n return new Cropping2D(args);\n}\n\n/**\n * Upsampling layer for 2D inputs.\n *\n * Repeats the rows and columns of the data\n * by size[0] and size[1] respectively.\n *\n *\n * Input shape:\n * 4D tensor with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, rows, cols, channels]`\n * - If `dataFormat` is `\"channelsFirst\"`:\n * `[batch, channels, rows, cols]`\n *\n * Output shape:\n * 4D tensor with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, upsampledRows, upsampledCols, channels]`\n * - If `dataFormat` is `\"channelsFirst\"`:\n * `[batch, channels, upsampledRows, upsampledCols]`\n *\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function upSampling2d(args: UpSampling2DLayerArgs) {\n return new UpSampling2D(args);\n}\n\n// Convolutional(depthwise) Layers.\n\n/**\n * Depthwise separable 2D convolution.\n *\n * Depthwise Separable convolutions consists in performing just the first step\n * in a depthwise spatial convolution (which acts on each input channel\n * separately). The `depthMultplier` argument controls how many output channels\n * are generated per input channel in the depthwise step.\n *\n * @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}\n */\nexport function depthwiseConv2d(args: DepthwiseConv2DLayerArgs) {\n return new DepthwiseConv2D(args);\n}\n\n// Basic Layers.\n\n/**\n * Applies an activation function to an output.\n *\n * This layer applies element-wise activation function. Other layers, notably\n * `dense` can also apply activation functions. Use this isolated activation\n * function to extract the values before and after the\n * activation. For instance:\n *\n * ```js\n * const input = tf.input({shape: [5]});\n * const denseLayer = tf.layers.dense({units: 1});\n * const activationLayer = tf.layers.activation({activation: 'relu6'});\n *\n * // Obtain the output symbolic tensors by applying the layers in order.\n * const denseOutput = denseLayer.apply(input);\n * const activationOutput = activationLayer.apply(denseOutput);\n *\n * // Create the model based on the inputs.\n * const model = tf.model({\n * inputs: input,\n * outputs: [denseOutput, activationOutput]\n * });\n *\n * // Collect both outputs and print separately.\n * const [denseOut, activationOut] = model.predict(tf.randomNormal([6, 5]));\n * denseOut.print();\n * activationOut.print();\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function activation(args: ActivationLayerArgs) {\n return new Activation(args);\n}\n\n/**\n * Creates a dense (fully connected) layer.\n *\n * This layer implements the operation:\n * `output = activation(dot(input, kernel) + bias)`\n *\n * `activation` is the element-wise activation function\n * passed as the `activation` argument.\n *\n * `kernel` is a weights matrix created by the layer.\n *\n * `bias` is a bias vector created by the layer (only applicable if `useBias`\n * is `true`).\n *\n * **Input shape:**\n *\n * nD `tf.Tensor` with shape: `(batchSize, ..., inputDim)`.\n *\n * The most common situation would be\n * a 2D input with shape `(batchSize, inputDim)`.\n *\n * **Output shape:**\n *\n * nD tensor with shape: `(batchSize, ..., units)`.\n *\n * For instance, for a 2D input with shape `(batchSize, inputDim)`,\n * the output would have shape `(batchSize, units)`.\n *\n * Note: if the input to the layer has a rank greater than 2, then it is\n * flattened prior to the initial dot product with the kernel.\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function dense(args: DenseLayerArgs) {\n return new Dense(args);\n}\n\n/**\n * Applies\n * [dropout](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) to\n * the input.\n *\n * Dropout consists in randomly setting a fraction `rate` of input units to 0 at\n * each update during training time, which helps prevent overfitting.\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function dropout(args: DropoutLayerArgs) {\n return new Dropout(args);\n}\n\n/**\n * Spatial 1D version of Dropout.\n *\n * This Layer type performs the same function as the Dropout layer, but it drops\n * entire 1D feature maps instead of individual elements. For example, if an\n * input example consists of 3 timesteps and the feature map for each timestep\n * has a size of 4, a `spatialDropout1d` layer may zero out the feature maps\n * of the 1st timesteps and 2nd timesteps completely while sparing all feature\n * elements of the 3rd timestep.\n *\n * If adjacent frames (timesteps) are strongly correlated (as is normally the\n * case in early convolution layers), regular dropout will not regularize the\n * activation and will otherwise just result in merely an effective learning\n * rate decrease. In this case, `spatialDropout1d` will help promote\n * independence among feature maps and should be used instead.\n *\n * **Arguments:**\n * rate: A floating-point number >=0 and <=1. Fraction of the input elements\n * to drop.\n *\n * **Input shape:**\n * 3D tensor with shape `(samples, timesteps, channels)`.\n *\n * **Output shape:**\n * Same as the input shape.\n *\n * References:\n * - [Efficient Object Localization Using Convolutional\n * Networks](https://arxiv.org/abs/1411.4280)\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function spatialDropout1d(args: SpatialDropout1DLayerConfig) {\n return new SpatialDropout1D(args);\n}\n\n/**\n * Flattens the input. Does not affect the batch size.\n *\n * A `Flatten` layer flattens each batch in its inputs to 1D (making the output\n * 2D).\n *\n * For example:\n *\n * ```js\n * const input = tf.input({shape: [4, 3]});\n * const flattenLayer = tf.layers.flatten();\n * // Inspect the inferred output shape of the flatten layer, which\n * // equals `[null, 12]`. The 2nd dimension is 4 * 3, i.e., the result of the\n * // flattening. (The 1st dimension is the undermined batch size.)\n * console.log(JSON.stringify(flattenLayer.apply(input).shape));\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function flatten(args?: FlattenLayerArgs) {\n return new Flatten(args);\n}\n\n/**\n * Repeats the input n times in a new dimension.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.repeatVector({n: 4, inputShape: [2]}));\n * const x = tf.tensor2d([[10, 20]]);\n * // Use the model to do inference on a data point the model hasn't see\n * model.predict(x).print();\n * // output shape is now [batch, 2, 4]\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function repeatVector(args: RepeatVectorLayerArgs) {\n return new RepeatVector(args);\n}\n\n/**\n * Reshapes an input to a certain shape.\n *\n * ```js\n * const input = tf.input({shape: [4, 3]});\n * const reshapeLayer = tf.layers.reshape({targetShape: [2, 6]});\n * // Inspect the inferred output shape of the Reshape layer, which\n * // equals `[null, 2, 6]`. (The 1st dimension is the undermined batch size.)\n * console.log(JSON.stringify(reshapeLayer.apply(input).shape));\n * ```\n *\n * Input shape:\n * Arbitrary, although all dimensions in the input shape must be fixed.\n * Use the configuration `inputShape` when using this layer as the\n * first layer in a model.\n *\n *\n * Output shape:\n * [batchSize, targetShape[0], targetShape[1], ...,\n * targetShape[targetShape.length - 1]].\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function reshape(args: ReshapeLayerArgs) {\n return new Reshape(args);\n}\n\n/**\n * Permutes the dimensions of the input according to a given pattern.\n *\n * Useful for, e.g., connecting RNNs and convnets together.\n *\n * Example:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.permute({\n * dims: [2, 1],\n * inputShape: [10, 64]\n * }));\n * console.log(model.outputShape);\n * // Now model's output shape is [null, 64, 10], where null is the\n * // unpermuted sample (batch) dimension.\n * ```\n *\n * Input shape:\n * Arbitrary. Use the configuration field `inputShape` when using this\n * layer as the first layer in a model.\n *\n * Output shape:\n * Same rank as the input shape, but with the dimensions re-ordered (i.e.,\n * permuted) according to the `dims` configuration of this layer.\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function permute(args: PermuteLayerArgs) {\n return new Permute(args);\n}\n\n/**\n * Maps positive integers (indices) into dense vectors of fixed size.\n * eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]\n *\n * **Input shape:** 2D tensor with shape: `[batchSize, sequenceLength]`.\n *\n * **Output shape:** 3D tensor with shape: `[batchSize, sequenceLength,\n * outputDim]`.\n *\n * @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}\n */\nexport function embedding(args: EmbeddingLayerArgs) {\n return new Embedding(args);\n}\n\n// Merge Layers.\n\n/**\n * Layer that performs element-wise addition on an `Array` of inputs.\n *\n * It takes as input a list of tensors, all of the same shape, and returns a\n * single tensor (also of the same shape). The inputs are specified as an\n * `Array` when the `apply` method of the `Add` layer instance is called. For\n * example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const addLayer = tf.layers.add();\n * const sum = addLayer.apply([input1, input2]);\n * console.log(JSON.stringify(sum.shape));\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function add(args?: LayerArgs) {\n return new Add(args);\n}\n\n/**\n * Layer that performs element-wise averaging on an `Array` of inputs.\n *\n * It takes as input a list of tensors, all of the same shape, and returns a\n * single tensor (also of the same shape). For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const averageLayer = tf.layers.average();\n * const average = averageLayer.apply([input1, input2]);\n * console.log(JSON.stringify(average.shape));\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function average(args?: LayerArgs) {\n return new Average(args);\n}\n\n/**\n * Layer that concatenates an `Array` of inputs.\n *\n * It takes a list of tensors, all of the same shape except for the\n * concatenation axis, and returns a single tensor, the concatenation\n * of all inputs. For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 3]});\n * const concatLayer = tf.layers.concatenate();\n * const output = concatLayer.apply([input1, input2]);\n * console.log(JSON.stringify(output.shape));\n * // You get [null, 2, 5], with the first dimension as the undetermined batch\n * // dimension. The last dimension (5) is the result of concatenating the\n * // last dimensions of the inputs (2 and 3).\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function concatenate(args?: ConcatenateLayerArgs) {\n return new Concatenate(args);\n}\n\n/**\n * Layer that computes the element-wise maximum an `Array` of inputs.\n *\n * It takes as input a list of tensors, all of the same shape and returns a\n * single tensor (also of the same shape). For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const maxLayer = tf.layers.maximum();\n * const max = maxLayer.apply([input1, input2]);\n * console.log(JSON.stringify(max.shape));\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function maximum(args?: LayerArgs) {\n return new Maximum(args);\n}\n\n/**\n * Layer that computes the element-wise minimum of an `Array` of inputs.\n *\n * It takes as input a list of tensors, all of the same shape and returns a\n * single tensor (also of the same shape). For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const minLayer = tf.layers.minimum();\n * const min = minLayer.apply([input1, input2]);\n * console.log(JSON.stringify(min.shape));\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function minimum(args?: LayerArgs) {\n return new Minimum(args);\n}\n\n/**\n * Layer that multiplies (element-wise) an `Array` of inputs.\n *\n * It takes as input an Array of tensors, all of the same\n * shape, and returns a single tensor (also of the same shape).\n * For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const input3 = tf.input({shape: [2, 2]});\n * const multiplyLayer = tf.layers.multiply();\n * const product = multiplyLayer.apply([input1, input2, input3]);\n * console.log(product.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function multiply(args?: LayerArgs) {\n return new Multiply(args);\n}\n\n/**\n * Layer that computes a dot product between samples in two tensors.\n *\n * E.g., if applied to a list of two tensors `a` and `b` both of shape\n * `[batchSize, n]`, the output will be a tensor of shape `[batchSize, 1]`,\n * where each entry at index `[i, 0]` will be the dot product between\n * `a[i, :]` and `b[i, :]`.\n *\n * Example:\n *\n * ```js\n * const dotLayer = tf.layers.dot({axes: -1});\n * const x1 = tf.tensor2d([[10, 20], [30, 40]]);\n * const x2 = tf.tensor2d([[-1, -2], [-3, -4]]);\n *\n * // Invoke the layer's apply() method in eager (imperative) mode.\n * const y = dotLayer.apply([x1, x2]);\n * y.print();\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}\n */\nexport function dot(args: DotLayerArgs) {\n return new Dot(args);\n}\n\n// Normalization Layers.\n\n/**\n * Batch normalization layer (Ioffe and Szegedy, 2014).\n *\n * Normalize the activations of the previous layer at each batch,\n * i.e. applies a transformation that maintains the mean activation\n * close to 0 and the activation standard deviation close to 1.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape` (Array of integers, does\n * not include the sample axis) when calling the constructor of this class,\n * if this layer is used as a first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * References:\n * - [Batch Normalization: Accelerating Deep Network Training by Reducing\n * Internal Covariate Shift](https://arxiv.org/abs/1502.03167)\n *\n * @doc {heading: 'Layers', subheading: 'Normalization', namespace: 'layers'}\n */\nexport function batchNormalization(args?: BatchNormalizationLayerArgs) {\n return new BatchNormalization(args);\n}\n\n/**\n * Layer-normalization layer (Ba et al., 2016).\n *\n * Normalizes the activations of the previous layer for each given example in a\n * batch independently, instead of across a batch like in `batchNormalization`.\n * In other words, this layer applies a transformation that maintanis the mean\n * activation within each example close to0 and activation variance close to 1.\n *\n * Input shape:\n * Arbitrary. Use the argument `inputShape` when using this layer as the first\n * layer in a model.\n *\n * Output shape:\n * Same as input.\n *\n * References:\n * - [Layer Normalization](https://arxiv.org/abs/1607.06450)\n *\n * @doc {heading: 'Layers', subheading: 'Normalization', namespace: 'layers'}\n */\nexport function layerNormalization(args?: LayerNormalizationLayerArgs) {\n return new LayerNormalization(args);\n}\n\n// Padding Layers.\n\n/**\n * Zero-padding layer for 2D input (e.g., image).\n *\n * This layer can add rows and columns of zeros\n * at the top, bottom, left and right side of an image tensor.\n *\n * Input shape:\n * 4D tensor with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, rows, cols, channels]`\n * - If `data_format` is `\"channels_first\"`:\n * `[batch, channels, rows, cols]`.\n *\n * Output shape:\n * 4D with shape:\n * - If `dataFormat` is `\"channelsLast\"`:\n * `[batch, paddedRows, paddedCols, channels]`\n * - If `dataFormat` is `\"channelsFirst\"`:\n * `[batch, channels, paddedRows, paddedCols]`.\n *\n * @doc {heading: 'Layers', subheading: 'Padding', namespace: 'layers'}\n */\nexport function zeroPadding2d(args?: ZeroPadding2DLayerArgs) {\n return new ZeroPadding2D(args);\n}\n\n// Pooling Layers.\n\n/**\n * Average pooling operation for spatial data.\n *\n * Input shape: `[batchSize, inLength, channels]`\n *\n * Output shape: `[batchSize, pooledLength, channels]`\n *\n * `tf.avgPool1d` is an alias.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function averagePooling1d(args: Pooling1DLayerArgs) {\n return new AveragePooling1D(args);\n}\nexport function avgPool1d(args: Pooling1DLayerArgs) {\n return averagePooling1d(args);\n}\n// For backwards compatibility.\n// See https://github.com/tensorflow/tfjs/issues/152\nexport function avgPooling1d(args: Pooling1DLayerArgs) {\n return averagePooling1d(args);\n}\n\n/**\n * Average pooling operation for spatial data.\n *\n * Input shape:\n * - If `dataFormat === CHANNEL_LAST`:\n * 4D tensor with shape:\n * `[batchSize, rows, cols, channels]`\n * - If `dataFormat === CHANNEL_FIRST`:\n * 4D tensor with shape:\n * `[batchSize, channels, rows, cols]`\n *\n * Output shape\n * - If `dataFormat === CHANNEL_LAST`:\n * 4D tensor with shape:\n * `[batchSize, pooleRows, pooledCols, channels]`\n * - If `dataFormat === CHANNEL_FIRST`:\n * 4D tensor with shape:\n * `[batchSize, channels, pooleRows, pooledCols]`\n *\n * `tf.avgPool2d` is an alias.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function averagePooling2d(args: Pooling2DLayerArgs) {\n return new AveragePooling2D(args);\n}\nexport function avgPool2d(args: Pooling2DLayerArgs) {\n return averagePooling2d(args);\n}\n// For backwards compatibility.\n// See https://github.com/tensorflow/tfjs/issues/152\nexport function avgPooling2d(args: Pooling2DLayerArgs) {\n return averagePooling2d(args);\n}\n\n/**\n * Average pooling operation for 3D data.\n *\n * Input shape\n * - If `dataFormat === channelsLast`:\n * 5D tensor with shape:\n * `[batchSize, depths, rows, cols, channels]`\n * - If `dataFormat === channelsFirst`:\n * 4D tensor with shape:\n * `[batchSize, channels, depths, rows, cols]`\n *\n * Output shape\n * - If `dataFormat=channelsLast`:\n * 5D tensor with shape:\n * `[batchSize, pooledDepths, pooledRows, pooledCols, channels]`\n * - If `dataFormat=channelsFirst`:\n * 5D tensor with shape:\n * `[batchSize, channels, pooledDepths, pooledRows, pooledCols]`\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function averagePooling3d(args: Pooling3DLayerArgs) {\n return new AveragePooling3D(args);\n}\nexport function avgPool3d(args: Pooling3DLayerArgs) {\n return averagePooling3d(args);\n}\n// For backwards compatibility.\n// See https://github.com/tensorflow/tfjs/issues/152\nexport function avgPooling3d(args: Pooling3DLayerArgs) {\n return averagePooling3d(args);\n}\n\n/**\n * Global average pooling operation for temporal data.\n *\n * Input Shape: 3D tensor with shape: `[batchSize, steps, features]`.\n *\n * Output Shape:2D tensor with shape: `[batchSize, features]`.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function globalAveragePooling1d(args?: LayerArgs) {\n return new GlobalAveragePooling1D(args);\n}\n\n/**\n * Global average pooling operation for spatial data.\n *\n * Input shape:\n * - If `dataFormat` is `CHANNEL_LAST`:\n * 4D tensor with shape: `[batchSize, rows, cols, channels]`.\n * - If `dataFormat` is `CHANNEL_FIRST`:\n * 4D tensor with shape: `[batchSize, channels, rows, cols]`.\n *\n * Output shape:\n * 2D tensor with shape: `[batchSize, channels]`.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function globalAveragePooling2d(args: GlobalPooling2DLayerArgs) {\n return new GlobalAveragePooling2D(args);\n}\n\n/**\n * Global max pooling operation for temporal data.\n *\n * Input Shape: 3D tensor with shape: `[batchSize, steps, features]`.\n *\n * Output Shape:2D tensor with shape: `[batchSize, features]`.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function globalMaxPooling1d(args?: LayerArgs) {\n return new GlobalMaxPooling1D(args);\n}\n\n/**\n * Global max pooling operation for spatial data.\n *\n * Input shape:\n * - If `dataFormat` is `CHANNEL_LAST`:\n * 4D tensor with shape: `[batchSize, rows, cols, channels]`.\n * - If `dataFormat` is `CHANNEL_FIRST`:\n * 4D tensor with shape: `[batchSize, channels, rows, cols]`.\n *\n * Output shape:\n * 2D tensor with shape: `[batchSize, channels]`.\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function globalMaxPooling2d(args: GlobalPooling2DLayerArgs) {\n return new GlobalMaxPooling2D(args);\n}\n\n/**\n * Max pooling operation for temporal data.\n *\n * Input shape: `[batchSize, inLength, channels]`\n *\n * Output shape: `[batchSize, pooledLength, channels]`\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function maxPooling1d(args: Pooling1DLayerArgs) {\n return new MaxPooling1D(args);\n}\n\n/**\n * Max pooling operation for spatial data.\n *\n * Input shape\n * - If `dataFormat === CHANNEL_LAST`:\n * 4D tensor with shape:\n * `[batchSize, rows, cols, channels]`\n * - If `dataFormat === CHANNEL_FIRST`:\n * 4D tensor with shape:\n * `[batchSize, channels, rows, cols]`\n *\n * Output shape\n * - If `dataFormat=CHANNEL_LAST`:\n * 4D tensor with shape:\n * `[batchSize, pooleRows, pooledCols, channels]`\n * - If `dataFormat=CHANNEL_FIRST`:\n * 4D tensor with shape:\n * `[batchSize, channels, pooleRows, pooledCols]`\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function maxPooling2d(args: Pooling2DLayerArgs) {\n return new MaxPooling2D(args);\n}\n\n/**\n * Max pooling operation for 3D data.\n *\n * Input shape\n * - If `dataFormat === channelsLast`:\n * 5D tensor with shape:\n * `[batchSize, depths, rows, cols, channels]`\n * - If `dataFormat === channelsFirst`:\n * 5D tensor with shape:\n * `[batchSize, channels, depths, rows, cols]`\n *\n * Output shape\n * - If `dataFormat=channelsLast`:\n * 5D tensor with shape:\n * `[batchSize, pooledDepths, pooledRows, pooledCols, channels]`\n * - If `dataFormat=channelsFirst`:\n * 5D tensor with shape:\n * `[batchSize, channels, pooledDepths, pooledRows, pooledCols]`\n *\n * @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}\n */\nexport function maxPooling3d(args: Pooling3DLayerArgs) {\n return new MaxPooling3D(args);\n}\n\n// Recurrent Layers.\n\n/**\n * Gated Recurrent Unit - Cho et al. 2014.\n *\n * This is an `RNN` layer consisting of one `GRUCell`. However, unlike\n * the underlying `GRUCell`, the `apply` method of `SimpleRNN` operates\n * on a sequence of inputs. The shape of the input (not including the first,\n * batch dimension) needs to be at least 2-D, with the first dimension being\n * time steps. For example:\n *\n * ```js\n * const rnn = tf.layers.gru({units: 8, returnSequences: true});\n *\n * // Create an input with 10 time steps.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the `GRUCell`'s number of units.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function gru(args: GRULayerArgs) {\n return new GRU(args);\n}\n\n/**\n * Cell class for `GRU`.\n *\n * `GRUCell` is distinct from the `RNN` subclass `GRU` in that its\n * `apply` method takes the input data of only a single time step and returns\n * the cell's output at the time step, while `GRU` takes the input data\n * over a number of time steps. For example:\n *\n * ```js\n * const cell = tf.layers.gruCell({units: 2});\n * const input = tf.input({shape: [10]});\n * const output = cell.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10]: This is the cell's output at a single time step. The 1st\n * // dimension is the unknown batch size.\n * ```\n *\n * Instance(s) of `GRUCell` can be used to construct `RNN` layers. The\n * most typical use of this workflow is to combine a number of cells into a\n * stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an\n * RNN. For example:\n *\n * ```js\n * const cells = [\n * tf.layers.gruCell({units: 4}),\n * tf.layers.gruCell({units: 8}),\n * ];\n * const rnn = tf.layers.rnn({cell: cells, returnSequences: true});\n *\n * // Create an input with 10 time steps and a length-20 vector at each step.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the last `gruCell`'s number of units.\n * ```\n *\n * To create an `RNN` consisting of only *one* `GRUCell`, use the\n * `tf.layers.gru`.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function gruCell(args: GRUCellLayerArgs) {\n return new GRUCell(args);\n}\n\n/**\n * Long-Short Term Memory layer - Hochreiter 1997.\n *\n * This is an `RNN` layer consisting of one `LSTMCell`. However, unlike\n * the underlying `LSTMCell`, the `apply` method of `LSTM` operates\n * on a sequence of inputs. The shape of the input (not including the first,\n * batch dimension) needs to be at least 2-D, with the first dimension being\n * time steps. For example:\n *\n * ```js\n * const lstm = tf.layers.lstm({units: 8, returnSequences: true});\n *\n * // Create an input with 10 time steps.\n * const input = tf.input({shape: [10, 20]});\n * const output = lstm.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the `LSTMCell`'s number of units.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function lstm(args: LSTMLayerArgs) {\n return new LSTM(args);\n}\n\n/**\n * Cell class for `LSTM`.\n *\n * `LSTMCell` is distinct from the `RNN` subclass `LSTM` in that its\n * `apply` method takes the input data of only a single time step and returns\n * the cell's output at the time step, while `LSTM` takes the input data\n * over a number of time steps. For example:\n *\n * ```js\n * const cell = tf.layers.lstmCell({units: 2});\n * const input = tf.input({shape: [10]});\n * const output = cell.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10]: This is the cell's output at a single time step. The 1st\n * // dimension is the unknown batch size.\n * ```\n *\n * Instance(s) of `LSTMCell` can be used to construct `RNN` layers. The\n * most typical use of this workflow is to combine a number of cells into a\n * stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an\n * RNN. For example:\n *\n * ```js\n * const cells = [\n * tf.layers.lstmCell({units: 4}),\n * tf.layers.lstmCell({units: 8}),\n * ];\n * const rnn = tf.layers.rnn({cell: cells, returnSequences: true});\n *\n * // Create an input with 10 time steps and a length-20 vector at each step.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the last `lstmCell`'s number of units.\n * ```\n *\n * To create an `RNN` consisting of only *one* `LSTMCell`, use the\n * `tf.layers.lstm`.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function lstmCell(args: LSTMCellLayerArgs) {\n return new LSTMCell(args);\n}\n\n/**\n * Fully-connected RNN where the output is to be fed back to input.\n *\n * This is an `RNN` layer consisting of one `SimpleRNNCell`. However, unlike\n * the underlying `SimpleRNNCell`, the `apply` method of `SimpleRNN` operates\n * on a sequence of inputs. The shape of the input (not including the first,\n * batch dimension) needs to be at least 2-D, with the first dimension being\n * time steps. For example:\n *\n * ```js\n * const rnn = tf.layers.simpleRNN({units: 8, returnSequences: true});\n *\n * // Create an input with 10 time steps.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the `SimpleRNNCell`'s number of units.\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function simpleRNN(args: SimpleRNNLayerArgs) {\n return new SimpleRNN(args);\n}\n\n/**\n * Cell class for `SimpleRNN`.\n *\n * `SimpleRNNCell` is distinct from the `RNN` subclass `SimpleRNN` in that its\n * `apply` method takes the input data of only a single time step and returns\n * the cell's output at the time step, while `SimpleRNN` takes the input data\n * over a number of time steps. For example:\n *\n * ```js\n * const cell = tf.layers.simpleRNNCell({units: 2});\n * const input = tf.input({shape: [10]});\n * const output = cell.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10]: This is the cell's output at a single time step. The 1st\n * // dimension is the unknown batch size.\n * ```\n *\n * Instance(s) of `SimpleRNNCell` can be used to construct `RNN` layers. The\n * most typical use of this workflow is to combine a number of cells into a\n * stacked RNN cell (i.e., `StackedRNNCell` internally) and use it to create an\n * RNN. For example:\n *\n * ```js\n * const cells = [\n * tf.layers.simpleRNNCell({units: 4}),\n * tf.layers.simpleRNNCell({units: 8}),\n * ];\n * const rnn = tf.layers.rnn({cell: cells, returnSequences: true});\n *\n * // Create an input with 10 time steps and a length-20 vector at each step.\n * const input = tf.input({shape: [10, 20]});\n * const output = rnn.apply(input);\n *\n * console.log(JSON.stringify(output.shape));\n * // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the\n * // same as the sequence length of `input`, due to `returnSequences`: `true`;\n * // 3rd dimension is the last `SimpleRNNCell`'s number of units.\n * ```\n *\n * To create an `RNN` consisting of only *one* `SimpleRNNCell`, use the\n * `tf.layers.simpleRNN`.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function simpleRNNCell(args: SimpleRNNCellLayerArgs) {\n return new SimpleRNNCell(args);\n}\n\n/**\n * Convolutional LSTM layer - Xingjian Shi 2015.\n *\n * This is an `ConvRNN2D` layer consisting of one `ConvLSTM2DCell`. However,\n * unlike the underlying `ConvLSTM2DCell`, the `apply` method of `ConvLSTM2D`\n * operates on a sequence of inputs. The shape of the input (not including the\n * first, batch dimension) needs to be 4-D, with the first dimension being time\n * steps. For example:\n *\n * ```js\n * const filters = 3;\n * const kernelSize = 3;\n *\n * const batchSize = 4;\n * const sequenceLength = 2;\n * const size = 5;\n * const channels = 3;\n *\n * const inputShape = [batchSize, sequenceLength, size, size, channels];\n * const input = tf.ones(inputShape);\n *\n * const layer = tf.layers.convLstm2d({filters, kernelSize});\n *\n * const output = layer.apply(input);\n * ```\n */\n/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */\nexport function convLstm2d(args: ConvLSTM2DArgs) {\n return new ConvLSTM2D(args);\n}\n\n/**\n * Cell class for `ConvLSTM2D`.\n *\n * `ConvLSTM2DCell` is distinct from the `ConvRNN2D` subclass `ConvLSTM2D` in\n * that its `call` method takes the input data of only a single time step and\n * returns the cell's output at the time step, while `ConvLSTM2D` takes the\n * input data over a number of time steps. For example:\n *\n * ```js\n * const filters = 3;\n * const kernelSize = 3;\n *\n * const sequenceLength = 1;\n * const size = 5;\n * const channels = 3;\n *\n * const inputShape = [sequenceLength, size, size, channels];\n * const input = tf.ones(inputShape);\n *\n * const cell = tf.layers.convLstm2dCell({filters, kernelSize});\n *\n * cell.build(input.shape);\n *\n * const outputSize = size - kernelSize + 1;\n * const outShape = [sequenceLength, outputSize, outputSize, filters];\n *\n * const initialH = tf.zeros(outShape);\n * const initialC = tf.zeros(outShape);\n *\n * const [o, h, c] = cell.call([input, initialH, initialC], {});\n * ```\n */\n/** @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'} */\nexport function convLstm2dCell(args: ConvLSTM2DCellArgs) {\n return new ConvLSTM2DCell(args);\n}\n\n/**\n * Base class for recurrent layers.\n *\n * Input shape:\n * 3D tensor with shape `[batchSize, timeSteps, inputDim]`.\n *\n * Output shape:\n * - if `returnState`, an Array of tensors (i.e., `tf.Tensor`s). The first\n * tensor is the output. The remaining tensors are the states at the\n * last time step, each with shape `[batchSize, units]`.\n * - if `returnSequences`, the output will have shape\n * `[batchSize, timeSteps, units]`.\n * - else, the output will have shape `[batchSize, units]`.\n *\n * Masking:\n * This layer supports masking for input data with a variable number\n * of timesteps. To introduce masks to your data,\n * use an embedding layer with the `mask_zero` parameter\n * set to `True`.\n *\n * Notes on using statefulness in RNNs:\n * You can set RNN layers to be 'stateful', which means that the states\n * computed for the samples in one batch will be reused as initial states\n * for the samples in the next batch. This assumes a one-to-one mapping\n * between samples in different successive batches.\n *\n * To enable statefulness:\n * - specify `stateful: true` in the layer constructor.\n * - specify a fixed batch size for your model, by passing\n * if sequential model:\n * `batchInputShape=[...]` to the first layer in your model.\n * else for functional model with 1 or more Input layers:\n * `batchShape=[...]` to all the first layers in your model.\n * This is the expected shape of your inputs *including the batch size*.\n * It should be a tuple of integers, e.g. `(32, 10, 100)`.\n * - specify `shuffle=False` when calling fit().\n *\n * To reset the states of your model, call `.resetStates()` on either\n * a specific layer, or on your entire model.\n *\n * Note on specifying the initial state of RNNs\n * You can specify the initial state of RNN layers symbolically by\n * calling them with the option `initialState`. The value of\n * `initialState` should be a tensor or list of tensors representing\n * the initial state of the RNN layer.\n *\n * You can specify the initial state of RNN layers numerically by\n * calling `resetStates` with the keyword argument `states`. The value of\n * `states` should be a numpy array or list of numpy arrays representing\n * the initial state of the RNN layer.\n *\n * Note on passing external constants to RNNs\n * You can pass \"external\" constants to the cell using the `constants`\n * keyword argument of `RNN.call` method. This requires that the `cell.call`\n * method accepts the same keyword argument `constants`. Such constants\n * can be used to conditon the cell transformation on additional static inputs\n * (not changing over time), a.k.a an attention mechanism.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function rnn(args: RNNLayerArgs) {\n return new RNN(args);\n}\n\n/**\n * Wrapper allowing a stack of RNN cells to behave as a single cell.\n *\n * Used to implement efficient stacked RNNs.\n *\n * @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}\n */\nexport function stackedRNNCells(args: StackedRNNCellsArgs){\n return new StackedRNNCells(args);\n}\n\n// Wrapper Layers.\n\n/** @doc {heading: 'Layers', subheading: 'Wrapper', namespace: 'layers'} */\nexport function bidirectional(args: BidirectionalLayerArgs) {\n return new Bidirectional(args);\n}\n\n/**\n * This wrapper applies a layer to every temporal slice of an input.\n *\n * The input should be at least 3D, and the dimension of the index `1` will be\n * considered to be the temporal dimension.\n *\n * Consider a batch of 32 samples, where each sample is a sequence of 10 vectors\n * of 16 dimensions. The batch input shape of the layer is then `[32, 10,\n * 16]`, and the `inputShape`, not including the sample dimension, is\n * `[10, 16]`.\n *\n * You can then use `TimeDistributed` to apply a `Dense` layer to each of the 10\n * timesteps, independently:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.timeDistributed({\n * layer: tf.layers.dense({units: 8}),\n * inputShape: [10, 16],\n * }));\n *\n * // Now model.outputShape = [null, 10, 8].\n * // The output will then have shape `[32, 10, 8]`.\n *\n * // In subsequent layers, there is no need for `inputShape`:\n * model.add(tf.layers.timeDistributed({layer: tf.layers.dense({units: 32})}));\n * console.log(JSON.stringify(model.outputs[0].shape));\n * // Now model.outputShape = [null, 10, 32].\n * ```\n *\n * The output will then have shape `[32, 10, 32]`.\n *\n * `TimeDistributed` can be used with arbitrary layers, not just `Dense`, for\n * instance a `Conv2D` layer.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.timeDistributed({\n * layer: tf.layers.conv2d({filters: 64, kernelSize: [3, 3]}),\n * inputShape: [10, 299, 299, 3],\n * }));\n * console.log(JSON.stringify(model.outputs[0].shape));\n * ```\n *\n * @doc {heading: 'Layers', subheading: 'Wrapper', namespace: 'layers'}\n */\nexport function timeDistributed(args: WrapperLayerArgs) {\n return new TimeDistributed(args);\n}\n\n// Aliases for pooling.\nexport const globalMaxPool1d = globalMaxPooling1d;\nexport const globalMaxPool2d = globalMaxPooling2d;\nexport const maxPool1d = maxPooling1d;\nexport const maxPool2d = maxPooling2d;\n\nexport {Layer, RNN, RNNCell, input /* alias for tf.input */};\n\n/**\n * Apply additive zero-centered Gaussian noise.\n *\n * As it is a regularization layer, it is only active at training time.\n *\n * This is useful to mitigate overfitting\n * (you could see it as a form of random data augmentation).\n * Gaussian Noise (GS) is a natural choice as corruption process\n * for real valued inputs.\n *\n * # Arguments\n * stddev: float, standard deviation of the noise distribution.\n *\n * # Input shape\n * Arbitrary. Use the keyword argument `input_shape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * # Output shape\n * Same shape as input.\n *\n * @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'}\n */\nexport function gaussianNoise(args: GaussianNoiseArgs) {\n return new GaussianNoise(args);\n}\n\n/**\n * Apply multiplicative 1-centered Gaussian noise.\n *\n * As it is a regularization layer, it is only active at training time.\n *\n * Arguments:\n * - `rate`: float, drop probability (as with `Dropout`).\n * The multiplicative noise will have\n * standard deviation `sqrt(rate / (1 - rate))`.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * References:\n * - [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](\n * http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf)\n *\n * @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'}\n */\nexport function gaussianDropout(args: GaussianDropoutArgs) {\n return new GaussianDropout(args);\n}\n\n/**\n * Applies Alpha Dropout to the input.\n *\n * As it is a regularization layer, it is only active at training time.\n *\n * Alpha Dropout is a `Dropout` that keeps mean and variance of inputs\n * to their original values, in order to ensure the self-normalizing property\n * even after this dropout.\n * Alpha Dropout fits well to Scaled Exponential Linear Units\n * by randomly setting activations to the negative saturation value.\n *\n * Arguments:\n * - `rate`: float, drop probability (as with `Dropout`).\n * The multiplicative noise will have\n * standard deviation `sqrt(rate / (1 - rate))`.\n * - `noise_shape`: A 1-D `Tensor` of type `int32`, representing the\n * shape for randomly generated keep/drop flags.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * References:\n * - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)\n *\n * @doc {heading: 'Layers', subheading: 'Noise', namespace: 'layers'}\n */\nexport function alphaDropout(args: AlphaDropoutArgs) {\n return new AlphaDropout(args);\n}\n\n/**\n * Masks a sequence by using a mask value to skip timesteps.\n *\n * If all features for a given sample timestep are equal to `mask_value`,\n * then the sample timestep will be masked (skipped) in all downstream layers\n * (as long as they support masking).\n *\n * If any downstream layer does not support masking yet receives such\n * an input mask, an exception will be raised.\n *\n * Arguments:\n * - `maskValue`: Either None or mask value to skip.\n *\n * Input shape:\n * Arbitrary. Use the keyword argument `inputShape`\n * (tuple of integers, does not include the samples axis)\n * when using this layer as the first layer in a model.\n *\n * Output shape:\n * Same shape as input.\n *\n * @doc {heading: 'Layers', subheading: 'Mask', namespace: 'layers'}\n */\nexport function masking(args?: MaskingArgs) {\n return new Masking(args);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Utilities related to persistent state in the backend.\n */\n\n/**\n * An ID to track `tf.SymbolicTensor`s and derived classes.\n * Required in different places in engine/topology.ts to identify unique\n * tensors.\n */\nlet _nextUniqueTensorId = 0;\n\nexport function getNextUniqueTensorId(): number {\n return _nextUniqueTensorId++;\n}\n\nconst _uidPrefixes: {[prefix: string]: number} = {};\n\n/**\n * Provides a unique UID given a string prefix.\n *\n * @param prefix\n */\nexport function getUid(prefix = ''): string {\n if (!(prefix in _uidPrefixes)) {\n _uidPrefixes[prefix] = 0;\n }\n _uidPrefixes[prefix] += 1;\n return prefix + _uidPrefixes[prefix].toString();\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: utils/generic_utils.py */\n\nimport {Tensor} from '@tensorflow/tfjs-core';\nimport {ValueError} from '../errors';\nimport {Shape} from '../keras_format/common';\n// tslint:enable\n\n/**\n * Determine whether the input is an Array of Shapes.\n */\nexport function isArrayOfShapes(x: Shape|Shape[]): boolean {\n return Array.isArray(x) && Array.isArray(x[0]);\n}\n\n/**\n * Special case of normalizing shapes to lists.\n *\n * @param x A shape or list of shapes to normalize into a list of Shapes.\n * @return A list of Shapes.\n */\nexport function normalizeShapeList(x: Shape|Shape[]): Shape[] {\n if (x.length === 0) {\n return [];\n }\n if (!Array.isArray(x[0])) {\n return [x] as Shape[];\n }\n return x as Shape[];\n}\n\n/**\n * Helper function to obtain exactly one Tensor.\n * @param xs: A single `tf.Tensor` or an `Array` of `tf.Tensor`s.\n * @return A single `tf.Tensor`. If `xs` is an `Array`, return the first one.\n * @throws ValueError: If `xs` is an `Array` and its length is not 1.\n */\nexport function getExactlyOneTensor(xs: Tensor|Tensor[]): Tensor {\n let x: Tensor;\n if (Array.isArray(xs)) {\n if (xs.length !== 1) {\n throw new ValueError(`Expected Tensor length to be 1; got ${xs.length}`);\n }\n x = xs[0];\n } else {\n x = xs;\n }\n return x;\n}\n\n/**\n * Helper function to obtain exactly on instance of Shape.\n *\n * @param shapes Input single `Shape` or Array of `Shape`s.\n * @returns If input is a single `Shape`, return it unchanged. If the input is\n * an `Array` containing exactly one instance of `Shape`, return the instance.\n * Otherwise, throw a `ValueError`.\n * @throws ValueError: If input is an `Array` of `Shape`s, and its length is not\n * 1.\n */\nexport function getExactlyOneShape(shapes: Shape|Shape[]): Shape {\n if (Array.isArray(shapes) && Array.isArray(shapes[0])) {\n if (shapes.length === 1) {\n shapes = shapes as Shape[];\n return shapes[0];\n } else {\n throw new ValueError(`Expected exactly 1 Shape; got ${shapes.length}`);\n }\n } else {\n return shapes as Shape;\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {LayerVariable} from '../variables';\n\n/**\n * Count the elements in an Array of LayerVariables.\n *\n * @param weights: The LayerVariables of which the constituent numbers are to\n * be counted.\n * @returns A count of the elements in all the LayerVariables\n */\nexport function countParamsInWeights(weights: LayerVariable[]): number {\n let count = 0;\n for (const weight of weights) {\n if (weight.shape.length === 0) {\n count += 1;\n } else {\n count += weight.shape.reduce((a, b) => a * b);\n }\n }\n return count;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {DataType, Tensor, variableGrads} from '@tensorflow/tfjs-core';\n\nimport {getNextUniqueTensorId} from './backend/state';\nimport {getScopedTensorName, getUniqueTensorName} from './common';\nimport {Constraint} from './constraints';\nimport {NotImplementedError} from './errors';\nimport {Shape} from './keras_format/common';\nimport {HasShape} from './types';\n\nconst DEFAULT_VARIABLE_NAME_PREFIX = 'Variable';\n\n/**\n * A `tf.layers.LayerVariable` is similar to a `tf.Tensor` in that it has a\n * dtype and shape, but its value is mutable. The value is itself represented\n * as a`tf.Tensor`, and can be read with the `read()` method and updated with\n * the `write()` method.\n */\nexport class LayerVariable {\n readonly dtype: DataType;\n readonly shape: Shape;\n\n readonly id: number;\n // The fully scoped name of this Variable, including a unique suffix if needed\n readonly name: string;\n // The originally requested fully scoped name of this Variable, not including\n // any unique suffix. This may be needed when restoring weights because this\n // original name is used as a key.\n readonly originalName: string;\n private trainable_: boolean;\n\n protected readonly val: tfc.Variable;\n readonly constraint: Constraint;\n /**\n * Construct Variable from a `tf.Tensor`.\n *\n * If not explicitly named, the Variable will be given a name with the\n * prefix 'Variable'. Variable names are unique. In the case of name\n * collision, suffixies '_<num>' will be added to the name.\n *\n * @param val Initial value of the Variable.\n * @param name Name of the variable. If `null` or `undefined` is provided, it\n * will default a name with the prefix 'Variable'.\n * @param constraint Optional, projection function to be applied to the\n * variable after optimize updates\n * @throws ValueError if `name` is `null` or `undefined`.\n */\n constructor(\n val: Tensor, dtype: DataType = 'float32',\n name = DEFAULT_VARIABLE_NAME_PREFIX, trainable = true,\n constraint: Constraint = null) {\n this.dtype = dtype == null ? 'float32' : dtype;\n this.shape = val.shape;\n this.id = getNextUniqueTensorId();\n\n name = name == null ? DEFAULT_VARIABLE_NAME_PREFIX : name;\n this.originalName = getScopedTensorName(name);\n this.name = getUniqueTensorName(this.originalName);\n\n this.trainable_ = trainable;\n this.constraint = constraint;\n\n this.val = tfc.variable(val, this.trainable_, this.name, this.dtype);\n }\n\n /**\n * Get a snapshot of the Variable's value.\n *\n * The returned value is a snapshot of the Variable's value at the time of\n * the invocation. Future mutations in the value of the tensor will only\n * be reflected by future calls to this method.\n */\n read(): Tensor {\n this.assertNotDisposed();\n return this.val;\n }\n\n /**\n * Update the value of the Variable.\n *\n * @param newVal: The new value to update to. Must be consistent with the\n * dtype and shape of the Variable.\n * @return This Variable.\n */\n write(newVal: Tensor) {\n // TODO(cais): Once TF.js Core supports Tensor.dtype, check dtype match.\n this.assertNotDisposed();\n checkShapesMatch(this.val, newVal);\n // Skip updating if this is the exact same tensor.\n if (this.val.id !== newVal.id) {\n this.val.assign(newVal);\n if (this.constraint != null) {\n this.val.assign(this.constraint.apply(this.val));\n }\n }\n return this;\n }\n\n /**\n * Dispose this LayersVariable instance from memory.\n */\n dispose(): void {\n this.assertNotDisposed();\n this.val.dispose();\n }\n\n protected assertNotDisposed(): void {\n if (this.val.isDisposed) {\n throw new Error(`LayersVariable ${this.name} is already disposed.`);\n }\n }\n\n get trainable(): boolean {\n return this.trainable_;\n }\n\n set trainable(trainable: boolean) {\n this.trainable_ = trainable;\n this.val.trainable = trainable;\n }\n}\n\nfunction checkShapesMatch(x: HasShape, y: HasShape): void {\n if (x.shape.toString() !== y.shape.toString()) {\n throw new Error(\n 'Shape mismatch: ' + JSON.stringify(x.shape) + ' vs. ' +\n JSON.stringify(y.shape));\n }\n}\n\n/**\n * Create a Variable.\n * @param x The initial value of the `Variable`.\n * @param dtype optional, the type of the variable.\n * @param name optional, the name of the variable, default provided by\n * Variable.\n * @param constraint optional, a constraint to be applied after every update.\n * @return The newly instantiated `Variable`.\n */\nexport function variable(\n x: Tensor, dtype?: DataType, name?: string,\n constraint?: Constraint): LayerVariable {\n return new LayerVariable(x, dtype, name, true, constraint);\n}\n\n/**\n * Instantiates an all-zeros Variable and returns it.\n *\n * @param shape Shape of the tensor.\n * @param dtype DType of the tensor.\n * @param name Name of the tensor.\n * @return An all-zero Variable.\n */\nexport function zerosVariable(\n shape: Shape, dtype?: DataType, name?: string): LayerVariable {\n // TODO(cais): Implement logic for dtype.\n return new LayerVariable(tfc.zeros(shape), dtype, name);\n}\n\n/**\n * Instantiates an all-zeros tensor of the same shape as another tensor.\n *\n * @param x The other tensor.\n * @param dtype DType of the tensor.\n * @param name Name of the tensor.\n * @return A newly instantiated Variable.\n */\nexport function zerosLike(\n x: Tensor, dtype?: DataType, name?: string): LayerVariable {\n return new LayerVariable(tfc.zerosLike(x), dtype, name);\n}\n\n/**\n * Instantiates an all-ones tensor and returns it.\n *\n * @param shape Shape of the tensor.\n * @param dtype DType of the tensor.\n * @param name Name of the tensor.\n * @return An all-ones Variable.\n */\nexport function onesVariable(\n shape: Shape, dtype?: DataType, name?: string): LayerVariable {\n // TODO(cais): Implement logic for dtype.\n const allocated = tfc.ones(shape);\n return new LayerVariable(allocated, dtype, name);\n}\n\n/**\n * Instantiates an all-ones tensor of the same shape as another tensor.\n *\n * @param x The other tensor.\n * @param dtype DType of the tensor.\n * @param name Name of the tensor.\n * @return A newly instantiated Variable.\n */\nexport function onesLike(\n x: Tensor, dtype?: DataType, name?: string): LayerVariable {\n const allocated = tfc.onesLike(x);\n return new LayerVariable(allocated, dtype, name);\n}\n\n/**\n * Instantiate an identity matrix and returns it, as a Variable\n *\n * @param size Number of rows/columns.\n * @param dtype Data type of returned Variable.\n * @param name Name of returned Variable.\n * @return A Variable, an identity matrix.\n */\nexport function eyeVariable(\n size: number, dtype?: DataType, name?: string): LayerVariable {\n return new LayerVariable(tfc.eye(size), dtype, name);\n}\n\n/**\n * Get a Variable with uniform distribution of values.\n * @param shape Shape of the tensor.\n * @param minval Lower bound of the uniform distribution.\n * @param maxval Upper bound of the uniform distribution.\n * @param dtype\n * @param seed\n * @param name Optional name.\n * @return The uniform-random Variable.\n */\nexport function randomUniformVariable(\n shape: Shape, minval: number, maxval: number, dtype?: DataType,\n seed?: number, name = 'randomUniform'): LayerVariable {\n return new LayerVariable(\n tfc.randomUniform(shape, minval, maxval, dtype), dtype, name);\n}\n\n/**\n * Get a Variable with truncated-normal distribution of values.\n * @param shape Shape of the tensor.\n * @param mean mean value of the normal distribution.\n * @param stddev standard deviation of the normal distribution.\n * @param dtype\n * @param seed\n * @param name Optional name.\n * @return The truncated-normal-random Variable.\n */\nexport function truncatedNormalVariable(\n shape: Shape, mean = 0.0, stddev = 1.0, dtype?: DataType, seed?: number,\n name = 'truncatedNormal'): LayerVariable {\n // TODO(cais): Implement logic for dtype and seed once they are supported\n // by deeplearn.js.\n dtype = dtype || 'float32';\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new NotImplementedError(\n `randomNormal does not support dType ${dtype}.`);\n }\n return new LayerVariable(\n tfc.truncatedNormal(shape, mean, stddev, dtype, seed), dtype, name);\n}\n/**\n * Get a Variable with normal distribution of values.\n * @param shape Shape of the tensor.\n * @param mean mean value of the normal distribution.\n * @param stddev standard deviation of the normal distribution.\n * @param dtype\n * @param seed\n * @param name Optional name.\n * @return The truncated-normal-random Variable.\n */\nexport function randomNormalVariable(\n shape: Shape, mean = 0.0, stddev = 1.0, dtype?: DataType, seed?: number,\n name = 'randomNormal'): LayerVariable {\n dtype = dtype || 'float32';\n if (dtype !== 'float32' && dtype !== 'int32') {\n throw new NotImplementedError(\n `randomNormalVariable does not support dType ${dtype}.`);\n }\n return new LayerVariable(\n tfc.randomNormal(shape, mean, stddev, dtype, seed), dtype, name);\n}\n\n/**\n * Update the value of a Variable.\n * @param x The Variable to be updated.\n * @param xNew The new value to update to.\n * @return The Variable updated.\n */\nexport function update(x: LayerVariable, xNew: Tensor): LayerVariable {\n return x.write(xNew);\n}\n\n/**\n * Update the value of a Variable by adding an increment.\n * @param x The Variable to be updated.\n * @param increment The incrment to add to `x`.\n * @return The Variable updated.\n */\nexport function updateAdd(x: LayerVariable, increment: Tensor): LayerVariable {\n return x.write(tfc.add(x.read(), increment));\n}\n\n/**\n * Update the value of a Variable by subtracting a decrement.\n * @param x The Variable to be updated.\n * @param decrement The decrement to subtract from `x`.\n * @return The Variable updated.\n */\nexport function updateSub(x: LayerVariable, decrement: Tensor): LayerVariable {\n return x.write(tfc.sub(x.read(), decrement));\n}\n\n/**\n * Get the values of an array of Variables.\n *\n * @param tensors An `Array` of `Variable`s to get the values of.\n * @return The values of the inputs, as an `Array` of`tf.Tensor`s.\n */\nexport function batchGetValue(xs: LayerVariable[]): Tensor[] {\n return xs.map(x => x.read());\n}\n\n/**\n * Update the value of multiple Variables at once.\n *\n * @param variablesAndValues An `Array`, each element is of type\n * [Variable, Tensor]. The first item is the\n * `Variable` of which the value is to be updated. The second item\n * carries the new value.\n */\nexport function batchSetValue(\n variablesAndValues: Array<[LayerVariable, Tensor]>): void {\n variablesAndValues.forEach(variableAndValue => {\n const variable: LayerVariable = variableAndValue[0];\n variable.write(variableAndValue[1]);\n });\n}\n\n/**\n * Returns the gradients of `variables` w.r.t. the return value of `lossFn`.\n * @param lossFn A function which returns a Scalar to be used as the function\n * value (i.e., numerator) for differentiation.\n * @param variables List of variables to be used as the independent variables\n * (i.e., denominator) for differentiation.\n * @returns An Array of gradients tensors.\n */\nexport function gradients(\n lossFn: () => tfc.Scalar, variables: LayerVariable[]): Tensor[] {\n // TODO(cais): The return type signature can be simplified if deeplearn makes\n // the corresponding type public.\n const variableList =\n variables.map(variable => variable.read() as tfc.Variable);\n const valudAndGrads = variableGrads(lossFn, variableList);\n return variables.map(variable => valudAndGrads.grads[variable.name]);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: keras/engine/topology.py */\n\nimport {DataType, Scalar, serialization, Tensor, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {getNextUniqueTensorId, getUid} from '../backend/state';\nimport {getScopedTensorName, getUniqueTensorName, nameScope} from '../common';\nimport {Constraint} from '../constraints';\nimport {AttributeError, NotImplementedError, RuntimeError, ValueError} from '../errors';\nimport {getInitializer, Initializer} from '../initializers';\nimport {Shape} from '../keras_format/common';\nimport {Regularizer} from '../regularizers';\nimport {Kwargs, RegularizerFn} from '../types';\nimport * as generic_utils from '../utils/generic_utils';\nimport * as types_utils from '../utils/types_utils';\nimport * as variable_utils from '../utils/variable_utils';\nimport {batchGetValue, batchSetValue, LayerVariable} from '../variables';\n\n// TODO(michaelterry): This is a stub until it's defined.\nexport type Op = (x: LayerVariable) => LayerVariable;\n\n/**\n * Constructor arguments for InputSpec.\n */\nexport interface InputSpecArgs {\n /** Expected datatype of the input. */\n dtype?: DataType;\n /** Expected shape of the input (may include null for unchecked axes). */\n shape?: Shape;\n /** Expected rank of the input. */\n ndim?: number;\n /** Maximum rank of the input. */\n maxNDim?: number;\n /** Minimum rank of the input. */\n minNDim?: number;\n /** Dictionary mapping integer axes to a specific dimension value. */\n axes?: {[axis: number]: number};\n}\n\n/**\n * Specifies the ndim, dtype and shape of every input to a layer.\n *\n * Every layer should expose (if appropriate) an `inputSpec` attribute:\n * a list of instances of InputSpec (one per input tensor).\n *\n * A null entry in a shape is compatible with any dimension,\n * a null shape is compatible with any shape.\n */\nexport class InputSpec {\n /** Expected datatype of the input. */\n dtype?: DataType;\n /** Expected shape of the input (may include null for unchecked axes). */\n shape?: Shape;\n /** Expected rank of the input. */\n ndim?: number;\n /** Maximum rank of the input. */\n maxNDim?: number;\n /** Minimum rank of the input. */\n minNDim?: number;\n /** Dictionary mapping integer axes to a specific dimension value. */\n axes?: {[axis: number]: number};\n\n constructor(args: InputSpecArgs) {\n this.dtype = args.dtype;\n this.shape = args.shape;\n /*\n TODO(michaelterry): Could throw error if ndim and shape are both defined\n (then backport).\n */\n if (args.shape != null) {\n this.ndim = args.shape.length;\n } else {\n this.ndim = args.ndim;\n }\n this.maxNDim = args.maxNDim;\n this.minNDim = args.minNDim;\n this.axes = args.axes || {};\n }\n}\n\n/**\n * `tf.SymbolicTensor` is a placeholder for a Tensor without any concrete value.\n *\n * They are most often encountered when building a graph of `Layer`s for a\n * a `tf.LayersModel` and the input data's shape, but not values are known.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\nexport class SymbolicTensor {\n /* A unique ID for the tensor to be able to differentiate tensors. */\n readonly id: number;\n // The fully scoped name of this Variable, including a unique suffix if needed\n readonly name: string;\n // The originally requested fully scoped name of this Variable, not including\n // any unique suffix. This may be needed when restoring weights because this\n // original name is used as a key.\n readonly originalName?: string;\n /**\n * Rank/dimensionality of the tensor.\n */\n readonly rank: number;\n /**\n * Replacement for _keras_history.\n */\n nodeIndex: number;\n /**\n * Replacement for _keras_history.\n */\n tensorIndex: number;\n\n /**\n *\n * @param dtype\n * @param shape\n * @param sourceLayer The Layer that produced this symbolic tensor.\n * @param inputs The inputs passed to sourceLayer's __call__() method.\n * @param nodeIndex\n * @param tensorIndex\n * @param callArgs The keyword arguments passed to the __call__() method.\n * @param name\n * @param outputTensorIndex The index of this tensor in the list of outputs\n * returned by apply().\n */\n constructor(\n readonly dtype: DataType, readonly shape: Shape,\n public sourceLayer: Layer, readonly inputs: SymbolicTensor[],\n readonly callArgs: Kwargs, name?: string,\n readonly outputTensorIndex?: number) {\n this.id = getNextUniqueTensorId();\n if (name != null) {\n this.originalName = getScopedTensorName(name);\n this.name = getUniqueTensorName(this.originalName);\n }\n this.rank = shape.length;\n }\n}\n\n/**\n * Constructor arguments for Node.\n */\nexport interface NodeArgs {\n /**\n * The layer that takes `inputTensors` and turns them into `outputTensors`.\n * (the node gets created when the `call` method of the layer is called).\n */\n outboundLayer: Layer;\n /**\n * A list of layers, the same length as `inputTensors`, the layers from where\n * `inputTensors` originate.\n */\n inboundLayers: Layer[];\n /**\n * A list of integers, the same length as `inboundLayers`. `nodeIndices[i]` is\n * the origin node of `inputTensors[i]` (necessary since each inbound layer\n * might have several nodes, e.g. if the layer is being shared with a\n * different data stream).\n */\n nodeIndices: number[];\n /**\n * A list of integers, the same length as `inboundLayers`. `tensorIndices[i]`\n * is the index of `inputTensors[i]` within the output of the inbound layer\n * (necessary since each inbound layer might have multiple tensor outputs,\n * with each one being independently manipulable).\n */\n tensorIndices: number[];\n /** List of input tensors. */\n inputTensors: SymbolicTensor[];\n /** List of output tensors. */\n outputTensors: SymbolicTensor[];\n /** List of input masks (a mask can be a tensor, or null). */\n inputMasks: Tensor[];\n /** List of output masks (a mask can be a tensor, or null). */\n outputMasks: Tensor[];\n /** List of input shape tuples. */\n inputShapes: Shape|Shape[];\n /** List of output shape tuples. */\n outputShapes: Shape|Shape[];\n}\n\n/**\n * The type of the return value of Layer.dispose() and Container.dispose().\n */\nexport interface DisposeResult {\n /**\n * Reference count after the dispose call.\n */\n refCountAfterDispose: number;\n\n /**\n * Number of variables dispose in this dispose call.\n */\n numDisposedVariables: number;\n}\n\nlet _nextNodeID = 0;\n\n/**\n * A `Node` describes the connectivity between two layers.\n *\n * Each time a layer is connected to some new input,\n * a node is added to `layer.inboundNodes`.\n *\n * Each time the output of a layer is used by another layer,\n * a node is added to `layer.outboundNodes`.\n *\n * `nodeIndices` and `tensorIndices` are basically fine-grained coordinates\n * describing the origin of the `inputTensors`, verifying the following:\n *\n * `inputTensors[i] ==\n * inboundLayers[i].inboundNodes[nodeIndices[i]].outputTensors[\n * tensorIndices[i]]`\n *\n * A node from layer A to layer B is added to:\n * A.outboundNodes\n * B.inboundNodes\n */\nexport class Node {\n /**\n * The layer that takes `inputTensors` and turns them into `outputTensors`\n * (the node gets created when the `call` method of the layer is called).\n */\n outboundLayer: Layer;\n /**\n * A list of layers, the same length as `inputTensors`, the layers from where\n * `inputTensors` originate.\n */\n inboundLayers: Layer[];\n /**\n * A list of integers, the same length as `inboundLayers`. `nodeIndices[i]` is\n * the origin node of `inputTensors[i]` (necessary since each inbound layer\n * might have several nodes, e.g. if the layer is being shared with a\n * different data stream).\n */\n nodeIndices: number[];\n /**\n * A list of integers, the same length as `inboundLayers`. `tensorIndices[i]`\n * is the index of `inputTensors[i]` within the output of the inbound layer\n * (necessary since each inbound layer might have multiple tensor outputs,\n * with each one being independently manipulable).\n */\n tensorIndices: number[];\n /** List of input tensors. */\n inputTensors: SymbolicTensor[];\n /** List of output tensors. */\n outputTensors: SymbolicTensor[];\n /** List of input masks (a mask can be a tensor, or null). */\n inputMasks: Tensor[];\n /** List of output masks (a mask can be a tensor, or null). */\n outputMasks: Tensor[];\n /** List of input shape tuples. */\n inputShapes: Shape|Shape[];\n /** List of output shape tuples. */\n outputShapes: Shape|Shape[];\n\n readonly id: number;\n\n constructor(\n args: NodeArgs,\n // TODO(michaelterry): Define actual type for this.\n public callArgs?: Kwargs) {\n this.id = _nextNodeID++;\n /*\n Layer instance (NOT a list).\n this is the layer that takes a list of input tensors\n and turns them into a list of output tensors.\n the current node will be added to\n the inboundNodes of outboundLayer.\n */\n this.outboundLayer = args.outboundLayer;\n\n /*\n The following 3 properties describe where\n the input tensors come from: which layers,\n and for each layer, which node and which\n tensor output of each node.\n */\n\n // List of layer instances.\n this.inboundLayers = args.inboundLayers;\n // List of integers, 1:1 mapping with inboundLayers.\n this.nodeIndices = args.nodeIndices;\n // List of integers, 1:1 mapping with inboundLayers.\n this.tensorIndices = args.tensorIndices;\n\n /*\n Following 2 properties:\n tensor inputs and outputs of outboundLayer.\n */\n\n // List of tensors. 1:1 mapping with inboundLayers.\n this.inputTensors = args.inputTensors;\n // List of tensors, created by outboundLayer.call().\n this.outputTensors = args.outputTensors;\n\n /*\n Following 2 properties: input and output masks.\n List of tensors, 1:1 mapping with inputTensor.\n */\n this.inputMasks = args.inputMasks;\n // List of tensors, created by outboundLayer.computeMask().\n this.outputMasks = args.outputMasks;\n\n // Following 2 properties: input and output shapes.\n\n // List of shape tuples, shapes of inputTensors.\n this.inputShapes = args.inputShapes;\n // List of shape tuples, shapes of outputTensors.\n this.outputShapes = args.outputShapes;\n\n // Add nodes to all layers involved.\n for (const layer of args.inboundLayers) {\n if (layer != null) {\n layer.outboundNodes.push(this);\n }\n }\n args.outboundLayer.inboundNodes.push(this);\n }\n\n getConfig(): serialization.ConfigDict {\n const inboundNames: string[] = [];\n for (const layer of this.inboundLayers) {\n if (layer != null) {\n inboundNames.push(layer.name);\n } else {\n inboundNames.push(null);\n }\n }\n return {\n outboundLayer: this.outboundLayer ? this.outboundLayer.name : null,\n inboundLayers: inboundNames,\n nodeIndices: this.nodeIndices,\n tensorIndices: this.tensorIndices\n };\n }\n}\n\n/** Constructor arguments for Layer. */\nexport declare interface LayerArgs {\n /**\n * If defined, will be used to create an input layer to insert before this\n * layer. If both `inputShape` and `batchInputShape` are defined,\n * `batchInputShape` will be used. This argument is only applicable to input\n * layers (the first layer of a model).\n */\n inputShape?: Shape;\n /**\n * If defined, will be used to create an input layer to insert before this\n * layer. If both `inputShape` and `batchInputShape` are defined,\n * `batchInputShape` will be used. This argument is only applicable to input\n * layers (the first layer of a model).\n */\n batchInputShape?: Shape;\n /**\n * If `inputShape` is specified and `batchInputShape` is *not* specified,\n * `batchSize` is used to construct the `batchInputShape`: `[batchSize,\n * ...inputShape]`\n */\n batchSize?: number;\n /**\n * The data-type for this layer. Defaults to 'float32'.\n * This argument is only applicable to input layers (the first layer of a\n * model).\n */\n dtype?: DataType;\n /** Name for this layer. */\n name?: string;\n /**\n * Whether the weights of this layer are updatable by `fit`.\n * Defaults to true.\n */\n trainable?: boolean;\n /**\n * Initial weight values of the layer.\n */\n weights?: Tensor[];\n /** Legacy support. Do not use for new code. */\n inputDType?: DataType;\n}\n\n// If necessary, add `output` arguments to the CallHook function.\n// This is currently used for testing only, but may be used for debugger-related\n// purposes in the future.\nexport type CallHook = (inputs: Tensor|Tensor[], kwargs: Kwargs) => void;\n\nlet _nextLayerID = 0;\n\n/**\n * A layer is a grouping of operations and weights that can be composed to\n * create a `tf.LayersModel`.\n *\n * Layers are constructed by using the functions under the\n * [tf.layers](#Layers-Basic) namespace.\n *\n * @doc {heading: 'Layers', subheading: 'Classes', namespace: 'layers'}\n */\nexport abstract class Layer extends serialization.Serializable {\n /** Name for this layer. Must be unique within a model. */\n name: string;\n /**\n * List of InputSpec class instances.\n *\n * Each entry describes one required input:\n * - ndim\n * - dtype\n * A layer with `n` input tensors must have an `inputSpec` of length `n`.\n */\n inputSpec: InputSpec[];\n supportsMasking: boolean;\n /** Whether the layer weights will be updated during training. */\n protected trainable_: boolean;\n batchInputShape: Shape;\n dtype: DataType;\n initialWeights: Tensor[];\n\n inboundNodes: Node[];\n outboundNodes: Node[];\n\n activityRegularizer: Regularizer;\n\n protected _trainableWeights: LayerVariable[];\n private _nonTrainableWeights: LayerVariable[];\n private _losses: RegularizerFn[];\n // TODO(cais): _updates is currently unused.\n private _updates: Tensor[];\n private _built: boolean;\n private _callHook: CallHook = null;\n\n private _addedWeightNames: string[] = [];\n\n readonly id: number;\n\n // Porting Notes: PyKeras does not have this property in this base Layer\n // class. Instead lets Layer subclass set it dynamically and checks the\n // value with `hasattr`. In tfjs-layers, we let this be a member of this\n // base class.\n protected _stateful = false;\n\n protected _refCount: number|null;\n\n // A flag for whether fast (i.e., all-zero) weight initialization is to\n // be used during `build()` call. This speeds up weight initialization\n // by saving unnecessary calls to expensive initializers in cases where\n // the initialized values will be overwritten by loaded weight values\n // during model loading.\n private fastWeightInitDuringBuild: boolean;\n\n constructor(args: LayerArgs = {}) {\n super();\n this.id = _nextLayerID++;\n\n this.activityRegularizer = null;\n\n this.inputSpec = null;\n this.supportsMasking = false;\n\n // These properties will be set upon call of this.build()\n this._trainableWeights = [];\n this._nonTrainableWeights = [];\n this._losses = [];\n this._updates = [];\n this._built = false;\n\n /*\n These lists will be filled via successive calls\n to this.addInboundNode().\n */\n this.inboundNodes = [];\n this.outboundNodes = [];\n\n let name = args.name;\n if (!name) {\n const prefix = this.getClassName();\n name = generic_utils.toSnakeCase(prefix) + '_' + getUid(prefix);\n }\n this.name = name;\n\n this.trainable_ = args.trainable == null ? true : args.trainable;\n\n if (args.inputShape != null || args.batchInputShape != null) {\n /*\n In this case we will later create an input layer\n to insert before the current layer\n */\n let batchInputShape: Shape;\n if (args.batchInputShape != null) {\n batchInputShape = args.batchInputShape;\n } else if (args.inputShape != null) {\n let batchSize: number = null;\n if (args.batchSize != null) {\n batchSize = args.batchSize;\n }\n batchInputShape = [batchSize].concat(args.inputShape);\n }\n this.batchInputShape = batchInputShape;\n\n // Set dtype.\n let dtype = args.dtype;\n if (dtype == null) {\n dtype = args.inputDType;\n }\n if (dtype == null) {\n dtype = 'float32';\n }\n this.dtype = dtype;\n }\n\n if (args.weights != null) {\n this.initialWeights = args.weights;\n } else {\n this.initialWeights = null;\n }\n\n // The value of `_refCount` is initialized to null. When the layer is used\n // in a symbolic way for the first time, it will be set to 1.\n this._refCount = null;\n\n this.fastWeightInitDuringBuild = false;\n }\n\n /**\n * Converts a layer and its index to a unique (immutable type) name.\n * This function is used internally with `this.containerNodes`.\n * @param layer The layer.\n * @param nodeIndex The layer's position (e.g. via enumerate) in a list of\n * nodes.\n *\n * @returns The unique name.\n */\n protected static nodeKey(layer: Layer, nodeIndex: number) {\n return layer.name + '_ib-' + nodeIndex.toString();\n }\n\n /**\n * Returns this.inboundNode at index nodeIndex.\n *\n * Porting note: This is a replacement for _get_node_attribute_at_index()\n * @param nodeIndex\n * @param attrName The name of the attribute related to request for this node.\n */\n private getNodeAtIndex(nodeIndex: number, attrName: string): Node {\n if (this.inboundNodes.length === 0) {\n throw new RuntimeError(\n 'The layer has never been called ' +\n `and thus has no defined ${attrName}.`);\n }\n if (this.inboundNodes.length <= nodeIndex) {\n throw new ValueError(\n `Asked to get ${attrName} at node ${nodeIndex}, ` +\n `but the layer has only ${this.inboundNodes.length} inbound nodes.`);\n }\n return this.inboundNodes[nodeIndex];\n }\n\n /**\n * Retrieves the input tensor(s) of a layer at a given node.\n *\n * @param nodeIndex Integer, index of the node from which to retrieve the\n * attribute. E.g. `nodeIndex=0` will correspond to the first time the layer\n * was called.\n *\n * @return A tensor (or list of tensors if the layer has multiple inputs).\n */\n getInputAt(nodeIndex: number): SymbolicTensor|SymbolicTensor[] {\n return generic_utils.singletonOrArray(\n this.getNodeAtIndex(nodeIndex, 'input').inputTensors);\n }\n\n /**\n * Retrieves the output tensor(s) of a layer at a given node.\n *\n * @param nodeIndex Integer, index of the node from which to retrieve the\n * attribute. E.g. `nodeIndex=0` will correspond to the first time the layer\n * was called.\n *\n * @return A tensor (or list of tensors if the layer has multiple outputs).\n */\n getOutputAt(nodeIndex: number): SymbolicTensor|SymbolicTensor[] {\n return generic_utils.singletonOrArray(\n this.getNodeAtIndex(nodeIndex, 'output').outputTensors);\n }\n\n // Properties\n\n /**\n * Retrieves the input tensor(s) of a layer.\n *\n * Only applicable if the layer has exactly one inbound node,\n * i.e. if it is connected to one incoming layer.\n *\n * @return Input tensor or list of input tensors.\n *\n * @exception AttributeError if the layer is connected to more than one\n * incoming layers.\n */\n get input(): SymbolicTensor|SymbolicTensor[] {\n if (this.inboundNodes.length > 1) {\n throw new AttributeError(\n `Layer ${this.name}` +\n ' has multiple inbound nodes, ' +\n 'hence the notion of \"layer input\" ' +\n 'is ill-defined. ' +\n 'Use `getInputAt(nodeIndex)` instead.');\n } else if (this.inboundNodes.length === 0) {\n throw new AttributeError(\n `Layer ${this.name}` +\n ' is not connected, no input to return.');\n }\n return generic_utils.singletonOrArray(\n this.getNodeAtIndex(0, 'input').inputTensors);\n }\n\n /**\n * Retrieves the output tensor(s) of a layer.\n *\n * Only applicable if the layer has exactly one inbound node,\n * i.e. if it is connected to one incoming layer.\n *\n * @return Output tensor or list of output tensors.\n *\n * @exception AttributeError if the layer is connected to more than one\n * incoming layers.\n */\n get output(): SymbolicTensor|SymbolicTensor[] {\n if (this.inboundNodes.length === 0) {\n throw new AttributeError(\n `Layer ${this.name}` +\n ' has no inbound nodes.');\n }\n if (this.inboundNodes.length > 1) {\n throw new AttributeError(\n `Layer ${this.name}` +\n ' has multiple inbound nodes, ' +\n 'hence the notion of \"layer output\" ' +\n 'is ill-defined. ' +\n 'Use `getOutputAt(nodeIndex)` instead.');\n }\n return generic_utils.singletonOrArray(\n this.getNodeAtIndex(0, 'output').outputTensors);\n }\n\n get losses(): RegularizerFn[] {\n return this._losses;\n }\n\n /**\n * Retrieves the Layer's current loss values.\n *\n * Used for regularizers during training.\n */\n calculateLosses(): Scalar[] {\n // Porting Node: This is an augmentation to Layer.loss in PyKeras.\n // In PyKeras, Layer.loss returns symbolic tensors. Here a concrete\n // Tensor (specifically Scalar) values are returned. This is due to the\n // imperative backend.\n return this.losses.map(lossFn => lossFn());\n }\n\n get updates(): Tensor[] {\n return this._updates;\n }\n\n get built(): boolean {\n return this._built;\n }\n\n set built(built: boolean) {\n this._built = built;\n }\n\n get trainable(): boolean {\n return this.trainable_;\n }\n\n set trainable(trainable: boolean) {\n this._trainableWeights.forEach(w => w.trainable = trainable);\n this.trainable_ = trainable;\n }\n\n get trainableWeights(): LayerVariable[] {\n if (this.trainable_) {\n return this._trainableWeights.filter(w => w.trainable);\n } else {\n return [];\n }\n }\n\n set trainableWeights(weights: LayerVariable[]) {\n this._trainableWeights = weights;\n }\n\n get nonTrainableWeights(): LayerVariable[] {\n if (this.trainable) {\n return this._trainableWeights.filter(w => !w.trainable)\n .concat(this._nonTrainableWeights);\n } else {\n return this._trainableWeights.concat(this._nonTrainableWeights);\n }\n }\n\n set nonTrainableWeights(weights: LayerVariable[]) {\n this._nonTrainableWeights = weights;\n }\n\n /**\n * The concatenation of the lists trainableWeights and nonTrainableWeights\n * (in this order).\n */\n get weights(): LayerVariable[] {\n return this.trainableWeights.concat(this.nonTrainableWeights);\n }\n\n get stateful(): boolean {\n return this._stateful;\n }\n\n /**\n * Reset the states of the layer.\n *\n * This method of the base Layer class is essentially a no-op.\n * Subclasses that are stateful (e.g., stateful RNNs) should override this\n * method.\n */\n resetStates(): void {\n if (!this.stateful) {\n throw new Error(\n 'Cannot call the resetStates() method of a non-stateful Layer ' +\n 'object.');\n }\n }\n\n /**\n * Checks compatibility between the layer and provided inputs.\n *\n * This checks that the tensor(s) `input`\n * verify the input assumptions of the layer\n * (if any). If not, exceptions are raised.\n *\n * @param inputs Input tensor or list of input tensors.\n *\n * @exception ValueError in case of mismatch between\n * the provided inputs and the expectations of the layer.\n */\n protected assertInputCompatibility(inputs: Tensor|Tensor[]|SymbolicTensor|\n SymbolicTensor[]): void {\n inputs = generic_utils.toList(inputs);\n if (this.inputSpec == null || this.inputSpec.length === 0) {\n return;\n }\n const inputSpec = generic_utils.toList(this.inputSpec);\n if (inputs.length !== inputSpec.length) {\n throw new ValueError(\n `Layer ${this.name} expects ${inputSpec.length} inputs, ` +\n `but it received ${inputs.length} input tensors. ` +\n `Input received: ${inputs}`);\n }\n for (let inputIndex = 0; inputIndex < inputs.length; inputIndex++) {\n const x = inputs[inputIndex];\n const spec: InputSpec = inputSpec[inputIndex];\n if (spec == null) {\n continue;\n }\n\n // Check ndim.\n const ndim = x.rank;\n if (spec.ndim != null) {\n if (ndim !== spec.ndim) {\n throw new ValueError(\n `Input ${inputIndex} is incompatible with layer ${this.name}: ` +\n `expected ndim=${spec.ndim}, found ndim=${ndim}`);\n }\n }\n if (spec.maxNDim != null) {\n if (ndim > spec.maxNDim) {\n throw new ValueError(\n `Input ${inputIndex} is incompatible with layer ${this.name}` +\n `: expected max_ndim=${spec.maxNDim}, found ndim=${ndim}`);\n }\n }\n if (spec.minNDim != null) {\n if (ndim < spec.minNDim) {\n throw new ValueError(\n `Input ${inputIndex} is incompatible with layer ${this.name}` +\n `: expected min_ndim=${spec.minNDim}, found ndim=${ndim}.`);\n }\n }\n\n // Check dtype.\n if (spec.dtype != null) {\n if (x.dtype !== spec.dtype) {\n throw new ValueError(\n `Input ${inputIndex} is incompatible with layer ${this.name} ` +\n `: expected dtype=${spec.dtype}, found dtype=${x.dtype}.`);\n }\n }\n\n // Check specific shape axes.\n if (spec.axes) {\n const xShape = x.shape;\n for (const key in spec.axes) {\n const axis = Number(key);\n const value = spec.axes[key];\n // Perform Python-style slicing in case axis < 0;\n // TODO(cais): Use https://github.com/alvivi/typescript-underscore to\n // ensure type safety through Underscore calls.\n const xShapeAtAxis =\n axis >= 0 ? xShape[axis] : xShape[xShape.length + axis];\n if (value != null && [value, null].indexOf(xShapeAtAxis) === -1) {\n throw new ValueError(\n `Input ${inputIndex} is incompatible with layer ` +\n `${this.name}: expected axis ${axis} of input shape to ` +\n `have value ${value} but got shape ${xShape}.`);\n }\n }\n }\n\n // Check shape.\n if (spec.shape != null) {\n for (let i = 0; i < spec.shape.length; ++i) {\n const specDim = spec.shape[i];\n const dim = x.shape[i];\n if (specDim != null && dim != null) {\n if (specDim !== dim) {\n throw new ValueError(\n `Input ${inputIndex} is incompatible with layer ` +\n `${this.name}: expected shape=${spec.shape}, ` +\n `found shape=${x.shape}.`);\n }\n }\n }\n }\n }\n }\n\n /**\n * This is where the layer's logic lives.\n *\n * @param inputs Input tensor, or list/tuple of input tensors.\n * @param kwargs Additional keyword arguments.\n *\n * @return A tensor or list/tuple of tensors.\n */\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return inputs;\n }\n\n protected invokeCallHook(inputs: Tensor|Tensor[], kwargs: Kwargs) {\n if (this._callHook != null) {\n this._callHook(inputs, kwargs);\n }\n }\n\n /**\n * Set call hook.\n * This is currently used for testing only.\n * @param callHook\n */\n setCallHook(callHook: CallHook) {\n this._callHook = callHook;\n }\n\n /**\n * Clear call hook.\n * This is currently used for testing only.\n */\n clearCallHook() {\n this._callHook = null;\n }\n\n /**\n * Builds or executes a `Layer's logic.\n *\n * When called with `tf.Tensor`(s), execute the `Layer`s computation and\n * return Tensor(s). For example:\n *\n * ```js\n * const denseLayer = tf.layers.dense({\n * units: 1,\n * kernelInitializer: 'zeros',\n * useBias: false\n * });\n *\n * // Invoke the layer's apply() method with a `tf.Tensor` (with concrete\n * // numeric values).\n * const input = tf.ones([2, 2]);\n * const output = denseLayer.apply(input);\n *\n * // The output's value is expected to be [[0], [0]], due to the fact that\n * // the dense layer has a kernel initialized to all-zeros and does not have\n * // a bias.\n * output.print();\n * ```\n *\n * When called with `tf.SymbolicTensor`(s), this will prepare the layer for\n * future execution. This entails internal book-keeping on shapes of\n * expected Tensors, wiring layers together, and initializing weights.\n *\n * Calling `apply` with `tf.SymbolicTensor`s are typically used during the\n * building of non-`tf.Sequential` models. For example:\n *\n * ```js\n * const flattenLayer = tf.layers.flatten();\n * const denseLayer = tf.layers.dense({units: 1});\n *\n * // Use tf.layers.input() to obtain a SymbolicTensor as input to apply().\n * const input = tf.input({shape: [2, 2]});\n * const output1 = flattenLayer.apply(input);\n *\n * // output1.shape is [null, 4]. The first dimension is the undetermined\n * // batch size. The second dimension comes from flattening the [2, 2]\n * // shape.\n * console.log(JSON.stringify(output1.shape));\n *\n * // The output SymbolicTensor of the flatten layer can be used to call\n * // the apply() of the dense layer:\n * const output2 = denseLayer.apply(output1);\n *\n * // output2.shape is [null, 1]. The first dimension is the undetermined\n * // batch size. The second dimension matches the number of units of the\n * // dense layer.\n * console.log(JSON.stringify(output2.shape));\n *\n * // The input and output and be used to construct a model that consists\n * // of the flatten and dense layers.\n * const model = tf.model({inputs: input, outputs: output2});\n * ```\n *\n * @param inputs a `tf.Tensor` or `tf.SymbolicTensor` or an Array of them.\n * @param kwargs Additional keyword arguments to be passed to `call()`.\n *\n * @return Output of the layer's `call` method.\n *\n * @exception ValueError error in case the layer is missing shape information\n * for its `build` call.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n // Porting Note: This is a replacement for __call__() in Python.\n apply(\n inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],\n kwargs?: Kwargs): Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[] {\n kwargs = kwargs || {};\n\n this.assertNotDisposed();\n\n // Ensure inputs are all the same type.\n const inputsList = generic_utils.toList(inputs);\n\n let allAreSymbolic = true;\n for (const input of inputsList) {\n if (!(input instanceof SymbolicTensor)) {\n allAreSymbolic = false;\n break;\n }\n }\n let noneAreSymbolic = true;\n for (const input of inputsList) {\n if (input instanceof SymbolicTensor) {\n noneAreSymbolic = false;\n break;\n }\n }\n\n if (allAreSymbolic === noneAreSymbolic) {\n throw new ValueError(\n 'Arguments to apply() must be all ' +\n 'SymbolicTensors or all Tensors');\n }\n\n // TODO(michaelterry): nameScope() may not be necessary.\n return nameScope(this.name, () => {\n // Handle laying building (weight creating, input spec locking).\n if (!this.built) {\n /*\n Throw exceptions in case the input is not compatible\n with the inputSpec specified in the layer constructor.\n */\n this.assertInputCompatibility(inputs);\n\n // Collect input shapes to build layer.\n const inputShapes: Shape[] = [];\n for (const xElem of generic_utils.toList(inputs)) {\n inputShapes.push(xElem.shape);\n }\n this.build(generic_utils.singletonOrArray(inputShapes));\n this.built = true;\n\n // Load weights that were specified at layer instantiation.\n if (this.initialWeights) {\n this.setWeights(this.initialWeights);\n }\n\n if (this._refCount === null && noneAreSymbolic) {\n // The first use of this layer is a non-symbolic call, set ref count\n // to 1 so the Layer can be properly disposed if its dispose() method\n // is called.\n this._refCount = 1;\n }\n }\n\n /*\n Throw exceptions in case the input is not compatible\n with the inputSpec set at build time.\n */\n this.assertInputCompatibility(inputs);\n\n // Handle mask propagation.\n // TODO(michaelterry): Mask propagation not currently implemented.\n\n // Actually call the layer, collecting output(s), mask(s), and shape(s).\n if (noneAreSymbolic) {\n let output = this.call(inputs as Tensor | Tensor[], kwargs);\n // TODO(michaelterry): Compute the outputMask\n\n // If the layer returns tensors from its inputs, unmodified,\n // we copy them to avoid loss of tensor metadata.\n const outputList: Tensor[] = generic_utils.toList(output);\n const outputListCopy: Tensor[] = [];\n // TODO(michaelterry): This copying may not be necessary given our eager\n // backend.\n for (let x of outputList) {\n if (inputsList.indexOf(x) !== -1) {\n x = x.clone();\n }\n outputListCopy.push(x);\n }\n output = generic_utils.singletonOrArray(outputListCopy);\n\n if (this.activityRegularizer != null) {\n throw new NotImplementedError(\n 'Layer invocation in the presence of activity ' +\n 'regularizer(s) is not supported yet.');\n }\n\n // TODO(michaelterry): Call addInboundNode()?\n return output;\n } else {\n const inputShape = collectInputShape(inputs);\n const outputShape = this.computeOutputShape(inputShape);\n let output: SymbolicTensor|SymbolicTensor[];\n const outputDType = guessOutputDType(inputs);\n this.warnOnIncompatibleInputShape(\n Array.isArray(inputs) ? inputShape[0] as Shape :\n inputShape as Shape);\n\n if (outputShape != null && outputShape.length > 0 &&\n Array.isArray(outputShape[0])) {\n // We have multiple output shapes. Create multiple output tensors.\n output = (outputShape as Shape[])\n .map(\n (shape, index) => new SymbolicTensor(\n outputDType, shape, this,\n generic_utils.toList(inputs), kwargs, this.name,\n index));\n } else {\n output = new SymbolicTensor(\n outputDType, outputShape as Shape, this,\n generic_utils.toList(inputs), kwargs, this.name);\n }\n\n /*\n Add an inbound node to the layer, so that it keeps track\n of the call and of all new variables created during the call.\n This also updates the layer history of the output tensor(s).\n If the input tensor(s) had no previous history,\n this does nothing.\n */\n this.addInboundNode(\n inputs as SymbolicTensor | SymbolicTensor[], output, null, null,\n inputShape, outputShape, kwargs);\n this._refCount++;\n\n if (this.activityRegularizer != null) {\n throw new NotImplementedError(\n 'Layer invocation in the presence of activity ' +\n 'regularizer(s) is not supported yet.');\n }\n\n return output;\n }\n });\n }\n\n /**\n * Check compatibility between input shape and this layer's batchInputShape.\n *\n * Print warning if any incompatibility is found.\n *\n * @param inputShape Input shape to be checked.\n */\n protected warnOnIncompatibleInputShape(inputShape: Shape) {\n if (this.batchInputShape == null) {\n return;\n } else if (inputShape.length !== this.batchInputShape.length) {\n console.warn(\n `The rank of the input tensor provided (shape: ` +\n `${JSON.stringify(inputShape)}) does not match that of the ` +\n `batchInputShape (${JSON.stringify(this.batchInputShape)}) ` +\n `of the layer ${this.name}`);\n } else {\n let dimMismatch = false;\n this.batchInputShape.forEach((dimension, i) => {\n if (dimension != null && inputShape[i] != null &&\n inputShape[i] !== dimension) {\n dimMismatch = true;\n }\n });\n if (dimMismatch) {\n console.warn(\n `The shape of the input tensor ` +\n `(${JSON.stringify(inputShape)}) does not ` +\n `match the expectation of layer ${this.name}: ` +\n `${JSON.stringify(this.batchInputShape)}`);\n }\n }\n }\n\n /**\n * Retrieves the output shape(s) of a layer.\n *\n * Only applicable if the layer has only one inbound node, or if all inbound\n * nodes have the same output shape.\n *\n * @returns Output shape or shapes.\n * @throws AttributeError: if the layer is connected to more than one incoming\n * nodes.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n get outputShape(): Shape|Shape[] {\n if (this.inboundNodes == null || this.inboundNodes.length === 0) {\n throw new AttributeError(\n `The layer ${this.name} has never been called and thus has no ` +\n `defined output shape.`);\n }\n const allOutputShapes: string[] = [];\n for (const node of this.inboundNodes) {\n const shapeString = JSON.stringify(node.outputShapes);\n if (allOutputShapes.indexOf(shapeString) === -1) {\n allOutputShapes.push(shapeString);\n }\n }\n if (allOutputShapes.length === 1) {\n const outputShapes = this.inboundNodes[0].outputShapes;\n if (Array.isArray(outputShapes) && Array.isArray(outputShapes[0]) &&\n outputShapes.length === 1) {\n return (outputShapes as Shape[])[0];\n } else {\n return outputShapes;\n }\n\n } else {\n throw new AttributeError(\n `The layer ${this.name} has multiple inbound nodes with different ` +\n `output shapes. Hence the notion of \"output shape\" is ill-defined ` +\n `for the layer.`);\n // TODO(cais): Implement getOutputShapeAt().\n }\n }\n\n /**\n * Counts the total number of numbers (e.g., float32, int32) in the\n * weights.\n *\n * @returns An integer count.\n * @throws RuntimeError: If the layer is not built yet (in which case its\n * weights are not defined yet.)\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n countParams(): number {\n if (!this.built) {\n throw new RuntimeError(\n `You tried to call countParams() on ${this.name}, ` +\n `but the layer is not built yet. Build it first by calling ` +\n `build(batchInputShape).`);\n }\n return variable_utils.countParamsInWeights(this.weights);\n }\n\n /**\n * Creates the layer weights.\n *\n * Must be implemented on all layers that have weights.\n *\n * Called when apply() is called to construct the weights.\n *\n * @param inputShape A `Shape` or array of `Shape` (unused).\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n build(inputShape: Shape|Shape[]) {\n this.built = true;\n }\n\n /**\n * Returns the current values of the weights of the layer.\n *\n * @param trainableOnly Whether to get the values of only trainable weights.\n * @returns Weight values as an `Array` of `tf.Tensor`s.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n getWeights(trainableOnly = false): Tensor[] {\n return batchGetValue(trainableOnly ? this.trainableWeights : this.weights);\n }\n\n /**\n * Sets the weights of the layer, from Tensors.\n *\n * @param weights a list of Tensors. The number of arrays and their shape\n * must match number of the dimensions of the weights of the layer (i.e.\n * it should match the output of `getWeights`).\n *\n * @exception ValueError If the provided weights list does not match the\n * layer's specifications.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n setWeights(weights: Tensor[]): void {\n tidy(() => {\n const params = this.weights;\n if (params.length !== weights.length) {\n // TODO(cais): Restore the following and use `providedWeights`, instead\n // of `weights` in the error message, once the deeplearn.js bug is\n // fixed: https://github.com/PAIR-code/deeplearnjs/issues/498 const\n // providedWeights = JSON.stringify(weights).substr(0, 50);\n throw new ValueError(\n `You called setWeights(weights) on layer \"${this.name}\" ` +\n `with a weight list of length ${weights.length}, ` +\n `but the layer was expecting ${params.length} weights. ` +\n `Provided weights: ${weights}...`);\n }\n if (params.length === 0) {\n return;\n }\n const weightValueTuples: Array<[LayerVariable, Tensor]> = [];\n const paramValues = batchGetValue(params);\n for (let i = 0; i < paramValues.length; ++i) {\n const pv = paramValues[i];\n const p = params[i];\n const w = weights[i];\n if (!util.arraysEqual(pv.shape, w.shape)) {\n throw new ValueError(\n `Layer weight shape ${pv.shape} ` +\n `not compatible with provided weight shape ${w.shape}`);\n }\n weightValueTuples.push([p, w]);\n }\n batchSetValue(weightValueTuples);\n });\n }\n\n /**\n * Adds a weight variable to the layer.\n *\n * @param name Name of the new weight variable.\n * @param shape The shape of the weight.\n * @param dtype The dtype of the weight.\n * @param initializer An initializer instance.\n * @param regularizer A regularizer instance.\n * @param trainable Whether the weight should be trained via backprop or not\n * (assuming that the layer itself is also trainable).\n * @param constraint An optional trainable.\n * @return The created weight variable.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n protected addWeight(\n name: string, shape: Shape, dtype?: DataType, initializer?: Initializer,\n regularizer?: Regularizer, trainable?: boolean,\n constraint?: Constraint): LayerVariable {\n // Reject duplicate weight names.\n if (this._addedWeightNames.indexOf(name) !== -1) {\n throw new ValueError(\n `Duplicate weight name ${name} for layer ${this.name}`);\n }\n this._addedWeightNames.push(name);\n\n if (dtype == null) {\n dtype = 'float32';\n }\n\n if (this.fastWeightInitDuringBuild) {\n initializer = getInitializer('zeros');\n }\n const initValue = initializer.apply(shape, dtype);\n const weight =\n new LayerVariable(initValue, dtype, name, trainable, constraint);\n initValue.dispose();\n // Request backend not to dispose the weights of the model on scope() exit.\n if (regularizer != null) {\n this.addLoss(() => regularizer.apply(weight.read()));\n }\n if (trainable == null) {\n trainable = true;\n }\n if (trainable) {\n this._trainableWeights.push(weight);\n } else {\n this._nonTrainableWeights.push(weight);\n }\n return weight;\n }\n\n /**\n * Set the fast-weight-initialization flag.\n *\n * In cases where the initialized weight values will be immediately\n * overwritten by loaded weight values during model loading, setting\n * the flag to `true` saves unnecessary calls to potentially expensive\n * initializers and speeds up the loading process.\n *\n * @param value Target value of the flag.\n */\n setFastWeightInitDuringBuild(value: boolean) {\n this.fastWeightInitDuringBuild = value;\n }\n\n /**\n * Add losses to the layer.\n *\n * The loss may potentionally be conditional on some inputs tensors,\n * for instance activity losses are conditional on the layer's inputs.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n addLoss(losses: RegularizerFn|RegularizerFn[]): void {\n if (losses == null || Array.isArray(losses) && losses.length === 0) {\n return;\n }\n // Update this.losses\n losses = generic_utils.toList(losses);\n if (this._losses !== undefined && this._losses !== null) {\n this.losses.push(...losses);\n }\n }\n\n /**\n * Computes the output shape of the layer.\n *\n * Assumes that the layer will be built to match that input shape provided.\n *\n * @param inputShape A shape (tuple of integers) or a list of shape tuples\n * (one per output tensor of the layer). Shape tuples can include null for\n * free dimensions, instead of an integer.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n /**\n * Computes an output mask tensor.\n *\n * @param inputs Tensor or list of tensors.\n * @param mask Tensor or list of tensors.\n *\n * @return null or a tensor (or list of tensors, one per output tensor of the\n * layer).\n */\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor\n |Tensor[] {\n if (!this.supportsMasking) {\n if (mask != null) {\n if (Array.isArray(mask)) {\n mask.forEach(maskElement => {\n if (maskElement != null) {\n throw new TypeError(\n `Layer ${this.name} does not support masking, ` +\n 'but was passed an inputMask.');\n }\n });\n } else {\n throw new TypeError(\n `Layer ${this.name} does not support masking, ` +\n 'but was passed an inputMask.');\n }\n }\n // masking not explicitly supported: return null as mask\n return null;\n }\n // if masking is explictly supported, by default\n // carry over the input mask\n return mask;\n }\n\n /**\n * Internal method to create an inbound node for the layer.\n *\n * @param inputTensors List of input tensors.\n * @param outputTensors List of output tensors.\n * @param inputMasks List of input masks (a mask can be a tensor, or null).\n * @param outputMasks List of output masks (a mask can be a tensor, or null).\n * @param inputShapes List of input shape tuples.\n * @param outputShapes List of output shape tuples.\n * @param kwargs Dictionary of keyword arguments that were passed to the\n * `call` method of the layer at the call that created the node.\n */\n private addInboundNode(\n inputTensors: SymbolicTensor|SymbolicTensor[],\n outputTensors: SymbolicTensor|SymbolicTensor[],\n inputMasks: Tensor|Tensor[], outputMasks: Tensor|Tensor[],\n inputShapes: Shape|Shape[], outputShapes: Shape|Shape[],\n kwargs: {} = null): void {\n const inputTensorList: SymbolicTensor[] =\n generic_utils.toList(inputTensors);\n outputTensors = generic_utils.toList(outputTensors);\n inputMasks = generic_utils.toList(inputMasks);\n outputMasks = generic_utils.toList(outputMasks);\n inputShapes = types_utils.normalizeShapeList(inputShapes);\n outputShapes = types_utils.normalizeShapeList(outputShapes);\n\n // Collect input tensor(s) coordinates.\n const inboundLayers: Layer[] = [];\n const nodeIndices: number[] = [];\n const tensorIndices: number[] = [];\n for (const x of inputTensorList) {\n /*\n * TODO(michaelterry): Keras adds this value to tensors; it's not\n * clear whether we'll use this or not.\n */\n inboundLayers.push(x.sourceLayer);\n nodeIndices.push(x.nodeIndex);\n tensorIndices.push(x.tensorIndex);\n }\n\n // Create node, add it to inbound nodes.\n // (This call has side effects.)\n // tslint:disable-next-line:no-unused-expression\n new Node(\n {\n outboundLayer: this,\n inboundLayers,\n nodeIndices,\n tensorIndices,\n inputTensors: inputTensorList,\n outputTensors,\n inputMasks,\n outputMasks,\n inputShapes,\n outputShapes\n },\n kwargs);\n\n // Update tensor history\n for (let i = 0; i < outputTensors.length; i++) {\n // TODO(michaelterry: _uses_learning_phase not tracked.\n outputTensors[i].sourceLayer = this;\n outputTensors[i].nodeIndex = this.inboundNodes.length - 1;\n outputTensors[i].tensorIndex = i;\n }\n }\n\n /**\n * Returns the config of the layer.\n *\n * A layer config is a TS dictionary (serializable)\n * containing the configuration of a layer.\n * The same layer can be reinstantiated later\n * (without its trained weights) from this configuration.\n *\n * The config of a layer does not include connectivity\n * information, nor the layer class name. These are handled\n * by 'Container' (one layer of abstraction above).\n *\n * Porting Note: The TS dictionary follows TS naming standrds for\n * keys, and uses tfjs-layers type-safe Enums. Serialization methods\n * should use a helper function to convert to the pythonic storage\n * standard. (see serialization_utils.convertTsToPythonic)\n *\n * @returns TS dictionary of configuration.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n getConfig(): serialization.ConfigDict {\n const config:\n serialization.ConfigDict = {name: this.name, trainable: this.trainable};\n if (this.batchInputShape != null) {\n config['batchInputShape'] = this.batchInputShape;\n }\n if (this.dtype != null) {\n config['dtype'] = this.dtype;\n }\n return config;\n }\n\n /**\n * Dispose the weight variables that this Layer instance holds.\n *\n * @returns {number} Number of disposed variables.\n */\n protected disposeWeights(): number {\n this.weights.forEach(weight => weight.dispose());\n return this.weights.length;\n }\n\n protected assertNotDisposed() {\n if (this._refCount === 0) {\n throw new Error(`Layer '${this.name}' is already disposed.`);\n }\n }\n\n /**\n * Attempt to dispose layer's weights.\n *\n * This method decrease the reference count of the Layer object by 1.\n *\n * A Layer is reference-counted. Its reference count is incremented by 1\n * the first item its `apply()` method is called and when it becomes a part\n * of a new `Node` (through calling the `apply()`) method on a\n * `tf.SymbolicTensor`).\n *\n * If the reference count of a Layer becomes 0, all the weights will be\n * disposed and the underlying memory (e.g., the textures allocated in WebGL)\n * will be freed.\n *\n * Note: If the reference count is greater than 0 after the decrement, the\n * weights of the Layer will *not* be disposed.\n *\n * After a Layer is disposed, it cannot be used in calls such as `apply()`,\n * `getWeights()` or `setWeights()` anymore.\n *\n * @returns A DisposeResult Object with the following fields:\n * - refCountAfterDispose: The reference count of the Container after this\n * `dispose()` call.\n * - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed\n * during this `dispose()` call.\n * @throws {Error} If the layer is not built yet, or if the layer has already\n * been disposed.\n *\n * @doc {heading: 'Models', 'subheading': 'Classes'}\n */\n dispose(): DisposeResult {\n if (!this.built) {\n throw new Error(\n `Cannot dispose Layer ${this.name} because it has not been ` +\n `built yet.`);\n }\n\n if (this._refCount === null) {\n throw new Error(\n `Cannot dispose Layer ${this.name} because it has not been used ` +\n `yet.`);\n }\n\n this.assertNotDisposed();\n\n let numDisposedVariables = 0;\n if (--this._refCount === 0) {\n numDisposedVariables = this.disposeWeights();\n }\n\n return {refCountAfterDispose: this._refCount, numDisposedVariables};\n }\n}\n\n/**\n * Collects the input shape(s) of a list of `tf.Tensor`s or\n * `tf.SymbolicTensor`s.\n *\n * TODO(michaelterry): Update PyKeras docs (backport).\n *\n * @param inputTensors List of input tensors (or single input tensor).\n *\n * @return List of shape tuples (or single tuple), one tuple per input.\n */\nfunction collectInputShape(inputTensors: SymbolicTensor|SymbolicTensor[]|Tensor|\n Tensor[]): Shape|Shape[] {\n inputTensors =\n generic_utils.toList(inputTensors) as SymbolicTensor[] | Tensor[];\n const shapes: Shape[] = [];\n for (const x of inputTensors) {\n shapes.push(x.shape);\n }\n return generic_utils.singletonOrArray(shapes);\n}\n\n/**\n * Guesses output dtype based on inputs.\n *\n * At present, just returns 'float32' for any input.\n *\n * @param inputTensors List of input tensors (or single input tensor).\n *\n * @return The guessed DType. At present, always returns 'float32'.\n */\nfunction guessOutputDType(inputTensors: SymbolicTensor|SymbolicTensor[]|Tensor|\n Tensor[]): DataType {\n return 'float32';\n}\n\n/**\n * Returns the list of input tensors necessary to compute `tensor`.\n *\n * Output will always be a list of tensors (potentially with 1 element).\n *\n * @param tensor The tensor to start from.\n * @param layer Origin layer of the tensor.\n * @param nodeIndex Origin node index of the tensor.\n *\n * @return Array of input tensors.\n */\nexport function getSourceInputs(\n tensor: SymbolicTensor, layer?: Layer,\n nodeIndex?: number): SymbolicTensor[] {\n if (layer == null || (nodeIndex != null && nodeIndex > 0)) {\n layer = tensor.sourceLayer;\n nodeIndex = tensor.nodeIndex;\n }\n if (layer.inboundNodes.length === 0) {\n return [tensor];\n } else {\n const node = layer.inboundNodes[nodeIndex];\n if (node.inboundLayers.length === 0) {\n return node.inputTensors;\n } else {\n const sourceTensors: SymbolicTensor[] = [];\n for (let i = 0; i < node.inboundLayers.length; i++) {\n const x = node.inputTensors[i];\n const layer = node.inboundLayers[i];\n const nodeIndex = node.nodeIndices[i];\n const previousSources = getSourceInputs(x, layer, nodeIndex);\n // Avoid input redundancy.\n for (const x of previousSources) {\n if (sourceTensors.indexOf(x) === -1) {\n sourceTensors.push(x);\n }\n }\n }\n return sourceTensors;\n }\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {DataType, serialization, Tensor} from '@tensorflow/tfjs-core';\n\nimport {getUid} from '../backend/state';\nimport {ValueError} from '../errors';\nimport {Shape} from '../keras_format/common';\nimport {Kwargs} from '../types';\n\nimport {DisposeResult, Layer, Node, SymbolicTensor} from './topology';\n\n/**\n * Constructor arguments for InputLayer.\n *\n * Note: You should provide only inputShape or batchInputShape (not both).\n * If only inputShape is provided, then the batchInputShape is determined by\n * the batchSize argument and the inputShape: [batchSize].concat(inputShape).\n */\nexport declare interface InputLayerArgs {\n /** Input shape, not including the batch axis. */\n inputShape?: Shape;\n /** Optional input batch size (integer or null). */\n batchSize?: number;\n /** Batch input shape, including the batch axis. */\n batchInputShape?: Shape;\n /** Datatype of the input. */\n dtype?: DataType;\n /**\n * Whether the placeholder created is meant to be sparse.\n */\n sparse?: boolean; // TODO(michaelterry): Not clear whether we'll need this.\n\n /** Name of the layer. */\n name?: string;\n}\n\nexport class InputLayer extends Layer {\n /** @nocollapse */\n static readonly className = 'InputLayer';\n sparse: boolean;\n constructor(args: InputLayerArgs) {\n super({\n dtype: args.dtype,\n name: args.name != null ? args.name : getUid('input').toString()\n });\n // Normalize config.batchSize and config.sparse\n if (args.batchSize == null) {\n args.batchSize = null;\n }\n if (args.sparse == null) {\n args.sparse = false;\n }\n\n this.trainable = false;\n this.built = true;\n this.sparse = args.sparse;\n\n if (args.inputShape != null && args.batchInputShape != null) {\n throw new ValueError(\n 'Only provide the inputShape OR ' +\n 'batchInputShape argument to inputLayer, not both at the same time.');\n }\n let batchInputShape = args.batchInputShape;\n if (batchInputShape == null) {\n if (args.inputShape == null) {\n throw new ValueError(\n 'An InputLayer should be passed either a ' +\n '`batchInputShape` or an `inputShape`.');\n } else {\n batchInputShape = [args.batchSize].concat(args.inputShape);\n }\n } else {\n // TODO(michaelterry): Backport to PyKeras\n if (args.batchSize != null) {\n throw new ValueError(\n 'Cannot specify batchSize if batchInputShape is ' +\n 'specified when creating an InputLayer.');\n }\n }\n\n const dtype = args.dtype || 'float32';\n\n this.batchInputShape = batchInputShape;\n this.dtype = dtype;\n // TODO(michaelterry): Backport this to PyKeras?\n this.inputSpec = [{shape: batchInputShape}];\n\n const inputTensor = new SymbolicTensor(\n this.dtype, this.batchInputShape, this, [], {}, this.name);\n inputTensor.nodeIndex = 0;\n inputTensor.tensorIndex = 0;\n\n // Create an input node to add to this.outboundNode.\n // (This call has side effects.)\n // tslint:disable-next-line:no-unused-expression\n new Node({\n outboundLayer: this,\n inboundLayers: [],\n nodeIndices: [],\n tensorIndices: [],\n inputTensors: [inputTensor],\n outputTensors: [inputTensor],\n inputMasks: [null],\n outputMasks: [null],\n inputShapes: [batchInputShape],\n outputShapes: [batchInputShape]\n });\n }\n\n apply(\n inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],\n kwargs?: Kwargs): Tensor|Tensor[]|SymbolicTensor {\n throw new ValueError(\n 'Cannot pass any input to an ' +\n `InputLayer's apply() method. InputLayer name: ${this.name}`);\n }\n\n dispose(): DisposeResult {\n // dispose() for InputLayer is overridden as no-op.\n return {refCountAfterDispose: this._refCount, numDisposedVariables: 0};\n }\n\n getConfig(): serialization.ConfigDict {\n return {\n batchInputShape: this.batchInputShape,\n dtype: this.dtype,\n sparse: this.sparse,\n name: this.name\n };\n }\n}\nserialization.registerClass(InputLayer);\n\n/**\n * Config for the Input function.\n *\n * Note: You should provide only shape or batchShape (not both).\n * If only shape is provided, then the batchShape becomes\n * [null].concat(inputShape).\n */\nexport interface InputConfig {\n /**\n * A shape, not including the batch size. For instance, `shape=[32]`\n * indicates that the expected input will be batches of 32-dimensional\n * vectors.\n */\n shape?: Shape;\n /**\n * A shape tuple (integer), including the batch size. For instance,\n * `batchShape=[10, 32]` indicates that the expected input will be batches of\n * 10 32-dimensional vectors. `batchShape=[null, 32]` indicates batches of an\n * arbitrary number of 32-dimensional vectors.\n */\n batchShape?: Shape;\n /**\n * An optional name string for the layer. Should be unique in a model (do not\n * reuse the same name twice). It will be autogenerated if it isn't provided.\n */\n name?: string;\n dtype?: DataType;\n /**\n * A boolean specifying whether the placeholder to be created is sparse.\n */\n sparse?: boolean;\n}\n\nexport function Input(config: InputConfig): SymbolicTensor {\n if (config.batchShape == null && config.shape == null) {\n throw new Error(\n 'Please provide to Input either a `shape`' +\n ' or a `batchShape` argument. Note that ' +\n '`shape` does not include the batch ' +\n 'dimension.');\n }\n if (config.batchShape != null && config.shape != null) {\n // TODO(michaelterry): Backport to PyKeras.\n throw new ValueError(\n 'Please provide either a `shape` or `batchShape` ' +\n 'argument to Input, but not both.');\n }\n let batchShape = config.batchShape;\n if (config.shape != null && batchShape == null) {\n batchShape = [null].concat(config.shape);\n }\n\n let dtype = config.dtype;\n if (dtype == null) {\n dtype = 'float32';\n }\n\n const inputLayer = new InputLayer({\n batchInputShape: batchShape,\n name: config.name,\n dtype,\n sparse: config.sparse\n });\n\n const outputs = inputLayer.inboundNodes[0].outputTensors;\n return outputs[0];\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {dispose, Scalar} from '@tensorflow/tfjs-core';\n\n/**\n * Logs in which values can be either numbers or Tensors (Scalars).\n *\n * Used internally.\n */\nexport type UnresolvedLogs = {\n [key: string]: number|Scalar;\n};\n\n/**\n * Turn any Scalar values in a Logs object into actual number values.\n *\n * @param logs The `Logs` object to be resolved in place.\n */\nexport async function resolveScalarsInLogs(logs: UnresolvedLogs) {\n if (logs == null) {\n return;\n }\n const promises: Array<Promise<Float32Array|Int32Array|Uint8Array>> = [];\n const keys: string[] = [];\n const scalarsToDispose: Scalar[] = [];\n for (const key in logs) {\n const value = logs[key];\n if (typeof value !== 'number') {\n const valueScalar = value;\n promises.push(valueScalar.data());\n keys.push(key);\n scalarsToDispose.push(valueScalar);\n }\n }\n if (promises.length > 0) {\n const values = await Promise.all(promises);\n for (let i = 0; i < values.length; ++i) {\n logs[keys[i]] = values[i][0];\n }\n // Dispose the original scalar tensors.\n dispose(scalarsToDispose);\n }\n}\n\n/**\n * Dispose all Tensors in an UnresolvedLogs object.\n *\n * @param logs An `UnresolvedLogs` object potentially containing `tf.Tensor`s in\n * places where the values can be `tf.Tensor` or `number`.\n */\nexport function disposeTensorsInLogs(logs: UnresolvedLogs) {\n if (logs == null) {\n return;\n }\n for (const key in logs) {\n const value = logs[key];\n if (typeof value !== 'number') {\n value.dispose();\n }\n }\n}\n\n/**\n * Logs in which values can only be numbers.\n *\n * Used when calling client-provided custom callbacks.\n */\nexport type Logs = {\n [key: string]: number;\n};\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: keras/callbacks.py */\n\nimport {add, div, keep, mul, nextFrame, Scalar, Tensor, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {Container} from './engine/container';\nimport {ValueError} from './errors';\nimport {Logs, resolveScalarsInLogs, UnresolvedLogs} from './logs';\nimport * as generic_utils from './utils/generic_utils';\n\n/** Verbosity logging level when fitting a model. */\nexport enum ModelLoggingVerbosity {\n SILENT = 0,\n VERBOSE = 1\n}\n\n/** How often to yield to the main thread when training (in ms). */\nexport const DEFAULT_YIELD_EVERY_MS = 125;\n\nexport type Params = {\n [key: string]: number|string|boolean|number[]|string[]|boolean[];\n};\n\nexport type YieldEveryOptions = 'auto'|'batch'|'epoch'|'never'|number;\n\n/**\n * Abstract base class used to build new callbacks.\n *\n * The `logs` dictionary that callback methods take as argument will contain\n * keys for quantities relevant to the current batch or epoch.\n *\n * Currently, the `.fit()` method of the `Sequential` model class\n * will include the following quantities in the `logs` that\n * it passes to its callbacks:\n *\n * onEpochEnd: Logs include `acc` and `loss`, and optionally include `valLoss`\n * (if validation is enabled in `fit`), and `valAcc` (if validation and\n * accuracy monitoring are enabled).\n * onBatchBegin: Logs include `size`, the number of samples in the current\n * batch.\n * onBatchEnd: Logs include `loss`, and optionally `acc` (if accuracy monitoring\n * is enabled).\n */\nexport abstract class BaseCallback {\n // TODO(michaelterry): This type is a best guess.\n validationData: Tensor|Tensor[] = null;\n /**\n * Training parameters (eg. verbosity, batch size, number of epochs...).\n */\n params: Params;\n\n setParams(params: Params): void {\n this.params = params;\n }\n\n async onEpochBegin(epoch: number, logs?: UnresolvedLogs) {}\n\n async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {}\n\n async onBatchBegin(batch: number, logs?: UnresolvedLogs) {}\n\n async onBatchEnd(batch: number, logs?: UnresolvedLogs) {}\n\n async onTrainBegin(logs?: UnresolvedLogs) {}\n\n async onTrainEnd(logs?: UnresolvedLogs) {}\n\n // LayersModel needs to call Callback.setModel(), but cannot actually depend\n // on Callback because that creates a cyclic dependency. Providing this no-op\n // method on BaseCallback breaks the cycle: this way LayersModel can depend on\n // BaseCallback but not on Callback. The argument is typed as `Container`\n // (the superclass of LayersModel) to avoid recapitulating the cycle. Callback\n // overrides this method and enforces that the argument is really a\n // LayersModel.\n setModel(model: Container): void {\n // Do nothing. Use Callback instead of BaseCallback to track the model.\n }\n}\n\n/**\n * Container abstracting a list of callbacks.\n */\nexport class CallbackList {\n callbacks: BaseCallback[];\n queueLength: number;\n\n // TODO(cais): When the need arises, uncomment the following lines and\n // implement the queue for time values.\n // private deltaTBatch: number;\n // private deltaTsBatchBegin: Array<number>;\n // private deltaTsBatchEnd: Array<number>;\n\n /**\n * Constructor of CallbackList.\n * @param callbacks Array of `Callback` instances.\n * @param queueLength Queue length for keeping running statistics over\n * callback execution time.\n */\n constructor(callbacks?: BaseCallback[], queueLength = 10) {\n // TODO(cais): Make use of queueLength when implementing the queue for time\n // values.\n if (callbacks == null) {\n callbacks = [];\n }\n this.callbacks = callbacks;\n this.queueLength = queueLength;\n }\n\n append(callback: BaseCallback): void {\n this.callbacks.push(callback);\n }\n\n setParams(params: Params): void {\n for (const callback of this.callbacks) {\n callback.setParams(params);\n }\n }\n\n setModel(model: Container): void {\n for (const callback of this.callbacks) {\n callback.setModel(model);\n }\n }\n\n /**\n * Called at the start of an epoch.\n * @param epoch Index of epoch.\n * @param logs Dictionary of logs.\n */\n async onEpochBegin(epoch: number, logs?: UnresolvedLogs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onEpochBegin(epoch, logs);\n }\n }\n\n /**\n * Called at the end of an epoch.\n * @param epoch Index of epoch.\n * @param logs Dictionary of logs.\n */\n async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onEpochEnd(epoch, logs);\n }\n }\n\n /**\n * Called right before processing a batch.\n * @param batch Index of batch within the current epoch.\n * @param logs Dictionary of logs.\n */\n async onBatchBegin(batch: number, logs?: UnresolvedLogs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onBatchBegin(batch, logs);\n }\n }\n\n /**\n * Called at the end of a batch.\n * @param batch Index of batch within the current epoch.\n * @param logs Dictionary of logs.\n */\n async onBatchEnd(batch: number, logs?: UnresolvedLogs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onBatchEnd(batch, logs);\n }\n }\n\n /**\n * Called at the beginning of training.\n * @param logs Dictionary of logs.\n */\n async onTrainBegin(logs?: UnresolvedLogs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onTrainBegin(logs);\n }\n }\n\n /**\n * Called at the end of training.\n * @param logs Dictionary of logs.\n */\n async onTrainEnd(logs?: UnresolvedLogs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onTrainEnd(logs);\n }\n }\n}\n\n/**\n * Callback that accumulates epoch averages of metrics.\n *\n * This callback is automatically applied to every LayersModel.\n */\nexport class BaseLogger extends BaseCallback {\n private seen: number;\n private totals: UnresolvedLogs;\n\n constructor() {\n super();\n }\n\n async onEpochBegin(epoch: number) {\n this.seen = 0;\n this.totals = {};\n }\n\n async onBatchEnd(batch: number, logs?: UnresolvedLogs) {\n if (logs == null) {\n logs = {};\n }\n const batchSize = logs['size'] == null ? 0 : logs['size'] as number;\n this.seen += batchSize;\n for (const key in logs) {\n const value = logs[key];\n if (typeof value === 'number') {\n if (!this.totals.hasOwnProperty(key)) {\n this.totals[key] = 0;\n }\n this.totals[key] = this.totals[key] as number + value * batchSize;\n } else {\n let oldTotalsToDispose: Scalar;\n if (key in this.totals) {\n oldTotalsToDispose = this.totals[key] as Scalar;\n } else {\n this.totals[key] = 0;\n }\n const total: Scalar =\n tidy(() => add((this.totals[key]), mul(value, batchSize)));\n this.totals[key] = total;\n if (oldTotalsToDispose != null) {\n oldTotalsToDispose.dispose();\n }\n }\n }\n }\n\n async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {\n if (logs != null) {\n for (const key of this.params['metrics'] as string[]) {\n if (this.totals[key] == null) {\n continue;\n }\n if (typeof this.totals[key] === 'number') {\n logs[key] = this.totals[key] as number / this.seen;\n } else {\n tidy(() => {\n const log: Scalar = mul(div(1, this.seen), this.totals[key]);\n logs[key] = log;\n (this.totals[key] as Tensor).dispose();\n keep(logs[key] as Scalar);\n });\n }\n }\n }\n }\n}\n\n/**\n * Callback that records events into a `History` object. This callback is\n * automatically applied to every TF.js Layers model. The `History` object\n * gets returned by the `fit` method of models.\n */\nexport class History extends BaseCallback {\n epoch: number[];\n history: {[key: string]: Array<number|Tensor>};\n\n async onTrainBegin(logs?: UnresolvedLogs) {\n this.epoch = [];\n this.history = {};\n }\n\n async onEpochEnd(epoch: number, logs?: UnresolvedLogs) {\n if (logs == null) {\n logs = {};\n }\n this.epoch.push(epoch);\n for (const key in logs) {\n if (this.history[key] == null) {\n this.history[key] = [];\n }\n this.history[key].push(logs[key]);\n }\n }\n\n /**\n * Await the values of all losses and metrics.\n */\n async syncData() {\n const promises: Array<Promise<Float32Array|Int32Array|Uint8Array>> = [];\n const keys: string[] = [];\n const indices: number[] = [];\n for (const key in this.history) {\n const valueArray = this.history[key];\n for (let i = 0; i < valueArray.length; ++i) {\n if (typeof valueArray[i] !== 'number') {\n const valueScalar = valueArray[i] as Tensor;\n promises.push(valueScalar.data());\n keys.push(key);\n indices.push(i);\n }\n }\n }\n const values = await Promise.all(promises);\n for (let n = 0; n < values.length; ++n) {\n const tensorToDispose = this.history[keys[n]][indices[n]] as Tensor;\n tensorToDispose.dispose();\n this.history[keys[n]][indices[n]] = values[n][0];\n }\n }\n}\n\nexport interface CustomCallbackArgs {\n onTrainBegin?: (logs?: Logs) => void | Promise<void>;\n onTrainEnd?: (logs?: Logs) => void | Promise<void>;\n onEpochBegin?: (epoch: number, logs?: Logs) => void | Promise<void>;\n onEpochEnd?: (epoch: number, logs?: Logs) => void | Promise<void>;\n onBatchBegin?: (batch: number, logs?: Logs) => void | Promise<void>;\n onBatchEnd?: (batch: number, logs?: Logs) => void | Promise<void>;\n onYield?: (epoch: number, batch: number, logs: Logs) => void | Promise<void>;\n}\n\n/**\n * Custom callback for training.\n */\nexport class CustomCallback extends BaseCallback {\n protected readonly trainBegin: (logs?: Logs) => void | Promise<void>;\n protected readonly trainEnd: (logs?: Logs) => void | Promise<void>;\n protected readonly epochBegin:\n (epoch: number, logs?: Logs) => void | Promise<void>;\n protected readonly epochEnd:\n (epoch: number, logs?: Logs) => void | Promise<void>;\n protected readonly batchBegin:\n (batch: number, logs?: Logs) => void | Promise<void>;\n protected readonly batchEnd:\n (batch: number, logs?: Logs) => void | Promise<void>;\n protected readonly yield:\n (epoch: number, batch: number, logs: Logs) => void | Promise<void>;\n\n private yieldEvery: YieldEveryOptions;\n private currentEpoch = 0;\n\n constructor(args: CustomCallbackArgs, yieldEvery?: YieldEveryOptions) {\n super();\n this.yieldEvery = yieldEvery || 'auto';\n if (this.yieldEvery === 'auto') {\n this.yieldEvery = DEFAULT_YIELD_EVERY_MS;\n }\n if (this.yieldEvery === 'never' && args.onYield != null) {\n throw new Error(\n 'yieldEvery is `never` but you provided an `onYield` callback. ' +\n 'Either change `yieldEvery` or remove the callback');\n }\n if (util.isNumber(this.yieldEvery)) {\n // Decorate `maybeWait` so it will be called at most once every\n // `yieldEvery` ms.\n this.maybeWait = generic_utils.debounce(\n this.maybeWait.bind(this), this.yieldEvery as number);\n }\n this.trainBegin = args.onTrainBegin;\n this.trainEnd = args.onTrainEnd;\n this.epochBegin = args.onEpochBegin;\n this.epochEnd = args.onEpochEnd;\n this.batchBegin = args.onBatchBegin;\n this.batchEnd = args.onBatchEnd;\n this.yield = args.onYield;\n }\n\n async maybeWait(epoch: number, batch: number, logs: UnresolvedLogs) {\n const ps: Array<void|Promise<void>> = [];\n if (this.yield != null) {\n await resolveScalarsInLogs(logs);\n ps.push(this.yield(epoch, batch, logs as Logs));\n }\n ps.push(nextFrame());\n await Promise.all(ps);\n }\n\n async onEpochBegin(epoch: number, logs?: UnresolvedLogs): Promise<void> {\n this.currentEpoch = epoch;\n if (this.epochBegin != null) {\n await resolveScalarsInLogs(logs);\n await this.epochBegin(epoch, logs as Logs);\n }\n }\n\n async onEpochEnd(epoch: number, logs?: UnresolvedLogs): Promise<void> {\n const ps: Array<void|Promise<void>> = [];\n if (this.epochEnd != null) {\n await resolveScalarsInLogs(logs);\n ps.push(this.epochEnd(epoch, logs as Logs));\n }\n if (this.yieldEvery === 'epoch') {\n ps.push(nextFrame());\n }\n await Promise.all(ps);\n }\n\n async onBatchBegin(batch: number, logs?: UnresolvedLogs): Promise<void> {\n if (this.batchBegin != null) {\n await resolveScalarsInLogs(logs);\n await this.batchBegin(batch, logs as Logs);\n }\n }\n\n async onBatchEnd(batch: number, logs?: UnresolvedLogs): Promise<void> {\n const ps: Array<void|Promise<void>> = [];\n if (this.batchEnd != null) {\n await resolveScalarsInLogs(logs);\n ps.push(this.batchEnd(batch, logs as Logs));\n }\n if (this.yieldEvery === 'batch') {\n ps.push(nextFrame());\n } else if (util.isNumber(this.yieldEvery)) {\n ps.push(this.maybeWait(this.currentEpoch, batch, logs));\n }\n await Promise.all(ps);\n }\n\n async onTrainBegin(logs?: UnresolvedLogs): Promise<void> {\n if (this.trainBegin != null) {\n await resolveScalarsInLogs(logs);\n await this.trainBegin(logs as Logs);\n }\n }\n\n async onTrainEnd(logs?: UnresolvedLogs): Promise<void> {\n if (this.trainEnd != null) {\n await resolveScalarsInLogs(logs);\n await this.trainEnd(logs as Logs);\n }\n }\n}\n\n/**\n * Standardize callbacks or configurations of them to an Array of callbacks.\n */\nexport function standardizeCallbacks(\n callbacks: BaseCallback|BaseCallback[]|CustomCallbackArgs|\n CustomCallbackArgs[],\n yieldEvery: YieldEveryOptions): BaseCallback[] {\n if (callbacks == null) {\n callbacks = {} as BaseCallback;\n }\n if (callbacks instanceof BaseCallback) {\n return [callbacks];\n }\n if (Array.isArray(callbacks) && callbacks[0] instanceof BaseCallback) {\n return callbacks as BaseCallback[];\n }\n // Convert custom callback configs to custom callback objects.\n const callbackConfigs =\n generic_utils.toList(callbacks) as CustomCallbackArgs[];\n return callbackConfigs.map(\n callbackConfig => new CustomCallback(callbackConfig, yieldEvery));\n}\n\nexport declare type BaseCallbackConstructor = {\n new (): BaseCallback\n};\n\n/**\n * A global registry for callback constructors to be used during\n * LayersModel.fit().\n */\nexport class CallbackConstructorRegistry {\n private static constructors:\n {[verbosityLevel: number]: BaseCallbackConstructor[]} = {};\n\n /**\n * Blocks public access to constructor.\n */\n private constructor() {}\n\n /**\n * Register a tf.LayersModel.fit() callback constructor.\n *\n * The registered callback constructor will be used to instantiate\n * callbacks for every tf.LayersModel.fit() call afterwards.\n *\n * @param verbosityLevel Level of verbosity at which the `callbackConstructor`\n * is to be reigstered.\n * @param callbackConstructor A no-arg constructor for `tf.Callback`.\n * @throws Error, if the same callbackConstructor has been registered before,\n * either at the same or a different `verbosityLevel`.\n */\n static registerCallbackConstructor(\n verbosityLevel: number, callbackConstructor: BaseCallbackConstructor) {\n util.assert(\n verbosityLevel >= 0 && Number.isInteger(verbosityLevel),\n () => `Verbosity level is expected to be an integer >= 0, ` +\n `but got ${verbosityLevel}`);\n CallbackConstructorRegistry.checkForDuplicate(callbackConstructor);\n if (CallbackConstructorRegistry.constructors[verbosityLevel] == null) {\n CallbackConstructorRegistry.constructors[verbosityLevel] = [];\n }\n CallbackConstructorRegistry.constructors[verbosityLevel].push(\n callbackConstructor);\n }\n\n private static checkForDuplicate(callbackConstructor:\n BaseCallbackConstructor) {\n for (const levelName in CallbackConstructorRegistry.constructors) {\n const constructors = CallbackConstructorRegistry.constructors[+levelName];\n constructors.forEach(ctor => {\n if (ctor === callbackConstructor) {\n throw new ValueError('Duplicate callback constructor.');\n }\n });\n }\n }\n\n /**\n * Clear all registered callback constructors.\n */\n protected static clear() {\n CallbackConstructorRegistry.constructors = {};\n }\n\n /**\n * Create callbacks using the registered callback constructors.\n *\n * Given `verbosityLevel`, all constructors registered at that level or above\n * will be called and the instantiated callbacks will be used.\n *\n * @param verbosityLevel: Level of verbosity.\n */\n static createCallbacks(verbosityLevel: number): BaseCallback[] {\n const constructors: BaseCallbackConstructor[] = [];\n for (const levelName in CallbackConstructorRegistry.constructors) {\n const level = +levelName;\n if (verbosityLevel >= level) {\n constructors.push(...CallbackConstructorRegistry.constructors[level]);\n }\n }\n return constructors.map(ctor => new ctor());\n }\n}\n\nexport function configureCallbacks(\n callbacks: BaseCallback[], verbose: ModelLoggingVerbosity, epochs: number,\n initialEpoch: number, numTrainSamples: number, stepsPerEpoch: number,\n batchSize: number, doValidation: boolean,\n callbackMetrics: string[]): {callbackList: CallbackList, history: History} {\n const history = new History();\n const actualCallbacks: BaseCallback[] = [\n new BaseLogger(), ...CallbackConstructorRegistry.createCallbacks(verbose)\n ];\n if (callbacks != null) {\n actualCallbacks.push(...callbacks);\n }\n actualCallbacks.push(history);\n const callbackList = new CallbackList(actualCallbacks);\n\n // TODO(cais): Figure out when this LayersModel instance can have a\n // dynamically\n // set property called 'callback_model' as in PyKeras.\n\n callbackList.setParams({\n epochs,\n initialEpoch,\n samples: numTrainSamples,\n steps: stepsPerEpoch,\n batchSize,\n verbose,\n doValidation,\n metrics: callbackMetrics,\n });\n return {callbackList, history};\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original Source layers/__init__.py */\nimport {serialization} from '@tensorflow/tfjs-core';\n\nimport {deserializeKerasObject} from '../utils/generic_utils';\n\n/**\n * Instantiate a layer from a config dictionary.\n * @param config dict of the form {class_name: str, config: dict}\n * @param customObjects dict mapping class names (or function names)\n * of custom (non-Keras) objects to class/functions\n * @param fastWeightInit Optional flag to use fast weight initialization\n * during deserialization. This is applicable to cases in which\n * the initialization will be immediately overwritten by loaded weight\n * values. Default: `false`.\n * @returns Layer instance (may be LayersModel, Sequential, Layer...)\n */\nexport function deserialize(\n config: serialization.ConfigDict,\n customObjects = {} as serialization.ConfigDict,\n fastWeightInit = false): serialization.Serializable {\n return deserializeKerasObject(\n config, serialization.SerializationMap.getMap().classNameMap,\n customObjects, 'layer', fastWeightInit);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original Source: losses.py */\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {Tensor, Tensor1D, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {epsilon} from './backend/common';\nimport * as K from './backend/tfjs_backend';\nimport {ValueError} from './errors';\nimport {LossOrMetricFn} from './types';\n\n/**\n * Normalizes a tensor wrt the L2 norm alongside the specified axis.\n * @param x\n * @param axis Axis along which to perform normalization.\n */\nexport function l2Normalize(x: Tensor, axis?: number): Tensor {\n return tidy(() => {\n if (x.dtype !== 'float32') {\n x = tfc.cast(x, 'float32');\n }\n const squareSum = tfc.sum(K.square(x), axis, true);\n const epsilonTensor = tfc.fill(squareSum.shape, epsilon());\n const norm = tfc.sqrt(tfc.maximum(squareSum, epsilonTensor));\n return tfc.div(x, norm);\n });\n}\n\nexport function meanSquaredError(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => tfc.mean(K.square(tfc.sub(yPred, yTrue)), -1));\n}\n\nexport function meanAbsoluteError(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => tfc.mean(tfc.abs(tfc.sub(yPred, yTrue)), -1));\n}\n\nexport function meanAbsolutePercentageError(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const diff = tfc.sub(yTrue, yPred);\n const clippedTrue =\n tfc.clipByValue(tfc.abs(yTrue), epsilon(), Number.MAX_VALUE);\n const absResult = tfc.abs(tfc.div(diff, clippedTrue));\n return tfc.mul(100, tfc.mean(absResult, -1));\n });\n}\n\nexport function meanSquaredLogarithmicError(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const clippedPred = tfc.clipByValue(yPred, epsilon(), Number.MAX_VALUE);\n const firstLog = tfc.log(tfc.add(1, clippedPred));\n\n const clippedTrue = tfc.clipByValue(yTrue, epsilon(), Number.MAX_VALUE);\n const secondLog = tfc.log(tfc.add(1, clippedTrue));\n\n return tfc.mean(K.square(tfc.sub(firstLog, secondLog)), -1);\n });\n}\n\nexport function squaredHinge(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const maxResult = tfc.maximum(0, tfc.sub(1, tfc.mul(yTrue, yPred)));\n return tfc.mean(K.square(maxResult), -1);\n });\n}\n\nexport function hinge(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const maxResult = tfc.maximum(0, tfc.sub(1, tfc.mul(yTrue, yPred)));\n return tfc.mean(maxResult, -1);\n });\n}\n\nexport function categoricalHinge(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const pos = tfc.sum(tfc.mul(yTrue, yPred), -1);\n const neg = tfc.max(tfc.mul(tfc.sub(1, yTrue), yPred), -1);\n return tfc.maximum(0, tfc.add(1, tfc.sub(neg, pos)));\n });\n}\n\n/**\n * Logarithm of the hyperbolic cosine of the prediction error.\n *\n * `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and\n * to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly\n * like the mean squared error, but will not be so strongly affected by the\n * occasional wildly incorrect prediction.\n */\nexport function logcosh(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const log2 = Math.log(2);\n const predictionDiff = tfc.sub(yPred, yTrue);\n const logcoshResult = tfc.sub(\n tfc.add(predictionDiff, tfc.softplus(tfc.mul(-2, predictionDiff))),\n log2);\n return tfc.mean(logcoshResult, -1);\n });\n}\n\nexport function categoricalCrossentropy(\n target: Tensor, output: Tensor, fromLogits = false): Tensor {\n return tidy(() => {\n if (fromLogits) {\n output = tfc.softmax(output);\n } else {\n // scale preds so that the class probabilities of each sample sum to 1.\n const outputSum = tfc.sum(output, output.shape.length - 1, true);\n output = tfc.div(output, outputSum);\n }\n output = tfc.clipByValue(output, epsilon(), 1 - epsilon());\n return tfc.neg(tfc.sum(\n tfc.mul(tfc.cast(target, 'float32'), tfc.log(output)),\n output.shape.length - 1));\n });\n}\n\n/**\n * Categorical crossentropy with integer targets.\n *\n * @param target An integer tensor.\n * @param output A tensor resulting from a softmax (unless `fromLogits` is\n * `true`, in which case `output` is expected to be the logits).\n * @param fromLogits Boolean, whether `output` is the result of a softmax, or is\n * a tensor of logits.\n */\nexport function sparseCategoricalCrossentropy(\n target: Tensor, output: Tensor, fromLogits = false): Tensor {\n return tidy(() => {\n const flatTarget =\n tfc.cast(tfc.floor(K.flatten(target)), 'int32') as Tensor1D;\n output = tfc.clipByValue(output, epsilon(), 1 - epsilon());\n const outputShape = output.shape;\n const oneHotTarget = tfc.reshape(\n tfc.oneHot(flatTarget, outputShape[outputShape.length - 1]),\n outputShape);\n return categoricalCrossentropy(oneHotTarget, output, fromLogits);\n });\n}\n\n/**\n * From TensorFlow's implementation in nn_impl.py:\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 * 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 * Hence, to ensure stability and avoid overflow, the implementation uses this\n * equivalent formulation\n * max(x, 0) - x * z + log(1 + exp(-abs(x)))\n *\n * @param labels The labels.\n * @param logits The logits.\n */\nexport function sigmoidCrossEntropyWithLogits(\n labels: Tensor, logits: Tensor): Tensor {\n if (!util.arraysEqual(labels.shape, logits.shape)) {\n throw new ValueError(\n `logits and labels must have the same shape, but got shapes ` +\n `${JSON.stringify(labels.shape)} and ${JSON.stringify(logits.shape)}`);\n }\n return tidy(() => {\n // The logistic loss formula from above is\n // x - x * z + log(1 + exp(-x))\n // For x < 0, a more numerically stable formula is\n // -x * z + log(1 + exp(x))\n // Note that these two expressions can be combined into the following:\n // max(x, 0) - x * z + log(1 + exp(-abs(x)))\n const reluLogits = tfc.relu(logits);\n const negAbsLogits = tfc.neg(tfc.abs(logits));\n return tfc.add(\n tfc.sub(reluLogits, tfc.mul(logits, labels)),\n tfc.log1p(tfc.exp(negAbsLogits)));\n });\n}\n\nexport function binaryCrossentropy(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n let y: Tensor;\n y = tfc.clipByValue(yPred, epsilon(), 1 - epsilon());\n y = tfc.log(tfc.div(y, tfc.sub(1, y)));\n return tfc.mean(sigmoidCrossEntropyWithLogits(yTrue, y), -1);\n });\n}\n\nexport function kullbackLeiblerDivergence(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const clippedTrue = tfc.clipByValue(yTrue, epsilon(), 1);\n const clippedPred = tfc.clipByValue(yPred, epsilon(), 1);\n return tfc.sum(\n tfc.mul(yTrue, tfc.log(tfc.div(clippedTrue, clippedPred))), -1);\n });\n}\n\nexport function poisson(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const logPred = tfc.log(tfc.add(epsilon(), yPred));\n return tfc.mean(tfc.sub(yPred, tfc.mul(yTrue, logPred)), -1);\n });\n}\n\nexport function cosineProximity(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const trueNormalized = l2Normalize(yTrue, -1);\n const predNormalized = l2Normalize(yPred, -1);\n const trueXPred = tfc.mul(trueNormalized, predNormalized);\n return tfc.neg(tfc.sum(trueXPred, -1));\n });\n}\n\nexport const mse = meanSquaredError;\nexport const MSE = meanSquaredError;\nexport const mae = meanAbsoluteError;\nexport const MAE = meanAbsoluteError;\nexport const mape = meanAbsolutePercentageError;\nexport const MAPE = meanAbsolutePercentageError;\nexport const msle = meanSquaredLogarithmicError;\nexport const MSLE = meanSquaredLogarithmicError;\nexport const kld = kullbackLeiblerDivergence;\nexport const KLD = kullbackLeiblerDivergence;\nexport const cosine = cosineProximity;\n\n// TODO(michaelterry): Add deserialize() function.\n\nexport const lossesMap: {[functionName: string]: LossOrMetricFn} = {\n meanSquaredError,\n meanAbsoluteError,\n meanAbsolutePercentageError,\n meanSquaredLogarithmicError,\n squaredHinge,\n hinge,\n categoricalHinge,\n logcosh,\n categoricalCrossentropy,\n sparseCategoricalCrossentropy,\n binaryCrossentropy,\n kullbackLeiblerDivergence,\n poisson,\n cosineProximity\n};\n\n// Porting note: This diverges from the PyKeras implementation and may need to\n// change based on (de)serialization requirements.\nexport function get(identifierOrFn: string|LossOrMetricFn): LossOrMetricFn {\n if (typeof identifierOrFn === 'string') {\n if (identifierOrFn in lossesMap) {\n return lossesMap[identifierOrFn];\n }\n let errMsg = `Unknown loss ${identifierOrFn}`;\n if (identifierOrFn.toLowerCase().includes('softmaxcrossentropy')) {\n errMsg = `Unknown loss ${identifierOrFn}. ` +\n 'Use \"categoricalCrossentropy\" as the string name for ' +\n 'tf.losses.softmaxCrossEntropy';\n }\n throw new ValueError(errMsg);\n } else {\n return identifierOrFn;\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Built-in metrics.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {Tensor, tidy} from '@tensorflow/tfjs-core';\n\nimport * as K from './backend/tfjs_backend';\nimport {NotImplementedError, ValueError} from './errors';\nimport {categoricalCrossentropy as categoricalCrossentropyLoss, cosineProximity, meanAbsoluteError, meanAbsolutePercentageError, meanSquaredError, sparseCategoricalCrossentropy as sparseCategoricalCrossentropyLoss} from './losses';\nimport {binaryCrossentropy as lossBinaryCrossentropy} from './losses';\nimport {lossesMap} from './losses';\nimport {LossOrMetricFn} from './types';\nimport * as util from './utils/generic_utils';\n\nexport function binaryAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const threshold = tfc.mul(.5, tfc.onesLike(yPred));\n const yPredThresholded = K.cast(tfc.greater(yPred, threshold), yTrue.dtype);\n return tfc.mean(tfc.equal(yTrue, yPredThresholded), -1);\n });\n}\n\nexport function categoricalAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(\n () => K.cast(\n tfc.equal(tfc.argMax(yTrue, -1), tfc.argMax(yPred, -1)), 'float32'));\n}\n\nfunction truePositives(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n return tfc.cast(\n tfc.sum(tfc.logicalAnd(tfc.equal(yTrue, 1), tfc.equal(yPred, 1))),\n 'float32');\n });\n}\n\nfunction falseNegatives(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n return tfc.cast(\n tfc.sum(tfc.logicalAnd(tfc.equal(yTrue, 1), tfc.equal(yPred, 0))),\n 'float32');\n });\n}\n\nfunction falsePositives(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n return tfc.cast(\n tfc.sum(tfc.logicalAnd(tfc.equal(yTrue, 0), tfc.equal(yPred, 1))),\n 'float32');\n });\n}\n\nexport function precision(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const tp = truePositives(yTrue, yPred);\n const fp = falsePositives(yTrue, yPred);\n\n const denominator = tfc.add(tp, fp);\n\n return tfc.cast(\n tfc.where(tfc.greater(denominator, 0), tfc.div(tp, denominator), 0),\n 'float32');\n });\n}\n\nexport function recall(yTrue: Tensor, yPred: Tensor): Tensor {\n return tidy(() => {\n const tp = truePositives(yTrue, yPred);\n const fn = falseNegatives(yTrue, yPred);\n\n const denominator = tfc.add(tp, fn);\n\n return tfc.cast(\n tfc.where(tfc.greater(denominator, 0), tfc.div(tp, denominator), 0),\n 'float32');\n });\n}\n\nexport function binaryCrossentropy(yTrue: Tensor, yPred: Tensor): Tensor {\n return lossBinaryCrossentropy(yTrue, yPred);\n}\n\nexport function sparseCategoricalAccuracy(\n yTrue: Tensor, yPred: Tensor): Tensor {\n if (yTrue.rank === yPred.rank) {\n yTrue = tfc.squeeze(yTrue, [yTrue.rank - 1]);\n }\n yPred = tfc.argMax(yPred, -1);\n if (yPred.dtype !== yTrue.dtype) {\n yPred = tfc.cast(yPred, yTrue.dtype);\n }\n return tfc.cast(tfc.equal(yTrue, yPred), 'float32');\n}\n\nexport function topKCategoricalAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n throw new NotImplementedError();\n}\n\nexport function sparseTopKCategoricalAccuracy(\n yTrue: Tensor, yPred: Tensor): Tensor {\n throw new NotImplementedError();\n}\n\n// Aliases.\nexport const mse = meanSquaredError;\nexport const MSE = meanSquaredError;\nexport const mae = meanAbsoluteError;\nexport const MAE = meanAbsoluteError;\nexport const mape = meanAbsolutePercentageError;\nexport const MAPE = meanAbsolutePercentageError;\nexport const categoricalCrossentropy = categoricalCrossentropyLoss;\nexport const cosine = cosineProximity;\nexport const sparseCategoricalCrossentropy = sparseCategoricalCrossentropyLoss;\n\n// TODO(cais, nielsene): Add serialize().\n\nexport const metricsMap: {[functionName: string]: LossOrMetricFn} = {\n binaryAccuracy,\n categoricalAccuracy,\n precision,\n categoricalCrossentropy,\n sparseCategoricalCrossentropy,\n mse,\n MSE,\n mae,\n MAE,\n mape,\n MAPE,\n cosine\n};\n\nexport function get(identifier: string|LossOrMetricFn): LossOrMetricFn {\n if (typeof identifier === 'string' && identifier in metricsMap) {\n return metricsMap[identifier];\n } else if (typeof identifier !== 'string' && identifier != null) {\n return identifier;\n } else {\n throw new ValueError(`Unknown metric ${identifier}`);\n }\n}\n\n/**\n * Get the shortcut function name.\n *\n * If the fn name is a string,\n * directly return the string name.\n * If the function is included in metricsMap or lossesMap,\n * return key of the map.\n * - If the function relative to multiple keys,\n * return the first found key as the function name.\n * - If the function exists in both lossesMap and metricsMap,\n * search lossesMap first.\n * If the function is not included in metricsMap or lossesMap,\n * return the function name.\n *\n * @param fn loss function, metric function, or short cut name.\n * @returns Loss or Metric name in string.\n */\nexport function getLossOrMetricName(fn: string|LossOrMetricFn): string {\n util.assert(fn !== null, `Unknown LossOrMetricFn ${fn}`);\n if (typeof fn === 'string') {\n return fn;\n } else {\n let fnName;\n for (const key of Object.keys(lossesMap)) {\n if (lossesMap[key] === fn) {\n fnName = key;\n break;\n }\n }\n if (fnName !== undefined) {\n return fnName;\n }\n for (const key of Object.keys(metricsMap)) {\n if (metricsMap[key] === fn) {\n fnName = key;\n break;\n }\n }\n if (fnName !== undefined) {\n return fnName;\n }\n return (fn as Function).name;\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Optimizers.\n */\n\nimport {Optimizer, train} from '@tensorflow/tfjs-core';\n\nimport {epsilon} from './backend/common';\n\nimport {ValueError} from './errors';\n\n// Add (de)serialize()\n\n// Porting note: This diverges from the PyKeras implementation and may need to\n// change based on (de)serialization requirements.\nexport function getOptimizer(identifier: string): Optimizer {\n const optimizerMap: {[optimizerName: string]: () => Optimizer} = {\n 'Adagrad': () => train.adagrad(0.01),\n 'Adadelta': () => train.adadelta(1, 0.95, epsilon()),\n 'Adam': () => train.adam(0.001, 0.9, 0.999, epsilon()),\n 'Adamax': () => train.adamax(0.002, 0.9, 0.999, epsilon(), 0),\n 'RMSProp': () => train.rmsprop(0.001, 0.9, 0, epsilon()),\n 'SGD': () => train.sgd(0.01)\n };\n optimizerMap['adagrad'] = optimizerMap['Adagrad'];\n optimizerMap['adadelta'] = optimizerMap['Adadelta'];\n optimizerMap['adam'] = optimizerMap['Adam'];\n optimizerMap['adamax'] = optimizerMap['Adamax'];\n optimizerMap['rmsprop'] = optimizerMap['RMSProp'];\n optimizerMap['sgd'] = optimizerMap['SGD'];\n\n if (identifier in optimizerMap) {\n return optimizerMap[identifier]();\n }\n throw new ValueError(`Unknown Optimizer ${identifier}`);\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/** Utility functions related to user-defined metadata. */\n\n// Maximum recommended serialized size for user-defined metadata.\n// Beyond this limit, a warning message will be printed during model loading and\n// saving.\nexport const MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH = 1 * 1024 * 1024;\n\n/**\n * Check validity of user-defined metadata.\n *\n * @param userDefinedMetadata\n * @param modelName Name of the model that the user-defined metadata belongs to.\n * Used during construction of error messages.\n * @param checkSize Whether to check the size of the metadata is under\n * recommended limit. Default: `false`. If `true`, will try stringify the\n * JSON object and print a console warning if the serialzied size is above the\n * limit.\n * @throws Error if `userDefinedMetadata` is not a plain JSON object.\n */\nexport function checkUserDefinedMetadata(\n userDefinedMetadata: {}, modelName: string, checkSize = false): void {\n if (userDefinedMetadata == null ||\n typeof userDefinedMetadata !== 'object' ||\n Object.getPrototypeOf(userDefinedMetadata) !== Object.prototype ||\n !plainObjectCheck(userDefinedMetadata)) {\n throw new Error(\n 'User-defined metadata is expected to be a JSON object, but is not.');\n }\n\n if (checkSize) {\n const out = JSON.stringify(userDefinedMetadata);\n if (out.length > MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH) {\n console.warn(\n `User-defined metadata of model \"${modelName}\" is too large in ` +\n `size (length=${out.length} when serialized). It is not ` +\n `recommended to store such large objects in user-defined metadata. ` +\n `Please make sure its serialized length is <= ` +\n `${MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH}.`);\n }\n }\n}\n\n/**\n * Check if an input is plain JSON object or any valid subfield of it.\n *\n * @param x The input to be checked.\n * @param assertObject Whether to assert `x` is a JSON object, i.e., reject\n * cases of arrays and primitives.\n * @return Returns `true` if and only if `x` is a plain JSON object,\n * a JSON-valid primitive including string, number, boolean and null,\n * or an array of the said types.\n */\n// tslint:disable-next-line:no-any\nexport function plainObjectCheck(x: any): boolean {\n if (x === null) {\n // Note: typeof `null` is 'object', and `null` is valid in JSON.\n return true;\n } else if (typeof x === 'object') {\n if (Object.getPrototypeOf(x) === Object.prototype) {\n // `x` is a JavaScript object and its prototype is Object.\n const keys = Object.keys(x);\n for (const key of keys) {\n if (typeof key !== 'string') {\n // JSON keys must be strings.\n return false;\n }\n if (!plainObjectCheck(x[key])) { // Recursive call.\n return false;\n }\n }\n return true;\n } else {\n // `x` is a JavaScript object but its prototype is not Object.\n if (Array.isArray(x)) {\n // `x` is a JavaScript array.\n for (const item of x) {\n if (!plainObjectCheck(item)) { // Recursive call.\n return false;\n }\n }\n return true;\n } else {\n // `x` is a JavaScript object and its prototype is not Object,\n // and it's not an Array. I.e., it's a complex object such as\n // `Error` and `Date`.\n return false;\n }\n }\n } else {\n // `x` is not a JavaScript object or `null`.\n const xType = typeof x;\n return xType === 'string' || xType === 'number' || xType === 'boolean';\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {Container} from '../engine/container';\nimport {Layer, Node} from '../engine/topology';\nimport {countParamsInWeights} from './variable_utils';\n\n/**\n * Print the summary of a LayersModel object.\n *\n * @param model tf.LayersModel instance.\n * @param lineLength Total length of printed lines. Set this to adapt to the\n * display to different terminal or console sizes.\n * @param positions Relative or absolute positions of log elements in each\n * line. Each number corresponds to right-most (i.e., ending) position of a\n * column.\n * If not provided, defaults to `[0.45, 0.85, 1]` for sequential-like\n * models and `[0.33, 0.55, 0.67, 1]` for non-sequential like models.\n * @param printFn Print function to use.\n * It will be called on each line of the summary. You can provide a custom\n * function in order to capture the string summary. Defaults to `console.log`.\n */\nexport function printSummary(\n model: Container, lineLength?: number, positions?: number[],\n // tslint:disable-next-line:no-any\n printFn: (message?: any, ...optionalParams: any[]) => void =\n console.log): void {\n const sequentialLike = isModelSequentialLike(model);\n\n // Header names for different log elements.\n const toDisplay: string[] = ['Layer (type)', 'Output shape', 'Param #'];\n if (sequentialLike) {\n lineLength = lineLength || 65;\n positions = positions || [0.45, 0.85, 1];\n } else {\n lineLength = lineLength || 98;\n positions = positions || [0.33, 0.55, 0.67, 1];\n // Header names for different log elements.\n }\n\n if (positions[positions.length - 1] <= 1) {\n // `positions` is relative. Convert it to absolute positioning.\n positions = positions.map(p => Math.floor(lineLength * p));\n }\n\n let relevantNodes: Node[];\n if (!sequentialLike) {\n toDisplay.push('Receives inputs');\n relevantNodes = [];\n for (const depth in model.nodesByDepth) {\n relevantNodes.push(...model.nodesByDepth[depth]);\n }\n }\n\n printFn('_'.repeat(lineLength));\n printRow(toDisplay, positions, printFn);\n printFn('='.repeat(lineLength));\n\n const layers = model.layers;\n for (let i = 0; i < layers.length; ++i) {\n if (sequentialLike) {\n printLayerSummary(layers[i], positions, printFn);\n } else {\n printLayerSummaryWithConnections(\n layers[i], positions, relevantNodes, printFn);\n }\n printFn((i === layers.length - 1 ? '=' : '_').repeat(lineLength));\n }\n\n // tslint:disable-next-line:no-any\n (model as any).checkTrainableWeightsConsistency();\n\n const trainableCount = countTrainableParams(model);\n const nonTrainableCount = countParamsInWeights(model.nonTrainableWeights);\n\n printFn(`Total params: ${trainableCount + nonTrainableCount}`);\n printFn(`Trainable params: ${trainableCount}`);\n printFn(`Non-trainable params: ${nonTrainableCount}`);\n printFn('_'.repeat(lineLength));\n}\n\nfunction countTrainableParams(model: Container): number {\n let trainableCount: number;\n // tslint:disable:no-any\n if ((model as any).collectedTrainableWeights != null) {\n trainableCount =\n countParamsInWeights((model as any).collectedTrainableWeights);\n } else {\n trainableCount = countParamsInWeights(model.trainableWeights);\n }\n // tslint:enable:no-any\n return trainableCount;\n}\n\nfunction isModelSequentialLike(model: Container): boolean {\n let sequentialLike = true;\n const nodesByDepth: Node[][] = [];\n const nodes: Node[] = [];\n for (const depth in model.nodesByDepth) {\n nodesByDepth.push(model.nodesByDepth[depth]);\n }\n for (const depthNodes of nodesByDepth) {\n if (depthNodes.length > 1 ||\n depthNodes.length === 1 && depthNodes[0].inboundLayers.length > 1) {\n sequentialLike = false;\n break;\n }\n nodes.push(...depthNodes);\n }\n if (sequentialLike) {\n // Search for shared layers.\n for (const layer of model.layers) {\n let flag = false;\n for (const node of layer.inboundNodes) {\n if (nodes.indexOf(node) !== -1) {\n if (flag) {\n sequentialLike = false;\n break;\n } else {\n flag = true;\n }\n }\n }\n if (!sequentialLike) {\n break;\n }\n }\n }\n return sequentialLike;\n}\n\nfunction printRow(\n fields: string[], positions: number[],\n // tslint:disable-next-line:no-any\n printFn: (message?: any, ...optionalParams: any[]) => void = console.log) {\n let line = '';\n for (let i = 0; i < fields.length; ++i) {\n if (i > 0) {\n line = line.slice(0, line.length - 1) + ' ';\n }\n line += fields[i];\n line = line.slice(0, positions[i]);\n line += ' '.repeat(positions[i] - line.length);\n }\n printFn(line);\n}\n\n/**\n * Prints a summary for a single Layer, without connectivity information.\n *\n * @param layer: Layer instance to print.\n */\nfunction printLayerSummary(\n layer: Layer, positions: number[],\n // tslint:disable-next-line:no-any\n printFn: (message?: any, ...optionalParams: any[]) => void) {\n let outputShape: string;\n try {\n outputShape = JSON.stringify(layer.outputShape);\n } catch (err) {\n outputShape = 'multiple';\n }\n\n const name = layer.name;\n const className = layer.getClassName();\n const fields: string[] =\n [`${name} (${className})`, outputShape, layer.countParams().toString()];\n printRow(fields, positions, printFn);\n}\n\n/**\n * Prints a summary for a single Layer, with connectivity information.\n */\nfunction printLayerSummaryWithConnections(\n layer: Layer, positions: number[], relevantNodes: Node[],\n // tslint:disable-next-line:no-any\n printFn: (message?: any, ...optionalParams: any[]) => void) {\n let outputShape: string;\n try {\n outputShape = JSON.stringify(layer.outputShape);\n } catch (err) {\n outputShape = 'multiple';\n }\n\n const connections: string[] = [];\n for (const node of layer.inboundNodes) {\n if (relevantNodes != null && relevantNodes.length > 0 &&\n relevantNodes.indexOf(node) === -1) {\n continue;\n }\n for (let i = 0; i < node.inboundLayers.length; ++i) {\n const inboundLayer = node.inboundLayers[i].name;\n const inboundLayerIndex = node.nodeIndices[i];\n const inboundTensorIndex = node.tensorIndices[i];\n connections.push(\n `${inboundLayer}[${inboundLayerIndex}][${inboundTensorIndex}]`);\n }\n }\n const name = layer.name;\n const className = layer.getClassName();\n const firstConnection = connections.length === 0 ? '' : connections[0];\n const fields: string[] = [\n `${name} (${className})`, outputShape, layer.countParams().toString(),\n firstConnection\n ];\n\n printRow(fields, positions, printFn);\n for (let i = 1; i < connections.length; ++i) {\n printRow(['', '', '', connections[i]], positions, printFn);\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n// Porting note: This file doesn't exist in PyKeras.\n// Its purpose here is to centralize the boundary layer between\n// tfjs-layers's internal Config TS-Centric format and PyKeras's\n// serialized Python Config format.\n\nimport {serialization} from '@tensorflow/tfjs-core';\n\nimport {PyJsonValue} from '../keras_format/types';\nimport * as generic_utils from '../utils/generic_utils';\n// tslint:enable\n\n/**\n * Test whether a value in an array is the name of a LayersModel or Layer.\n * @param key The key name that the value is found under. Note that the key\n * may not be at the level immediately above the value, if the value is in a\n * nested array.\n * @param index Index of the value in the Array that it is found in.\n * @param value The value object.\n * @returns A boolean indicating whether value is a name.\n */\nfunction isArrayItemInputOrOutputName<T>(\n key: string, index: number, value: T): boolean {\n return (key === 'inboundNodes' || key === 'outputLayers' ||\n key === 'inputLayers') &&\n index === 0 && typeof value === 'string';\n}\n\n/**\n * Convert a Pythonic config object to TypeScript config object.\n * @param pythonicConfig The config object to convert.\n * @param key Optional key name of the object being converted.\n * @returns Result of the conversion.\n */\nexport function convertPythonicToTs(\n pythonicConfig: PyJsonValue, key?: string): serialization.ConfigDictValue {\n if (pythonicConfig === null) {\n return null;\n } else if (typeof pythonicConfig === 'string') {\n return generic_utils.toCamelCase(pythonicConfig);\n } else if (\n (typeof pythonicConfig === 'number') ||\n (typeof pythonicConfig === 'boolean')) {\n return pythonicConfig;\n } else if (pythonicConfig instanceof Array) {\n const tsArray = [];\n const arrayLength = pythonicConfig.length;\n for (let i = 0; i < arrayLength; ++i) {\n const item = pythonicConfig[i];\n if (isArrayItemInputOrOutputName(key, i, item)) {\n tsArray.push(item);\n } else {\n tsArray.push(convertPythonicToTs(item, key));\n }\n }\n return tsArray;\n } else {\n const tsDict: serialization.ConfigDict = {};\n for (const pythonicKey of Object.keys(pythonicConfig)) {\n const pythonicValue = pythonicConfig[pythonicKey];\n if (pythonicKey === 'name' && typeof pythonicValue === 'string') {\n // Special case the 'name' key with a string value. Name values, such as\n // the names of LayersModel and Layer instances, should not undergo the\n // camel-case conversion.\n tsDict[pythonicKey] = pythonicValue;\n } else {\n const tsKey = generic_utils.toCamelCase(pythonicKey);\n tsDict[tsKey] = convertPythonicToTs(pythonicValue, tsKey);\n }\n }\n return tsDict;\n }\n}\n\n/**\n * Convert a TypeScript config object to Python config object.\n * @param tsConfig The config object to convert.\n * @param key Optional key name of the object being converted.\n * @returns Result of the conversion.\n */\nexport function convertTsToPythonic(\n tsConfig: serialization.ConfigDictValue, key?: string): PyJsonValue {\n if (tsConfig === null || tsConfig === undefined) {\n return null;\n } else if (typeof tsConfig === 'string') {\n return generic_utils.toSnakeCase(tsConfig);\n } else if (\n (typeof tsConfig === 'number') || (typeof tsConfig === 'boolean')) {\n return tsConfig;\n } else if (tsConfig instanceof Array) {\n const pyArray = [];\n const arrayLength = tsConfig.length;\n for (let i = 0; i < arrayLength; ++i) {\n const item = tsConfig[i];\n if (isArrayItemInputOrOutputName(key, i, item)) {\n pyArray.push(item);\n } else {\n pyArray.push(convertTsToPythonic(item, key));\n }\n }\n return pyArray;\n } else {\n const pyDict: serialization.ConfigDict = {};\n for (const tsKey of Object.keys(tsConfig)) {\n const tsValue = tsConfig[tsKey];\n const pyKey = generic_utils.toSnakeCase(tsKey);\n if ((tsKey === 'name' || tsKey === 'className') &&\n typeof tsValue === 'string') {\n // Special case the 'name' key with a string value. Name values, such as\n // the names of LayersModel and Layer instances, should not undergo the\n // snake-case conversion.\n pyDict[pyKey] = tsValue;\n } else {\n pyDict[pyKey] = convertTsToPythonic(tsValue, tsKey);\n }\n }\n return pyDict;\n }\n}\n", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.8.0';\nexport {version};\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Executor: Evaluates SymbolicTensor based on feeds.\n */\n\nimport {cast, dispose, memory, Tensor, util} from '@tensorflow/tfjs-core';\n\nimport {ValueError} from '../errors';\nimport {Kwargs} from '../types';\nimport {toList} from '../utils/generic_utils';\n\nimport {InputLayer} from './input_layer';\nimport {SymbolicTensor} from './topology';\n\n/**\n * Helper function to check the dtype and shape compatibility of a feed value.\n */\nfunction assertFeedCompatibility(key: SymbolicTensor, val: Tensor): Tensor {\n // Check dtype compatibility.\n if (key.dtype == null || key.dtype === val.dtype) {\n // a. If types match, return val tensor as is.\n return val;\n }\n try {\n // b. Attempt to convert to expected type.\n return cast(val, key.dtype);\n } catch (err) {\n // c. If conversion fails, return helpful error.\n throw new ValueError(\n `The dtype of the feed (${val.dtype}) can not be cast to the dtype ` +\n `of the key '${key.name}' (${key.dtype}).`);\n }\n}\n\n/**\n * A concrete Tensor value for a symbolic tensor as the key.\n */\nexport interface Feed {\n key: SymbolicTensor;\n value: Tensor;\n}\n\n/**\n * FeedDict: A mapping from unique SymbolicTensors to feed values for them.\n * A feed value is a concrete value represented as an `Tensor`.\n */\nexport class FeedDict {\n private id2Value: {[id: number]: Tensor} = {};\n private id2Mask: {[id: number]: Tensor} = {};\n private name2Id: {[name: string]: number} = {};\n\n /**\n * Constructor, optionally does copy-construction.\n * @param feeds An Array of `Feed`s, or another `FeedDict`, in which case\n * copy-construction will be performed.\n */\n constructor(feeds?: Feed[]|FeedDict) {\n if (feeds instanceof FeedDict) {\n for (const id in feeds.id2Value) {\n this.id2Value[id] = feeds.id2Value[id];\n if (id in feeds.id2Mask) {\n this.id2Mask[id] = feeds.id2Mask[id];\n }\n }\n } else {\n if (feeds == null) {\n return;\n }\n for (const feed of feeds) {\n this.add(feed.key, feed.value);\n }\n }\n }\n\n /**\n * Add a key-value pair to the FeedDict.\n *\n * @param key The key of the feed.\n * @param value The value of the tensor feed.\n * @param mask The value of the mask feed (optional).\n * @returns This `FeedDict`.\n * @throws ValueError: If the key `SymbolicTensor` already exists in the\n * `FeedDict`.\n */\n add(key: SymbolicTensor, value: Tensor, mask?: Tensor): FeedDict {\n if (this.id2Value[key.id] == null) {\n this.id2Value[key.id] = assertFeedCompatibility(key, value);\n this.name2Id[key.name] = key.id;\n if (mask != null) {\n this.id2Mask[key.id] = mask;\n }\n } else {\n throw new ValueError(`Duplicate key: name=${key.name}, id=${key.id}`);\n }\n return this;\n }\n\n /**\n * Add a Feed to the FeedDict.\n * @param feed The new `Feed` to add.\n * @returns This `FeedDict`.\n */\n addFeed(feed: Feed) {\n this.add(feed.key, feed.value);\n }\n\n /**\n * Probe whether a key already exists in the FeedDict.\n * @param key\n */\n hasKey(key: SymbolicTensor): boolean {\n return this.id2Value[key.id] != null;\n }\n\n /**\n * Get all the SymbolicTensor available in this FeedDict.\n */\n names(): string[] {\n return Object.keys(this.name2Id);\n }\n\n /**\n * Get the feed value for given key.\n * @param key The SymbolicTensor, or its name (as a string), of which the\n * value is sought.\n * @returns If `key` exists, the corresponding feed value.\n * @throws ValueError: If `key` does not exist in this `FeedDict`.\n */\n getValue(key: SymbolicTensor|string): Tensor {\n if (key instanceof SymbolicTensor) {\n if (this.id2Value[key.id] == null) {\n throw new ValueError(`Nonexistent key: ${key.name}`);\n } else {\n return this.id2Value[key.id];\n }\n } else {\n const id = this.name2Id[key];\n if (id == null) {\n throw new ValueError(`Feed dict has no SymbolicTensor name: ${key}`);\n }\n return this.id2Value[id];\n }\n }\n\n /**\n * Get the feed mask for given key.\n * @param key The SymbolicTensor, or its name (as a string), of which the\n * value is sought.\n * @returns If `key` exists, the corresponding feed mask.\n * @throws ValueError: If `key` does not exist in this `FeedDict`.\n */\n getMask(key: SymbolicTensor|string): Tensor {\n if (key instanceof SymbolicTensor) {\n if (this.id2Value[key.id] == null) {\n throw new ValueError(`Nonexistent key: ${key.name}`);\n } else {\n return this.id2Mask[key.id];\n }\n } else {\n const id = this.name2Id[key];\n if (id == null) {\n throw new ValueError(`Feed dict has no SymbolicTensor name: ${key}`);\n }\n return this.id2Mask[id];\n }\n }\n\n /** Dispose all mask Tensors held by this object. */\n disposeMasks() {\n if (this.id2Mask != null) {\n dispose(this.id2Mask);\n }\n }\n}\n\n// Cache for topologically sorted SymbolicTensors for given execution\n// targets (i.e., fetches).\nconst cachedSorted: {[concatFetchNames: string]: SymbolicTensor[]} = {};\n\n// Cache for recipient count maps for given execution targets (i.e., fetches).\nconst cachedRecipientCounts:\n {[concatFetchNames: string]: {[fetchName: string]: number}} = {};\n\n/**\n * Interface for the optional object used for probing the memory\n * usage and other statistics during execution.\n */\nexport interface ExecutionProbe {\n /**\n * Maximum number of tensors that exist during all steps of the\n * execution. Tensor counts are measured at the beginning of every\n * step.\n */\n maxNumTensors?: number;\n\n /**\n * Minimum number of tensors that exist during all steps of the\n * execution. Tensor counts are measured at the beginning of every\n * step.\n */\n minNumTensors?: number;\n}\n\n/**\n * Execute a SymbolicTensor by using concrete feed values.\n *\n * A `SymbolicTensor` object is a node in a computation graph of TF.js\n * Layers. The object is backed by a source layer and input\n * `SymbolicTensor`s to the source layer. This method evaluates\n * the `call()` method of the source layer, using concrete values of the\n * inputs obtained from either\n * * `feedDict`, if the input key exists in `feedDict`, or else,\n * * a recursive call to `execute()` itself.\n *\n * @param x: The `SymbolicTensor` to execute.\n * @param feedDict: The feed values, as base condition of the recursion.\n * execution.\n * @param kwargs: Optional keyword arguments.\n * @param probe: A probe object (of interface `ExecutionProbe`) used for\n * testing memory footprint of `execute` calls.\n * @returns Result of the execution.\n * @throws ValueError: If any `SymbolicTensor`s from `InputLayer`s\n * encountered during the execution lacks a feed value in `feedDict`.\n */\nexport function execute(\n fetches: SymbolicTensor|SymbolicTensor[], feedDict: FeedDict,\n kwargs?: Kwargs, probe?: ExecutionProbe): Tensor|\n Tensor[]|[Tensor | Tensor[]] {\n const training: boolean = kwargs == null ? false : kwargs['training'];\n\n const arrayFetches = Array.isArray(fetches);\n const fetchArray: SymbolicTensor[] =\n arrayFetches ? fetches as SymbolicTensor[] : [fetches as SymbolicTensor];\n\n const outputNames = fetchArray.map(t => t.name);\n const finalOutputs: Tensor[] = [];\n const feedNames = feedDict.names();\n for (const outputName of outputNames) {\n if (feedNames.indexOf(outputName) !== -1) {\n finalOutputs.push(feedDict.getValue(outputName));\n } else {\n finalOutputs.push(null);\n }\n }\n\n if (probe != null) {\n // For optional probing of memory footprint during execution.\n probe.maxNumTensors = -Infinity;\n probe.minNumTensors = Infinity;\n }\n\n // Check cache.\n const fetchAndFeedKey =\n outputNames.join(',') + '|' + feedDict.names().join(',');\n let sorted: SymbolicTensor[];\n let recipientCounts: {[fetchName: string]: number};\n if (cachedSorted[fetchAndFeedKey] == null) {\n // Cache doesn't contain the desired combination of fetches. Compute\n // topological sort for the combination for the first time.\n const out = getTopologicalSortAndRecipientCounts(fetchArray, feedDict);\n sorted = out.sorted;\n recipientCounts = out.recipientCounts;\n\n // Store results in cache for future use.\n cachedSorted[fetchAndFeedKey] = sorted;\n cachedRecipientCounts[fetchAndFeedKey] = recipientCounts;\n }\n sorted = cachedSorted[fetchAndFeedKey];\n recipientCounts = {};\n if (!training) {\n Object.assign(recipientCounts, cachedRecipientCounts[fetchAndFeedKey]);\n }\n\n const internalFeedDict = new FeedDict(feedDict);\n\n // Start iterative execution on the topologically-sorted SymbolicTensors.\n for (let i = 0; i < sorted.length; ++i) {\n if (probe != null) {\n // For optional probing of memory usage during execution.\n const numTensors = memory().numTensors;\n if (numTensors > probe.maxNumTensors) {\n probe.maxNumTensors = numTensors;\n }\n if (numTensors < probe.minNumTensors) {\n probe.minNumTensors = numTensors;\n }\n }\n\n const symbolic = sorted[i];\n const srcLayer = symbolic.sourceLayer;\n if (srcLayer instanceof InputLayer) {\n continue;\n }\n const inputValues: Tensor[] = [];\n const inputMasks: Tensor[] = [];\n const tensorsToDispose: Tensor[] = [];\n\n let maskExists = false;\n for (const input of symbolic.inputs) {\n const value = internalFeedDict.getValue(input);\n const mask = internalFeedDict.getMask(input);\n inputValues.push(value);\n inputMasks.push(mask);\n if (mask != null) {\n maskExists = true;\n }\n if (!training) {\n recipientCounts[input.name]--;\n if (recipientCounts[input.name] === 0 && !feedDict.hasKey(input) &&\n outputNames.indexOf(input.name) === -1 && !value.isDisposed &&\n input.sourceLayer.stateful !== true) {\n tensorsToDispose.push(value);\n }\n }\n }\n\n if (maskExists) {\n kwargs = kwargs || {};\n kwargs['mask'] = inputMasks[0];\n }\n const outputTensors =\n toList(srcLayer.apply(inputValues, kwargs)) as Tensor[];\n let outputMask: Tensor|Tensor[] = null;\n if (srcLayer.supportsMasking) {\n outputMask = srcLayer.computeMask(inputValues, inputMasks);\n }\n const layerOutputs = getNodeOutputs(symbolic);\n const outputSymbolicTensors =\n Array.isArray(layerOutputs) ? layerOutputs : [layerOutputs];\n for (let i = 0; i < outputSymbolicTensors.length; ++i) {\n if (!internalFeedDict.hasKey(outputSymbolicTensors[i])) {\n internalFeedDict.add(\n outputSymbolicTensors[i], outputTensors[i],\n Array.isArray(outputMask) ? outputMask[0] : outputMask);\n }\n const index = outputNames.indexOf(outputSymbolicTensors[i].name);\n if (index !== -1) {\n finalOutputs[index] = outputTensors[i];\n }\n }\n\n if (!training) {\n // Clean up Tensors that are no longer needed.\n dispose(tensorsToDispose);\n }\n }\n // NOTE(cais): Unlike intermediate tensors, we don't discard mask\n // tensors as we go, because these tensors are sometimes passed over a\n // series of mutliple layers, i.e., not obeying the immediate input\n // relations in the graph. If this becomes a memory-usage concern,\n // we can improve this in the future.\n internalFeedDict.disposeMasks();\n\n return arrayFetches ? finalOutputs : finalOutputs[0];\n}\n\ntype RecipientCounts = {\n [fetchName: string]: number\n};\n\nexport type RecipientMap = {\n [fetchName: string]: Set<string>;\n};\n\n/**\n * Sort the `SymbolicTensor`s topologically, for an array of fetches.\n *\n * This function calls getTopologicalSortAndRecipientCountsForOneFetch and\n * merges their results.\n *\n * @param fetch The array of fetches requested. Must be a non-empty array.\n * @param feedDict The dictionary of fed values.\n * @returns sorted: Topologically-sorted array of SymbolicTensors.\n * recipientCounts: Recipient counts for all SymbolicTensors in `sorted`.\n */\nfunction getTopologicalSortAndRecipientCounts(\n fetches: SymbolicTensor[], feedDict: FeedDict):\n {sorted: SymbolicTensor[], recipientCounts: RecipientCounts} {\n util.assert(\n fetches != null && fetches.length > 0,\n () => `Expected at least one fetch, got none`);\n\n let finalSorted: SymbolicTensor[] = [];\n let finalRecipientMap: RecipientMap = {};\n if (fetches.length === 1) {\n // Special-casing 1 fetch for efficiency.\n const out =\n getTopologicalSortAndRecipientCountsForOneFetch(fetches[0], feedDict);\n finalSorted = out.sorted;\n finalRecipientMap = out.recipientMap;\n } else {\n const visited = new Set<string>();\n for (const fetch of fetches) {\n const {sorted, recipientMap} =\n getTopologicalSortAndRecipientCountsForOneFetch(fetch, feedDict);\n\n // Merge sorted SymbolicTensor Arrays.\n for (const symbolicTensor of sorted) {\n if (!visited.has(symbolicTensor.name)) {\n finalSorted.push(symbolicTensor);\n visited.add(symbolicTensor.name);\n }\n }\n\n // Merge recipient maps.\n for (const name in recipientMap) {\n if (finalRecipientMap[name] == null) {\n finalRecipientMap[name] = new Set<string>();\n }\n recipientMap[name].forEach(\n recipient => finalRecipientMap[name].add(recipient));\n }\n }\n }\n return {\n sorted: finalSorted,\n recipientCounts: recipientMap2Counts(finalRecipientMap)\n };\n}\n\nfunction recipientMap2Counts(recipientMap: RecipientMap): RecipientCounts {\n const recipientCounts: RecipientCounts = {};\n for (const name in recipientMap) {\n recipientCounts[name] = recipientMap[name].size;\n }\n return recipientCounts;\n}\n\n/**\n * Sort the `SymbolicTensor`s topologically, for a single fetch.\n *\n * This helper function processes the upstream SymbolicTensors of a single\n * fetch.\n *\n * @param fetch The single fetch requested.\n * @param feedDict The dictionary of fed values.\n * @returns sorted: Topologically-sorted array of SymbolicTensors.\n * recipientMap: Recipient names for all SymbolicTensors in `sorted`.\n */\nexport function getTopologicalSortAndRecipientCountsForOneFetch(\n fetch: SymbolicTensor, feedDict: FeedDict):\n {sorted: SymbolicTensor[], recipientMap: RecipientMap} {\n const visited = new Set<string>();\n const sorted: SymbolicTensor[] = [];\n const recipientMap: RecipientMap = {};\n\n // Put keys of the feedDict into visited first, so they don't have to be\n // walked. This is needed in case where there are feeds for intermediate\n // SymbolicTensors of the graph.\n for (const key of feedDict.names()) {\n visited.add(key);\n }\n\n const stack: SymbolicTensor[] = [];\n const marks: number[] = [];\n\n // Initial population of stack and marks.\n stack.push(fetch);\n\n while (stack.length > 0) {\n const top = stack[stack.length - 1];\n if (visited.has(top.name)) {\n stack.pop();\n continue;\n }\n const topIsMarked = marks[marks.length - 1] === stack.length - 1;\n if (top.inputs.length === 0 || topIsMarked) {\n // Input SymbolicTensor or all children have been visited.\n stack.pop();\n sorted.push(top);\n visited.add(top.name);\n if (topIsMarked) {\n marks.pop();\n }\n } else {\n // A non-input SymbolicTensor whose upstream SymbolicTensors haven't\n // been visited yet. Push them onto the stack.\n marks.push(stack.length - 1);\n for (const input of top.inputs) {\n // Increment the recipient count. Note that this needs to happen\n // regardless of whether the SymbolicTensor has been visited before.\n if (recipientMap[input.name] == null) {\n recipientMap[input.name] = new Set<string>();\n }\n recipientMap[input.name].add(top.name);\n\n if (visited.has(input.name)) {\n continue; // Avoid repeated visits to the same SymbolicTensor.\n }\n stack.push(input);\n }\n }\n }\n return {sorted, recipientMap};\n}\n\n/**\n * Get the symbolic output tensors of the node to which a given fetch belongs.\n * @param fetch The fetched symbolic tensor.\n * @returns The Array of symbolic tensors output by the node to which `fetch`\n * belongs.\n */\nfunction getNodeOutputs(fetch: SymbolicTensor): SymbolicTensor|\n SymbolicTensor[] {\n let layerOutputs: SymbolicTensor|SymbolicTensor[];\n if (fetch.sourceLayer.inboundNodes.length === 1) {\n layerOutputs = fetch.sourceLayer.output;\n } else {\n let nodeIndex: number = null;\n for (let i = 0; i < fetch.sourceLayer.inboundNodes.length; ++i) {\n for (const outputTensor of fetch.sourceLayer.inboundNodes[i]\n .outputTensors) {\n if (outputTensor.id === fetch.id) {\n nodeIndex = i;\n break;\n }\n }\n }\n layerOutputs = fetch.sourceLayer.getOutputAt(nodeIndex);\n }\n return layerOutputs;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: keras/engine/topology.py */\n\nimport {NamedTensorMap, Scalar, serialization, Tensor, tidy} from '@tensorflow/tfjs-core';\n\nimport {getUid} from '../backend/state';\nimport {NotImplementedError, RuntimeError, ValueError} from '../errors';\nimport {Shape} from '../keras_format/common';\nimport {TensorKeyWithArgsArray} from '../keras_format/node_config';\nimport {PyJsonDict} from '../keras_format/types';\nimport {deserialize as deserializeLayer} from '../layers/serialization';\nimport {Kwargs} from '../types';\nimport * as generic_utils from '../utils/generic_utils';\nimport {convertTsToPythonic} from '../utils/serialization_utils';\nimport * as types_utils from '../utils/types_utils';\nimport {batchSetValue, LayerVariable} from '../variables';\nimport {version as layersVersion} from '../version';\n\nimport {execute, FeedDict} from './executor';\nimport {InputLayer} from './input_layer';\nimport {DisposeResult, Layer, Node, SymbolicTensor} from './topology';\n\n/** Constructor config for Container. */\nexport interface ContainerArgs {\n inputs: SymbolicTensor|SymbolicTensor[];\n outputs: SymbolicTensor|SymbolicTensor[];\n name?: string;\n}\n\n/**\n * A Container is a directed acyclic graph of layers.\n *\n * It is the topological form of a \"model\". A LayersModel\n * is simply a Container with added training routines.\n *\n */\nexport abstract class Container extends Layer {\n inputs: SymbolicTensor[];\n outputs: SymbolicTensor[];\n\n inputLayers: Layer[];\n inputLayersNodeIndices: number[];\n inputLayersTensorIndices: number[];\n\n outputLayers: Layer[];\n outputLayersNodeIndices: number[];\n outputLayersTensorIndices: number[];\n\n layers: Layer[];\n layersByDepth: {[depth: string]: Layer[]};\n nodesByDepth: {[depth: string]: Node[]};\n\n internalContainerRefs: Container[];\n\n containerNodes = new Set<string>();\n\n // TODO(michaelterry): Add cache support\n // private outputMaskCache: any;\n // private outputTensorCache: any;\n // private outputShapeCache: any;\n\n inputNames: string[];\n outputNames: string[];\n feedInputShapes: Shape[];\n\n protected internalInputShapes: Shape[];\n protected internalOutputShapes: Shape[];\n // TODO(cais): Maybe 'feed' should not in the names of these variables,\n // due to the fact that our backend is not symbolic.\n protected feedInputNames: string[];\n protected feedOutputNames: string[];\n\n constructor(args: ContainerArgs) {\n // No args passed to super's constructor.\n super({});\n this.name = args.name;\n if (this.name == null) {\n const prefix = this.getClassName().toLowerCase();\n this.name = getUid(prefix);\n }\n\n this.supportsMasking = false;\n this.trainable_ = true;\n\n // TODO(michaelterry): Initialize perInputLosses/Updates here.\n\n // Container-specific properties.\n if (Array.isArray(args.inputs)) {\n this.inputs = args.inputs.slice();\n } else {\n this.inputs = [args.inputs];\n }\n if (Array.isArray(args.outputs)) {\n this.outputs = args.outputs.slice();\n } else {\n this.outputs = [args.outputs];\n }\n\n // Check for redundancy in inputs.\n if (generic_utils.unique(this.inputs).length !== this.inputs.length) {\n throw new ValueError(\n 'The list of inputs passed to the model is ' +\n 'redundant. All inputs should only appear once. Found: ' +\n `${this.inputs.map(x => x.name)}`);\n }\n\n // Check for redundancy in outputs.\n if (generic_utils.unique(this.outputs).length !== this.outputs.length) {\n console.warn(\n 'The list of outputs passed to the model is redundant. ' +\n 'All outputs should only appear once. Found: ' +\n `${this.outputs.map(x => x.name)}`);\n }\n\n /*\n List of initial layers (1 to 1 mapping with this.inputs, hence the same\n layer might appear twice)\n */\n this.inputLayers = [];\n this.inputLayersNodeIndices = [];\n this.inputLayersTensorIndices = [];\n /*\n List of layers (1 to 1 mapping with this.outputs, hence the same layer\n might appear twice)\n */\n this.outputLayers = [];\n this.outputLayersNodeIndices = [];\n this.outputLayersTensorIndices = [];\n /*\n All layers in order of horizontal graph traversal. Entries are unique.\n Includes input and output layers.\n */\n this.layers = [];\n\n /*\n References to container layers that were constructed internally. We need\n these to properly dispose of tensors from nested containers.\n */\n this.internalContainerRefs = [];\n\n // TODO(michaelterry): Determine if caching still needed with eager\n // backend.\n /*\n This is for performance optimization when calling the Container on new\n inputs. Every time the Container is called on a set on input tensors,\n we compute the output tensors, output masks and output shapes in one pass,\n then cache them here. When one of these outputs is queried later,\n we retrieve it from there instead of recomputing it.\n */\n // this.outputTensorCache = {};\n // this.outputShapeCache = {};\n\n // Build this.outputLayers:\n for (const x of this.outputs) {\n const layer = x.sourceLayer;\n const nodeIndex = x.nodeIndex;\n const tensorIndex = x.tensorIndex;\n this.outputLayers.push(layer);\n this.outputLayersNodeIndices.push(nodeIndex);\n this.outputLayersTensorIndices.push(tensorIndex);\n }\n\n // TODO(michaelterry): Add output mask cache code.\n\n // Build this.inputLayers:\n for (const x of this.inputs) {\n const layer = x.sourceLayer;\n const nodeIndex = x.nodeIndex;\n const tensorIndex = x.tensorIndex;\n /*\n It's supposed to be an input layer, so only one node\n and one tensor output.\n */\n generic_utils.assert(nodeIndex === 0, 'input layer has >1 nodes');\n generic_utils.assert(tensorIndex === 0, 'input layer has >1 tensors');\n this.inputLayers.push(layer);\n this.inputLayersNodeIndices.push(nodeIndex);\n this.inputLayersTensorIndices.push(tensorIndex);\n }\n\n // Build this.inputNames and this.outputNames.\n this.inputNames = [];\n this.outputNames = [];\n this.feedInputShapes = [];\n this.feedInputNames = [];\n this.feedOutputNames = [];\n for (let i = 0; i < this.inputLayers.length; i++) {\n const layer = this.inputLayers[i];\n // Check that layer is an InputLayer.\n if (!(layer instanceof InputLayer)) {\n throw new TypeError(\n 'Input layers to a LayersModel must be InputLayer objects. ' +\n `Received inputs: ${args.inputs}. ` +\n `Input ${i} (0-based) originates ` +\n `from layer type ${layer.getClassName()}.`);\n }\n this.inputNames.push(layer.name);\n this.feedInputShapes.push(layer.batchInputShape);\n\n this.feedInputNames.push(layer.name);\n }\n for (const layer of this.outputLayers) {\n this.outputNames.push(layer.name);\n }\n\n this.internalInputShapes = this.inputs.map(x => x.shape);\n this.internalOutputShapes = this.outputs.map(x => x.shape);\n\n /*\n Container_nodes: set of nodes included in the graph (not all nodes\n included in the layers are relevant to the current graph).\n */\n // ids of all nodes relevant to the Container:\n const nodesDepths: {[nodeID: string]: number} = {};\n // To recover nodes from their ID.\n const nodeIDToNode: {[nodeID: string]: Node} = {};\n const layersDepths: {[layerID: string]: number} = {};\n // To layers from their ID.\n const layerIDToLayer: {[layerID: string]: Layer} = {};\n const layerIndices: {[layerID: string]: number} = {};\n const nodesInDecreasingDepth: Node[] = [];\n\n /**\n * Builds a map of the graph of layers.\n *\n * This recursively updates the map `layerIndices`,\n * the list `nodesInDecreasingDepth` and the set `containerNodes`.\n *\n * @param tensor Some tensor in a graph.\n * @param finishedNodes Set of nodes whose subgraphs have been traversed\n * completely. Useful to prevent duplicated work.\n * @param nodesInProgress Set of nodes that are currently active on the\n * recursion stack. Useful to detect cycles.\n * @param layer Layer from which `tensor` comes from. If not provided,\n * will be obtained from tensor.sourceLayer.\n * @param nodeIndex Node index from which `tensor` comes from.\n * @param tensorIndex TensorIndex from which `tensor` comes from.\n *\n * @exception RuntimeError if a cycle is detected.\n */\n const buildMapOfGraph =\n (tensor: SymbolicTensor, finishedNodes: Node[], nodesInProgress: Node[],\n layer?: Layer, nodeIndex?: number, tensorIndex?: number) => {\n if (layer == null || nodeIndex == null || tensorIndex == null) {\n layer = tensor.sourceLayer;\n nodeIndex = tensor.nodeIndex;\n tensorIndex = tensor.tensorIndex;\n }\n const node = layer.inboundNodes[nodeIndex];\n\n // Prevent cycles.\n if (nodesInProgress.indexOf(node) !== -1) {\n throw new RuntimeError(\n `The tensor ${tensor.name} at layer \"${layer.name}\" ` +\n 'is part of a cycle.');\n }\n\n // Don't repeat work for shared subgraphs\n if (finishedNodes.indexOf(node) !== -1) {\n return;\n }\n\n // Update containerNodes.\n this.containerNodes.add(Container.nodeKey(layer, nodeIndex));\n\n // Store the traversal order for layer sorting.\n if (!(layer.id in layerIndices)) {\n layerIndices[layer.id] = Object.keys(layerIndices).length;\n }\n\n if (nodesInProgress.indexOf(node) === -1) {\n nodesInProgress.push(node);\n }\n\n // Propagate to all previous tensors connected to this node.\n const numInboundLayers = node.inboundLayers.length;\n for (let i = 0; i < numInboundLayers; i++) {\n const x = node.inputTensors[i];\n const layer = node.inboundLayers[i];\n const nodeIndex = node.nodeIndices[i];\n const tensorIndex = node.tensorIndices[i];\n buildMapOfGraph(\n x, finishedNodes, nodesInProgress, layer, nodeIndex,\n tensorIndex);\n }\n finishedNodes.push(node);\n while (nodesInProgress.indexOf(node) >= 0) {\n nodesInProgress.splice(nodesInProgress.indexOf(node), 1);\n }\n nodesInDecreasingDepth.push(node);\n };\n\n const finishedNodes: Node[] = [];\n const nodesInProgress: Node[] = [];\n for (const x of this.outputs) {\n buildMapOfGraph(x, finishedNodes, nodesInProgress);\n }\n\n const reversedNodesInDecreasingDepth =\n nodesInDecreasingDepth.slice().reverse();\n for (const node of reversedNodesInDecreasingDepth) {\n nodeIDToNode[node.id] = node;\n // If the depth is not set, the node has no outbound nodes (depth 0).\n if (!(node.id in nodesDepths)) {\n nodesDepths[node.id] = 0;\n }\n let depth = nodesDepths[node.id];\n\n // Update the depth of the corresponding layer\n const previousDepth =\n (layersDepths[node.outboundLayer.id] == null ?\n 0 :\n layersDepths[node.outboundLayer.id]);\n\n /*\n If we've seen this layer before at a higher depth, we should use that\n depth instead of the node depth. This is necessary for shared layers\n that have inputs at different depth levels in the graph.\n */\n depth = Math.max(depth, previousDepth);\n layersDepths[node.outboundLayer.id] = depth;\n layerIDToLayer[node.outboundLayer.id] = node.outboundLayer;\n nodesDepths[node.id] = depth;\n\n // Update the depth of inbound nodes.\n for (let i = 0; i < node.inboundLayers.length; i++) {\n const inboundLayer = node.inboundLayers[i];\n const nodeIndex = node.nodeIndices[i];\n const inboundNode = inboundLayer.inboundNodes[nodeIndex];\n const previousDepth =\n (nodesDepths[inboundNode.id] == null ? 0 :\n nodesDepths[inboundNode.id]);\n nodesDepths[inboundNode.id] = Math.max(depth + 1, previousDepth);\n nodeIDToNode[inboundNode.id] = inboundNode;\n }\n }\n\n // Build a dict {depth: list of nodes with this depth}\n const nodesByDepth: {[depth: string]: Node[]} = {};\n for (const nodeID in nodesDepths) {\n const depth = nodesDepths[nodeID];\n if (!(depth in nodesByDepth)) {\n nodesByDepth[depth] = [];\n }\n nodesByDepth[depth].push(nodeIDToNode[nodeID]);\n }\n\n // Build a dict {depth: list of layers with this depth}\n const layersByDepth: {[depth: string]: Layer[]} = {};\n for (const layerID in layersDepths) {\n const depth = layersDepths[layerID];\n if (!(depth in layersByDepth)) {\n layersByDepth[depth] = [];\n }\n layersByDepth[depth].push(layerIDToLayer[layerID]);\n }\n\n // Get sorted list of layer depths.\n let depthKeys = Object.keys(layersByDepth)\n .map(x => parseInt(x, 10))\n .sort(generic_utils.reverseNumberCompare);\n\n // Set this.layers and this.layersByDepth.\n this.layers = [];\n for (const depth of depthKeys) {\n const layersForDepth = layersByDepth[depth];\n // Container.layers needs to have a deterministic order:\n // here we order them by traversal order.\n layersForDepth.sort((a, b) => {\n const aIndex = layerIndices[a.id];\n const bIndex = layerIndices[b.id];\n if (aIndex < bIndex) {\n return -1;\n }\n if (aIndex > bIndex) {\n return 1;\n }\n return 0;\n });\n for (const layer of layersForDepth) {\n if (layer instanceof Container) {\n this.internalContainerRefs.push(layer);\n }\n this.layers.push(layer);\n }\n }\n this.layersByDepth = layersByDepth;\n\n // Get sorted list of node depths;\n depthKeys = Object.keys(nodesByDepth)\n .map(x => parseInt(x, 10))\n .sort(generic_utils.reverseNumberCompare);\n\n // Check that all tensors required are computable.\n // computable_tensors: all tensors in the graph\n // that can be computed from the inputs provided.\n const computableTensors = this.inputs.slice();\n\n // To provide a better error msg.\n const layersWithCompleteInput: string[] = [];\n for (const depth of depthKeys) {\n for (const node of nodesByDepth[depth]) {\n const layer = node.outboundLayer;\n if (layer != null) {\n for (const x of node.inputTensors) {\n if (computableTensors.indexOf(x) === -1) {\n throw new RuntimeError(\n `Graph disconnected: cannot obtain value for tensor ${x}` +\n ` at layer \"${layer.name}\". ` +\n 'The following previous layers were accessed without ' +\n `issue: ${layersWithCompleteInput}`);\n }\n }\n for (const x of node.outputTensors) {\n computableTensors.push(x);\n }\n layersWithCompleteInput.push(layer.name);\n }\n }\n }\n\n // Set this.containerNodes and this.nodesByDepth.\n this.nodesByDepth = nodesByDepth;\n\n // Ensure name unicity, which will be crucial for serialization\n // (since serialized nodes refer to layers by their name).\n const allNames = this.layers.map(x => x.name);\n for (const name of allNames) {\n const numOccurrences = allNames.filter(x => x === name).length;\n if (numOccurrences !== 1) {\n throw new RuntimeError(\n `The name \"${name}\" is used ${numOccurrences} times ` +\n 'in the model. All layer names should be unique. Layer names: ' +\n JSON.stringify(allNames));\n }\n }\n\n // Layer parameters.\n // The new container starts with a single inbound node\n // for its inputs, and no outbound nodes.\n // Will be appended to by future calls to apply().\n this.outboundNodes = [];\n // Will be appended to below, and by future calls to apply().\n this.inboundNodes = [];\n\n // Create the node linking internal inputs to internal outputs.\n // (This call has side effects.)\n // tslint:disable-next-line:no-unused-expression\n new Node({\n outboundLayer: this,\n inboundLayers: [],\n nodeIndices: [],\n tensorIndices: [],\n inputTensors: this.inputs,\n outputTensors: this.outputs,\n inputMasks: this.inputs.map(x => null),\n outputMasks: this.outputs.map(x => null),\n inputShapes: this.inputs.map(x => x.shape),\n outputShapes: this.outputs.map(x => x.shape)\n });\n this.built = true;\n this._refCount = 1; // The ref count of a container always start at 1.\n }\n\n protected assertNotDisposed() {\n if (this._refCount === 0) {\n throw new Error(`Container '${this.name}' is already disposed.`);\n }\n }\n\n /**\n * Attempt to dispose a LayersModel's weights.\n *\n * This method decrease the reference count of the LayersModel object by 1.\n *\n * A LayersModel is reference-counted. Its reference count is incremented by 1\n * when it is first constructed and when it is used as a Layer of another\n * LayersModel.\n *\n * If the reference count of a LayersModel becomes 0, the `dispose` method of\n * all its constituent `Layer`s will be called.\n *\n * Note: If the reference count is greater than 0 after the decrement, the\n * `dispose` method of its constituent `Layer`s will *not* be called.\n *\n * After a LayersModel is disposed, it cannot be used in calls such as\n * 'predict`, `evaluate` or `fit` anymore.\n *\n * @returns A DisposeResult Object with the following fields:\n * - refCountAfterDispose: The reference count of the LayersModel after this\n * `dispose()` call.\n * - numDisposedVariables: Number of `tf.Variable`s (i.e., weights) disposed\n * during this `dispose()` call.\n * @throws {Error} If the layer is not built yet, or if the LayersModel has\n * already been disposed.\n */\n dispose(): DisposeResult {\n this.assertNotDisposed();\n const result:\n DisposeResult = {refCountAfterDispose: null, numDisposedVariables: 0};\n if (--this._refCount === 0) {\n for (const layer of this.layers) {\n result.numDisposedVariables += layer.dispose().numDisposedVariables;\n }\n\n // Call dispose on each internally created container layer again to ensure\n // their refCounts hit zero and their tensors are subsequently deleted.\n for (const container of this.internalContainerRefs) {\n result.numDisposedVariables += container.dispose().numDisposedVariables;\n }\n }\n result.refCountAfterDispose = this._refCount;\n return result;\n }\n\n get trainable() {\n return this.trainable_;\n }\n\n set trainable(trainable: boolean) {\n this.layers.forEach(layer => {\n // tslint:disable-next-line:no-any\n ((layer as any)._trainableWeights as LayerVariable[])\n .forEach(w => w.trainable = trainable);\n });\n this.trainable_ = trainable;\n }\n\n get trainableWeights(): LayerVariable[] {\n // Porting Note: This check below is to prevent errors where the\n // _trainableWeights inherited from the parent class (Layer) gets\n // inadvertently used.\n if (this._trainableWeights.length > 0) {\n throw new ValueError(\n 'Container instance unexpectedly contains _trainableWeights.' +\n 'The trainable weights of a Container are a union of the ' +\n 'trainable weights of its consituent Layers. Its own ' +\n '_trainableWeights must remain an empty Array.');\n }\n\n if (!this.trainable) {\n return [];\n }\n let weights: LayerVariable[] = [];\n for (const layer of this.layers) {\n weights = weights.concat(layer.trainableWeights);\n }\n return weights;\n }\n\n get nonTrainableWeights(): LayerVariable[] {\n const weights: LayerVariable[] = [];\n for (const layer of this.layers) {\n weights.push(...layer.nonTrainableWeights);\n }\n if (!this.trainable) {\n const trainableWeights: LayerVariable[] = [];\n for (const layer of this.layers) {\n trainableWeights.push(...layer.trainableWeights);\n }\n return trainableWeights.concat(weights);\n }\n return weights;\n }\n\n get weights(): LayerVariable[] {\n return this.trainableWeights.concat(this.nonTrainableWeights);\n }\n\n /**\n * Loads all layer weights from a JSON object.\n *\n * Porting Note: HDF5 weight files cannot be directly loaded in JavaScript /\n * TypeScript. The utility script at `scripts/pykeras.py` offers means\n * to convert them into JSON strings compatible with this method.\n * Porting Note: TensorFlow.js Layers supports only loading by name currently.\n *\n * @param weights A JSON mapping weight names to weight values as nested\n * arrays of numbers, or a `NamedTensorMap`, i.e., a JSON mapping weight\n * names to `tf.Tensor` objects.\n * @param strict Require that the provided weights exactly match those\n * required by the container. Default: `true`. Passing `false` means that\n * extra weights and missing weights will be silently ignored.\n */\n loadWeights(weights: NamedTensorMap, strict = true) {\n const nameToWeight: {[name: string]: LayerVariable} = {};\n let totalWeightsCount = 0;\n for (const layer of this.layers) {\n for (const weight of layer.weights) {\n if (nameToWeight[weight.originalName] != null) {\n throw new ValueError(`Duplicate weight name: ${weight.originalName}`);\n }\n nameToWeight[weight.originalName] = weight;\n totalWeightsCount++;\n }\n }\n\n const weightValueTuples: Array<[LayerVariable, Tensor]> = [];\n for (const name in weights) {\n // TF 2.2.0 added cell name to the weight name in the format of\n // layer_name/cell_name/weight_name, we need to remove\n // the inner cell name.\n let validatedName = name;\n if (nameToWeight[name] == null) {\n const tokens = name.split('/');\n const shortenNameArray =\n tokens.slice(0, -2).concat([tokens[tokens.length - 1]]);\n validatedName = shortenNameArray.join('/');\n }\n if (nameToWeight[validatedName] != null) {\n weightValueTuples.push([nameToWeight[validatedName], weights[name]]);\n } else if (strict) {\n throw new ValueError(\n `Provided weight data has no target variable: ${name}`);\n }\n delete nameToWeight[validatedName];\n }\n\n if (strict) {\n // Check that all weights are set.\n const unsetNames: string[] = [];\n for (const name in nameToWeight) {\n unsetNames.push(name);\n }\n if (unsetNames.length > 0) {\n throw new ValueError(\n `${unsetNames.length} of ${\n totalWeightsCount} weights are not set: ` +\n `${unsetNames}`);\n }\n }\n\n batchSetValue(weightValueTuples);\n }\n\n /**\n * Util shared between different serialization methods.\n * @returns LayersModel config with Keras version information added.\n */\n protected updatedConfig(): serialization.ConfigDict {\n const theConfig = this.getConfig();\n const modelConfig: serialization.ConfigDict = {};\n modelConfig['className'] = this.getClassName();\n modelConfig['config'] = theConfig;\n modelConfig['kerasVersion'] = `tfjs-layers ${layersVersion}`;\n // TODO(nielsene): Replace something like K.backend() once\n // possible.\n modelConfig['backend'] = 'TensorFlow.js';\n return modelConfig;\n }\n\n /**\n * Returns a JSON string containing the network configuration.\n *\n * To load a network from a JSON save file, use\n * models.modelFromJSON(jsonString);\n * @param extraJsonArgs Unused in tfjs-layers, maintained for PyKeras\n * @param returnString Whether the return value should be stringified\n * (default: `true`).\n * @returns a JSON string if `returnString` (default), or a JSON object if\n * `!returnString`.\n */\n // tslint:disable-next-line:no-any\n toJSON(unused?: any, returnString = true): string|PyJsonDict {\n const modelConfig = convertTsToPythonic(this.updatedConfig()) as PyJsonDict;\n return returnString ? JSON.stringify(modelConfig) : modelConfig;\n }\n\n /**\n * Call the model on new inputs.\n *\n * In this case `call` just reapplies all ops in the graph to the new inputs\n * (e.g. build a new computational graph from the provided inputs).\n *\n * @param inputs A tensor or list of tensors.\n * @param mask A mask or list of masks. A mask can be either a tensor or null\n * (no mask).\n *\n * @return A tensor if there is a single output, or a list of tensors if there\n * are more than one outputs.\n */\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = generic_utils.toList(inputs);\n const feedDict = new FeedDict();\n for (let i = 0; i < this.inputs.length; ++i) {\n feedDict.add(this.inputs[i], inputs[i]);\n }\n return execute(this.outputs, feedDict, kwargs) as Tensor | Tensor[];\n });\n }\n\n /**\n * Computes an output mask tensor.\n *\n * @param inputs Tensor or list of tensors.\n * @param mask Tensor or list of tensors.\n *\n * @return null or a tensor (or list of tensors, one per output tensor of the\n * layer).\n */\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor\n |Tensor[] {\n return tidy(() => {\n inputs = generic_utils.toList(inputs);\n let masks: Tensor[];\n if (mask == null) {\n masks = generic_utils.pyListRepeat(null, inputs.length);\n } else {\n masks = generic_utils.toList(mask);\n }\n // TODO(michaelterry): Add support for mask caching.\n return this.runInternalGraph(inputs, masks)[1];\n });\n }\n\n /**\n * Computes the output shape of the layer.\n *\n * Assumes that the layer will be built to match that input shape provided.\n *\n * @param inputShape A shape (tuple of integers) or a list of shape tuples\n * (one per output tensor of the layer). Shape tuples can include null for\n * free dimensions, instead of an integer.\n */\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n const inputShapes = types_utils.normalizeShapeList(inputShape);\n if (inputShapes.length !== this.inputLayers.length) {\n throw new ValueError(\n `Invalid inputShape argument ${inputShape}: ` +\n `model has ${this.inputLayers.length} tensor inputs.`);\n }\n\n // TODO(michaelterry): Add caching\n const layersToOutputShapes: {[shapeKey: string]: Shape} = {};\n for (let i = 0; i < inputShapes.length; i++) {\n const layer = this.inputLayers[i];\n const inputShape = inputShapes[i];\n // It's an input layer: computeOutputShape is identity,\n // and there is only one node and one tensor output.\n const shapeKey = layer.name + '_0_0';\n layersToOutputShapes[shapeKey] = inputShape;\n }\n\n const depthKeys = Object.keys(this.nodesByDepth)\n .map(x => parseInt(x, 10))\n .sort(generic_utils.reverseNumberCompare);\n // Iterate over nodes, by depth level.\n if (depthKeys.length > 1) {\n for (const depth of depthKeys) {\n const nodes = this.nodesByDepth[depth];\n for (const node of nodes) {\n // This is always a single layer, never a list.\n const layer = node.outboundLayer;\n if (this.inputLayers.map(x => x.id).indexOf(layer.id) !== -1) {\n // We've already covered the input layers a few lines above.\n continue;\n }\n // Potentially redundant list, same size of node.inputTensors.\n const inputShapes: Shape[] = [];\n for (let j = 0; j < node.inboundLayers.length; j++) {\n const inboundLayer = node.inboundLayers[j];\n const nodeIndex = node.nodeIndices[j];\n const tensorIndex = node.tensorIndices[j];\n const shapeKey = `${inboundLayer.name}_${nodeIndex}_${tensorIndex}`;\n const inputShape = layersToOutputShapes[shapeKey];\n inputShapes.push(inputShape);\n }\n\n const outputShape = layer.computeOutputShape(\n generic_utils.singletonOrArray(inputShapes));\n\n const outputShapes = types_utils.normalizeShapeList(outputShape);\n const nodeIndex = layer.inboundNodes.indexOf(node);\n for (let j = 0; j < outputShapes.length; j++) {\n const shapeKey = `${layer.name}_${nodeIndex}_${j}`;\n layersToOutputShapes[shapeKey] = outputShapes[j];\n }\n }\n }\n }\n\n // Read final output shapes from layersToOutputShapes.\n const outputShapes: Shape[] = [];\n const outputShapeKeys: string[] = [];\n for (let i = 0; i < this.outputLayers.length; i++) {\n const layer = this.outputLayers[i];\n const nodeIndex = this.outputLayersNodeIndices[i];\n const tensorIndex = this.outputLayersTensorIndices[i];\n const shapeKey = `${layer.name}_${nodeIndex}_${tensorIndex}`;\n outputShapeKeys.push(shapeKey);\n }\n\n for (let i = 0; i < outputShapeKeys.length; i++) {\n const key = outputShapeKeys[i];\n generic_utils.assert(key in layersToOutputShapes);\n outputShapes.push(layersToOutputShapes[key]);\n }\n\n // TODO(michaelterry): Update cache\n return generic_utils.singletonOrArray(outputShapes);\n }\n\n /**\n * Computes output tensors for new inputs.\n *\n * Note:\n * - Expects `inputs` to be a list (potentially with 1 element).\n *\n * @param inputs List of tensors\n * @param masks List of masks (tensors or null).\n * @return Three lists: outputTensors, outputMasks, outputShapes\n */\n protected runInternalGraph(inputs: Tensor[], masks?: Tensor[]):\n [Tensor[], Tensor[], Shape[]] {\n if (masks == null) {\n masks = generic_utils.pyListRepeat(null, inputs.length);\n }\n\n // Dictionary mapping reference tensors to tuples\n // (computed tensor, compute mask)\n // we assume a 1:1 mapping from tensor to mask\n // TODO: raise exception when a `.computeMask()` call\n // does not return a list the same size as `call`\n const tensorMap: {[tensorID: string]: [Tensor, Tensor]} = {};\n for (let i = 0; i < this.inputs.length; ++i) {\n const x = this.inputs[i];\n const y = inputs[i];\n const mask = masks[i];\n tensorMap[x.id] = [y, mask];\n }\n\n const depthKeys = Object.keys(this.nodesByDepth)\n .map(x => parseInt(x, 10))\n .sort(generic_utils.reverseNumberCompare);\n for (const depth of depthKeys) {\n const nodes = this.nodesByDepth[depth];\n for (const node of nodes) {\n // This is always a single layer, never a list.\n const layer = node.outboundLayer;\n const referenceInputTensors = node.inputTensors;\n const referenceOutputTensors = node.outputTensors;\n\n // If all previous input tensors are available in tensorMap,\n // then call node.inboundLayer on them.\n // List of tuples [input, mask]:\n const computedData = new Array<[Tensor, Tensor]>();\n for (const x of referenceInputTensors) {\n if (x.id in tensorMap) {\n computedData.push(tensorMap[x.id]);\n }\n }\n if (computedData.length === referenceInputTensors.length) {\n // TODO(michaelterry): Add K.name_scope here, if we need it.\n let kwargs: Kwargs = {};\n let computedTensors: Tensor[];\n let computedMasks: Tensor[];\n let outputTensors: Tensor[];\n let outputMasks: Tensor[];\n // call layer\n if (node.callArgs != null) {\n kwargs = node.callArgs;\n }\n if (computedData.length === 1) {\n const [computedTensor, computedMask] = computedData[0];\n if (kwargs['mask'] == null) {\n kwargs['mask'] = computedMask;\n }\n outputTensors =\n generic_utils.toList(layer.call(computedTensor, kwargs));\n outputMasks = generic_utils.toList(\n layer.computeMask(computedTensor, computedMask));\n computedTensors = [computedTensor];\n computedMasks = [computedMask];\n } else {\n computedTensors = computedData.map(x => x[0]);\n computedMasks = computedData.map(x => x[1]);\n if (kwargs['mask'] == null) {\n kwargs['mask'] = computedMasks;\n }\n outputTensors =\n generic_utils.toList(layer.call(computedTensors, kwargs));\n outputMasks = generic_utils.toList(\n layer.computeMask(computedTensors, computedMasks));\n }\n\n if (layer.activityRegularizer) {\n throw new NotImplementedError(\n 'LayersModel invocation with concrete Tensor value(s) in the ' +\n 'presence of activity regularizer(s) is not supported yet.');\n }\n // TODO(michaelterry): Add model updates and losses\n\n // Update tensor map.\n for (let i = 0; i < referenceOutputTensors.length; ++i) {\n const x = referenceOutputTensors[i];\n const y = outputTensors[i];\n const mask = outputMasks[i];\n tensorMap[x.id] = [y, mask];\n }\n }\n }\n }\n\n const outputTensors: Tensor[] = [];\n const outputMasks: Tensor[] = [];\n const outputShapes: Shape[] = [];\n for (const x of this.outputs) {\n generic_utils.assert(\n x.id in tensorMap, `Could not compute output ${x.name} : ${x.id}`);\n const [tensor, mask] = tensorMap[x.id];\n outputShapes.push(tensor.shape);\n outputTensors.push(tensor);\n outputMasks.push(mask);\n }\n\n // TODO(michaelterry): Add support for caches.\n return [outputTensors, outputMasks, outputShapes];\n }\n\n /**\n * Builds a map of internal node keys to node ordering.\n * Used in serializaion a node orderings may change as unused nodes are\n * dropped. Porting Note: This helper method was pulled out of getConfig to\n * improve readability.\n * @param layers An array of Layers in the model.\n * @returns Map of Node Keys to index order within the layer.\n */\n private buildNodeConversionMap(layers: Layer[]): {[nodeKey: string]: number} {\n const nodeConversionMap: {[nodeKey: string]: number} = {};\n let keptNodes: number;\n for (const layer of this.layers) {\n keptNodes = layer instanceof Container ? 1 : 0;\n for (let originalNodeIndex = 0;\n originalNodeIndex < layer.inboundNodes.length; originalNodeIndex++) {\n const nodeKey = Container.nodeKey(layer, originalNodeIndex);\n if (this.containerNodes.has(nodeKey)) {\n // i.e. we mark it to be saved\n nodeConversionMap[nodeKey] = keptNodes;\n keptNodes += 1;\n }\n }\n }\n return nodeConversionMap;\n }\n\n /**\n * Retrieves a layer based on either its name (unique) or index.\n *\n * Indices are based on order of horizontal graph traversal (bottom-up).\n *\n * If both `name` and `index` are specified, `index` takes precedence.\n *\n * @param name Name of layer.\n * @param index Index of layer.\n * @returns A Layer instance.\n * @throws ValueError: In case of invalid layer name or index.\n *\n * @doc {\n * heading: 'Layers',\n * subheading: 'Classes',\n * namespace: 'layers',\n * subclasses: ['LayersModel']\n * }\n */\n getLayer(name?: string, index?: number): Layer {\n if (index != null) {\n if (this.layers.length <= index) {\n throw new ValueError(\n `Was asked to retrieve layer at index ${index}, but model only ` +\n `has ${this.layers.length} layer(s).`);\n } else {\n return this.layers[index];\n }\n } else {\n if (name == null) {\n throw new ValueError('Provide either a layer name or layer index');\n }\n }\n\n for (const layer of this.layers) {\n if (layer.name === name) {\n return layer;\n }\n }\n throw new ValueError(`No such layer: ${name}`);\n }\n\n /**\n * Retrieves the Container's current loss values.\n *\n * Used for regularizers during training.\n */\n calculateLosses(): Scalar[] {\n // Porting Node: This is an augmentation to Container.loss in PyKeras.\n // In PyKeras, Container.loss returns symbolic tensors. Here a concrete\n // Tensor (specifically Scalar) values are returned. This is due to the\n // imperative backend.\n return tidy(() => {\n const losses: Scalar[] = [];\n for (const layer of this.layers) {\n for (let nodeIndex = 0; nodeIndex < layer.inboundNodes.length;\n ++nodeIndex) {\n const nodeKey = Container.nodeKey(layer, nodeIndex);\n if (this.containerNodes.has(nodeKey)) {\n losses.push(...layer.calculateLosses());\n }\n }\n }\n // TODO(cais): Add any unconditional model-level losses?\n return losses;\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {name: this.name};\n\n // Build a map from layer unique name (self._node_key)\n // to the index of the nodes that are saved in the config.\n // Only nodes in container_nodes are saved.\n const nodeConversionMap: {[nodeKey: string]: number} =\n this.buildNodeConversionMap(this.layers);\n\n // Serialize and save the layers in layerConfigs\n const layerConfigs = [];\n for (const layer of this.layers) {\n const layerClassName = layer.getClassName();\n const layerConfig = layer.getConfig();\n const filteredInboundNodes = [];\n for (let originalNodeIndex = 0;\n originalNodeIndex < layer.inboundNodes.length; originalNodeIndex++) {\n const node = layer.inboundNodes[originalNodeIndex];\n const nodeKey = Container.nodeKey(layer, originalNodeIndex);\n let kwargs = {};\n if (this.containerNodes.has(nodeKey)) {\n // The node is relevant to the model:\n // add to filteredInboundNodes.\n if (node.callArgs) {\n try {\n JSON.stringify(node.callArgs);\n kwargs = node.callArgs;\n } catch (err) {\n console.warn(\n `Layer ${layer.name} was passed ` +\n `non-serializable keyword arguments: ` +\n `${node.callArgs}. They will not be included ` +\n `in the serialized model (and thus will be ` +\n `missing at deserialization time).`);\n kwargs = {};\n }\n }\n if (node.inboundLayers.length > 0) {\n const nodeData = [];\n for (let i = 0; i < node.inboundLayers.length; i++) {\n const inboundLayer = node.inboundLayers[i];\n const nodeIndex = node.nodeIndices[i];\n const tensorIndex = node.tensorIndices[i];\n const nodeKey = Container.nodeKey(inboundLayer, nodeIndex);\n let newNodeIndex = nodeConversionMap[nodeKey];\n if (newNodeIndex == null) {\n newNodeIndex = 0;\n }\n nodeData.push(\n [inboundLayer.name, newNodeIndex, tensorIndex, kwargs]);\n }\n filteredInboundNodes.push(nodeData);\n }\n }\n }\n const dict: serialization.ConfigDict = {};\n dict['name'] = layer.name;\n dict['className'] = layerClassName;\n dict['config'] = layerConfig;\n dict['inboundNodes'] = filteredInboundNodes;\n layerConfigs.push(dict);\n }\n config['layers'] = layerConfigs;\n // Gather info about inputs and outputs\n const modelInputs = [];\n for (let i = 0; i < this.inputLayers.length; i++) {\n const layer = this.inputLayers[i];\n const nodeIndex = this.inputLayersNodeIndices[i];\n\n const nodeKey = Container.nodeKey(layer, nodeIndex);\n if (!this.containerNodes.has(nodeKey)) {\n continue;\n }\n let newNodeIndex = nodeConversionMap[nodeKey];\n if (newNodeIndex === null || newNodeIndex === undefined) {\n newNodeIndex = 0;\n }\n const tensorIndex = this.inputLayersTensorIndices[i];\n modelInputs.push([layer.name, newNodeIndex, tensorIndex]);\n }\n config['inputLayers'] = modelInputs;\n\n const modelOutputs = [];\n for (let i = 0; i < this.outputLayers.length; i++) {\n const layer = this.outputLayers[i];\n const nodeIndex = this.outputLayersNodeIndices[i];\n\n const nodeKey = Container.nodeKey(layer, nodeIndex);\n if (!this.containerNodes.has(nodeKey)) {\n continue;\n }\n let newNodeIndex = nodeConversionMap[nodeKey];\n if (newNodeIndex === null || newNodeIndex === undefined) {\n newNodeIndex = 0;\n }\n const tensorIndex = this.outputLayersTensorIndices[i];\n modelOutputs.push([layer.name, newNodeIndex, tensorIndex]);\n }\n config['outputLayers'] = modelOutputs;\n return config;\n }\n\n /**\n * Instantiates a LayersModel from its config (output of `get_config()`).\n * @param cls the class to create\n * @param config LayersModel config dictionary.\n * @param customObjects An optional dictionary of custom objects.\n * @param fastWeightInit Optional flag to use fast weight initialization\n * during deserialization. This is applicable to cases in which\n * the initialization will be immediately overwritten by loaded weight\n * values. Default: `false`.\n * @returns A LayersModel instance.\n * @throws ValueError: In case of improperly formatted config dict.\n */\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict,\n customObjects = {} as serialization.ConfigDict,\n fastWeightInit = false): T {\n // Layer instances created during\n // the graph reconstruction process\n const createdLayers: {[layerName: string]: Layer} = {};\n\n // Dictionary mapping layer instances to\n // node data that specifies a layer call.\n // It acts as a queue that maintains any unprocessed\n // layer call until it becomes possible to process it\n // (i.e. until the input tensors to the call all exist).\n const unprocessedNodes: {[layer: string]: TensorKeyWithArgsArray[][]} = {};\n function addUnprocessedNode(\n layer: Layer, nodeData: TensorKeyWithArgsArray[]) {\n if (!(layer.name in unprocessedNodes)) {\n unprocessedNodes[layer.name] = [nodeData];\n } else {\n unprocessedNodes[layer.name].push(nodeData);\n }\n }\n\n function processNode(layer: Layer, nodeData: TensorKeyWithArgsArray[]) {\n const inputTensors: SymbolicTensor[] = [];\n let kwargs;\n for (const inputData of nodeData) {\n const inboundLayerName = inputData[0];\n const inboundNodeIndex = inputData[1];\n const inboundTensorIndex = inputData[2];\n\n kwargs = inputData[3] == null ?\n {} :\n inputData[3] as serialization.ConfigDict;\n if (!(inboundLayerName in createdLayers)) {\n addUnprocessedNode(layer, nodeData);\n return;\n }\n const inboundLayer = createdLayers[inboundLayerName];\n if (inboundLayer.inboundNodes.length <= inboundNodeIndex) {\n addUnprocessedNode(layer, nodeData);\n return;\n }\n const inboundNode = inboundLayer.inboundNodes[inboundNodeIndex];\n inputTensors.push(inboundNode.outputTensors[inboundTensorIndex]);\n }\n // Call layer on its inputs, thus creating the node\n // and building the layer if needed.\n // Note: This has Eager vs Graph Implications.\n if (inputTensors.length > 0) {\n layer.apply(\n generic_utils.singletonOrArray(inputTensors),\n kwargs); // was ** kwargs\n }\n }\n\n /**\n * Deserialize a layer, then call it on appropriate inputs.\n * @param layerData: layer config dict.\n * @throws ValueError: In case of improperly formatted `layer_data`\n * dict.\n */\n function processLayer(layerData: serialization.ConfigDict|null) {\n const layerName = layerData['name'] as string;\n // Instantiate layer.\n const layer =\n deserializeLayer(\n layerData,\n config['customObjects'] != null ?\n config['customObjects'] as serialization.ConfigDict :\n {}) as Layer;\n layer.setFastWeightInitDuringBuild(fastWeightInit);\n createdLayers[layerName] = layer;\n // Gather layer inputs.\n const inboundNodesData =\n layerData['inboundNodes'] as TensorKeyWithArgsArray[][];\n inboundNodesData.forEach(nodeData => {\n if (!(nodeData instanceof Array)) {\n throw new ValueError(\n `Corrupted configuration, expected array for nodeData: ${\n nodeData}`);\n }\n // We don't process nodes (i.e. make layer calls)\n // on the fly because the inbound node may not yet exist,\n // in case of layer shared at different topological depths\n // (e.g.a model such as A(B(A(B(x)))))\n addUnprocessedNode(layer, nodeData);\n });\n }\n\n // First, we create all layers and enqueue nodes to be processed.\n const name = config['name'];\n const layersFromConfig = config['layers'] as serialization.ConfigDict[];\n for (const layerData of layersFromConfig) {\n processLayer(layerData);\n }\n\n // Then we process nodes in order of layer depth.\n // Nodes that cannot yet be processed(if the inbound node\n // does not yet exist) are re - enqueued, and the process\n // is repeated until all nodes are processed.\n while (!generic_utils.isObjectEmpty(unprocessedNodes)) {\n for (const layerData of layersFromConfig) {\n const layer = createdLayers[layerData['name'] as string];\n if (layer.name in unprocessedNodes) {\n const currentUnprocessedNodesForLayer = unprocessedNodes[layer.name];\n delete unprocessedNodes[layer.name];\n for (const nodeData of currentUnprocessedNodesForLayer) {\n processNode(layer, nodeData);\n }\n }\n }\n }\n\n const inputTensors: SymbolicTensor[] = [];\n const outputTensors: SymbolicTensor[] = [];\n const inputLayersFromConfig =\n config['inputLayers'] as serialization.ConfigDict[];\n for (const layerData of inputLayersFromConfig) {\n const layerName = layerData[0] as string;\n const nodeIndex = layerData[1] as number;\n const tensorIndex = layerData[2] as number;\n generic_utils.assert(layerName in createdLayers);\n const layer = createdLayers[layerName];\n const layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;\n inputTensors.push(layerOutputTensors[tensorIndex]);\n }\n const outputLayersFromConfig =\n config['outputLayers'] as serialization.ConfigDict[];\n for (const layerData of outputLayersFromConfig) {\n const layerName = layerData[0] as string;\n const nodeIndex = layerData[1] as number;\n const tensorIndex = layerData[2] as number;\n generic_utils.assert(layerName in createdLayers);\n const layer = createdLayers[layerName];\n const layerOutputTensors = layer.inboundNodes[nodeIndex].outputTensors;\n outputTensors.push(layerOutputTensors[tensorIndex]);\n }\n return new cls({inputs: inputTensors, outputs: outputTensors, name});\n }\n\n /**\n * Determine whether the container is stateful.\n *\n * Porting Note: this is the equivalent of the stateful @property of\n * the Container class in PyKeras.\n */\n get stateful(): boolean {\n // Porting Note: This check is to prevent inadvertent setting of the\n // _stateful property of the Container instance.\n if (this._stateful) {\n throw new ValueError(\n 'Container instance unexpectedly has _stateful = true. The ' +\n 'statefulness of a Container is determined by the Layers it ' +\n 'contains. Its _stateful property must remain the default false.');\n }\n for (const layer of this.layers) {\n if (layer.stateful) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Reset the state of all stateful constituent layers (if any).\n *\n * Examples of stateful layers include RNN layers whose `stateful` property\n * is set as `true`.\n */\n resetStates() {\n tidy(() => {\n this.layers.forEach(layer => {\n // tslint:disable:no-any\n if (layer.stateful) {\n layer.resetStates();\n }\n // tslint:enable:no-any\n });\n });\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {argMax, clone, dispose, mul, reshape, Tensor, Tensor1D, tensor1d, tidy} from '@tensorflow/tfjs-core';\n\n/**\n * For multi-class classification problems, this object is designed to store a\n * mapping from class index to the \"weight\" of the class, where higher weighted\n * classes have larger impact on loss, accuracy, and other metrics.\n *\n * This is useful for cases in which you want the model to \"pay more attention\"\n * to examples from an under-represented class, e.g., in unbalanced datasets.\n */\nexport type ClassWeight = {\n [classIndex: number]: number\n};\n\n/**\n * Class weighting for a model with multiple outputs.\n *\n * This object maps each output name to a class-weighting object.\n */\nexport type ClassWeightMap = {\n [outputName: string]: ClassWeight\n};\n\nfunction standardizeSampleOrClassWeights(\n xWeight: ClassWeight|ClassWeight[]|ClassWeightMap, outputNames: string[],\n weightType: 'sampleWeight'|'classWeight'): ClassWeight[] {\n const numOutputs = outputNames.length;\n if (xWeight == null || (Array.isArray(xWeight) && xWeight.length === 0)) {\n return outputNames.map(name => null);\n }\n if (numOutputs === 1) {\n if (Array.isArray(xWeight) && xWeight.length === 1) {\n return xWeight;\n } else if (typeof xWeight === 'object' && outputNames[0] in xWeight) {\n return [(xWeight as ClassWeightMap)[outputNames[0]]];\n } else {\n return [xWeight as ClassWeight];\n }\n }\n if (Array.isArray(xWeight)) {\n if (xWeight.length !== numOutputs) {\n throw new Error(\n `Provided ${weightType} is an array of ${xWeight.length} ` +\n `element(s), but the model has ${numOutputs} outputs. ` +\n `Make sure a set of weights is provided for each model output.`);\n }\n return xWeight;\n } else if (\n typeof xWeight === 'object' && Object.keys(xWeight).length > 0 &&\n typeof (xWeight as ClassWeightMap)[Object.keys(xWeight)[0]] ===\n 'object') {\n const output: ClassWeight[] = [];\n outputNames.forEach(outputName => {\n if (outputName in xWeight) {\n output.push((xWeight as ClassWeightMap)[outputName]);\n } else {\n output.push(null);\n }\n });\n return output;\n } else {\n throw new Error(\n `The model has multiple (${numOutputs}) outputs, ` +\n `so ${weightType} must be either an array with ` +\n `${numOutputs} elements or an object with ${outputNames} keys. ` +\n `Provided ${weightType} not understood: ${JSON.stringify(xWeight)}`);\n }\n}\n\n/**\n * Standardize class weighting objects.\n *\n * This function takes a single class-weighting object, an array of them,\n * or a map from output name to class-weighting object. It compares it to the\n * output name(s) of the model, base on which it outputs an array of\n * class-weighting objects of which the length matches the number of outputs.\n *\n * @param classWeight Input class-weighting object(s).\n * @param outputNames All output name(s) of the model.\n * @return An array of class-weighting objects. The length of the array matches\n * the model's number of outputs.\n */\nexport function standardizeClassWeights(\n classWeight: ClassWeight|ClassWeight[]|ClassWeightMap,\n outputNames: string[]): ClassWeight[] {\n return standardizeSampleOrClassWeights(\n classWeight, outputNames, 'classWeight');\n}\n\nexport function standardizeSampleWeights(\n classWeight: ClassWeight|ClassWeight[]|ClassWeightMap,\n outputNames: string[]): ClassWeight[] {\n return standardizeSampleOrClassWeights(\n classWeight, outputNames, 'sampleWeight');\n}\n\n/**\n * Standardize by-sample and/or by-class weights for training.\n *\n * Note that this function operates on one model output at a time. For a model\n * with multiple outputs, you must call this function multiple times.\n *\n * @param y The target tensor that the by-sample and/or by-class weight is for.\n * The values of y are assumed to encode the classes, either directly\n * as an integer index, or as one-hot encoding.\n * @param sampleWeight By-sample weights.\n * @param classWeight By-class weights: an object mapping class indices\n * (integers) to a weight (float) to apply to the model's loss for the\n * samples from this class during training. This can be useful to tell the\n * model to \"pay more attention\" to samples from an under-represented class.\n * @param sampleWeightMode The mode for the sample weights.\n * @return A Promise of weight tensor, of which the size of the first dimension\n * matches that of `y`.\n */\nexport async function standardizeWeights(\n y: Tensor, sampleWeight?: Tensor, classWeight?: ClassWeight,\n sampleWeightMode?: 'temporal'): Promise<Tensor> {\n if (sampleWeight != null || sampleWeightMode != null) {\n // TODO(cais): Once 'temporal' mode is implemented, document it in the doc\n // string.\n throw new Error('Support sampleWeight is not implemented yet');\n }\n\n if (classWeight != null) {\n // Apply class weights per sample.\n const yClasses: Tensor1D = tidy(() => {\n if (y.shape.length === 1) {\n // Assume class indices.\n return clone(y) as Tensor1D;\n } else if (y.shape.length === 2) {\n if (y.shape[1] > 1) {\n // Assume one-hot encoding of classes.\n const axis = 1;\n return argMax(y, axis);\n } else if (y.shape[1] === 1) {\n // Class index.\n return reshape(y, [y.shape[0]]);\n } else {\n throw new Error(\n `Encountered unexpected last-dimension size (${y.shape[1]}) ` +\n `during handling of class weights. The size is expected to be ` +\n `>= 1.`);\n }\n } else {\n throw new Error(\n `Unexpected rank of target (y) tensor (${y.rank}) during ` +\n `handling of class weights. The rank is expected to be 1 or 2.`);\n }\n });\n\n const yClassIndices = Array.from(await yClasses.data());\n dispose(yClasses);\n const classSampleWeight: number[] = [];\n yClassIndices.forEach(classIndex => {\n if (classWeight[classIndex] == null) {\n throw new Error(\n `classWeight must contain all classes in the training data. ` +\n `The class ${classIndex} exists in the data but not in ` +\n `classWeight`);\n } else {\n classSampleWeight.push(classWeight[classIndex]);\n }\n });\n\n return tensor1d(classSampleWeight, 'float32');\n } else {\n return null;\n }\n}\n\n/**\n * Apply per-sample weights on the loss values from a number of samples.\n *\n * @param losses Loss tensor of shape `[batchSize]`.\n * @param sampleWeights Per-sample weight tensor of shape `[batchSize]`.\n * @returns Tensor of the same shape as`losses`.\n */\nexport function computeWeightedLoss(losses: Tensor, sampleWeights: Tensor) {\n return mul(losses, sampleWeights);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Interfaces and methods for training models using TensorFlow.js datasets.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {scalar} from '@tensorflow/tfjs-core';\nimport {BaseCallback, configureCallbacks, CustomCallbackArgs, History, ModelLoggingVerbosity, standardizeCallbacks, YieldEveryOptions} from '../base_callbacks';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {disposeTensorsInLogs, UnresolvedLogs} from '../logs';\nimport {TensorOrArrayOrMap} from '../types';\nimport {singletonOrArray, toList} from '../utils/generic_utils';\n\nimport {Dataset, LazyIterator} from './dataset_stub';\nimport {ClassWeight, ClassWeightMap, standardizeClassWeights, standardizeWeights} from './training_utils';\n\n/**\n * Interface for configuring model training based on a dataset object.\n */\nexport interface ModelFitDatasetArgs<T> {\n /**\n * (Optional) Total number of steps (batches of samples) before\n * declaring one epoch finished and starting the next epoch. It should\n * typically be equal to the number of samples of your dataset divided by\n * the batch size, so that `fitDataset`() call can utilize the entire dataset.\n * If it is not provided, use `done` return value in `iterator.next()` as\n * signal to finish an epoch.\n */\n batchesPerEpoch?: number;\n\n /**\n * Integer number of times to iterate over the training dataset.\n */\n epochs: number;\n\n /**\n * Verbosity level.\n *\n * Expected to be 0, 1, or 2. Default: 1.\n *\n * 0 - No printed message during fit() call.\n * 1 - In Node.js (tfjs-node), prints the progress bar, together with\n * real-time updates of loss and metric values and training speed.\n * In the browser: no action. This is the default.\n * 2 - Not implemented yet.\n */\n verbose?: ModelLoggingVerbosity;\n\n /**\n * List of callbacks to be called during training.\n * Can have one or more of the following callbacks:\n * - `onTrainBegin(logs)`: called when training starts.\n * - `onTrainEnd(logs)`: called when training ends.\n * - `onEpochBegin(epoch, logs)`: called at the start of every epoch.\n * - `onEpochEnd(epoch, logs)`: called at the end of every epoch.\n * - `onBatchBegin(batch, logs)`: called at the start of every batch.\n * - `onBatchEnd(batch, logs)`: called at the end of every batch.\n * - `onYield(epoch, batch, logs)`: called every `yieldEvery` milliseconds\n * with the current epoch, batch and logs. The logs are the same\n * as in `onBatchEnd()`. Note that `onYield` can skip batches or\n * epochs. See also docs for `yieldEvery` below.\n */\n callbacks?: BaseCallback[]|CustomCallbackArgs|CustomCallbackArgs[];\n\n /**\n * Data on which to evaluate the loss and any model\n * metrics at the end of each epoch. The model will not be trained on this\n * data. This could be any of the following:\n *\n * - An array `[xVal, yVal]`, where the two values may be `tf.Tensor`,\n * an array of Tensors, or a map of string to Tensor.\n * - Similarly, an array ` [xVal, yVal, valSampleWeights]`\n * (not implemented yet).\n * - a `Dataset` object with elements of the form `{xs: xVal, ys: yVal}`,\n * where `xs` and `ys` are the feature and label tensors, respectively.\n *\n * If `validationData` is an Array of Tensor objects, each `tf.Tensor` will be\n * sliced into batches during validation, using the parameter\n * `validationBatchSize` (which defaults to 32). The entirety of the\n * `tf.Tensor` objects will be used in the validation.\n *\n * If `validationData` is a dataset object, and the `validationBatches`\n * parameter is specified, the validation will use `validationBatches` batches\n * drawn from the dataset object. If `validationBatches` parameter is not\n * specified, the validation will stop when the dataset is exhausted.\n *\n * The model will not be trained on this data.\n */\n validationData?: [\n TensorOrArrayOrMap, TensorOrArrayOrMap\n ]|[TensorOrArrayOrMap, TensorOrArrayOrMap, TensorOrArrayOrMap]|Dataset<T>;\n\n /**\n * Optional batch size for validation.\n *\n * Used only if `validationData` is an array of `tf.Tensor` objects, i.e., not\n * a dataset object.\n *\n * If not specified, its value defaults to 32.\n */\n validationBatchSize?: number;\n\n /**\n * (Optional) Only relevant if `validationData` is specified and is a dataset\n * object.\n *\n * Total number of batches of samples to draw from `validationData` for\n * validation purpose before stopping at the end of every epoch. If not\n * specified, `evaluateDataset` will use `iterator.next().done` as signal to\n * stop validation.\n */\n validationBatches?: number;\n\n /**\n * Configures the frequency of yielding the main thread to other tasks.\n *\n * In the browser environment, yielding the main thread can improve the\n * responsiveness of the page during training. In the Node.js environment,\n * it can ensure tasks queued in the event loop can be handled in a timely\n * manner.\n *\n * The value can be one of the following:\n * - `'auto'`: The yielding happens at a certain frame rate (currently set\n * at 125ms). This is the default.\n * - `'batch'`: yield every batch.\n * - `'epoch'`: yield every epoch.\n * - a `number`: Will yield every `number` milliseconds.\n * - `'never'`: never yield. (But yielding can still happen through `await\n * nextFrame()` calls in custom callbacks.)\n */\n yieldEvery?: YieldEveryOptions;\n\n /**\n * Epoch at which to start training (useful for resuming a previous training\n * run). When this is used, `epochs` is the index of the \"final epoch\".\n * The model is not trained for a number of iterations given by `epochs`,\n * but merely until the epoch of index `epochs` is reached.\n */\n initialEpoch?: number;\n\n /**\n * Optional object mapping class indices (integers) to\n * a weight (float) to apply to the model's loss for the samples from this\n * class during training. This can be useful to tell the model to \"pay more\n * attention\" to samples from an under-represented class.\n *\n * If the model has multiple outputs, a class weight can be specified for\n * each of the outputs by setting this field an array of weight object\n * or a object that maps model output names (e.g., `model.outputNames[0]`)\n * to weight objects.\n */\n classWeight?: ClassWeight|ClassWeight[]|ClassWeightMap;\n}\n\nexport interface FitDatasetElement {\n xs: TensorOrArrayOrMap;\n ys: TensorOrArrayOrMap;\n}\n\n/**\n * Interface for configuring model evaluation based on a dataset object.\n */\nexport interface ModelEvaluateDatasetArgs {\n /**\n * Number of batches to draw from the dataset object before ending the\n * evaluation.\n */\n batches?: number;\n\n /**\n * Verbosity mode.\n */\n verbose?: ModelLoggingVerbosity;\n}\n\n// Default batch size used during tensor-based validation.\nconst DEFAULT_VALIDATION_BATCH_SIZE = 32;\n\n/**\n * Standardize the output of a dataset iterator for use by\n * LayersModel.fitDataset().\n *\n * @param model: A `tf.LayersModel` object.\n * @param iteratorOut The output of a dataset iterator. It is required to be\n * an object of the form `{xs: TensorOrArrayOrMap, ys:\n * TensorOrArrayOrMap}`, where `TensorOrArrayOrMap` is a single `tf.Tensor`,\n * a `tf.Tensor[]`, or a flat map from string names to `tf.Tensor`s.\n * @returns A flat array of `tf.Tensor` objects: the input `tf.Tensor`s\n * followed by the target `tf.Tensor`s. When `tf.Tensor`s are provided\n * as a map, the order in the resulting array is taken from the `inputNames`\n * and `outputNames` of the model.\n */\nfunction standardizeDataIteratorOutput(\n // Type `model` as `any` here to avoid circular dependency w/\n // training.ts.\n // tslint:disable-next-line:no-any\n model: any, iteratorOut: {}): {xs: tfc.Tensor[], ys: tfc.Tensor[]} {\n let xs: TensorOrArrayOrMap;\n let ys: TensorOrArrayOrMap;\n\n const iteratorOutObj = iteratorOut as FitDatasetElement;\n xs = iteratorOutObj['xs'];\n ys = iteratorOutObj['ys'];\n tfc.util.assert(\n xs != null && ys != null,\n () => 'A Dataset iterator for fitDataset() is expected to generate ' +\n 'objects of the form `{xs: xVal, ys: yVal}`, where the two ' +\n 'values may be `tf.Tensor`, an array of Tensors, or a map of ' +\n 'string to Tensor. The provided Dataset instead generates ' +\n `${iteratorOut}`);\n\n const flattenedXs: tfc.Tensor[] =\n flattenTensorOrArrayOrMap('input', model.inputNames, xs);\n const flattenedYs: tfc.Tensor[] =\n flattenTensorOrArrayOrMap('output', model.outputNames, ys);\n\n const batchSize: number = flattenedXs[0].shape[0];\n\n tfc.util.assert(\n flattenedXs.length === model.inputs.length,\n () => `LayersModel has ${model.inputs.length} inputs, but the dataset ` +\n `provides ${flattenedXs.length} inputs. (Expected input keys: ` +\n `${JSON.stringify(model.inputNames)})`);\n\n tfc.util.assert(\n flattenedYs.length === model.outputs.length,\n () =>\n `LayersModel has ${model.outputs.length} outputs, but the dataset ` +\n `provides ${flattenedYs.length} outputs. (Expected output keys: ` +\n `${JSON.stringify(model.outputNames)})`);\n\n for (let xIndex = 0; xIndex < flattenedXs.length; xIndex++) {\n tfc.util.assert(\n flattenedXs[xIndex].shape[0] === batchSize,\n () => `Batch size mismatch: input ` +\n `${model.inputNames[xIndex]} has ${\n flattenedXs[xIndex].shape[0]}; ` +\n `expected ${batchSize} based on input ${model.inputNames[0]}.`);\n }\n\n for (let yIndex = 0; yIndex < flattenedYs.length; yIndex++) {\n tfc.util.assert(\n flattenedYs[yIndex].shape[0] === batchSize,\n () => `Batch size mismatch: output ` +\n `${model.outputNames[yIndex]} has ${\n flattenedYs[yIndex].shape[0]}; ` +\n `expected ${batchSize} based on input ${model.inputNames[0]}.`);\n }\n\n return {xs: flattenedXs, ys: flattenedYs};\n}\n\nfunction flattenTensorOrArrayOrMap(\n inputOrOutput: string, names: string[], values: TensorOrArrayOrMap) {\n if (values instanceof tfc.Tensor) {\n return [values];\n } else if (Array.isArray(values)) {\n tfc.util.assert(\n values.length === names.length,\n () => `Received an array of ${values.length} Tensors, but expected ${\n names.length} to match the ${inputOrOutput} keys ${names}.`);\n return values;\n } else {\n const result: tfc.Tensor[] = [];\n // Check that all the required keys are available.\n for (const name of names) {\n if (values[name] == null) {\n throw new ValueError(\n `The feature data generated by the dataset lacks the required ` +\n `${inputOrOutput} key '${name}'.`);\n }\n result.push(values[name]);\n }\n return result;\n }\n}\n\nfunction standardizeTensorValidationData<T>(\n data:\n [\n tfc.Tensor|tfc.Tensor[], tfc.Tensor|tfc.Tensor[]\n ]|[tfc.Tensor | tfc.Tensor[], tfc.Tensor | tfc.Tensor[],\n tfc.Tensor | tfc.Tensor[]]):\n {xs: tfc.Tensor|tfc.Tensor[], ys: tfc.Tensor|tfc.Tensor[]} {\n if (data.length === 3) {\n throw new NotImplementedError(\n 'Validation with sample weights is not implemented yet.');\n }\n return {xs: data[0], ys: data[1]};\n}\n\nexport async function fitDataset<T>(\n // Type `model` as `any` here to avoid circular dependency w/\n // training.ts.\n // tslint:disable-next-line:no-any\n model: any, dataset: Dataset<T>,\n args: ModelFitDatasetArgs<T>): Promise<History> {\n const hasBatchesPerEpoch = args.batchesPerEpoch != null;\n tfc.util.assert(\n model.optimizer != null,\n () => 'You must compile a model before training/testing. Use ' +\n 'LayersModel.compile(modelCompileConfig).');\n\n tfc.util.assert(\n args != null,\n () => `For fitDataset(), the 2nd argument (config) is required, ` +\n `but it is not provided in this call.`);\n tfc.util.assert(\n args.epochs != null && args.epochs > 0 && Number.isInteger(args.epochs),\n () => `For fitDataset(), config.epochs is expected to be a positive ` +\n `integer, but got ${args.epochs}`);\n tfc.util.assert(\n !hasBatchesPerEpoch ||\n (args.batchesPerEpoch > 0 && Number.isInteger(args.batchesPerEpoch)),\n () => `For fitDataset(), config.batchesPerEpoch is expected to be a ` +\n `positive integer if specified, but got ${args.batchesPerEpoch}`);\n tfc.util.assert(\n // tslint:disable-next-line:no-any\n (args as any)['validationSplit'] == null,\n () => '`validationSplit` is not supported by `fitDataset()`. ' +\n 'Use validationData instead.');\n\n if (model.isTraining) {\n throw new Error(\n 'Cannot start training because another fit() call is ongoing.');\n }\n model.isTraining = true;\n\n try {\n const doValidation = args.validationData != null;\n let valXs: tfc.Tensor|tfc.Tensor[];\n let valYs: tfc.Tensor|tfc.Tensor[];\n if (doValidation) {\n if (isDatasetObject(args.validationData)) {\n tfc.util.assert(\n args.validationBatches == null ||\n (args.validationBatches > 0 &&\n Number.isInteger(args.validationBatches)),\n () => `For fitDataset() with dataset-based validation, ` +\n `config.validationBatches is expected not to be provided, ` +\n `or to be a positive integer, ` +\n `but got ${args.validationBatches}`);\n } else {\n const validationData = standardizeTensorValidationData(\n args.validationData as\n [tfc.Tensor | tfc.Tensor[], tfc.Tensor | tfc.Tensor[]] |\n [\n tfc.Tensor | tfc.Tensor[], tfc.Tensor | tfc.Tensor[],\n tfc.Tensor | tfc.Tensor[]\n ]);\n valXs = validationData.xs;\n valYs = validationData.ys;\n }\n }\n\n const trainFunction = model.makeTrainFunction();\n const outLabels = model.getDedupedMetricsNames() as string[];\n\n let callbackMetrics: string[];\n if (doValidation) {\n callbackMetrics =\n outLabels.slice().concat(outLabels.map(n => 'val_' + n));\n } else {\n callbackMetrics = outLabels.slice();\n }\n\n const callbacks = standardizeCallbacks(args.callbacks, args.yieldEvery);\n const verbose = args.verbose == null ? 1 : args.verbose;\n const {callbackList, history} = configureCallbacks(\n callbacks, verbose, args.epochs, null, null,\n getStepsPerEpoch(dataset, args),\n null, // Batch size determined by the dataset itself.\n doValidation, callbackMetrics);\n callbackList.setModel(model);\n model.history = history;\n\n await callbackList.onTrainBegin();\n model.stopTraining_ = false;\n let epoch = args.initialEpoch == null ? 0 : args.initialEpoch;\n\n let dataIterator = await dataset.iterator();\n while (epoch < args.epochs) {\n const epochLogs: UnresolvedLogs = {};\n await callbackList.onEpochBegin(epoch);\n let stepsDone = 0;\n let batchIndex = 0;\n if (!hasBatchesPerEpoch) {\n dataIterator = await dataset.iterator();\n }\n while (hasBatchesPerEpoch ? stepsDone < args.batchesPerEpoch : true) {\n const iteratorOut = await dataIterator.next();\n\n // If `batchesPerEpoch` is specified, the dataset should not be\n // exhausted until all epoches are done.\n if (hasBatchesPerEpoch && iteratorOut.done) {\n console.warn(\n 'You provided `batchesPerEpoch` as ' +\n `${args.batchesPerEpoch}, ` +\n 'but your dataset iterator ran out of data after ' +\n `${stepsDone} batches; ` +\n 'interrupting training. Make sure that your ' +\n 'dataset can generate at least `batchesPerEpoch * epochs` ' +\n 'batches (in this case, ' +\n `${args.batchesPerEpoch * args.epochs} batches). ` +\n 'You may need to use the repeat() function when building ' +\n 'your dataset.');\n break;\n }\n\n if (iteratorOut.value != null) {\n const {xs, ys} =\n standardizeDataIteratorOutput(model, iteratorOut.value);\n const batchLogs: UnresolvedLogs = {};\n batchLogs['batch'] = batchIndex;\n batchLogs['size'] = xs[0].shape[0];\n\n await callbackList.onBatchBegin(batchIndex, batchLogs);\n\n const sampleWeights: tfc.Tensor[] = [];\n if (args.classWeight != null) {\n const standardClassWeights =\n standardizeClassWeights(args.classWeight, model.outputNames);\n for (let i = 0; i < standardClassWeights.length; ++i) {\n sampleWeights.push(await standardizeWeights(\n ys[i], null, standardClassWeights[i]));\n }\n }\n\n // Train on batch.\n const ins = xs.concat(ys).concat(sampleWeights);\n const outs = trainFunction(ins);\n tfc.dispose(ins);\n for (let i = 0; i < outLabels.length; ++i) {\n const label = outLabels[i];\n const out = outs[i];\n batchLogs[label] = out;\n tfc.keep(out);\n }\n\n await callbackList.onBatchEnd(batchIndex, batchLogs);\n disposeTensorsInLogs(batchLogs);\n\n batchIndex++;\n stepsDone++;\n }\n\n if (hasBatchesPerEpoch ? stepsDone >= args.batchesPerEpoch :\n iteratorOut.done) {\n // Epoch finished. Perform validation.\n if (doValidation) {\n let valOuts: tfc.Scalar[];\n if (isDatasetObject(args.validationData)) {\n valOuts = toList(await model.evaluateDataset(\n args.validationData, {batches: args.validationBatches}));\n } else {\n valOuts = toList(model.evaluate(valXs, valYs, {\n batchSize: args.validationBatchSize == null ?\n DEFAULT_VALIDATION_BATCH_SIZE :\n args.validationBatchSize,\n verbose: 0\n }));\n }\n for (let i = 0; i < model.metricsNames.length; ++i) {\n epochLogs[`val_${model.metricsNames[i]}`] = valOuts[i];\n }\n }\n // Call `break` to exit one epoch lopp after validation is done. If\n // config.batchesPerEpoch is specified, an epoch while loop will\n // stop when `stepsDone >= config.batchesPerEpoch`. When\n // config.batchesPerEpoch is not provided, the following `break` is\n // required to exit the while lopp after dataset is exhausted.\n break;\n }\n\n if (model.stopTraining_) {\n break;\n }\n }\n await callbackList.onEpochEnd(epoch, epochLogs);\n epoch++;\n if (model.stopTraining_) {\n break;\n }\n }\n await callbackList.onTrainEnd();\n await model.history.syncData();\n return model.history;\n } finally {\n model.isTraining = false;\n }\n}\n\n/** Helper function that determines number of steps (batches) per epoch. */\nfunction getStepsPerEpoch<T>(\n dataset: Dataset<T>, args: ModelFitDatasetArgs<T>): number {\n // Attempt to determine # of batches in an epoch.\n let stepsPerEpoch: number = null;\n if (args.batchesPerEpoch != null) {\n stepsPerEpoch = args.batchesPerEpoch;\n } else if (Number.isFinite(dataset.size)) {\n stepsPerEpoch = dataset.size;\n }\n return stepsPerEpoch;\n}\n\n// Check if provided object is a Dataset object by checking its .iterator\n// element.\nfunction isDatasetObject<T>(\n dataset:\n [\n TensorOrArrayOrMap, TensorOrArrayOrMap\n ]|[TensorOrArrayOrMap, TensorOrArrayOrMap, TensorOrArrayOrMap]|\n Dataset<T>): boolean {\n return (typeof (dataset as Dataset<T>).iterator === 'function');\n}\n\n// Check if provided object is a LazyIterator object by checking it's .next\n// element.\nfunction isLazyIteratorObject<T>(iterator: Dataset<T>|\n LazyIterator<T>): boolean {\n return (typeof (iterator as LazyIterator<T>).next === 'function');\n}\n\nexport async function evaluateDataset<T>(\n // Type `model` as `any` here to avoid circular dependency w/\n // training.ts.\n // tslint:disable-next-line:no-any\n model: any, dataset: Dataset<T>|LazyIterator<T>,\n args: ModelEvaluateDatasetArgs): Promise<tfc.Scalar|tfc.Scalar[]> {\n args = args || {};\n const hasBatches = args.batches != null;\n const f = model.testFunction;\n let outs: tfc.Scalar[] = [];\n if (args.verbose > 0) {\n throw new NotImplementedError('Verbose mode is not implemented yet.');\n }\n\n tfc.util.assert(\n !hasBatches || (args.batches > 0 && Number.isInteger(args.batches)),\n () => 'Test loop expects `batches` to be a positive integer, but ' +\n `received ${JSON.stringify(args.batches)}`);\n const dataIterator = isLazyIteratorObject(dataset) ?\n dataset as LazyIterator<T>:\n await (dataset as Dataset<T>).iterator();\n // Keeps track of number of examples used in this evaluation.\n let numExamples = 0;\n let batch = 0;\n\n while (hasBatches ? batch < args.batches : true) {\n const iteratorOut = await dataIterator.next();\n outs = tfc.tidy(() => {\n if (iteratorOut.value) {\n // TODO(cais): Once real dataset is available, use\n // `map(x => standardizeDataIteratorOutput(model, x).map(f)`.\n const {xs, ys} =\n standardizeDataIteratorOutput(model, iteratorOut.value);\n const xsAndYs = xs.concat(ys);\n const batchOuts = tfc.tidy(() => f(xsAndYs));\n tfc.dispose(xsAndYs);\n\n if (batch === 0) {\n for (let i = 0; i < batchOuts.length; ++i) {\n outs.push(scalar(0));\n }\n }\n\n const batchSize = xsAndYs[0].shape[0];\n for (let i = 0; i < batchOuts.length; ++i) {\n const batchOut = batchOuts[i];\n const oldScalar = outs[i];\n outs[i] =\n tfc.tidy(() => tfc.add(outs[i], tfc.mul(batchSize, batchOut)));\n if (batch > 0) {\n tfc.dispose(oldScalar);\n }\n }\n tfc.dispose(batchOuts);\n numExamples += batchSize;\n\n ++batch;\n }\n return outs;\n });\n\n if (iteratorOut.done) {\n if (hasBatches) {\n console.warn(\n 'Your dataset iterator ran out of data during evaluateDataset(). ' +\n 'Interrupting evalution. Make sure that your ' +\n 'dataset can generate at least `batches` ' +\n `batches (in this case, ${args.batches} batches). ` +\n 'You may need to use the repeat() function when building ' +\n 'your dataset.');\n }\n break;\n }\n }\n\n for (let i = 0; i < outs.length; ++i) {\n const oldScalar = outs[i];\n outs[i] = tfc.div(outs[i], numExamples);\n tfc.dispose(oldScalar);\n }\n\n return singletonOrArray(outs);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Interfaces and methods for training models using tf.Tensor objects.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {Scalar, Tensor, Tensor1D, tensor1d, util} from '@tensorflow/tfjs-core';\n\nimport {expandDims, gather, sliceAlongFirstAxis} from '../backend/tfjs_backend';\nimport {BaseCallback, configureCallbacks, CustomCallbackArgs, History, ModelLoggingVerbosity, standardizeCallbacks, YieldEveryOptions} from '../base_callbacks';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {disposeTensorsInLogs, UnresolvedLogs} from '../logs';\nimport {range} from '../utils/math_utils';\nimport {ClassWeight, ClassWeightMap} from './training_utils';\n\n/**\n * Interface configuration model training based on data as `tf.Tensor`s.\n */\nexport interface ModelFitArgs {\n /**\n * Number of samples per gradient update. If unspecified, it\n * will default to 32.\n */\n batchSize?: number;\n\n /**\n * Integer number of times to iterate over the training data arrays.\n */\n epochs?: number;\n\n /**\n * Verbosity level.\n *\n * Expected to be 0, 1, or 2. Default: 1.\n *\n * 0 - No printed message during fit() call.\n * 1 - In Node.js (tfjs-node), prints the progress bar, together with\n * real-time updates of loss and metric values and training speed.\n * In the browser: no action. This is the default.\n * 2 - Not implemented yet.\n */\n verbose?: ModelLoggingVerbosity;\n\n /**\n * List of callbacks to be called during training.\n * Can have one or more of the following callbacks:\n * - `onTrainBegin(logs)`: called when training starts.\n * - `onTrainEnd(logs)`: called when training ends.\n * - `onEpochBegin(epoch, logs)`: called at the start of every epoch.\n * - `onEpochEnd(epoch, logs)`: called at the end of every epoch.\n * - `onBatchBegin(batch, logs)`: called at the start of every batch.\n * - `onBatchEnd(batch, logs)`: called at the end of every batch.\n * - `onYield(epoch, batch, logs)`: called every `yieldEvery` milliseconds\n * with the current epoch, batch and logs. The logs are the same\n * as in `onBatchEnd()`. Note that `onYield` can skip batches or\n * epochs. See also docs for `yieldEvery` below.\n */\n callbacks?: BaseCallback[]|CustomCallbackArgs|CustomCallbackArgs[];\n\n /**\n * Float between 0 and 1: fraction of the training data\n * to be used as validation data. The model will set apart this fraction of\n * the training data, will not train on it, and will evaluate the loss and\n * any model metrics on this data at the end of each epoch.\n * The validation data is selected from the last samples in the `x` and `y`\n * data provided, before shuffling.\n */\n validationSplit?: number;\n\n /**\n * Data on which to evaluate the loss and any model\n * metrics at the end of each epoch. The model will not be trained on this\n * data. This could be a tuple [xVal, yVal] or a tuple [xVal, yVal,\n * valSampleWeights]. The model will not be trained on this data.\n * `validationData` will override `validationSplit`.\n */\n validationData?: [\n Tensor|Tensor[], Tensor|Tensor[]\n ]|[Tensor | Tensor[], Tensor|Tensor[], Tensor|Tensor[]];\n\n /**\n * Whether to shuffle the training data before each epoch. Has\n * no effect when `stepsPerEpoch` is not `null`.\n */\n shuffle?: boolean;\n\n /**\n * Optional object mapping class indices (integers) to\n * a weight (float) to apply to the model's loss for the samples from this\n * class during training. This can be useful to tell the model to \"pay more\n * attention\" to samples from an under-represented class.\n *\n * If the model has multiple outputs, a class weight can be specified for\n * each of the outputs by setting this field an array of weight object\n * or a object that maps model output names (e.g., `model.outputNames[0]`)\n * to weight objects.\n */\n classWeight?: ClassWeight|ClassWeight[]|ClassWeightMap;\n\n /**\n * Optional array of the same length as x, containing\n * weights to apply to the model's loss for each sample. In the case of\n * temporal data, you can pass a 2D array with shape (samples,\n * sequenceLength), to apply a different weight to every timestep of every\n * sample. In this case you should make sure to specify\n * sampleWeightMode=\"temporal\" in compile().\n */\n sampleWeight?: Tensor;\n\n /**\n * Epoch at which to start training (useful for resuming a previous training\n * run). When this is used, `epochs` is the index of the \"final epoch\".\n * The model is not trained for a number of iterations given by `epochs`,\n * but merely until the epoch of index `epochs` is reached.\n */\n initialEpoch?: number;\n\n /**\n * Total number of steps (batches of samples) before\n * declaring one epoch finished and starting the next epoch. When training\n * with Input Tensors such as TensorFlow data tensors, the default `null` is\n * equal to the number of unique samples in your dataset divided by the\n * batch size, or 1 if that cannot be determined.\n */\n stepsPerEpoch?: number;\n\n /**\n * Only relevant if `stepsPerEpoch` is specified. Total number of steps\n * (batches of samples) to validate before stopping.\n */\n validationSteps?: number;\n\n /**\n * Configures the frequency of yielding the main thread to other tasks.\n *\n * In the browser environment, yielding the main thread can improve the\n * responsiveness of the page during training. In the Node.js environment,\n * it can ensure tasks queued in the event loop can be handled in a timely\n * manner.\n *\n * The value can be one of the following:\n * - `'auto'`: The yielding happens at a certain frame rate (currently set\n * at 125ms). This is the default.\n * - `'batch'`: yield every batch.\n * - `'epoch'`: yield every epoch.\n * - any `number`: yield every `number` milliseconds.\n * - `'never'`: never yield. (yielding can still happen through `await\n * nextFrame()` calls in custom callbacks.)\n */\n yieldEvery?: YieldEveryOptions;\n}\n\nexport function checkBatchSize(batchSize: number) {\n tfc.util.assert(\n batchSize > 0 && Number.isInteger(batchSize),\n () => `batchSize is required to be a positive integer, but got ${\n batchSize}`);\n}\n\n/**\n * Slice a Tensor or an Array of Tensors, by start and stop indices.\n *\n * Porting Note: The `_slice_arrays` function in PyKeras is covered by this\n * function and `sliceArraysByIndices()` together.\n *\n * @param arrays: the input.\n * @param start: the starting index (inclusive).\n * @param stop: the stopping index (exclusive).\n * @returns The result of the slicing. If `arrays` is an `Array` of\n * `tf.Tensor`s, the slicing will be applied to all elements of the `Array`\n * in the same way.\n */\nexport function sliceArrays(\n arrays: Tensor|Tensor[], start: number, stop: number): Tensor|Tensor[] {\n if (arrays == null) {\n return [null];\n } else if (Array.isArray(arrays)) {\n return arrays.map(array => sliceAlongFirstAxis(array, start, stop - start));\n } else { // Tensor.\n return sliceAlongFirstAxis(arrays, start, stop - start);\n }\n}\n\n/**\n * Slice a Tensor or an Array of Tensors, by random-order indices.\n *\n * Porting Note: The `_slice_arrays` function in PyKeras is covered by this\n * function and `sliceArrays()` together.\n *\n * @param arrays The input `tf.Tensor` or `Array` of `tf.Tensor`s to slice.\n * If an `Array` of `tf.Tensor`s, all `tf.Tensor`s will be sliced in the\n * same fashion.\n * @param indices The indices to use for slicing along the first (batch)\n * dimension.\n * @returns Result(s) of the slicing.\n */\nexport function sliceArraysByIndices(\n arrays: Tensor|Tensor[], indices: Tensor1D): Tensor|Tensor[] {\n return tfc.tidy(() => {\n if (arrays == null) {\n return null;\n } else if (Array.isArray(arrays)) {\n return arrays.map(\n array => (sliceArraysByIndices(array, indices) as Tensor));\n } else {\n // TODO(cais): indices should be a pre-constructed Tensor1D to avoid\n // tensor1d() calls.\n return gather(\n arrays,\n indices.dtype === 'int32' ? indices : tfc.cast(indices, 'int32'));\n }\n });\n}\n\n/**\n * Returns a list of batch indices (tuples of indices).\n * @param size: Integer, total size of the data to slice into batches.\n * @param batchSize: Integer, batch size.\n * @returns An Array of [batchStart, batchEnd] tuples. batchStart is\n * inclusive; batchEnd is exclusive. I.e., each batch consists of indices x\n * that satisfy batchStart <= x < batchEnd.\n */\nexport function makeBatches(\n size: number, batchSize: number): Array<[number, number]> {\n const output: Array<[number, number]> = [];\n let batchStart = 0;\n let batchEnd: number = null;\n while (batchStart < size) {\n batchEnd = batchStart + batchSize;\n if (batchEnd >= size) {\n batchEnd = size;\n }\n output.push([batchStart, batchEnd]);\n batchStart = batchEnd;\n }\n return output;\n}\n\n/**\n * Abstract fit function for `f(ins)`.\n * @param f A Function returning a list of tensors. For training, this\n * function is expected to perform the updates to the variables.\n * @param ins List of tensors to be fed to `f`.\n * @param outLabels List of strings, display names of the outputs of `f`.\n * @param batchSize Integer batch size or `== null` if unknown. Default : 32.\n * @param epochs Number of times to iterate over the data. Default : 1.\n * @param verbose Verbosity mode: 0, 1, or 2. Default: 1.\n * @param callbacks List of callbacks to be called during training.\n * @param valF Function to call for validation.\n * @param valIns List of tensors to be fed to `valF`.\n * @param shuffle Whether to shuffle the data at the beginning of every\n * epoch. Default : true.\n * @param callbackMetrics List of strings, the display names of the metrics\n * passed to the callbacks. They should be the concatenation of the\n * display names of the outputs of `f` and the list of display names\n * of the outputs of `valF`.\n * @param initialEpoch Epoch at which to start training (useful for\n * resuming a previous training run). Default : 0.\n * @param stepsPerEpoch Total number of steps (batches on samples) before\n * declaring one epoch finished and starting the next epoch. Ignored with\n * the default value of `undefined` or `null`.\n * @param validationSteps Number of steps to run validation for (only if\n * doing validation from data tensors). Not applicable for tfjs-layers.\n * @returns A `History` object.\n */\nasync function fitLoop(\n // Type `model` as `any` here to avoid circular dependency w/ training.ts.\n // tslint:disable-next-line:no-any\n model: any, f: (data: Tensor[]) => Scalar[], ins: Tensor[],\n outLabels?: string[], batchSize?: number, epochs?: number, verbose?: number,\n callbacks?: BaseCallback[], valF?: (data: Tensor[]) => Scalar[],\n valIns?: Tensor[], shuffle?: boolean|string, callbackMetrics?: string[],\n initialEpoch?: number, stepsPerEpoch?: number,\n validationSteps?: number): Promise<History> {\n if (batchSize == null) {\n batchSize = 32;\n }\n if (epochs == null) {\n epochs = 1;\n }\n if (shuffle == null) {\n shuffle = true;\n }\n if (initialEpoch == null) {\n initialEpoch = 0;\n }\n\n // TODO(cais): Change const to let below when implementing validation.\n let doValidation = false;\n if (valF != null && valIns != null) {\n doValidation = true;\n // TODO(cais): verbose message.\n }\n if (validationSteps != null) {\n doValidation = true;\n if (stepsPerEpoch == null) {\n throw new ValueError(\n 'Can only use `validationSteps` when doing step-wise training, ' +\n 'i.e., `stepsPerEpoch` must be set.');\n }\n }\n\n const numTrainSamples =\n model.checkNumSamples(ins, batchSize, stepsPerEpoch, 'steps_per_epoch');\n let indexArray: number[];\n if (numTrainSamples != null) {\n indexArray = range(0, numTrainSamples);\n }\n\n if (verbose == null) {\n verbose = 1;\n }\n\n const {callbackList, history} = configureCallbacks(\n callbacks, verbose, epochs, initialEpoch, numTrainSamples, stepsPerEpoch,\n batchSize, doValidation, callbackMetrics);\n callbackList.setModel(model);\n model.history = history;\n await callbackList.onTrainBegin();\n model.stopTraining_ = false;\n // TODO(cais): Take care of callbacks.validation_data as in PyKeras.\n // TODO(cais): Pre-convert feeds for performance as in PyKeras.\n\n for (let epoch = initialEpoch; epoch < epochs; ++epoch) {\n await callbackList.onEpochBegin(epoch);\n const epochLogs: UnresolvedLogs = {};\n if (stepsPerEpoch != null) {\n throw new NotImplementedError(\n 'stepsPerEpoch mode is not implemented yet.');\n } else {\n if (shuffle === 'batch') {\n throw new NotImplementedError('batch shuffling is not implemneted yet');\n } else if (shuffle) {\n util.shuffle(indexArray);\n }\n // Convert the potentially shuffled indices to Tensor1D, to avoid the\n // cost of repeated creation of Array1Ds later on.\n const epochIndexArray1D = tensor1d(indexArray);\n\n const batches = makeBatches(numTrainSamples, batchSize);\n for (let batchIndex = 0; batchIndex < batches.length; ++batchIndex) {\n const batchLogs: UnresolvedLogs = {};\n await callbackList.onBatchBegin(batchIndex, batchLogs);\n\n tfc.tidy(() => {\n const batchStart = batches[batchIndex][0];\n const batchEnd = batches[batchIndex][1];\n const batchIds = sliceAlongFirstAxis(\n epochIndexArray1D, batchStart,\n batchEnd - batchStart) as Tensor1D;\n batchLogs['batch'] = batchIndex;\n batchLogs['size'] = batchEnd - batchStart;\n\n // TODO(cais): In ins, train flag can be a number, instead of an\n // Tensor? Do we need to handle this in tfjs-layers?\n const insBatch = sliceArraysByIndices(ins, batchIds) as Tensor[];\n const outs = f(insBatch);\n for (let i = 0; i < outLabels.length; ++i) {\n const label = outLabels[i];\n const out = outs[i];\n batchLogs[label] = out;\n tfc.keep(out);\n // TODO(cais): Use scope() to avoid ownership.\n }\n\n if (batchIndex === batches.length - 1) { // Last batch.\n if (doValidation) {\n const valOuts = model.testLoop(valF, valIns, batchSize);\n // Porting Notes: In tfjs-layers, valOuts is always an Array.\n for (let i = 0; i < outLabels.length; ++i) {\n const label = outLabels[i];\n const out = valOuts[i];\n tfc.keep(out);\n // TODO(cais): Use scope() to avoid ownership.\n epochLogs['val_' + label] = out;\n }\n }\n }\n });\n\n await callbackList.onBatchEnd(batchIndex, batchLogs);\n disposeTensorsInLogs(batchLogs);\n\n if (model.stopTraining_) {\n break;\n }\n // TODO(cais): return outs as list of Tensor.\n }\n\n epochIndexArray1D.dispose();\n }\n // TODO(cais): Run validation at the end of the epoch.\n await callbackList.onEpochEnd(epoch, epochLogs);\n if (model.stopTraining_) {\n break;\n }\n }\n await callbackList.onTrainEnd();\n\n await model.history.syncData();\n return model.history;\n}\n\nexport async function fitTensors(\n // Type `model` as `any` here to avoid circular dependency w/ training.ts.\n // tslint:disable-next-line:no-any\n model: any, x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|{[inputName: string]: Tensor},\n args: ModelFitArgs = {}): Promise<History> {\n if (model.isTraining) {\n throw new Error(\n 'Cannot start training because another fit() call is ongoing.');\n }\n model.isTraining = true;\n let inputs: Tensor[];\n let targets: Tensor[];\n let inputValX: Tensor|Tensor[];\n let inputValY: Tensor|Tensor[];\n let valX: Tensor|Tensor[];\n let valY: Tensor|Tensor[];\n let sampleWeights: Tensor[];\n try {\n const batchSize = args.batchSize == null ? 32 : args.batchSize;\n checkBatchSize(batchSize);\n\n // Validate user data.\n // TODO(cais): Support sampleWeight.\n const checkBatchAxis = false;\n const standardizedOuts =\n await model.standardizeUserData(\n x, y, args.sampleWeight, args.classWeight, checkBatchAxis,\n batchSize) as [Tensor[], Tensor[], Tensor[]];\n inputs = standardizedOuts[0];\n targets = standardizedOuts[1];\n sampleWeights = standardizedOuts[2];\n\n // Prepare validation data.\n let doValidation = false;\n let valIns: Tensor[];\n if (args.validationData != null && args.validationData.length > 0) {\n doValidation = true;\n if (args.validationData.length === 2) {\n // config.validationData consists of valX and valY.\n inputValX = args.validationData[0];\n inputValY = args.validationData[1];\n } else if (args.validationData.length === 3) {\n throw new NotImplementedError(\n 'validationData including sample weights is not supported yet.');\n } else {\n throw new ValueError(\n `When passing validation data, it must contain 2 (valX, valY) ` +\n `or 3 (valX, valY, valSampleWeight) items; ` +\n `${args.validationData} is invalid.`);\n }\n\n const checkBatchAxis = true;\n const valStandardized =\n await model.standardizeUserData(\n inputValX, inputValY, null, /** Unused sample weights. */\n null, /** Unused class weights. */\n checkBatchAxis, batchSize) as [Tensor[], Tensor[], Tensor[]];\n valX = valStandardized[0];\n valY = valStandardized[1];\n valIns = valX.concat(valY);\n // TODO(cais): Add useLearningPhase data properly.\n } else if (\n args.validationSplit != null && args.validationSplit > 0 &&\n args.validationSplit < 1) {\n doValidation = true;\n // Porting Note: In tfjs-layers, inputs[0] is always a Tensor.\n const splitAt =\n Math.floor(inputs[0].shape[0] * (1 - args.validationSplit));\n const originalBatchSize = inputs[0].shape[0];\n valX = sliceArrays(inputs, splitAt, originalBatchSize) as Tensor[];\n inputs = sliceArrays(inputs, 0, splitAt) as Tensor[];\n valY = sliceArrays(targets, splitAt, originalBatchSize) as Tensor[];\n targets = sliceArrays(targets, 0, splitAt) as Tensor[];\n // TODO(cais): Once sampleWeights becomes available, slice it to get\n // valSampleWeights.\n valIns = valX.concat(valY);\n\n // TODO(cais): Add useLearningPhase data properly.\n } else if (args.validationSteps != null) {\n doValidation = true;\n // TODO(cais): Add useLearningPhase.\n }\n\n const ins = inputs.concat(targets).concat(sampleWeights);\n\n model.checkTrainableWeightsConsistency();\n\n // TODO(cais): Handle use_learning_phase and learning_phase?\n\n // Porting Note: Here we see a key deviation of tfjs-layers from\n // Keras.\n // Due to the imperative nature of tfjs-layers' backend (tfjs-core),\n // we do not construct symbolic computation graphs to embody the\n // training process. Instead, we define a function that performs the\n // training action. In PyKeras, the data (inputs and targets) are fed\n // through graph placeholders. In tfjs-layers, the data are fed as\n // function arguments. Since the function are defined below in the\n // scope, we don't have equivalents of PyKeras's\n // `_make_train_funciton`.\n const trainFunction = model.makeTrainFunction();\n const outLabels = model.getDedupedMetricsNames() as string[];\n\n let valFunction: (data: Tensor[]) => Scalar[];\n let callbackMetrics: string[];\n if (doValidation) {\n model.makeTestFunction();\n valFunction = model.testFunction;\n callbackMetrics =\n outLabels.slice().concat(outLabels.map(n => 'val_' + n));\n } else {\n valFunction = null;\n valIns = [];\n callbackMetrics = outLabels.slice();\n }\n\n const callbacks = standardizeCallbacks(args.callbacks, args.yieldEvery);\n const out = await fitLoop(\n model, trainFunction, ins, outLabels, batchSize, args.epochs,\n args.verbose, callbacks, valFunction, valIns, args.shuffle,\n callbackMetrics, args.initialEpoch, null, null);\n return out;\n } finally {\n model.isTraining = false;\n // Memory clean up.\n disposeNewTensors(inputs, x);\n disposeNewTensors(targets, y);\n disposeNewTensors(valX as Tensor[], inputValX);\n disposeNewTensors(valY as Tensor[], inputValY);\n if (sampleWeights != null) {\n tfc.dispose(sampleWeights);\n }\n }\n // TODO(cais): Add value to outLabels.\n}\n\n/**\n * Ensure tensors all have a rank of at least 2.\n *\n * If a tensor has a rank of 1, it is dimension-expanded to rank 2.\n * If any tensor has a rank of 0 (i.e., is a scalar), an error will be thrown.\n */\nexport function ensureTensorsRank2OrHigher(tensors: Tensor|Tensor[]): Tensor[] {\n const outs: Tensor[] = [];\n if (tensors instanceof Tensor) {\n tensors = [tensors];\n }\n\n // Make Tensors at least 2D.\n for (let i = 0; i < tensors.length; ++i) {\n const tensor = tensors[i];\n if (tensor.rank === 1) {\n outs.push(expandDims(tensor, 1));\n } else if (tensor.rank === 0) {\n throw new Error(\n 'Expected tensor to be at least 1D, but received a 0D tensor ' +\n '(scalar).');\n } else {\n outs.push(tensor);\n }\n }\n return outs;\n}\n\n/**\n * Compare a set of tensors with a reference (old) set, discard the ones\n * in the new set that are not present in the reference set.\n *\n * This method is used for memory clenaup during calls such as\n * LayersModel.fit().\n *\n * @param tensors New set which may contain Tensors not present in\n * `refTensors`.\n * @param refTensors Reference Tensor set.\n */\n// TODO(cais, kangyizhang): Deduplicate with tfjs-data.\nexport function disposeNewTensors(\n tensors: Tensor|Tensor[]|{[inputName: string]: Tensor},\n refTensors: Tensor|Tensor[]|{[inputName: string]: Tensor}): void {\n if (tensors == null) {\n return;\n }\n const oldTensorIds: number[] = [];\n if (refTensors instanceof Tensor) {\n oldTensorIds.push(refTensors.id);\n } else if (Array.isArray(refTensors)) {\n refTensors.forEach(t => oldTensorIds.push(t.id));\n } else if (refTensors != null) {\n // `oldTensors` is a map from string name to Tensor.\n for (const name in refTensors) {\n const oldTensor = refTensors[name];\n oldTensorIds.push(oldTensor.id);\n }\n }\n\n const tensorsToDispose: Tensor[] = [];\n if (tensors instanceof Tensor) {\n if (oldTensorIds.indexOf(tensors.id) === -1) {\n tensorsToDispose.push(tensors);\n }\n } else if (Array.isArray(tensors)) {\n tensors.forEach(t => {\n if (oldTensorIds.indexOf(t.id) === -1) {\n tensorsToDispose.push(t);\n }\n });\n } else if (tensors != null) {\n // `oldTensors` is a map from string name to Tensor.\n for (const name in tensors) {\n const tensor = tensors[name];\n if (oldTensorIds.indexOf(tensor.id) === -1) {\n tensorsToDispose.push(tensor);\n }\n }\n }\n\n tensorsToDispose.forEach(t => {\n if (!t.isDisposed) {\n t.dispose();\n }\n });\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original Source: engine/training.py */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {io, ModelPredictConfig as ModelPredictArgs, NamedTensorMap, Optimizer, Scalar, scalar, serialization, Tensor, Tensor1D, tensor1d, util} from '@tensorflow/tfjs-core';\n\nimport * as K from '../backend/tfjs_backend';\nimport {History, ModelLoggingVerbosity} from '../base_callbacks';\nimport {nameScope} from '../common';\nimport {NotImplementedError, RuntimeError, ValueError} from '../errors';\nimport {Shape} from '../keras_format/common';\nimport {LossIdentifier} from '../keras_format/loss_config';\nimport {OptimizerSerialization} from '../keras_format/optimizer_config';\nimport {MetricsIdentifier, TrainingConfig} from '../keras_format/training_config';\nimport {deserialize} from '../layers/serialization';\nimport * as losses from '../losses';\nimport * as Metrics from '../metrics';\nimport * as optimizers from '../optimizers';\nimport {LossOrMetricFn, NamedTensor} from '../types';\nimport {checkUserDefinedMetadata} from '../user_defined_metadata';\nimport {count, pyListRepeat, singletonOrArray, toCamelCase, toSnakeCase, unique} from '../utils/generic_utils';\nimport {printSummary} from '../utils/layer_utils';\nimport {range} from '../utils/math_utils';\nimport {convertPythonicToTs} from '../utils/serialization_utils';\nimport {LayerVariable} from '../variables';\nimport {version} from '../version';\n\nimport {Container, ContainerArgs} from './container';\nimport {Dataset} from './dataset_stub';\nimport {execute, FeedDict} from './executor';\nimport {DisposeResult, SymbolicTensor} from './topology';\nimport {evaluateDataset, fitDataset, ModelEvaluateDatasetArgs, ModelFitDatasetArgs} from './training_dataset';\nimport {checkBatchSize, disposeNewTensors, ensureTensorsRank2OrHigher, fitTensors, makeBatches, ModelFitArgs, sliceArrays, sliceArraysByIndices} from './training_tensors';\nimport {ClassWeight, ClassWeightMap, computeWeightedLoss, standardizeClassWeights, standardizeWeights} from './training_utils';\n\n/**\n * Helper function for polymorphic input data: 1. singleton Tensor.\n */\nexport function isDataTensor(x: Tensor|Tensor[]|{[inputName: string]: Tensor}|\n {[inputName: string]: Tensor[]}): boolean {\n return x instanceof Tensor;\n}\n\n/**\n * Helper function for polymorphic input data: 2. Array of Tensor.\n */\nexport function isDataArray(x: Tensor|Tensor[]|\n {[inputName: string]: Tensor}): boolean {\n return Array.isArray(x);\n}\n\n/**\n * Helper function for polymorphic input data: 3. \"dict\" of Tensor.\n */\nexport function isDataDict(x: Tensor|Tensor[]|\n {[inputName: string]: Tensor}): boolean {\n return !isDataTensor(x) && !isDataArray(x);\n}\n\n/**\n * Normalizes inputs and targets provided by users.\n * @param data User-provided input data (polymorphic).\n * @param names An Array of expected Tensor names.\n * @param shapes Optional Array of expected Tensor shapes.\n * @param checkBatchAxis Whether to check that the batch axis of the arrays\n * match the expected value found in `shapes`.\n * @param exceptionPrefix String prefix used for exception formatting.\n * @returns List of standardized input Tensors (one Tensor per model input).\n * @throws ValueError: in case of improperly formatted user data.\n */\nexport function standardizeInputData(\n data: Tensor|Tensor[]|{[inputName: string]: Tensor}, names: string[],\n shapes?: Shape[], checkBatchAxis = true, exceptionPrefix = ''): Tensor[] {\n if (names == null || names.length === 0) {\n // Check for the case where the model expected no data, but some data got\n // sent.\n if (data != null) {\n let gotUnexpectedData = false;\n if (isDataArray(data) && (data as Tensor[]).length > 0) {\n gotUnexpectedData = true;\n } else if (isDataDict(data)) {\n for (const key in data) {\n if (data.hasOwnProperty(key)) {\n gotUnexpectedData = true;\n break;\n }\n }\n } else {\n // `data` is a singleton Tensor in this case.\n gotUnexpectedData = true;\n }\n if (gotUnexpectedData) {\n throw new ValueError(\n `Error when checking model ${exceptionPrefix} expected no data, ` +\n `but got ${data}`);\n }\n }\n return [];\n }\n if (data == null) {\n return names.map(name => null);\n }\n\n let arrays: Tensor[];\n if (isDataDict(data)) {\n data = data as {[inputName: string]: Tensor};\n arrays = [];\n for (const name of names) {\n if (data[name] == null) {\n throw new ValueError(\n `No data provided for \"${name}\". Need data for each key in: ` +\n `${names}`);\n }\n arrays.push(data[name]);\n }\n } else if (isDataArray(data)) {\n data = data as Tensor[];\n if (data.length !== names.length) {\n throw new ValueError(\n `Error when checking model ${exceptionPrefix}: the Array of ` +\n `Tensors that you are passing to your model is not the size the ` +\n `model expected. Expected to see ${names.length} Tensor(s), but ` +\n `instead got the following list of Tensor(s): ${data}`);\n }\n arrays = data;\n } else {\n data = data as Tensor;\n if (names.length > 1) {\n throw new ValueError(\n `The model ${exceptionPrefix} expects ${names.length} Tensor(s), ` +\n `but only received one Tensor. Found: Tensor with shape ${\n data.shape}`);\n }\n arrays = [data];\n }\n\n arrays = ensureTensorsRank2OrHigher(arrays);\n\n // Check shape compatibility.\n if (shapes != null) {\n for (let i = 0; i < names.length; ++i) {\n if (shapes[i] == null) {\n continue;\n }\n const array = arrays[i];\n if (array.shape.length !== shapes[i].length) {\n throw new ValueError(\n `Error when checking ${exceptionPrefix}: expected ${names[i]} ` +\n `to have ${shapes[i].length} dimension(s). but got array with ` +\n `shape ${array.shape}`);\n }\n for (let j = 0; j < shapes[i].length; ++j) {\n if (j === 0 && !checkBatchAxis) {\n // Skip the first (batch) axis.\n continue;\n }\n const dim = array.shape[j];\n const refDim = shapes[i][j];\n if (refDim != null && refDim >= 0 && dim !== refDim) {\n throw new ValueError(\n `Error when checking ${exceptionPrefix}: expected ${names[i]} ` +\n `to have shape [${shapes[i]}], but got array with shape ` +\n `[${array.shape}].`);\n }\n }\n }\n }\n return arrays;\n}\n\n/**\n * User input validation for Tensors.\n * @param inputs `Array` of `tf.Tensor`s for inputs.\n * @param targets `Array` of `tf.Tensor`s for targets.\n * @param weights Optional `Array` of `tf.Tensor`s for sample weights.\n * @throws ValueError: in case of incorrectly formatted data.\n */\nexport function checkArrayLengths(\n inputs: Tensor[], targets: Tensor[], weights?: Tensor[]) {\n const setX = unique(inputs.map(input => input.shape[0]));\n setX.sort();\n const setY = unique(targets.map(target => target.shape[0]));\n setY.sort();\n // TODO(cais): Check `weights` as well.\n if (setX.length > 1) {\n throw new ValueError(\n `All input Tensors (x) should have the same number of samples. ` +\n `Got array shapes: ` +\n `${JSON.stringify(inputs.map(input => input.shape))}`);\n }\n if (setY.length > 1) {\n throw new ValueError(\n `All target Tensors (y) should have the same number of samples. ` +\n `Got array shapes: ` +\n `${JSON.stringify(targets.map(target => target.shape))}`);\n }\n if (setX.length > 0 && setY.length > 0 && !util.arraysEqual(setX, setY)) {\n throw new ValueError(\n `Input Tensors should have the same number of samples as target ` +\n `Tensors. Found ${setX[0]} input sample(s) and ${setY[0]} target ` +\n `sample(s).`);\n }\n}\n\n/**\n * Validation on the compatibility of targes and loss functions.\n *\n * This helps prevent users from using loss functions incorrectly.\n *\n * @param targets `Array` of `tf.Tensor`s of targets.\n * @param lossFns `Array` of loss functions.\n * @param outputShapes `Array` of shapes of model outputs.\n */\nfunction checkLossAndTargetCompatibility(\n targets: Tensor[], lossFns: LossOrMetricFn[], outputShapes: Shape[]) {\n // TODO(cais): Dedicated test coverage?\n const keyLosses = [\n losses.meanSquaredError, losses.binaryCrossentropy,\n losses.categoricalCrossentropy\n ];\n for (let i = 0; i < targets.length; ++i) {\n const y = targets[i];\n const loss = lossFns[i];\n const shape = outputShapes[i];\n if (loss == null) {\n continue;\n }\n if (loss === losses.categoricalCrossentropy) {\n if (y.shape[y.shape.length - 1] === 1) {\n throw new ValueError(\n `You are passing a target array of shape ${y.shape} while using ` +\n `a loss 'categorical_crossentropy'. 'categorical_crossentropy'` +\n `expects targets to be binary matrices (1s and 0s) of shape ` +\n `[samples, classes].`);\n // TODO(cais): Example code in error message.\n }\n }\n if (keyLosses.indexOf(loss) !== -1) {\n const slicedYShape = y.shape.slice(1);\n const slicedShape = shape.slice(1);\n for (let j = 0; j < slicedYShape.length; ++j) {\n const targetDim = slicedYShape[j];\n const outDim = slicedShape[j];\n if (outDim != null && targetDim !== outDim) {\n throw new ValueError(\n `A target Tensor with shape ${y.shape} was passed for an ` +\n `output of shape ${shape}, while using a loss function that ` +\n `expects targets to have the same shape as the output.`);\n }\n }\n }\n }\n}\n\n/**\n * Check inputs provided by the user.\n *\n * Porting Note: This corresponds to _standardize_input_data() in Python\n * Keras. Because of the strong typing in TF.js, we do not need to convert\n * the data. Specifically:\n * 1) in PyKeras, `data` can be `DataFrame` instances from pandas, for\n * example. We don't need to worry about that here because there is no\n * widely popular javascript/typesdcript equivalent of pandas (so far).\n * If one becomes available in the future, we can add support.\n * 2) in PyKeras, inputs can be Python dict. But here we are stipulating\n * that the data is either a single `tf.Tensor` or an Array of `tf.Tensor`s. We\n * may add support for `Object` data inputs in the future when the need\n * arises.\n *\n * Instead, we perform basic checks for number of parameters and shapes.\n *\n * @param data: The input data.\n * @param names: Name for the inputs, from the model.\n * @param shapes: Expected shapes for the input data, from the model.\n * @param checkBatchAxis: Whether the size along the batch axis (i.e., the\n * first dimension) will be checked for matching.\n * @param exceptionPrefix: Execption prefix message, used in generating error\n * messages.\n * @throws ValueError: on incorrect number of inputs or mismatches in shapes.\n */\nfunction checkInputData(\n data: Tensor|Tensor[], names: string[], shapes?: Shape[],\n checkBatchAxis = true, exceptionPrefix = '') {\n let arrays: Tensor[];\n if (Array.isArray(data)) {\n if (data.length !== names.length) {\n throw new ValueError(\n `Error when checking model ${exceptionPrefix}: the Array of ` +\n `Tensors that you are passing to your model is not the size the ` +\n `the model expected. Expected to see ${names.length} Tensor(s),` +\n ` but instead got ${data.length} Tensors(s).`);\n }\n arrays = data;\n } else {\n if (names.length > 1) {\n throw new ValueError(\n `The model expects ${names.length} ${exceptionPrefix} Tensors, ` +\n `but only received one Tensor. Found: array with shape ` +\n `${JSON.stringify(data.shape)}.`);\n }\n arrays = [data];\n }\n\n if (shapes != null) {\n for (let i = 0; i < names.length; ++i) {\n if (shapes[i] == null) {\n continue;\n }\n const array = arrays[i];\n if (array.shape.length !== shapes[i].length) {\n throw new ValueError(\n `Error when checking ${exceptionPrefix}: expected ${names[i]} ` +\n `to have ${shapes[i].length} dimension(s), but got array with ` +\n `shape ${JSON.stringify(array.shape)}`);\n }\n for (let j = 0; j < shapes[i].length; ++j) {\n if (j === 0 && !checkBatchAxis) {\n continue;\n }\n const dim = array.shape[j];\n const refDim = shapes[i][j];\n if (refDim != null) {\n if (refDim !== dim) {\n throw new ValueError(\n `Error when checking ${exceptionPrefix}: expected ` +\n `${names[i]} to have shape ${JSON.stringify(shapes[i])} but ` +\n `got array with shape ${JSON.stringify(array.shape)}.`);\n }\n }\n }\n }\n }\n}\n\n/**\n * Maps metric functions to model outputs.\n * @param metrics An shortcut strings name, metric function, `Array` or dict\n * (`Object`) of metric functions.\n * @param outputNames An `Array` of the names of model outputs.\n * @returns An `Array` (one entry per model output) of `Array` of metric\n * functions. For instance, if the model has 2 outputs, and for the first\n * output we want to compute `binaryAccuracy` and `binaryCrossentropy`,\n * and just `binaryAccuracy` for the second output, the `Array` would look\n * like:\n * `[[binaryAccuracy, binaryCrossentropy], [binaryAccuracy]]`\n * @throws TypeError: incompatible metrics format.\n */\nexport function collectMetrics(\n metrics: string|LossOrMetricFn|Array<string|LossOrMetricFn>|\n {[outputName: string]: string | LossOrMetricFn},\n outputNames: string[]): Array<Array<string|LossOrMetricFn>> {\n if (metrics == null || Array.isArray(metrics) && metrics.length === 0) {\n return outputNames.map(name => []);\n }\n\n let wrappedMetrics: Array<string|LossOrMetricFn>|\n {[outputName: string]: string | LossOrMetricFn};\n if (typeof metrics === 'string' || typeof metrics === 'function') {\n wrappedMetrics = [metrics];\n } else if (Array.isArray(metrics) || typeof metrics === 'object') {\n wrappedMetrics = metrics as Array<string|LossOrMetricFn>|\n {[outputName: string]: string} | {[outputName: string]: LossOrMetricFn};\n } else {\n throw new TypeError(\n 'Type of metrics argument not understood. Expected an string,' +\n `function, Array, or Object, found: ${metrics}`);\n }\n\n if (Array.isArray(wrappedMetrics)) {\n // We then apply all metrics to all outputs.\n return outputNames.map(\n name => wrappedMetrics as Array<string|LossOrMetricFn>);\n } else {\n // In this case, metrics is a dict.\n const nestedMetrics: Array<Array<string|LossOrMetricFn>> = [];\n for (const name of outputNames) {\n let outputMetrics: string|LossOrMetricFn|Array<string|LossOrMetricFn> =\n wrappedMetrics.hasOwnProperty(name) ? wrappedMetrics[name] : [];\n if (!Array.isArray(outputMetrics)) {\n outputMetrics = [outputMetrics];\n }\n nestedMetrics.push(outputMetrics);\n }\n return nestedMetrics;\n }\n}\n\nexport interface ModelEvaluateArgs {\n /**\n * Batch size (Integer). If unspecified, it will default to 32.\n */\n batchSize?: number;\n\n /**\n * Verbosity mode.\n */\n verbose?: ModelLoggingVerbosity;\n\n /**\n * Tensor of weights to weight the contribution of different samples to the\n * loss and metrics.\n */\n sampleWeight?: Tensor;\n\n /**\n * integer: total number of steps (batches of samples)\n * before declaring the evaluation round finished. Ignored with the default\n * value of `undefined`.\n */\n steps?: number;\n}\n\n/**\n * Configuration for calls to `LayersModel.compile()`.\n */\nexport interface ModelCompileArgs {\n /**\n * An instance of `tf.train.Optimizer` or a string name for an Optimizer.\n */\n optimizer: string|Optimizer;\n\n /**\n * Object function(s) or name(s) of object function(s).\n * If the model has multiple outputs, you can use a different loss\n * on each output by passing a dictionary or an Array of losses.\n * The loss value that will be minimized by the model will then be the sum\n * of all individual losses.\n */\n loss: string|string[]|{[outputName: string]: string}|LossOrMetricFn|\n LossOrMetricFn[]|{[outputName: string]: LossOrMetricFn};\n\n /**\n * List of metrics to be evaluated by the model during training and testing.\n * Typically you will use `metrics=['accuracy']`.\n * To specify different metrics for different outputs of a multi-output\n * model, you could also pass a dictionary.\n */\n metrics?: string|LossOrMetricFn|Array<string|LossOrMetricFn>|\n {[outputName: string]: string | LossOrMetricFn};\n\n // TODO(cais): Add lossWeights, sampleWeightMode, weightedMetrics, and\n // targetTensors.\n}\n\nconst LAYERS_MODEL_FORMAT_NAME = 'layers-model';\n\n/**\n * A `tf.LayersModel` is a directed, acyclic graph of `tf.Layer`s plus methods\n * for training, evaluation, prediction and saving.\n *\n * `tf.LayersModel` is the basic unit of training, inference and evaluation in\n * TensorFlow.js. To create a `tf.LayersModel`, use `tf.LayersModel`.\n *\n * See also:\n * `tf.Sequential`, `tf.loadLayersModel`.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\nexport class LayersModel extends Container implements tfc.InferenceModel {\n // The class name is 'Model' rather than 'LayersModel' for backwards\n // compatibility since this class name shows up in the serialization format.\n /** @nocollapse */\n static className = 'Model';\n protected optimizer_: Optimizer;\n // Whether the model instance owns the optimizer: `true` if and only if\n // `optimizer` is created from a string parameter during `compile()` call.\n protected isOptimizerOwned: boolean;\n\n loss: string|string[]|{[outputName: string]: string}|LossOrMetricFn|\n LossOrMetricFn[]|{[outputName: string]: LossOrMetricFn};\n lossFunctions: LossOrMetricFn[];\n\n // TODO(cais): These private variables should probably not have the string\n // 'feed' in their names, because we are not dealing with a symbolic\n // backend.\n private feedOutputShapes: Shape[];\n private feedLossFns: LossOrMetricFn[];\n private collectedTrainableWeights: LayerVariable[];\n private testFunction: (data: Tensor[]) => Scalar[];\n history: History;\n\n // A public property that can be set by Callbacks to order early stopping\n // during `fit()` calls.\n protected stopTraining_: boolean;\n protected isTraining: boolean;\n\n metrics: string|LossOrMetricFn|Array<string|LossOrMetricFn>|\n {[outputName: string]: string | LossOrMetricFn};\n metricsNames: string[];\n // Porting Note: `metrics_tensors` in PyKeras is a symbolic tensor. But given\n // the imperative nature of tfjs-core, `metricsTensors` is a\n // TypeScript function here.\n // Also note that due to the imperative nature of tfjs-core, `metricsTensor`\n // here needs an output index to keep track of which output of the\n // LayersModel a metric belongs to. This is unlike `metrics_tensors` in\n // PyKeras, which is a `list` of symbolic tensors, each of which has\n // implicit \"knowledge\" of the outputs it depends on.\n metricsTensors: Array<[LossOrMetricFn, number]>;\n\n // User defind metadata (if any).\n private userDefinedMetadata: {};\n\n constructor(args: ContainerArgs) {\n super(args);\n this.isTraining = false;\n }\n\n /**\n * Print a text summary of the model's layers.\n *\n * The summary includes\n * - Name and type of all layers that comprise the model.\n * - Output shape(s) of the layers\n * - Number of weight parameters of each layer\n * - If the model has non-sequential-like topology, the inputs each layer\n * receives\n * - The total number of trainable and non-trainable parameters of the model.\n *\n * ```js\n * const input1 = tf.input({shape: [10]});\n * const input2 = tf.input({shape: [20]});\n * const dense1 = tf.layers.dense({units: 4}).apply(input1);\n * const dense2 = tf.layers.dense({units: 8}).apply(input2);\n * const concat = tf.layers.concatenate().apply([dense1, dense2]);\n * const output =\n * tf.layers.dense({units: 3, activation: 'softmax'}).apply(concat);\n *\n * const model = tf.model({inputs: [input1, input2], outputs: output});\n * model.summary();\n * ```\n *\n * @param lineLength Custom line length, in number of characters.\n * @param positions Custom widths of each of the columns, as either\n * fractions of `lineLength` (e.g., `[0.5, 0.75, 1]`) or absolute number\n * of characters (e.g., `[30, 50, 65]`). Each number corresponds to\n * right-most (i.e., ending) position of a column.\n * @param printFn Custom print function. Can be used to replace the default\n * `console.log`. For example, you can use `x => {}` to mute the printed\n * messages in the console.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n summary(\n lineLength?: number, positions?: number[],\n printFn:\n // tslint:disable-next-line:no-any\n (message?: any, ...optionalParams: any[]) => void = console.log) {\n if (!this.built) {\n throw new ValueError(\n `This model has never been called, thus its weights have not been ` +\n `created yet. So no summary can be displayed. Build the model ` +\n `first (e.g., by calling it on some test data).`);\n }\n printSummary(this, lineLength, positions, printFn);\n }\n\n /**\n * Configures and prepares the model for training and evaluation. Compiling\n * outfits the model with an optimizer, loss, and/or metrics. Calling `fit`\n * or `evaluate` on an un-compiled model will throw an error.\n *\n * @param args a `ModelCompileArgs` specifying the loss, optimizer, and\n * metrics to be used for fitting and evaluating this model.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n compile(args: ModelCompileArgs): void {\n if (args.loss == null) {\n args.loss = [];\n }\n this.loss = args.loss;\n\n if (typeof args.optimizer === 'string') {\n this.optimizer_ = optimizers.getOptimizer(args.optimizer);\n this.isOptimizerOwned = true;\n } else {\n if (!(args.optimizer instanceof Optimizer)) {\n throw new ValueError(\n `User-defined optimizer must be an instance of tf.Optimizer.`);\n }\n this.optimizer_ = args.optimizer;\n this.isOptimizerOwned = false;\n }\n\n // TODO(cais): Add lossWeights.\n // TODO(cais): Add sampleWeightMode.\n\n // Prepare loss functions.\n let lossFunctions: LossOrMetricFn[] = [];\n if (!Array.isArray(args.loss) && typeof args.loss !== 'string' &&\n typeof args.loss !== 'function') {\n args.loss = args.loss as {[outputName: string]: string};\n for (const name in args.loss) {\n if (this.outputNames.indexOf(name) === -1) {\n throw new ValueError(\n `Unknown entry in loss dictionary: \"${name}\". ` +\n `Only expected the following keys: ${this.outputNames}`);\n }\n }\n for (const name of this.outputNames) {\n if (args.loss[name] == null) {\n console.warn(\n `Output \"${name}\" is missing from loss dictionary. We assume ` +\n `this was done on purpose, and we will not be expecting data ` +\n `to be passed to ${name} during training`);\n }\n lossFunctions.push(losses.get(args.loss[name]));\n }\n } else if (Array.isArray(args.loss)) {\n if (args.loss.length !== this.outputs.length) {\n throw new ValueError(\n `When passing an Array as loss, it should have one entry per ` +\n `model output. The model has ${this.outputs.length} output(s), ` +\n `but you passed loss=${args.loss}.`);\n }\n const theLosses = args.loss as Array<string|LossOrMetricFn>;\n lossFunctions = theLosses.map(l => losses.get(l));\n } else {\n const lossFunction = losses.get(args.loss);\n this.outputs.forEach(_ => {\n lossFunctions.push(lossFunction);\n });\n }\n\n this.lossFunctions = lossFunctions;\n\n this.feedOutputNames = [];\n this.feedOutputShapes = [];\n this.feedLossFns = [];\n for (let i = 0; i < this.outputs.length; ++i) {\n // TODO(cais): Logic for skipping target(s).\n const shape = this.internalOutputShapes[i];\n const name = this.outputNames[i];\n this.feedOutputNames.push(name);\n this.feedOutputShapes.push(shape);\n this.feedLossFns.push(this.lossFunctions[i]);\n }\n\n // TODO(cais): Add logic for output masks.\n // TODO(cais): Add logic for sample weights.\n const skipTargetIndices: number[] = [];\n\n // Prepare metrics.\n this.metrics = args.metrics;\n // TODO(cais): Add weightedMetrics.\n this.metricsNames = ['loss'];\n this.metricsTensors = [];\n\n // Compute total loss.\n // Porting Note: In PyKeras, metrics_tensors are symbolic tensor objects.\n // Here, metricsTensors are TypeScript functions. This difference is due\n // to the difference in symbolic/imperative property of the backends.\n nameScope('loss', () => {\n for (let i = 0; i < this.outputs.length; ++i) {\n if (skipTargetIndices.indexOf(i) !== -1) {\n continue;\n }\n // TODO(cais): Add weightedLoss, sampleWeight and mask.\n // The following line should be weightedLoss\n const weightedLoss = this.lossFunctions[i];\n if (this.outputs.length > 1) {\n this.metricsTensors.push([weightedLoss, i]);\n this.metricsNames.push(this.outputNames[i] + '_loss');\n }\n }\n\n // Porting Note: Due to the imperative nature of the backend, we calculate\n // the regularizer penalties in the totalLossFunction, instead of here.\n });\n\n const nestedMetrics = collectMetrics(args.metrics, this.outputNames);\n // TODO(cais): Add nestedWeightedMetrics.\n\n /**\n * Helper function used in loop below.\n */\n const appendMetric =\n (outputIndex: number, metricName: string,\n metricTensor: LossOrMetricFn) => {\n if (this.outputNames.length > 1) {\n metricName = this.outputNames[outputIndex] + '_' + metricName;\n }\n this.metricsNames.push(metricName);\n this.metricsTensors.push([metricTensor, outputIndex]);\n };\n\n nameScope('metric', () => {\n for (let i = 0; i < this.outputs.length; ++i) {\n if (skipTargetIndices.indexOf(i) !== -1) {\n continue;\n }\n const outputMetrics = nestedMetrics[i];\n // TODO(cais): Add weights and outputWeightedMetrics.\n\n // TODO(cais): Add optional arg `weights` to the following function.\n const handleMetrics = (metrics: Array<string|LossOrMetricFn>) => {\n const metricNamePrefix = '';\n let metricName: string;\n let accFn: LossOrMetricFn;\n let weightedMetricFn: LossOrMetricFn;\n // TODO(cais): Use 'weights_' for weighted metrics.\n\n for (const metric of metrics) {\n if (typeof metric === 'string' &&\n ['accuracy', 'acc', 'crossentropy', 'ce'].indexOf(metric) !==\n -1) {\n const outputShape = this.internalOutputShapes[i];\n\n if (outputShape[outputShape.length - 1] === 1 ||\n this.lossFunctions[i] === losses.binaryCrossentropy) {\n // case: binary accuracy/crossentropy.\n if (['accuracy', 'acc'].indexOf(metric) !== -1) {\n accFn = Metrics.binaryAccuracy;\n } else if (['crossentropy', 'ce'].indexOf(metric) !== -1) {\n accFn = Metrics.binaryCrossentropy;\n }\n } else if (\n this.lossFunctions[i] ===\n losses.sparseCategoricalCrossentropy) {\n // case: categorical accuracy / crossentropy with sparse\n // targets.\n if (['accuracy', 'acc'].indexOf(metric) !== -1) {\n accFn = Metrics.sparseCategoricalAccuracy;\n } else if (['crossentropy', 'ce'].indexOf(metric) !== -1) {\n accFn = Metrics.sparseCategoricalCrossentropy;\n }\n } else {\n // case: categorical accuracy / crossentropy.\n if (['accuracy', 'acc'].indexOf(metric) !== -1) {\n accFn = Metrics.categoricalAccuracy;\n } else if (['crossentropy', 'ce'].indexOf(metric) !== -1) {\n accFn = Metrics.categoricalCrossentropy;\n }\n }\n let suffix: string;\n if (['accuracy', 'acc'].indexOf(metric) !== -1) {\n suffix = 'acc';\n } else if (['crossentropy', 'ce'].indexOf(metric) !== -1) {\n suffix = 'ce';\n }\n // TODO(cais): Add weighting actually.\n weightedMetricFn = accFn;\n metricName = metricNamePrefix + suffix;\n } else {\n const metricFn = Metrics.get(metric);\n // TODO(cais): Add weighting actually.\n weightedMetricFn = metricFn;\n metricName =\n metricNamePrefix + Metrics.getLossOrMetricName(metric);\n }\n\n // TODO(cais): Add weighting and masking to metricResult.\n let metricResult: LossOrMetricFn;\n nameScope(metricName, () => {\n metricResult = weightedMetricFn;\n });\n appendMetric(i, metricName, metricResult);\n }\n };\n\n handleMetrics(outputMetrics);\n // TODO(cais): Call handleMetrics with weights.\n }\n });\n\n // Porting Notes: Given the imperative backend of tfjs-core,\n // there is no need for constructing the symbolic graph and placeholders.\n this.collectedTrainableWeights = this.trainableWeights;\n }\n\n /**\n * Check trainable weights count consistency.\n *\n * This will raise a warning if `this.trainableWeights` and\n * `this.collectedTrainableWeights` are inconsistent (i.e., have different\n * numbers of parameters).\n * Inconsistency will typically arise when one modifies `model.trainable`\n * without calling `model.compile()` again.\n */\n protected checkTrainableWeightsConsistency(): void {\n if (this.collectedTrainableWeights == null) {\n return;\n }\n if (this.trainableWeights.length !==\n this.collectedTrainableWeights.length) {\n console.warn(\n 'Discrepancy between trainableweights and collected trainable ' +\n 'weights. Did you set `model.trainable` without calling ' +\n '`model.compile()` afterwards?');\n }\n }\n\n /**\n * Returns the loss value & metrics values for the model in test mode.\n *\n * Loss and metrics are specified during `compile()`, which needs to happen\n * before calls to `evaluate()`.\n *\n * Computation is done in batches.\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 1, inputShape: [10]})]\n * });\n * model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});\n * const result = model.evaluate(\n * tf.ones([8, 10]), tf.ones([8, 1]), {batchSize: 4});\n * result.print();\n * ```\n *\n * @param x `tf.Tensor` of test data, or an `Array` of `tf.Tensor`s if the\n * model has multiple inputs.\n * @param y `tf.Tensor` of target data, or an `Array` of `tf.Tensor`s if the\n * model has multiple outputs.\n * @param args A `ModelEvaluateArgs`, containing optional fields.\n *\n * @return `Scalar` test loss (if the model has a single output and no\n * metrics) or `Array` of `Scalar`s (if the model has multiple outputs\n * and/or metrics). The attribute `model.metricsNames`\n * will give you the display labels for the scalar outputs.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n evaluate(\n x: Tensor|Tensor[], y: Tensor|Tensor[],\n args: ModelEvaluateArgs = {}): Scalar|Scalar[] {\n const batchSize = args.batchSize == null ? 32 : args.batchSize;\n checkBatchSize(batchSize);\n\n // TODO(cais): Standardize `config.sampleWeights` as well.\n // Validate user data.\n const checkBatchAxis = true;\n const standardizedOuts =\n this.standardizeUserDataXY(x, y, checkBatchAxis, batchSize);\n try {\n // TODO(cais): If uses `useLearningPhase`, set the corresponding element\n // of the input to 0.\n const ins = standardizedOuts[0].concat(standardizedOuts[1]);\n this.makeTestFunction();\n const f = this.testFunction;\n const testOuts =\n this.testLoop(f, ins, batchSize, args.verbose, args.steps);\n return singletonOrArray(testOuts);\n } finally {\n disposeNewTensors(standardizedOuts[0], x);\n disposeNewTensors(standardizedOuts[1], y);\n }\n }\n\n // TODO(cais): Add code snippet below once real dataset objects are\n // available.\n /**\n * Evaluate model using a dataset object.\n *\n * Note: Unlike `evaluate()`, this method is asynchronous (`async`);\n *\n * @param dataset A dataset object. Its `iterator()` method is expected\n * to generate a dataset iterator object, the `next()` method of which\n * is expected to produce data batches for evaluation. The return value\n * of the `next()` call ought to contain a boolean `done` field and a\n * `value` field. The `value` field is expected to be an array of two\n * `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former\n * case is for models with exactly one input and one output (e.g..\n * a sequential model). The latter case is for models with multiple\n * inputs and/or multiple outputs. Of the two items in the array, the\n * first is the input feature(s) and the second is the output target(s).\n * @param args A configuration object for the dataset-based evaluation.\n * @returns Loss and metric values as an Array of `Scalar` objects.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async evaluateDataset(dataset: Dataset<{}>, args?: ModelEvaluateDatasetArgs):\n Promise<Scalar|Scalar[]> {\n this.makeTestFunction();\n return evaluateDataset(this, dataset, args);\n }\n\n /**\n * Get number of samples provided for training, evaluation or prediction.\n *\n * @param ins Input `tf.Tensor`.\n * @param batchSize Integer batch size, optional.\n * @param steps Total number of steps (batches of samples) before\n * declaring loop finished. Optional.\n * @param stepsName The public API's parameter name for `steps`.\n * @returns Number of samples provided.\n */\n private checkNumSamples(\n ins: Tensor|Tensor[], batchSize?: number, steps?: number,\n stepsName = 'steps'): number {\n let numSamples: number;\n if (steps != null) {\n numSamples = null;\n if (batchSize != null) {\n throw new ValueError(\n `If ${stepsName} is set, batchSize must be null or undefined.` +\n `Got batchSize = ${batchSize}`);\n }\n } else if (ins != null) {\n if (Array.isArray(ins)) {\n numSamples = ins[0].shape[0];\n } else {\n numSamples = ins.shape[0];\n }\n } else {\n throw new ValueError(\n `Either the input data should have a defined shape, or ` +\n `${stepsName} shoud be specified.`);\n }\n return numSamples;\n }\n\n /**\n * Execute internal tensors of the model with input data feed.\n * @param inputs Input data feed. Must match the inputs of the model.\n * @param outputs Names of the output tensors to be fetched. Must match\n * names of the SymbolicTensors that belong to the graph.\n * @returns Fetched values for `outputs`.\n */\n execute(inputs: Tensor|Tensor[]|NamedTensorMap, outputs: string|string[]):\n Tensor|Tensor[] {\n if (Array.isArray(outputs) && outputs.length === 0) {\n throw new ValueError(\n '`outputs` is an empty Array, which is not allowed.');\n }\n\n const outputsIsArray = Array.isArray(outputs);\n const outputNames =\n (outputsIsArray ? outputs as string[] : [outputs as string]);\n const outputSymbolicTensors = this.retrieveSymbolicTensors(outputNames);\n\n // Format the input into a FeedDict.\n const feedDict = new FeedDict();\n if (inputs instanceof Tensor) {\n inputs = [inputs];\n }\n if (Array.isArray(inputs)) {\n if (inputs.length !== this.inputs.length) {\n throw new ValueError(\n `The number of inputs provided (${inputs.length}) ` +\n `does not match the number of inputs of this model ` +\n `(${this.inputs.length}).`);\n }\n for (let i = 0; i < this.inputs.length; ++i) {\n feedDict.add(this.inputs[i], inputs[i]);\n }\n } else {\n for (const input of this.inputs) {\n const tensorValue = inputs[input.name];\n if (tensorValue == null) {\n throw new ValueError(\n `No value is provided for the model's input ${input.name}`);\n }\n feedDict.add(input, tensorValue);\n }\n }\n\n // Run execution.\n const executeOutputs = execute(outputSymbolicTensors, feedDict) as Tensor[];\n return outputsIsArray ? executeOutputs : executeOutputs[0];\n }\n\n /**\n * Retrieve the model's internal symbolic tensors from symbolic-tensor names.\n */\n private retrieveSymbolicTensors(symbolicTensorNames: string[]):\n SymbolicTensor[] {\n const outputSymbolicTensors: SymbolicTensor[] =\n pyListRepeat(null, symbolicTensorNames.length);\n let outputsRemaining = symbolicTensorNames.length;\n for (const layer of this.layers) {\n const layerOutputs: SymbolicTensor[] =\n Array.isArray(layer.output) ? layer.output : [layer.output];\n const layerOutputNames = layerOutputs.map(output => output.name);\n for (let i = 0; i < symbolicTensorNames.length; ++i) {\n const index = layerOutputNames.indexOf(symbolicTensorNames[i]);\n if (index !== -1) {\n outputSymbolicTensors[i] = layerOutputs[index];\n outputsRemaining--;\n }\n if (outputsRemaining === 0) {\n break;\n }\n }\n if (outputsRemaining === 0) {\n break;\n }\n }\n\n if (outputsRemaining > 0) {\n const remainingNames: string[] = [];\n outputSymbolicTensors.forEach((tensor, i) => {\n if (tensor == null) {\n remainingNames.push(symbolicTensorNames[i]);\n }\n });\n throw new ValueError(\n `Cannot find SymbolicTensors for output name(s): ` +\n `${JSON.stringify(remainingNames)}`);\n }\n return outputSymbolicTensors;\n }\n\n /**\n * Helper method to loop over some data in batches.\n *\n * Porting Note: Not using the functional approach in the Python equivalent\n * due to the imperative backend.\n * Porting Note: Does not support step mode currently.\n *\n * @param ins: input data\n * @param batchSize: integer batch size.\n * @param verbose: verbosity model\n * @returns: Predictions as `tf.Tensor` (if a single output) or an `Array` of\n * `tf.Tensor` (if multipe outputs).\n */\n private predictLoop(ins: Tensor|Tensor[], batchSize = 32, verbose = false):\n Tensor|Tensor[] {\n return tfc.tidy(() => {\n const numSamples = this.checkNumSamples(ins);\n if (verbose) {\n throw new NotImplementedError(\n 'Verbose predictLoop() is not implemented yet.');\n }\n\n // Sample-based predictions.\n // Porting Note: Tensor currently does not support sliced assignments as\n // in numpy, e.g., x[1:3] = y. Therefore we use concatenation while\n // iterating over the batches.\n\n const batches = makeBatches(numSamples, batchSize);\n const outsBatches: Tensor[][] = this.outputs.map(output => []);\n\n // TODO(cais): Can the scope() be pushed down inside the for loop?\n for (let batchIndex = 0; batchIndex < batches.length; ++batchIndex) {\n const batchOuts = tfc.tidy(() => {\n const batchStart = batches[batchIndex][0];\n const batchEnd = batches[batchIndex][1];\n // TODO(cais): Take care of the case of the last element is a flag for\n // training/test.\n const insBatch = sliceArrays(ins, batchStart, batchEnd);\n\n // Construct the feeds for execute();\n const feeds = [];\n if (Array.isArray(insBatch)) {\n for (let i = 0; i < insBatch.length; ++i) {\n feeds.push({key: this.inputs[i], value: insBatch[i]});\n }\n } else {\n feeds.push({key: this.inputs[0], value: insBatch});\n }\n const feedDict = new FeedDict(feeds);\n return execute(this.outputs, feedDict) as Tensor[];\n });\n batchOuts.forEach((batchOut, i) => outsBatches[i].push(batchOut));\n }\n return singletonOrArray(\n outsBatches.map(batches => tfc.concat(batches, 0)));\n });\n }\n\n /**\n * Generates output predictions for the input samples.\n *\n * Computation is done in batches.\n *\n * Note: the \"step\" mode of predict() is currently not supported.\n * This is because the TensorFlow.js core backend is imperative only.\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 1, inputShape: [10]})]\n * });\n * model.predict(tf.ones([8, 10]), {batchSize: 4}).print();\n * ```\n *\n * @param x The input data, as a Tensor, or an `Array` of `tf.Tensor`s if\n * the model has multiple inputs.\n * @param args A `ModelPredictArgs` object containing optional fields.\n *\n * @return Prediction results as a `tf.Tensor`(s).\n *\n * @exception ValueError In case of mismatch between the provided input data\n * and the model's expectations, or in case a stateful model receives a\n * number of samples that is not a multiple of the batch size.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n predict(x: Tensor|Tensor[], args: ModelPredictArgs = {}): Tensor|Tensor[] {\n const xsRank2OrHigher = ensureTensorsRank2OrHigher(x);\n checkInputData(\n xsRank2OrHigher, this.inputNames, this.feedInputShapes, false);\n try {\n // TODO(cais): Take care of stateful models.\n // if (this.stateful) ...\n // TODO(cais): Take care of the learning_phase boolean flag.\n // if (this.useLearningPhase) ...\n const batchSize = args.batchSize == null ? 32 : args.batchSize;\n checkBatchSize(batchSize);\n return this.predictLoop(xsRank2OrHigher, batchSize);\n } finally {\n disposeNewTensors(xsRank2OrHigher, x);\n }\n }\n\n /**\n * Returns predictions for a single batch of samples.\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 1, inputShape: [10]})]\n * });\n * model.predictOnBatch(tf.ones([8, 10])).print();\n * ```\n * @param x: Input samples, as a Tensor (for models with exactly one\n * input) or an array of Tensors (for models with more than one input).\n * @return Tensor(s) of predictions\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n predictOnBatch(x: Tensor|Tensor[]): Tensor|Tensor[] {\n checkInputData(x, this.inputNames, this.feedInputShapes, true);\n // TODO(cais): Take care of the learning_phase boolean flag.\n // if (this.useLearningPhase) ...\n const batchSize = (Array.isArray(x) ? x[0] : x).shape[0];\n return this.predictLoop(x, batchSize);\n }\n\n protected standardizeUserDataXY(\n x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|{[inputName: string]: Tensor}, checkBatchAxis = true,\n batchSize?: number): [Tensor[], Tensor[]] {\n // TODO(cais): Add sampleWeight, classWeight\n if (this.optimizer_ == null) {\n throw new RuntimeError(\n 'You must compile a model before training/testing. Use ' +\n 'LayersModel.compile(modelCompileArgs).');\n }\n const outputShapes: Shape[] = [];\n for (let i = 0; i < this.feedOutputShapes.length; ++i) {\n const outputShape = this.feedOutputShapes[i];\n const lossFn = this.feedLossFns[i];\n if (lossFn === losses.sparseCategoricalCrossentropy) {\n outputShapes.push(\n outputShape.slice(0, outputShape.length - 1).concat([1]));\n } else {\n // Porting Note: Because of strong typing `lossFn` must be a function.\n outputShapes.push(outputShape);\n }\n }\n x = standardizeInputData(\n x, this.feedInputNames, this.feedInputShapes, false, 'input');\n y = standardizeInputData(\n y, this.feedOutputNames, outputShapes, false, 'target');\n // TODO(cais): Standardize sampleWeights & classWeights.\n checkArrayLengths(x, y, null);\n // TODO(cais): Check sampleWeights as well.\n checkLossAndTargetCompatibility(y, this.feedLossFns, this.feedOutputShapes);\n if (this.stateful && batchSize != null && batchSize > 0) {\n if (x[0].shape[0] % batchSize !== 0) {\n throw new ValueError(\n `In a stateful network, you should only pass inputs with a ` +\n `number of samples that is divisible by the batch size ` +\n `${batchSize}. Found: ${x[0].shape[0]} sample(s).`);\n }\n }\n return [x, y];\n }\n\n protected async standardizeUserData(\n x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|{[inputName: string]: Tensor},\n sampleWeight?: Tensor|Tensor[]|{[outputName: string]: Tensor},\n classWeight?: ClassWeight|ClassWeight[]|ClassWeightMap,\n checkBatchAxis = true,\n batchSize?: number): Promise<[Tensor[], Tensor[], Tensor[]]> {\n const [standardXs, standardYs] =\n this.standardizeUserDataXY(x, y, checkBatchAxis, batchSize);\n // TODO(cais): Handle sampleWeights.\n if (sampleWeight != null) {\n throw new Error('sample weight is not supported yet.');\n }\n\n let standardSampleWeights: Tensor[] = null;\n if (classWeight != null) {\n const classWeights =\n standardizeClassWeights(classWeight, this.outputNames);\n standardSampleWeights = [];\n for (let i = 0; i < classWeights.length; ++i) {\n standardSampleWeights.push(\n await standardizeWeights(standardYs[i], null, classWeights[i]));\n }\n }\n\n // TODO(cais): Deal with the case of model.stateful == true.\n return [standardXs, standardYs, standardSampleWeights];\n }\n\n /**\n * Loop over some test data in batches.\n * @param f A Function returning a list of tensors.\n * @param ins Array of tensors to be fed to `f`.\n * @param batchSize Integer batch size or `null` / `undefined`.\n * @param verbose verbosity mode.\n * @param steps Total number of steps (batches of samples) before\n * declaring test finished. Ignored with the default value of `null` /\n * `undefined`.\n * @returns Array of Scalars.\n */\n private testLoop(\n f: (data: Tensor[]) => Scalar[], ins: Tensor[], batchSize?: number,\n verbose = 0, steps?: number): Scalar[] {\n return tfc.tidy(() => {\n const numSamples = this.checkNumSamples(ins, batchSize, steps, 'steps');\n const outs: Scalar[] = [];\n if (verbose > 0) {\n throw new NotImplementedError('Verbose mode is not implemented yet.');\n }\n // TODO(cais): Use `indicesForConversionToDense' to prevent slow down.\n if (steps != null) {\n throw new NotImplementedError(\n 'steps mode in testLoop() is not implemented yet');\n } else {\n const batches = makeBatches(numSamples, batchSize);\n const indexArray = tensor1d(range(0, numSamples));\n for (let batchIndex = 0; batchIndex < batches.length; ++batchIndex) {\n const batchStart = batches[batchIndex][0];\n const batchEnd = batches[batchIndex][1];\n const batchIds =\n K.sliceAlongFirstAxis(\n indexArray, batchStart, batchEnd - batchStart) as Tensor1D;\n // TODO(cais): In ins, train flag can be a number, instead of an\n // Tensor? Do we need to handle this in tfjs-layers?\n const insBatch = sliceArraysByIndices(ins, batchIds) as Scalar[];\n const batchOuts = f(insBatch);\n if (batchIndex === 0) {\n for (let i = 0; i < batchOuts.length; ++i) {\n outs.push(scalar(0));\n }\n }\n for (let i = 0; i < batchOuts.length; ++i) {\n const batchOut = batchOuts[i];\n outs[i] =\n tfc.add(outs[i], tfc.mul(batchEnd - batchStart, batchOut));\n }\n }\n for (let i = 0; i < outs.length; ++i) {\n outs[i] = tfc.div(outs[i], numSamples);\n }\n }\n return outs;\n });\n }\n\n protected getDedupedMetricsNames(): string[] {\n const outLabels = this.metricsNames;\n // Rename duplicated metrics names (can happen with an output layer\n // shared among multiple dataflows).\n const dedupedOutLabels = [];\n for (let i = 0; i < outLabels.length; ++i) {\n const label = outLabels[i];\n let newLabel = label;\n if (count(outLabels, label) > 1) {\n const dupIndex = count(outLabels.slice(0, i), label);\n newLabel += `_${dupIndex}`;\n }\n dedupedOutLabels.push(newLabel);\n }\n return dedupedOutLabels;\n }\n\n /**\n * Creates a function that performs the following actions:\n *\n * 1. computes the losses\n * 2. sums them to get the total loss\n * 3. call the optimizer computes the gradients of the LayersModel's\n * trainable weights w.r.t. the total loss and update the variables\n * 4. calculates the metrics\n * 5. returns the values of the losses and metrics.\n */\n protected makeTrainFunction(): (data: Tensor[]) => Scalar[] {\n return (data: Tensor[]) => {\n const lossValues: Scalar[] = [];\n\n const inputs = data.slice(0, this.inputs.length);\n const targets = data.slice(\n this.inputs.length, this.inputs.length + this.outputs.length);\n const sampleWeights = data.slice(\n this.inputs.length + this.outputs.length,\n this.inputs.length + this.outputs.length * 2);\n\n const metricsValues: Scalar[] = [];\n\n // Create a function that computes the total loss based on the\n // inputs. This function is used for obtaining gradients through\n // backprop.\n const totalLossFunction = () => {\n const feeds = [];\n for (let i = 0; i < this.inputs.length; ++i) {\n feeds.push({key: this.inputs[i], value: inputs[i]});\n }\n const feedDict = new FeedDict(feeds);\n const outputs =\n execute(this.outputs, feedDict, {'training': true}) as Tensor[];\n // TODO(cais): Take care of the case of multiple outputs from a\n // single layer?\n\n let totalLoss: Tensor;\n for (let i = 0; i < this.lossFunctions.length; ++i) {\n const lossFunction = this.lossFunctions[i];\n let loss = lossFunction(targets[i], outputs[i]);\n if (sampleWeights[i] != null) {\n loss = computeWeightedLoss(loss, sampleWeights[i]);\n }\n\n // TODO(cais): push Scalar instead.\n const meanLoss: Scalar = tfc.mean(loss);\n // TODO(cais): Use a scope() instead, to avoid ownership.\n lossValues.push(meanLoss);\n if (i === 0) {\n totalLoss = loss;\n } else {\n totalLoss = tfc.add(totalLoss, loss);\n }\n }\n\n // Compute the metrics.\n // TODO(cais): These should probably be calculated outside\n // totalLossFunction to benefit speed?\n for (let i = 0; i < this.metricsTensors.length; ++i) {\n let weightedMetric: Scalar;\n\n if (this.outputs.length > 1 && i < this.outputs.length) {\n weightedMetric = lossValues[i];\n } else {\n const metric = this.metricsTensors[i][0];\n const outputIndex = this.metricsTensors[i][1];\n weightedMetric =\n tfc.mean(metric(targets[outputIndex], outputs[outputIndex]));\n }\n\n tfc.keep(weightedMetric);\n // TODO(cais): Use a scope() instead, to avoid ownership.\n metricsValues.push(weightedMetric);\n }\n\n totalLoss = tfc.mean(totalLoss);\n\n // Add regularizer penalties.\n this.calculateLosses().forEach(regularizerLoss => {\n totalLoss = tfc.add(totalLoss, regularizerLoss);\n });\n\n return totalLoss as Scalar;\n };\n\n const variables = this.collectedTrainableWeights.map(\n param => param.read() as tfc.Variable);\n const returnCost = true;\n const totalLossValue =\n this.optimizer_.minimize(totalLossFunction, returnCost, variables);\n\n return [totalLossValue].concat(metricsValues);\n };\n }\n\n /**\n * Create a function which, when invoked with an array of `tf.Tensor`s as a\n * batch of inputs, returns the prespecified loss and metrics of the model\n * under the batch of input data.\n */\n private makeTestFunction() {\n this.testFunction = (data: Tensor[]) => {\n return tfc.tidy(() => {\n const valOutputs: Scalar[] = [];\n let totalLoss: Scalar;\n const inputs = data.slice(0, this.inputs.length);\n const targets = data.slice(\n this.inputs.length, this.inputs.length + this.outputs.length);\n const feeds = [];\n for (let i = 0; i < this.inputs.length; ++i) {\n feeds.push({key: this.inputs[i], value: inputs[i]});\n }\n const feedDict = new FeedDict(feeds);\n const outputs = execute(this.outputs, feedDict) as Tensor[];\n // Compute total loss.\n for (let i = 0; i < this.lossFunctions.length; ++i) {\n const lossFunction = this.lossFunctions[i];\n // TODO(cais): Add sample weighting and replace the simple\n // averaging.\n const loss: Scalar = tfc.mean(lossFunction(targets[i], outputs[i]));\n if (i === 0) {\n totalLoss = loss;\n } else {\n totalLoss = tfc.add(totalLoss, loss);\n }\n valOutputs.push(totalLoss);\n }\n // Compute the metrics.\n for (let i = 0; i < this.metricsTensors.length; ++i) {\n const metric = this.metricsTensors[i][0];\n const outputIndex = this.metricsTensors[i][1];\n // TODO(cais): Replace K.mean() with a proper weighting function.\n const meanMetric =\n tfc.mean(metric(targets[outputIndex], outputs[outputIndex]));\n valOutputs.push(meanMetric as Scalar);\n }\n return valOutputs;\n });\n };\n }\n\n /**\n * Trains the model for a fixed number of epochs (iterations on a\n * dataset).\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 1, inputShape: [10]})]\n * });\n * model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});\n * for (let i = 1; i < 5 ; ++i) {\n * const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {\n * batchSize: 4,\n * epochs: 3\n * });\n * console.log(\"Loss after Epoch \" + i + \" : \" + h.history.loss[0]);\n * }\n * ```\n *\n * @param x `tf.Tensor` of training data, or an array of `tf.Tensor`s if the\n * model has multiple inputs. If all inputs in the model are named, you\n * can also pass a dictionary mapping input names to `tf.Tensor`s.\n * @param y `tf.Tensor` of target (label) data, or an array of `tf.Tensor`s if\n * the model has multiple outputs. If all outputs in the model are named,\n * you can also pass a dictionary mapping output names to `tf.Tensor`s.\n * @param args A `ModelFitArgs`, containing optional fields.\n *\n * @return A `History` instance. Its `history` attribute contains all\n * information collected during training.\n *\n * @exception ValueError In case of mismatch between the provided input\n * data and what the model expects.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async fit(\n x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|{[inputName: string]: Tensor},\n args: ModelFitArgs = {}): Promise<History> {\n return fitTensors(this, x, y, args);\n }\n\n // TODO(cais): Add code snippet below when it's possible to instantiate\n // actual dataset objects.\n /**\n * Trains the model using a dataset object.\n *\n * @param dataset A dataset object. Its `iterator()` method is expected\n * to generate a dataset iterator object, the `next()` method of which\n * is expected to produce data batches for training. The return value\n * of the `next()` call ought to contain a boolean `done` field and a\n * `value` field. The `value` field is expected to be an array of two\n * `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former\n * case is for models with exactly one input and one output (e.g..\n * a sequential model). The latter case is for models with multiple\n * inputs and/or multiple outputs.\n * Of the two items in the array, the first is the input feature(s) and\n * the second is the output target(s).\n * @param args A `ModelFitDatasetArgs`, containing optional fields.\n *\n * @return A `History` instance. Its `history` attribute contains all\n * information collected during training.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async fitDataset<T>(dataset: Dataset<T>, args: ModelFitDatasetArgs<T>):\n Promise<History> {\n return fitDataset(this, dataset, args);\n }\n\n /**\n * Runs a single gradient update on a single batch of data.\n *\n * This method differs from `fit()` and `fitDataset()` in the following\n * regards:\n * - It operates on exactly one batch of data.\n * - It returns only the loss and matric values, instead of\n * returning the batch-by-batch loss and metric values.\n * - It doesn't support fine-grained options such as verbosity and\n * callbacks.\n *\n * @param x Input data. It could be one of the following:\n * - A `tf.Tensor`, or an Array of `tf.Tensor`s (in case the model has\n * multiple inputs).\n * - An Object mapping input names to corresponding `tf.Tensor` (if the\n * model has named inputs).\n * @param y Target darta. It could be either a `tf.Tensor` a multiple\n * `tf.Tensor`s. It should be consistent with `x`.\n * @returns Training loss or losses (in case the model has\n * multiple outputs), along with metrics (if any), as numbers.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async trainOnBatch(\n x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|\n {[inputName: string]: Tensor}): Promise<number|number[]> {\n // TODO(cais): Support sampleWeight and classWeight.\n // TODO(cais): Support Dataset objects.\n const standardizeOut = await this.standardizeUserData(x, y);\n const inputs = standardizeOut[0];\n const targets = standardizeOut[1];\n const trainFunction = this.makeTrainFunction();\n const losses = trainFunction(inputs.concat(targets));\n const lossValues: number[] = [];\n for (const loss of losses) {\n const v = await loss.data();\n lossValues.push(v[0]);\n }\n tfc.dispose(losses);\n return singletonOrArray(lossValues);\n }\n\n /**\n * Extract weight values of the model.\n *\n * @param config: An instance of `io.SaveConfig`, which specifies\n * model-saving options such as whether only trainable weights are to be\n * saved.\n * @returns A `NamedTensorMap` mapping original weight names (i.e.,\n * non-uniqueified weight names) to their values.\n */\n protected getNamedWeights(config?: io.SaveConfig): NamedTensor[] {\n const namedWeights: NamedTensor[] = [];\n\n const trainableOnly = config != null && config.trainableOnly;\n const weights = trainableOnly ? this.trainableWeights : this.weights;\n const weightValues = this.getWeights(trainableOnly);\n for (let i = 0; i < weights.length; ++i) {\n if (trainableOnly && !weights[i].trainable) {\n // Optionally skip non-trainable weights.\n continue;\n }\n namedWeights.push(\n {name: weights[i].originalName, tensor: weightValues[i]});\n }\n return namedWeights;\n }\n\n /**\n * Setter used for force stopping of LayersModel.fit() (i.e., training).\n *\n * Example:\n *\n * ```js\n * const input = tf.input({shape: [10]});\n * const output = tf.layers.dense({units: 1}).apply(input);\n * const model = tf.model({inputs: [input], outputs: [output]});\n * model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});\n * const xs = tf.ones([8, 10]);\n * const ys = tf.zeros([8, 1]);\n *\n * const history = await model.fit(xs, ys, {\n * epochs: 10,\n * callbacks: {\n * onEpochEnd: async (epoch, logs) => {\n * if (epoch === 2) {\n * model.stopTraining = true;\n * }\n * }\n * }\n * });\n *\n * // There should be only 3 values in the loss array, instead of 10\n * values,\n * // due to the stopping after 3 epochs.\n * console.log(history.history.loss);\n * ```\n */\n set stopTraining(stop: boolean) {\n this.stopTraining_ = stop;\n }\n\n get stopTraining(): boolean {\n return this.stopTraining_;\n }\n\n get optimizer(): Optimizer {\n return this.optimizer_;\n }\n\n set optimizer(optimizer: Optimizer) {\n if (this.optimizer_ !== optimizer) {\n this.optimizer_ = optimizer;\n this.isOptimizerOwned = false;\n }\n }\n\n dispose(): DisposeResult {\n const result = super.dispose();\n if (result.refCountAfterDispose === 0 && this.optimizer != null &&\n this.isOptimizerOwned) {\n const numTensorsBeforeOptmizerDisposal = tfc.memory().numTensors;\n this.optimizer_.dispose();\n result.numDisposedVariables +=\n numTensorsBeforeOptmizerDisposal - tfc.memory().numTensors;\n }\n return result;\n }\n\n private getLossIdentifiers(): LossIdentifier|LossIdentifier[]|\n {[outputName: string]: LossIdentifier} {\n let lossNames: LossIdentifier|LossIdentifier[]|\n {[outputName: string]: LossIdentifier};\n if (typeof this.loss === 'string') {\n lossNames = toSnakeCase(this.loss) as LossIdentifier;\n } else if (Array.isArray(this.loss)) {\n for (const loss of this.loss) {\n if (typeof loss !== 'string') {\n throw new Error('Serialization of non-string loss is not supported.');\n }\n }\n lossNames = (this.loss as string[]).map(name => toSnakeCase(name)) as\n LossIdentifier[];\n } else {\n const outputNames = Object.keys(this.loss);\n lossNames = {} as {[outputName: string]: LossIdentifier};\n const losses =\n this.loss as {[outputName: string]: LossOrMetricFn | string};\n for (const outputName of outputNames) {\n if (typeof losses[outputName] === 'string') {\n lossNames[outputName] =\n toSnakeCase(losses[outputName] as string) as LossIdentifier;\n } else {\n throw new Error('Serialization of non-string loss is not supported.');\n }\n }\n }\n return lossNames;\n }\n\n private getMetricIdentifiers(): MetricsIdentifier[]|\n {[key: string]: MetricsIdentifier} {\n if (typeof this.metrics === 'string' ||\n typeof this.metrics === 'function') {\n return [toSnakeCase(Metrics.getLossOrMetricName(this.metrics))];\n } else if (Array.isArray(this.metrics)) {\n return this.metrics.map(\n metric => toSnakeCase(Metrics.getLossOrMetricName(metric)));\n } else {\n const metricsIdentifiers: {[key: string]: MetricsIdentifier} = {};\n for (const key in this.metrics) {\n metricsIdentifiers[key] =\n toSnakeCase(Metrics.getLossOrMetricName(this.metrics[key]));\n }\n return metricsIdentifiers;\n }\n }\n\n protected getTrainingConfig(): TrainingConfig {\n return {\n loss: this.getLossIdentifiers(),\n metrics: this.getMetricIdentifiers(),\n optimizer_config: {\n class_name: this.optimizer.getClassName(),\n config: this.optimizer.getConfig()\n } as OptimizerSerialization\n };\n // TODO(cais): Add weight_metrics when they are supported.\n // TODO(cais): Add sample_weight_mode when it's supported.\n // TODO(cais): Add loss_weights when it's supported.\n }\n\n loadTrainingConfig(trainingConfig: TrainingConfig) {\n if (trainingConfig.weighted_metrics != null) {\n throw new Error('Loading weight_metrics is not supported yet.');\n }\n if (trainingConfig.loss_weights != null) {\n throw new Error('Loading loss_weights is not supported yet.');\n }\n if (trainingConfig.sample_weight_mode != null) {\n throw new Error('Loading sample_weight_mode is not supported yet.');\n }\n\n const tsConfig = convertPythonicToTs(trainingConfig.optimizer_config) as\n serialization.ConfigDict;\n const optimizer = deserialize(tsConfig) as Optimizer;\n\n let loss;\n if (typeof trainingConfig.loss === 'string') {\n loss = toCamelCase(trainingConfig.loss);\n } else if (Array.isArray(trainingConfig.loss)) {\n loss = trainingConfig.loss.map(lossEntry => toCamelCase(lossEntry));\n } else if (trainingConfig.loss != null) {\n loss = {} as {[outputName: string]: LossIdentifier};\n for (const key in trainingConfig.loss) {\n loss[key] = toCamelCase(trainingConfig.loss[key]) as LossIdentifier;\n }\n }\n\n let metrics;\n if (Array.isArray(trainingConfig.metrics)) {\n metrics = trainingConfig.metrics.map(metric => toCamelCase(metric));\n } else if (trainingConfig.metrics != null) {\n metrics = {} as {[outputName: string]: MetricsIdentifier};\n for (const key in trainingConfig.metrics) {\n metrics[key] = toCamelCase(trainingConfig.metrics[key]);\n }\n }\n\n this.compile({loss, metrics, optimizer});\n }\n\n /**\n * Save the configuration and/or weights of the LayersModel.\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 model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * console.log('Prediction from original model:');\n * model.predict(tf.ones([1, 3])).print();\n *\n * const saveResults = await model.save('localstorage://my-model-1');\n *\n * const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');\n * console.log('Prediction from loaded model:');\n * loadedModel.predict(tf.ones([1, 3])).print();\n * ```\n *\n * Example 2. Saving `model`'s topology and weights to browser\n * [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API);\n * then load it back.\n *\n * ```js\n * const model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * console.log('Prediction from original model:');\n * model.predict(tf.ones([1, 3])).print();\n *\n * const saveResults = await model.save('indexeddb://my-model-1');\n *\n * const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');\n * console.log('Prediction from loaded model:');\n * loadedModel.predict(tf.ones([1, 3])).print();\n * ```\n *\n * Example 3. Saving `model`'s topology and weights as two files\n * (`my-model-1.json` and `my-model-1.weights.bin`) downloaded from\n * browser.\n *\n * ```js\n * const model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * const saveResults = await model.save('downloads://my-model-1');\n * ```\n *\n * Example 4. Send `model`'s topology and weights to an HTTP server.\n * See the documentation of `tf.io.http` for more details\n * including specifying request parameters and implementation of the\n * server.\n *\n * ```js\n * const model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * const saveResults = await model.save('http://my-server/model/upload');\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 = io.getSaveHandlers(handlerOrURL);\n if (handlers.length === 0) {\n throw new ValueError(\n `Cannot find any save handlers for URL '${handlerOrURL}'`);\n } else if (handlers.length > 1) {\n throw new ValueError(\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 ValueError(\n 'LayersModel.save() cannot proceed because the IOHandler ' +\n 'provided does not have the `save` attribute defined.');\n }\n\n const weightDataAndSpecs =\n await io.encodeWeights(this.getNamedWeights(config));\n\n const returnString = false;\n const unusedArg: {} = null;\n const modelConfig = this.toJSON(unusedArg, returnString);\n const modelArtifacts: io.ModelArtifacts = {\n modelTopology: modelConfig,\n format: LAYERS_MODEL_FORMAT_NAME,\n generatedBy: `TensorFlow.js tfjs-layers v${version}`,\n convertedBy: null,\n };\n\n const includeOptimizer = config == null ? false : config.includeOptimizer;\n if (includeOptimizer && this.optimizer != null) {\n modelArtifacts.trainingConfig = this.getTrainingConfig();\n const weightType = 'optimizer';\n const {data: optimizerWeightData, specs: optimizerWeightSpecs} =\n await io.encodeWeights(await this.optimizer.getWeights(), weightType);\n weightDataAndSpecs.specs.push(...optimizerWeightSpecs);\n weightDataAndSpecs.data = io.concatenateArrayBuffers(\n [weightDataAndSpecs.data, optimizerWeightData]);\n }\n\n if (this.userDefinedMetadata != null) {\n // Check serialized size of user-defined metadata.\n const checkSize = true;\n checkUserDefinedMetadata(this.userDefinedMetadata, this.name, checkSize);\n modelArtifacts.userDefinedMetadata = this.userDefinedMetadata;\n }\n\n modelArtifacts.weightData = weightDataAndSpecs.data;\n modelArtifacts.weightSpecs = weightDataAndSpecs.specs;\n return handlerOrURL.save(modelArtifacts);\n }\n\n /**\n * Set user-defined metadata.\n *\n * The set metadata will be serialized together with the topology\n * and weights of the model during `save()` calls.\n *\n * @param setUserDefinedMetadata\n */\n setUserDefinedMetadata(userDefinedMetadata: {}): void {\n checkUserDefinedMetadata(userDefinedMetadata, this.name);\n this.userDefinedMetadata = userDefinedMetadata;\n }\n\n /**\n * Get user-defined metadata.\n *\n * The metadata is supplied via one of the two routes:\n * 1. By calling `setUserDefinedMetadata()`.\n * 2. Loaded during model loading (if the model is constructed\n * via `tf.loadLayersModel()`.)\n *\n * If no user-defined metadata is available from either of the\n * two routes, this function will return `undefined`.\n */\n getUserDefinedMetadata(): {} {\n return this.userDefinedMetadata;\n }\n}\nserialization.registerClass(LayersModel);\n\n/**\n * A `tf.Functional` is an alias to `tf.LayersModel`.\n *\n * See also:\n * `tf.LayersModel`, `tf.Sequential`, `tf.loadLayersModel`.\n */\n/** @doc {heading: 'Models', subheading: 'Classes'} */\nexport class Functional extends LayersModel {\n static className = 'Functional';\n}\nserialization.registerClass(Functional);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source keras/models.py */\n\nimport {dispose, io, NamedTensorMap, Optimizer, Scalar, serialization, Tensor, util} from '@tensorflow/tfjs-core';\n\nimport {getUid} from './backend/state';\nimport {History} from './base_callbacks';\nimport {Dataset} from './engine/dataset_stub';\nimport {Input} from './engine/input_layer';\nimport {getSourceInputs, Layer, Node, SymbolicTensor} from './engine/topology';\nimport {LayersModel, ModelCompileArgs, ModelEvaluateArgs} from './engine/training';\nimport {ModelEvaluateDatasetArgs, ModelFitDatasetArgs} from './engine/training_dataset';\nimport {ModelFitArgs} from './engine/training_tensors';\nimport {NotImplementedError, RuntimeError, ValueError} from './errors';\nimport {Shape} from './keras_format/common';\nimport {TrainingConfig} from './keras_format/training_config';\nimport {PyJsonDict} from './keras_format/types';\nimport {deserialize} from './layers/serialization';\nimport {Kwargs, NamedTensor} from './types';\nimport * as generic_utils from './utils/generic_utils';\nimport {convertPythonicToTs} from './utils/serialization_utils';\nimport {getExactlyOneShape} from './utils/types_utils';\n\n/**\n * Parses a JSON model configuration file and returns a model instance.\n *\n * ```js\n * // This example shows how to serialize a model using `toJSON()` and\n * // deserialize it as another model using `tf.models.modelFromJSON()`.\n * // Note: this example serializes and deserializes only the topology\n * // of the model; the weights of the loaded model will be different\n * // from those of the the original model, due to random weight\n * // initialization.\n * // To load the topology and weights of a model, use `tf.loadLayersModel()`.\n * const model1 = tf.sequential();\n * model1.add(tf.layers.repeatVector({inputShape: [2], n: 4}));\n * // Serialize `model1` as a JSON object.\n * const model1JSON = model1.toJSON(null, false);\n * model1.summary();\n *\n * const model2 = await tf.models.modelFromJSON(model1JSON);\n * model2.summary();\n * ```\n *\n * @param modelAndWeightsConfig JSON object or string encoding a model and\n * weights configuration. It can also be only the topology JSON of the\n * model, in which case the weights will not be loaded.\n * @param custom_objects Optional dictionary mapping names\n * (strings) to custom classes or functions to be\n * considered during deserialization.\n * @returns A TensorFlow.js Layers `tf.LayersModel` instance (uncompiled).\n */\nexport async function modelFromJSON(\n modelAndWeightsConfig: ModelAndWeightsConfig|PyJsonDict,\n customObjects?: serialization.ConfigDict): Promise<LayersModel> {\n if (!('modelTopology' in modelAndWeightsConfig)) {\n modelAndWeightsConfig = {modelTopology: modelAndWeightsConfig};\n }\n modelAndWeightsConfig = modelAndWeightsConfig as ModelAndWeightsConfig;\n\n let modelTopology = modelAndWeightsConfig.modelTopology;\n if (modelTopology['model_config'] != null) {\n // If the model-topology JSON contains a 'model_config' field, then it is\n // a full model JSON (e.g., from `keras.Model.save()`), which contains\n // not only the model's architecture in its 'model_config' field, but\n // additional information such as the model's optimizer. We use only the\n // 'model_config' field currently.\n modelTopology = modelTopology['model_config'] as PyJsonDict;\n }\n const tsConfig =\n convertPythonicToTs(modelTopology) as serialization.ConfigDict;\n const model = deserialize(tsConfig, customObjects) as LayersModel;\n\n if (modelAndWeightsConfig.weightsManifest != null) {\n // Load the weight values keyed by the original tensor names in the model\n // file that was loaded. These should match the keys of the weight\n // manifest.\n const weightValues = await io.loadWeights(\n modelAndWeightsConfig.weightsManifest, modelAndWeightsConfig.pathPrefix,\n model.weights.map(weight => weight.originalName));\n\n // Map the weights to the unique tensor names generated during model loading\n const uniqueWeightValues: NamedTensorMap = {};\n for (const weight of model.weights) {\n uniqueWeightValues[weight.originalName] =\n weightValues[weight.originalName];\n }\n\n model.loadWeights(uniqueWeightValues);\n // Dispose temporary weight values.\n dispose(weightValues);\n }\n return model;\n}\n\n/**\n * Options for loading a saved mode in TensorFlow.js format.\n */\nexport interface ModelAndWeightsConfig {\n /**\n * A JSON object or JSON string containing the model config.\n *\n * This can be either of the following two formats:\n * - A model archiecture-only config, i.e., a format consistent with the\n * return value of`keras.Model.to_json()`.\n * - A full model config, containing not only model architecture, but also\n * training options and state, i.e., a format consistent with the return\n * value of `keras.models.save_model()`.\n */\n modelTopology: PyJsonDict;\n\n /**\n * A weights manifest in TensorFlow.js format.\n */\n weightsManifest?: io.WeightsManifestConfig;\n\n /**\n * Path to prepend to the paths in `weightManifest` before fetching.\n *\n * The path may optionally end in a slash ('/').\n */\n pathPrefix?: string;\n}\n\n// TODO(nielsene): Remove after: https://github.com/tensorflow/tfjs/issues/400\nexport interface ModelPredictArgs {\n /**\n * Optional. Batch size (Integer). If unspecified, it will default to 32.\n */\n batchSize?: number;\n\n /**\n * Optional. Verbosity mode. Defaults to false.\n */\n verbose?: boolean;\n}\n\n/**\n * Load a model, including its topology and optionally weights. See the\n * Tutorial named \"How to import a Keras Model\" for usage examples.\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 model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * console.log('Prediction from original model:');\n * model.predict(tf.ones([1, 3])).print();\n *\n * const saveResults = await model.save('localstorage://my-model-1');\n *\n * const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');\n * console.log('Prediction from loaded model:');\n * loadedModel.predict(tf.ones([1, 3])).print();\n * ```\n *\n * Example 2. Saving `model`'s topology and weights to browser\n * [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API);\n * then load it back.\n *\n * ```js\n * const model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * console.log('Prediction from original model:');\n * model.predict(tf.ones([1, 3])).print();\n *\n * const saveResults = await model.save('indexeddb://my-model-1');\n *\n * const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');\n * console.log('Prediction from loaded model:');\n * loadedModel.predict(tf.ones([1, 3])).print();\n * ```\n *\n * Example 3. Load a model from user-selected files from HTML\n * [file input\n * elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file).\n *\n * ```js\n * // Note: this code snippet will not work without the HTML elements in the\n * // page\n * const jsonUpload = document.getElementById('json-upload');\n * const weightsUpload = document.getElementById('weights-upload');\n *\n * const model = await tf.loadLayersModel(\n * tf.io.browserFiles([jsonUpload.files[0], weightsUpload.files[0]]));\n * ```\n *\n * Example 4. Load a model from an HTTP server.\n *\n * ```js\n * const model = await\n * tf.loadLayersModel('https://storage.googleapis.com/tfjs-models/tfjs/iris_v1/model.json');\n * model.summary();\n * ```\n *\n * @param pathOrIOHandler Can be either of the two formats\n * 1. A string path to the `ModelAndWeightsConfig` JSON describing\n * the model in the canonical TensorFlow.js format. This path will be\n * interpreted as a relative HTTP path, to which `fetch` will be used to\n * request the model topology and weight manifest JSON.\n * The content of the JSON file is assumed to be a JSON object with the\n * following fields and values:\n * - 'modelTopology': A JSON object that can be either of:\n * 1. a model architecture JSON consistent with the format of the return\n * value of `keras.Model.to_json()`\n * 2. a full model JSON in the format of `keras.models.save_model()`.\n * - 'weightsManifest': A TensorFlow.js weights manifest.\n * See the Python converter function `save_model()` for more details.\n * It is also assumed that model weights can be accessed from relative\n * paths described by the `paths` fields in weights manifest.\n * 2. An `tf.io.IOHandler` object that loads model artifacts with its `load`\n * method.\n * @param options Optional configuration arguments for the model loading,\n * including:\n * - `strict`: Require that the provided weights exactly match those required\n * by the layers. Default true. Passing false means that both extra\n * weights and missing weights will be silently ignored.\n * - `onProgress`: A progress callback of the form:\n * `(fraction: number) => void`. This callback can be used to monitor the\n * model-loading process.\n * @returns A `Promise` of `tf.LayersModel`, with the topology and weights\n * loaded.\n */\nexport async function loadLayersModelInternal(\n pathOrIOHandler: string|io.IOHandler,\n options?: io.LoadOptions): Promise<LayersModel> {\n if (options == null) {\n options = {};\n }\n if (typeof pathOrIOHandler === 'string') {\n const handlers = io.getLoadHandlers(pathOrIOHandler, options);\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 // TODO(cais): Reformat the args into a single `LoadOptions` once the core\n // is refactored.\n handlers.push(io.browserHTTPRequest(pathOrIOHandler, options));\n } else if (handlers.length > 1) {\n throw new ValueError(\n `Found more than one (${handlers.length}) load handlers for ` +\n `URL '${pathOrIOHandler}'`);\n }\n pathOrIOHandler = handlers[0];\n }\n return loadLayersModelFromIOHandler(pathOrIOHandler, undefined, options);\n}\n\n/**\n * Load a model and optionally its weights, using an IOHandler object.\n *\n * @param handler The instance of `IOHandler` to be used during the model\n * loading.\n * @param customObjects Any optional custom objects to be used during model\n * loading.\n * @param strict Whether the weight loading will be done in strict mode.\n * Default: `true`.\n */\nexport async function loadLayersModelFromIOHandler(\n handler: io.IOHandler, customObjects?: serialization.ConfigDict,\n options?: io.LoadOptions): Promise<LayersModel> {\n if (options == null) {\n options = {};\n }\n if (handler.load == null) {\n throw new ValueError(\n 'Cannot proceed with model loading because the IOHandler provided ' +\n 'does not have the `load` method implemented.');\n }\n const artifacts = await handler.load();\n let modelTopology = artifacts.modelTopology as PyJsonDict;\n if (modelTopology['model_config'] != null) {\n modelTopology = modelTopology['model_config'] as PyJsonDict;\n }\n\n const strict = options.strict == null ? true : options.strict;\n // If weights are provided and the weight-loading mode is strict, use\n // fast weight initialization. This skips costly initializers such as\n // 'orthogonal' and saves unnecessary computation in cases where\n // the initialized weight values will immediately be overwritten by\n // loaded weight values.\n const fastWeightInit =\n artifacts.weightData != null && artifacts.weightSpecs != null && strict;\n const model =\n deserialize(\n convertPythonicToTs(modelTopology) as serialization.ConfigDict,\n customObjects, fastWeightInit) as LayersModel;\n\n const trainingConfig = artifacts.trainingConfig as TrainingConfig;\n if (trainingConfig != null) {\n model.loadTrainingConfig(trainingConfig);\n }\n if (artifacts.userDefinedMetadata != null) {\n model.setUserDefinedMetadata(artifacts.userDefinedMetadata);\n }\n\n // If weightData is present, load the weights into the model.\n if (artifacts.weightData != null) {\n // Loading weights requires weightSpecs.\n if (artifacts.weightSpecs == null) {\n throw new ValueError(\n 'LayersModel artifacts contains weight data, but not weight specs. ' +\n 'Therefore loading of weights cannot proceed.');\n }\n\n const {modelWeights, optimizerWeights} = decodeModelAndOptimizerWeights(\n artifacts.weightData, artifacts.weightSpecs);\n model.loadWeights(modelWeights, strict);\n\n if (model.optimizer != null && optimizerWeights.length > 0) {\n await model.optimizer.setWeights(optimizerWeights);\n }\n\n // Dispose temporary weight values.\n dispose(modelWeights);\n dispose(optimizerWeights.map(w => w.tensor));\n }\n return model;\n}\n\nfunction decodeModelAndOptimizerWeights(\n buffer: ArrayBuffer, specs: io.WeightsManifestEntry[]):\n {modelWeights: NamedTensorMap, optimizerWeights: NamedTensor[]} {\n const name2Tensor = io.decodeWeights(buffer, specs);\n const modelWeights: NamedTensorMap = {};\n const optimizerWeights: NamedTensor[] = [];\n specs.forEach(spec => {\n if (spec.group === 'optimizer') {\n optimizerWeights.push({name: spec.name, tensor: name2Tensor[spec.name]});\n } else {\n modelWeights[spec.name] = name2Tensor[spec.name];\n }\n });\n return {modelWeights, optimizerWeights};\n}\n\n/**\n * Configuration for a Sequential model.\n */\nexport interface SequentialArgs {\n /** Stack of layers for the model. */\n layers?: Layer[];\n\n /** The name of this model. */\n name?: string;\n}\n\n/**\n * A model with a stack of layers, feeding linearly from one to the next.\n *\n * `tf.sequential` is a factory function that creates an instance of\n * `tf.Sequential`.\n *\n * ```js\n * // Define a model for linear regression.\n * const model = tf.sequential();\n * model.add(tf.layers.dense({units: 1, inputShape: [1]}));\n *\n * // Prepare the model for training: Specify the loss and the optimizer.\n * model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});\n *\n * // Generate some synthetic data for training.\n * const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);\n * const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);\n *\n * // Train the model using the data then do inference on a data point the\n * // model hasn't seen:\n * await model.fit(xs, ys);\n * model.predict(tf.tensor2d([5], [1, 1])).print();\n * ```\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\nexport class Sequential extends LayersModel {\n /** @nocollapse */\n static className = 'Sequential';\n private model: LayersModel;\n constructor(args?: SequentialArgs) {\n super({inputs: [], outputs: []});\n args = args || {};\n\n this.trainable = true;\n this.built = false;\n\n // Set model name.\n this.name = (args.name != null) ? args.name : getUid('sequential_');\n\n // Add to the model any layers passed to the constructor.\n if (args.layers != null) {\n for (const layer of args.layers) {\n this.add(layer);\n }\n }\n }\n\n // Helper function to Sequential.add Throws if the new output shape will be\n // invalid.\n private checkShape(layer: Layer) {\n const shape = layer.inboundNodes[0].outputTensors[0].shape;\n if (shape.some(x => x < 0)) {\n throw new ValueError(\n 'Negative dimension size caused by adding layer ' +\n `${layer.name} with input shape [` +\n `${layer.inboundNodes[0].inputTensors[0].shape}]`);\n }\n }\n\n /**\n * Adds a layer instance on top of the layer stack.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.dense({units: 8, inputShape: [1]}));\n * model.add(tf.layers.dense({units: 4, activation: 'relu6'}));\n * model.add(tf.layers.dense({units: 1, activation: 'relu6'}));\n * // Note that the untrained model is random at this point.\n * model.predict(tf.randomNormal([10, 1])).print();\n * ```\n * @param layer Layer instance.\n *\n * @exception ValueError In case the `layer` argument does not know its\n * input shape.\n * @exception ValueError In case the `layer` argument has multiple output\n * tensors, or is already connected somewhere else (forbidden in\n * `Sequential` models).\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n add(layer: Layer): void {\n const isLayerModelInstance =\n layer instanceof Sequential || layer instanceof LayersModel;\n let modelLayer: LayersModel;\n if (isLayerModelInstance) {\n modelLayer = layer as LayersModel;\n if (modelLayer.outputs.length !== 1) {\n throw new ValueError(\n 'All layers in a Sequential model ' +\n 'should have a single output tensor. ' +\n 'For multi-output layers, ' +\n 'use the functional API.');\n }\n if (modelLayer.inputs.length !== 1) {\n throw new ValueError(\n 'All layers in a Sequential model ' +\n 'should have a single input tensor. ' +\n 'For multi-input layers, ' +\n 'use the functional API.');\n }\n }\n\n if (this.outputs.length === 0) {\n // first layer in model: check that it is an input layer\n if (layer.inboundNodes.length === 0) {\n // create an input layer\n if (layer.batchInputShape == null) {\n throw new ValueError(\n 'The first layer in a Sequential model must ' +\n 'get an `inputShape` or `batchInputShape` argument.');\n }\n // Instantiate the input layer.\n const x = Input({\n batchShape: layer.batchInputShape,\n dtype: layer.dtype,\n name: layer.name + '_input'\n });\n // This will build the current layer and create the node connecting\n // the current layer to the input layer we just created.\n layer.apply(x);\n }\n\n if (isLayerModelInstance) {\n this.outputs = modelLayer.outputs;\n this.inputs = modelLayer.inputs;\n } else {\n if (layer.inboundNodes.length !== 1) {\n throw new ValueError(\n 'A layer added to a Sequential model must not already be ' +\n `connected somewhere else. LayersModel received layer ${\n layer.name} ` +\n `which has ${layer.inboundNodes.length} pre-existing inbound ` +\n 'connections.');\n }\n\n if (layer.inboundNodes[0].outputTensors.length !== 1) {\n throw new ValueError(\n 'All layers in a Sequential model ' +\n 'should have a single output tensor. ' +\n 'For multi-output layers, ' +\n 'use the functional API.');\n }\n this.checkShape(layer);\n this.outputs = [layer.inboundNodes[0].outputTensors[0]];\n this.inputs = getSourceInputs(this.outputs[0]);\n }\n\n this.inboundNodes = [];\n // We create an input node, which we will keep updated\n // as we add more layers.\n // (This call has side effects.)\n // tslint:disable-next-line:no-unused-expression\n new Node({\n outboundLayer: this,\n inboundLayers: [],\n nodeIndices: [],\n tensorIndices: [],\n inputTensors: this.inputs,\n outputTensors: this.outputs,\n // no model-level masking for now\n inputMasks: generic_utils.pyListRepeat(null, this.inputs.length),\n outputMasks: [null],\n inputShapes: this.inputs.map(x => x.shape),\n outputShapes: this.outputs[0].shape\n });\n } else {\n const outputTensor = layer.apply(this.outputs[0]);\n if (Array.isArray(outputTensor)) {\n throw new TypeError(\n 'All layers in a Sequential model ' +\n 'should have a single output tensor. ' +\n 'For multi-output layers, ' +\n 'use the functional API.');\n }\n this.checkShape(layer);\n this.outputs = [outputTensor as SymbolicTensor];\n // update self.inbound_nodes\n this.inboundNodes[0].outputTensors = this.outputs;\n this.inboundNodes[0].outputShapes = [this.outputs[0].shape];\n }\n\n this.layers.push(layer);\n this.built = false;\n }\n\n /**\n * Removes the last layer in the model.\n *\n * @exception TypeError if there are no layers in the model.\n */\n pop(): void {\n if (this.layers.length === 0) {\n throw new TypeError('There are no layers in the model.');\n }\n\n this.layers.pop();\n if (this.layers.length === 0) {\n this.outputs = [];\n this.inboundNodes = [];\n this.outboundNodes = [];\n } else {\n const lastLayerIndex = this.layers.length - 1;\n this.layers[lastLayerIndex].outboundNodes = [];\n this.outputs = [this.layers[lastLayerIndex].output as SymbolicTensor];\n // update self.inbound_nodes\n this.inboundNodes[0].outputTensors = this.outputs;\n this.inboundNodes[0].outputShapes = [this.outputs[0].shape];\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n if (this.model == null) {\n this.build();\n }\n return this.model.call(inputs, kwargs);\n }\n\n build(inputShape?: Shape|Shape[]) {\n // Call `getExactlyOneShape` without using its return value,\n // to verify that exactly one input shape is provided.\n getExactlyOneShape(inputShape);\n\n if (this.inputs.length === 0 || this.outputs.length === 0) {\n throw new TypeError(\n 'Sequential model cannot be built: model is empty.' +\n ' Add some layers first.');\n }\n // actually create the model\n this.model = new LayersModel({\n inputs: this.inputs,\n outputs: this.outputs[0],\n name: this.name + '_model'\n });\n this.model.trainable = this.trainable;\n\n // mirror model attributes\n this.supportsMasking = this.model.supportsMasking;\n // TODO(michaelterry): Add caches\n this.inputLayers = this.model.inputLayers;\n this.inputLayersNodeIndices = this.model.inputLayersNodeIndices;\n this.inputLayersTensorIndices = this.model.inputLayersTensorIndices;\n this.outputLayers = this.model.outputLayers;\n this.outputLayersNodeIndices = this.model.outputLayersNodeIndices;\n this.outputLayersTensorIndices = this.model.outputLayersTensorIndices;\n this.nodesByDepth = this.model.nodesByDepth;\n this.containerNodes = this.model.containerNodes;\n this.outputNames = this.model.outputNames;\n this.inputNames = this.model.inputNames;\n // TODO(michaelterry): Add feedInputNames, feedInputs, if needed.\n // TODO(michaelterry): Add callbackModel if needed.\n this.built = true;\n }\n\n countParams(): number {\n if (!this.built) {\n this.build();\n }\n return super.countParams();\n }\n\n /**\n * Print a text summary of the Sequential model's layers.\n *\n * The summary includes\n * - Name and type of all layers that comprise the model.\n * - Output shape(s) of the layers\n * - Number of weight parameters of each layer\n * - The total number of trainable and non-trainable parameters of the\n * model.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 100, inputShape: [10], activation: 'relu'}));\n * model.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));\n *\n * model.summary();\n * ```\n *\n * @param lineLength Custom line length, in number of characters.\n * @param positions Custom widths of each of the columns, as either\n * fractions of `lineLength` (e.g., `[0.5, 0.75, 1]`) or absolute number\n * of characters (e.g., `[30, 50, 65]`). Each number corresponds to\n * right-most (i.e., ending) position of a column.\n * @param printFn Custom print function. Can be used to replace the default\n * `console.log`. For example, you can use `x => {}` to mute the printed\n * messages in the console.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n summary(\n lineLength?: number, positions?: number[],\n printFn:\n // tslint:disable-next-line:no-any\n (message?: any, ...optionalParams: any[]) => void = console.log) {\n if (!this.built) {\n this.build();\n }\n super.summary(lineLength, positions, printFn);\n }\n\n /**\n * Sets the weights of the model.\n *\n * @param weights Should be a list of Tensors with shapes and types matching\n * the output of `model.getWeights()`.\n */\n setWeights(weights: Tensor[]): void {\n if (this.model == null) {\n this.build();\n }\n this.model.setWeights(weights);\n }\n\n /**\n * Returns the loss value & metrics values for the model in test mode.\n *\n * Loss and metrics are specified during `compile()`, which needs to happen\n * before calls to `evaluate()`.\n *\n * Computation is done in batches.\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 1, inputShape: [10]})]\n * });\n * model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});\n * const result = model.evaluate(tf.ones([8, 10]), tf.ones([8, 1]), {\n * batchSize: 4,\n * });\n * result.print();\n * ```\n *\n * @param x `tf.Tensor` of test data, or an `Array` of `tf.Tensor`s if the\n * model has multiple inputs.\n * @param y `tf.Tensor` of target data, or an `Array` of `tf.Tensor`s if the\n * model has multiple outputs.\n * @param args A `ModelEvaluateConfig`, containing optional fields.\n *\n * @return `Scalar` test loss (if the model has a single output and no\n * metrics) or `Array` of `Scalar`s (if the model has multiple outputs\n * and/or metrics). The attribute `model.metricsNames`\n * will give you the display labels for the scalar outputs.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n evaluate(\n x: Tensor|Tensor[], y: Tensor|Tensor[],\n args: ModelEvaluateArgs = {}): Scalar|Scalar[] {\n if (!this.built) {\n throw new RuntimeError(\n 'The model needs to be compiled before being used.');\n }\n return this.model.evaluate(x, y, args);\n }\n\n // TODO(cais): Add code snippet below once real dataset objects are\n // available.\n /**\n * Evaluate model using a dataset object.\n *\n * Note: Unlike `evaluate()`, this method is asynchronous (`async`);\n *\n * @param dataset A dataset object. Its `iterator()` method is expected\n * to generate a dataset iterator object, the `next()` method of which\n * is expected to produce data batches for evaluation. The return value\n * of the `next()` call ought to contain a boolean `done` field and a\n * `value` field. The `value` field is expected to be an array of two\n * `tf.Tensor`s or an array of two nested `tf.Tensor` structures. The former\n * case is for models with exactly one input and one output (e.g..\n * a sequential model). The latter case is for models with multiple\n * inputs and/or multiple outputs. Of the two items in the array, the\n * first is the input feature(s) and the second is the output target(s).\n * @param args A configuration object for the dataset-based evaluation.\n * @returns Loss and metric values as an Array of `Scalar` objects.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async evaluateDataset(dataset: Dataset<{}>, args: ModelEvaluateDatasetArgs):\n Promise<Scalar|Scalar[]> {\n if (!this.built) {\n throw new RuntimeError(\n 'The model needs to be compiled before being used.');\n }\n return this.model.evaluateDataset(dataset, args);\n }\n\n /**\n * Generates output predictions for the input samples.\n *\n * Computation is done in batches.\n *\n * Note: the \"step\" mode of predict() is currently not supported.\n * This is because the TensorFow.js core backend is imperative only.\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 1, inputShape: [10]})]\n * });\n * model.predict(tf.ones([2, 10])).print();\n * ```\n *\n * @param x The input data, as a Tensor, or an `Array` of `tf.Tensor`s if\n * the model has multiple inputs.\n * @param conifg A `ModelPredictConfig` object containing optional fields.\n *\n * @return `tf.Tensor`(s) of predictions.\n *\n * @exception ValueError In case of mismatch between the provided input data\n * and the model's expectations, or in case a stateful model receives a\n * number of samples that is not a multiple of the batch size.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n predict(x: Tensor|Tensor[], args: ModelPredictArgs = {}): Tensor|Tensor[] {\n if (this.model == null) {\n this.build();\n }\n return this.model.predict(x, args);\n }\n\n /**\n * Returns predictions for a single batch of samples.\n *\n * @param x: Input samples, as a Tensor, or list of Tensors (if the model\n * has multiple inputs).\n * @return Tensor(s) of predictions\n */\n predictOnBatch(x: Tensor): Tensor|Tensor[] {\n if (this.model == null) {\n this.build();\n }\n return this.model.predictOnBatch(x);\n }\n\n /**\n * See `LayersModel.compile`.\n *\n * @param args\n */\n compile(args: ModelCompileArgs): void {\n this.build();\n this.model.compile(args);\n this.optimizer_ = this.model.optimizer;\n // tslint:disable-next-line:no-any\n this.isOptimizerOwned = (this.model as any).isOptimizerOwned;\n this.loss = this.model.loss;\n this.metrics = this.model.metrics;\n // TODO(cais): Add this.lossWeights, this.sampleWeightMode,\n // this.weightedMetrics, this.targets.\n this.metricsTensors = this.model.metricsTensors;\n this.metricsNames = this.model.metricsNames;\n // TODO(cais): Add sampleWeights.\n }\n\n get optimizer(): Optimizer {\n return this.model == null ? undefined : this.model.optimizer;\n }\n\n set optimizer(optimizer: Optimizer) {\n this.model.optimizer = optimizer;\n }\n\n /**\n * Trains the model for a fixed number of epochs (iterations on a dataset).\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 1, inputShape: [10]})]\n * });\n * model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});\n * const history = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {\n * batchSize: 4,\n * epochs: 3\n * });\n * console.log(history.history.loss[0]);\n * ```\n *\n * @param x `tf.Tensor` of training data, or an array of `tf.Tensor`s if the\n * model has multiple inputs. If all inputs in the model are named, you can\n * also pass a dictionary mapping input names to `tf.Tensor`s.\n * @param y `tf.Tensor` of target (label) data, or an array of `tf.Tensor`s if\n * the model has multiple outputs. If all outputs in the model are named, you\n * can also pass a dictionary mapping output names to `tf.Tensor`s.\n * @param args A `ModelFitConfig`, containing optional fields.\n *\n * @return A `History` instance. Its `history` attribute contains all\n * information collected during training.\n *\n * @exception ValueError In case of mismatch between the provided input data\n * and what the model expects.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async fit(\n x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|{[inputName: string]: Tensor},\n args: ModelFitArgs = {}): Promise<History> {\n if (!this.built) {\n throw new RuntimeError(\n 'The model needs to be compiled before ' +\n 'being used.');\n }\n return this.model.fit(x, y, args);\n }\n\n /**\n * Trains the model using a dataset object.\n *\n * ```js\n * const xArray = [\n * [1, 1, 1, 1, 1, 1, 1, 1, 1],\n * [1, 1, 1, 1, 1, 1, 1, 1, 1],\n * [1, 1, 1, 1, 1, 1, 1, 1, 1],\n * [1, 1, 1, 1, 1, 1, 1, 1, 1],\n * ];\n * const yArray = [1, 1, 1, 1];\n * // Create a dataset from the JavaScript array.\n * const xDataset = tf.data.array(xArray);\n * const yDataset = tf.data.array(yArray);\n * // Zip combines the `x` and `y` Datasets into a single Dataset, the\n * // iterator of which will return an object containing of two tensors,\n * // corresponding to `x` and `y`. The call to `batch(4)` will bundle\n * // four such samples into a single object, with the same keys now pointing\n * // to tensors that hold 4 examples, organized along the batch dimension.\n * // The call to `shuffle(4)` causes each iteration through the dataset to\n * // happen in a different order. The size of the shuffle window is 4.\n * const xyDataset = tf.data.zip({xs: xDataset, ys: yDataset})\n * .batch(4)\n * .shuffle(4);\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 1, inputShape: [9]})]\n * });\n * model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});\n * const history = await model.fitDataset(xyDataset, {\n * epochs: 4,\n * callbacks: {onEpochEnd: (epoch, logs) => console.log(logs.loss)}\n * });\n * ```\n *\n * @param dataset A dataset object. Its `iterator()` method is expected to\n * generate a dataset iterator object, the `next()` method of which is\n * expected to produce data batches for evaluation. The return value of the\n * `next()` call ought to contain a boolean `done` field and a `value`\n * field.\n *\n * The `value` field is expected to be an object of with fields\n * `xs` and `ys`, which point to the feature tensor and the target tensor,\n * respectively. This case is for models with exactly one input and one\n * output (e.g.. a sequential model). For example:\n * ```js\n * {value: {xs: xsTensor, ys: ysTensor}, done: false}\n * ```\n *\n * If the model has multiple inputs, the `xs` field of `value` should\n * be an object mapping input names to their respective feature tensors.\n * For example:\n * ```js\n * {\n * value: {\n * xs: {\n * input_1: xsTensor1,\n * input_2: xsTensor2\n * },\n * ys: ysTensor\n * },\n * done: false\n * }\n * ```\n * If the model has multiple outputs, the `ys` field of `value` should\n * be an object mapping output names to their respective target tensors.\n * For example:\n * ```js\n * {\n * value: {\n * xs: xsTensor,\n * ys: {\n * output_1: ysTensor1,\n * output_2: ysTensor2\n * },\n * },\n * done: false\n * }\n * ```\n * @param args A `ModelFitDatasetArgs`, containing optional fields.\n *\n * @return A `History` instance. Its `history` attribute contains all\n * information collected during training.\n *\n * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}\n */\n async fitDataset<T>(dataset: Dataset<T>, args: ModelFitDatasetArgs<T>):\n Promise<History> {\n if (!this.built) {\n throw new RuntimeError(\n 'The model needs to be compiled before ' +\n 'being used.');\n }\n return this.model.fitDataset(dataset, args);\n }\n\n /**\n * Runs a single gradient update on a single batch of data.\n *\n * This method differs from `fit()` and `fitDataset()` in the following\n * regards:\n * - It operates on exactly one batch of data.\n * - It returns only the loss and matric values, instead of\n * returning the batch-by-batch loss and metric values.\n * - It doesn't support fine-grained options such as verbosity and\n * callbacks.\n *\n * @param x Input data. It could be one of the following:\n * - A `tf.Tensor`, or an Array of `tf.Tensor`s (in case the model has\n * multiple inputs).\n * - An Object mapping input names to corresponding `tf.Tensor` (if the\n * model has named inputs).\n * @param y Target darta. It could be either a `tf.Tensor` a multiple\n * `tf.Tensor`s. It should be consistent with `x`.\n * @returns Training loss or losses (in case the model has\n * multiple outputs), along with metrics (if any), as numbers.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n async trainOnBatch(\n x: Tensor|Tensor[]|{[inputName: string]: Tensor},\n y: Tensor|Tensor[]|\n {[inputName: string]: Tensor}): Promise<number|number[]> {\n return this.model.trainOnBatch(x, y);\n }\n\n /* See parent class for JsDoc */\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict,\n customObjects = {} as serialization.ConfigDict,\n fastWeightInit = false): T {\n let configArray: serialization.ConfigDictArray;\n let extraModelConfig: serialization.ConfigDict = {};\n if (config instanceof Array) {\n if (!(config[0].className != null) ||\n config[0]['className'] === 'Merge') {\n throw new ValueError('Legacy serialization format not supported yet.');\n }\n configArray = config;\n } else {\n util.assert(\n config['layers'] != null,\n () =>\n `When the config data for a Sequential model is not an Array, ` +\n `it must be an Object that contains the 'layers' field.`);\n configArray = config['layers'] as serialization.ConfigDictArray;\n delete config['layers'];\n extraModelConfig = config;\n }\n\n const model = new cls(extraModelConfig);\n if (!(model instanceof Sequential)) {\n throw new NotImplementedError(\n `Sequential.fromConfig called on non-Sequential input: ${model}`);\n }\n for (const conf of configArray) {\n const customObjects: serialization.ConfigDict = undefined;\n const layer = deserialize(\n conf as serialization.ConfigDict, customObjects,\n fastWeightInit) as Layer;\n if (fastWeightInit) {\n layer.setFastWeightInitDuringBuild(true);\n }\n model.add(layer);\n }\n return model;\n }\n\n /**\n * Setter used for force stopping of LayersModel.fit() (i.e., training).\n *\n * Example:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.dense({units: 1, inputShape: [10]}));\n * model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});\n * const xs = tf.ones([8, 10]);\n * const ys = tf.zeros([8, 1]);\n *\n * const history = await model.fit(xs, ys, {\n * epochs: 10,\n * callbacks: {\n * onEpochEnd: async (epoch, logs) => {\n * if (epoch === 2) {\n * model.stopTraining = true;\n * }\n * }\n * }\n * });\n *\n * // There should be only 3 values in the loss array, instead of 10 values,\n * // due to the stopping after 3 epochs.\n * console.log(history.history.loss);\n * ```\n */\n set stopTraining(stop: boolean) {\n // TODO(cais): When refactoring to remove the composition pattern happens,\n // remove this method overriding.\n if (this.model == null) {\n throw new ValueError(\n 'Cannot set the stopTraining property of a sequential model before ' +\n 'it is compiled.');\n }\n this.model.stopTraining = stop;\n }\n\n get stopTraining(): boolean {\n if (this.model == null) {\n throw new ValueError(\n 'Cannot get the stopTraining property of a sequential model before ' +\n 'it is compiled.');\n }\n return this.model.stopTraining;\n }\n\n // TODO(cais): Override get trainableWeights() here\n\n // tslint:disable-next-line:no-any\n getConfig(): any {\n // NOTE(cais): We override the return type of getConfig() to `any` here,\n // because the `Sequential` class is a special case among `Container`\n // subtypes in that its getConfig() method returns an Array (not a\n // dict).\n const layers: serialization.ConfigDict[] = [];\n for (const layer of this.layers) {\n const dict: serialization.ConfigDict = {};\n dict['className'] = layer.getClassName();\n dict['config'] = layer.getConfig();\n layers.push(dict);\n }\n return {name: this.name, layers};\n }\n}\nserialization.registerClass(Sequential);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Exported functions.\n */\n\nimport {io} from '@tensorflow/tfjs-core';\n\nimport {BaseCallbackConstructor, CallbackConstructorRegistry} from './base_callbacks';\nimport {ContainerArgs} from './engine/container';\nimport {Input, InputConfig,} from './engine/input_layer';\nimport {SymbolicTensor} from './engine/topology';\nimport {LayersModel} from './engine/training';\nimport {loadLayersModelInternal, Sequential, SequentialArgs} from './models';\n\n// TODO(cais): Add doc string to all the public static functions in this\n// class; include exectuable JavaScript code snippets where applicable\n// (b/74074458).\n\n// LayersModel and related factory methods.\n\n/**\n * A model is a data structure that consists of `Layers` and defines inputs\n * and outputs.\n *\n * The key difference between `tf.model` and `tf.sequential` is that\n * `tf.model` is more generic, supporting an arbitrary graph (without\n * cycles) of layers. `tf.sequential` is less generic and supports only a linear\n * stack of layers.\n *\n * When creating a `tf.LayersModel`, specify its input(s) and output(s). Layers\n * are used to wire input(s) to output(s).\n *\n * For example, the following code snippet defines a model consisting of\n * two `dense` layers, with 10 and 4 units, respectively.\n *\n * ```js\n * // Define input, which has a size of 5 (not including batch dimension).\n * const input = tf.input({shape: [5]});\n *\n * // First dense layer uses relu activation.\n * const denseLayer1 = tf.layers.dense({units: 10, activation: 'relu'});\n * // Second dense layer uses softmax activation.\n * const denseLayer2 = tf.layers.dense({units: 4, activation: 'softmax'});\n *\n * // Obtain the output symbolic tensor by applying the layers on the input.\n * const output = denseLayer2.apply(denseLayer1.apply(input));\n *\n * // Create the model based on the inputs.\n * const model = tf.model({inputs: input, outputs: output});\n *\n * // The model can be used for training, evaluation and prediction.\n * // For example, the following line runs prediction with the model on\n * // some fake data.\n * model.predict(tf.ones([2, 5])).print();\n * ```\n * See also:\n * `tf.sequential`, `tf.loadLayersModel`.\n *\n * @doc {heading: 'Models', subheading: 'Creation'}\n */\nexport function model(args: ContainerArgs): LayersModel {\n return new LayersModel(args);\n}\n\n/**\n * Creates a `tf.Sequential` model. A sequential model is any model where the\n * outputs of one layer are the inputs to the next layer, i.e. the model\n * topology is a simple 'stack' of layers, with no branching or skipping.\n *\n * This means that the first layer passed to a `tf.Sequential` model should have\n * a defined input shape. What that means is that it should have received an\n * `inputShape` or `batchInputShape` argument, or for some type of layers\n * (recurrent, Dense...) an `inputDim` argument.\n *\n * The key difference between `tf.model` and `tf.sequential` is that\n * `tf.sequential` is less generic, supporting only a linear stack of layers.\n * `tf.model` is more generic and supports an arbitrary graph (without\n * cycles) of layers.\n *\n * Examples:\n *\n * ```js\n * const model = tf.sequential();\n *\n * // First layer must have an input shape defined.\n * model.add(tf.layers.dense({units: 32, inputShape: [50]}));\n * // Afterwards, TF.js does automatic shape inference.\n * model.add(tf.layers.dense({units: 4}));\n *\n * // Inspect the inferred shape of the model's output, which equals\n * // `[null, 4]`. The 1st dimension is the undetermined batch dimension; the\n * // 2nd is the output size of the model's last layer.\n * console.log(JSON.stringify(model.outputs[0].shape));\n * ```\n *\n * It is also possible to specify a batch size (with potentially undetermined\n * batch dimension, denoted by \"null\") for the first layer using the\n * `batchInputShape` key. The following example is equivalent to the above:\n *\n * ```js\n * const model = tf.sequential();\n *\n * // First layer must have a defined input shape\n * model.add(tf.layers.dense({units: 32, batchInputShape: [null, 50]}));\n * // Afterwards, TF.js does automatic shape inference.\n * model.add(tf.layers.dense({units: 4}));\n *\n * // Inspect the inferred shape of the model's output.\n * console.log(JSON.stringify(model.outputs[0].shape));\n * ```\n *\n * You can also use an `Array` of already-constructed `Layer`s to create\n * a `tf.Sequential` model:\n *\n * ```js\n * const model = tf.sequential({\n * layers: [tf.layers.dense({units: 32, inputShape: [50]}),\n * tf.layers.dense({units: 4})]\n * });\n * console.log(JSON.stringify(model.outputs[0].shape));\n * ```\n *\n * @doc {heading: 'Models', subheading: 'Creation'}\n */\nexport function sequential(config?: SequentialArgs): Sequential {\n return new Sequential(config);\n}\n\n/**\n * Load a model composed of Layer objects, including its topology and optionally\n * weights. See the Tutorial named \"How to import a Keras Model\" for usage\n * examples.\n *\n * This method is applicable to:\n *\n * 1. Models created with the `tf.layers.*`, `tf.sequential`, and\n * `tf.model` APIs of TensorFlow.js and later saved with the\n * `tf.LayersModel.save` method.\n * 2. Models converted from Keras or TensorFlow tf.keras using the\n * [tensorflowjs_converter](https://github.com/tensorflow/tfjs/tree/master/tfjs-converter).\n *\n * This mode is *not* applicable to TensorFlow `SavedModel`s or their converted\n * forms. For those models, use `tf.loadGraphModel`.\n *\n * Example 1. Load a model from an HTTP server.\n *\n * ```js\n * const model = await tf.loadLayersModel(\n * 'https://storage.googleapis.com/tfjs-models/tfjs/iris_v1/model.json');\n * model.summary();\n * ```\n *\n * Example 2: 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 model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * console.log('Prediction from original model:');\n * model.predict(tf.ones([1, 3])).print();\n *\n * const saveResults = await model.save('localstorage://my-model-1');\n *\n * const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');\n * console.log('Prediction from loaded model:');\n * loadedModel.predict(tf.ones([1, 3])).print();\n * ```\n *\n * Example 3. Saving `model`'s topology and weights to browser\n * [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API);\n * then load it back.\n *\n * ```js\n * const model = tf.sequential(\n * {layers: [tf.layers.dense({units: 1, inputShape: [3]})]});\n * console.log('Prediction from original model:');\n * model.predict(tf.ones([1, 3])).print();\n *\n * const saveResults = await model.save('indexeddb://my-model-1');\n *\n * const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');\n * console.log('Prediction from loaded model:');\n * loadedModel.predict(tf.ones([1, 3])).print();\n * ```\n *\n * Example 4. Load a model from user-selected files from HTML\n * [file input\n * elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file).\n *\n * ```js\n * // Note: this code snippet will not work without the HTML elements in the\n * // page\n * const jsonUpload = document.getElementById('json-upload');\n * const weightsUpload = document.getElementById('weights-upload');\n *\n * const model = await tf.loadLayersModel(\n * tf.io.browserFiles([jsonUpload.files[0], weightsUpload.files[0]]));\n * ```\n *\n * @param pathOrIOHandler Can be either of the two formats\n * 1. A string path to the `ModelAndWeightsConfig` JSON describing\n * the model in the canonical TensorFlow.js format. For file://\n * (tfjs-node-only), http:// and https:// schemas, the path can be\n * either absolute or relative.\n * 2. An `tf.io.IOHandler` object that loads model artifacts with its `load`\n * method.\n * @param options Optional configuration arguments for the model loading,\n * including:\n * - `strict`: Require that the provided weights exactly match those required\n * by the layers. Default true. Passing false means that both extra\n * weights and missing weights will be silently ignored.\n * - `onProgress`: A function of the signature `(fraction: number) => void',\n * that can be used as the progress callback for the model loading.\n * @returns A `Promise` of `tf.LayersModel`, with the topology and weights\n * loaded.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport function loadLayersModel(\n pathOrIOHandler: string|io.IOHandler,\n options?: io.LoadOptions): Promise<LayersModel> {\n if (options == null) {\n options = {};\n }\n return loadLayersModelInternal(pathOrIOHandler, options);\n}\n\n/**\n * Used to instantiate an input to a model as a `tf.SymbolicTensor`.\n *\n * Users should call the `input` factory function for\n * consistency with other generator functions.\n *\n * Example:\n *\n * ```js\n * // Defines a simple logistic regression model with 32 dimensional input\n * // and 3 dimensional output.\n * const x = tf.input({shape: [32]});\n * const y = tf.layers.dense({units: 3, activation: 'softmax'}).apply(x);\n * const model = tf.model({inputs: x, outputs: y});\n * model.predict(tf.ones([2, 32])).print();\n * ```\n *\n * Note: `input` is only necessary when using `model`. When using\n * `sequential`, specify `inputShape` for the first layer or use `inputLayer`\n * as the first layer.\n *\n * @doc {heading: 'Models', subheading: 'Inputs'}\n */\nexport function input(config: InputConfig): SymbolicTensor {\n return Input(config);\n}\n\nexport function registerCallbackConstructor(\n verbosityLevel: number,\n callbackConstructor: BaseCallbackConstructor): void {\n CallbackConstructorRegistry.registerCallbackConstructor(\n verbosityLevel, callbackConstructor);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n// Layer activation functions\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {serialization, Tensor, tidy} from '@tensorflow/tfjs-core';\nimport * as K from './backend/tfjs_backend';\nimport {ActivationIdentifier} from './keras_format/activation_config';\nimport {deserializeKerasObject} from './utils/generic_utils';\n\n/**\n * Base class for Activations.\n *\n * Special note: due to cross-language compatibility reasons, the\n * static readonly className field in this family of classes must be set to\n * the initialLowerCamelCase name of the activation.\n */\nexport abstract class Activation extends serialization.Serializable {\n abstract apply(tensor: Tensor, axis?: number): Tensor;\n getConfig(): serialization.ConfigDict {\n return {};\n }\n}\n\n/**\n * Exponential linear unit (ELU).\n * Reference: https://arxiv.org/abs/1511.07289\n */\nexport class Elu extends Activation {\n /** @nocollapse */\n static readonly className = 'elu';\n /**\n * Calculate the activation function.\n *\n * @param x: Input.\n * @param alpha: Scaling factor the negative section.\n * @return Output of the ELU activation.\n */\n apply(x: Tensor, alpha = 1): Tensor {\n return K.elu(x, alpha);\n }\n}\nserialization.registerClass(Elu);\n\n/**\n * Scaled Exponential Linear Unit. (Klambauer et al., 2017).\n * Reference: Self-Normalizing Neural Networks, https://arxiv.org/abs/1706.02515\n * Notes:\n * - To be used together with the initialization \"lecunNormal\".\n * - To be used together with the dropout variant \"AlphaDropout\".\n */\nexport class Selu extends Activation {\n /** @nocollapse */\n static readonly className = 'selu';\n apply(x: Tensor): Tensor {\n return tfc.selu(x);\n }\n}\nserialization.registerClass(Selu);\n\n/**\n * Rectified linear unit\n */\nexport class Relu extends Activation {\n /** @nocollapse */\n static readonly className = 'relu';\n apply(x: Tensor): Tensor {\n return tfc.relu(x);\n }\n}\nserialization.registerClass(Relu);\n\n/**\n * Rectified linear unit activation maxing out at 6.0.\n */\nexport class Relu6 extends Activation {\n /** @nocollapse */\n static readonly className = 'relu6';\n apply(x: Tensor): Tensor {\n return tidy(() => tfc.minimum(6.0, tfc.relu(x)));\n }\n}\nserialization.registerClass(Relu6);\n\n//* Linear activation (no-op) */\nexport class Linear extends Activation {\n /** @nocollapse */\n static readonly className = 'linear';\n apply(x: Tensor): Tensor {\n return x;\n }\n}\nserialization.registerClass(Linear);\n\n/**\n * Sigmoid activation function.\n */\nexport class Sigmoid extends Activation {\n /** @nocollapse */\n static readonly className = 'sigmoid';\n apply(x: Tensor): Tensor {\n return tfc.sigmoid(x);\n }\n}\nserialization.registerClass(Sigmoid);\n\n/**\n * Segment-wise linear approximation of sigmoid.\n */\nexport class HardSigmoid extends Activation {\n /** @nocollapse */\n static readonly className = 'hardSigmoid';\n apply(x: Tensor): Tensor {\n return K.hardSigmoid(x);\n }\n}\nserialization.registerClass(HardSigmoid);\n\n/**\n * Softplus activation function.\n */\nexport class Softplus extends Activation {\n /** @nocollapse */\n static readonly className = 'softplus';\n apply(x: Tensor): Tensor {\n return tfc.softplus(x);\n }\n}\nserialization.registerClass(Softplus);\n\n/**\n * Softsign activation function.\n */\nexport class Softsign extends Activation {\n /** @nocollapse */\n static readonly className = 'softsign';\n apply(x: Tensor): Tensor {\n return K.softsign(x);\n }\n}\nserialization.registerClass(Softsign);\n\n/**\n * Hyperbolic tangent function.\n */\nexport class Tanh extends Activation {\n /** @nocollapse */\n static readonly className = 'tanh';\n apply(x: Tensor): Tensor {\n return tfc.tanh(x);\n }\n}\nserialization.registerClass(Tanh);\n\n/**\n * Softmax activation function\n */\nexport class Softmax extends Activation {\n /** @nocollapse */\n static readonly className = 'softmax';\n /**\n * Calculate the activation function.\n *\n * @param x Tensor.\n * @param axis Integer, axis along which the softmax normalization is applied.\n * Invalid if < 2, as softmax across 1 (the batch dimension) is assumed to be\n * an error.\n *\n * @returns a Tensor of the same shape as x\n *\n * @throws ValueError: In case `dim(x) < 2`.\n */\n apply(x: Tensor, axis: number = (-1)): Tensor {\n return tfc.softmax(x, axis);\n }\n}\nserialization.registerClass(Softmax);\n\n/**\n * Log softmax activation function\n */\nexport class LogSoftmax extends Activation {\n /** @nocollapse */\n static readonly className = 'logSoftmax';\n /**\n * Calculate the activation function of log softmax:\n * log( exp(x_i) / sum(exp(x)) )\n *\n * @param x Tensor.\n * @param axis Integer, axis along which the softmax normalization is applied.\n * Invalid if < 2, as softmax across 1 (the batch dimension) is assumed to be\n * an error.\n *\n * @returns a Tensor of the same shape as x\n *\n * @throws ValueError: In case `dim(x) < 2`.\n */\n apply(x: Tensor, axis: number = (-1)): Tensor {\n return tfc.logSoftmax(x, axis);\n }\n}\nserialization.registerClass(LogSoftmax);\n\n/**\n * Swish activation function\n */\nexport class Swish extends Activation {\n /** @nocollapse */\n static readonly className = 'swish';\n /**\n * Calculate the activation function.\n *\n * @param x Tensor.\n * @param alpha Scaling factor for the sigmoid function.\n * @returns a Tensor of the same shape as x\n */\n apply(x: Tensor, alpha = 1): Tensor {\n return tidy(() => tfc.mul(tfc.sigmoid(tfc.mul(x, alpha)), x));\n }\n}\nserialization.registerClass(Swish);\n\n/**\n * Mish activation function\n */\nexport class Mish extends Activation {\n /** @nocollapse */\n static readonly className = 'mish';\n /**\n * Calculate the activation function.\n *\n * @param x Tensor.\n * @returns a Tensor of the same shape as x\n */\n apply(x: Tensor): Tensor {\n return tidy(() => tfc.mul(x, tfc.tanh(tfc.softplus(x))));\n }\n}\nserialization.registerClass(Mish);\n\nexport function serializeActivation(activation: Activation): string {\n return activation.getClassName();\n}\n\nexport function deserializeActivation(\n config: serialization.ConfigDict,\n customObjects: serialization.ConfigDict = {}): Activation {\n return deserializeKerasObject(\n config, serialization.SerializationMap.getMap().classNameMap,\n customObjects, 'activation');\n}\n\nexport function getActivation(identifier: ActivationIdentifier|\n serialization.ConfigDict|Activation): Activation {\n if (identifier == null) {\n const config: serialization.ConfigDict = {};\n config['className'] = 'linear';\n config['config'] = {};\n return deserializeActivation(config);\n }\n if (typeof identifier === 'string') {\n const config: serialization.ConfigDict = {};\n config['className'] = identifier;\n config['config'] = {};\n return deserializeActivation(config);\n } else if (identifier instanceof Activation) {\n return identifier;\n } else {\n return deserializeActivation(identifier);\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* original source: keras/regularizers.py */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {abs, add, Scalar, serialization, sum, Tensor, tidy, zeros} from '@tensorflow/tfjs-core';\nimport * as K from './backend/tfjs_backend';\nimport {deserializeKerasObject, serializeKerasObject} from './utils/generic_utils';\n\nfunction assertObjectArgs(args: L1Args|L2Args|L1L2Args): void {\n if (args != null && typeof args !== 'object') {\n throw new Error(\n `Argument to L1L2 regularizer's constructor is expected to be an ` +\n `object, but received: ${args}`);\n }\n}\n\n/**\n * Regularizer base class.\n */\nexport abstract class Regularizer extends serialization.Serializable {\n abstract apply(x: Tensor): Scalar;\n}\n\nexport interface L1L2Args {\n /** L1 regularization rate. Defaults to 0.01. */\n l1?: number;\n /** L2 regularization rate. Defaults to 0.01. */\n l2?: number;\n}\n\nexport interface L1Args {\n /** L1 regularization rate. Defaults to 0.01. */\n l1: number;\n}\n\nexport interface L2Args {\n /** L2 regularization rate. Defaults to 0.01. */\n l2: number;\n}\n\nexport class L1L2 extends Regularizer {\n /** @nocollapse */\n static className = 'L1L2';\n\n private readonly l1: number;\n private readonly l2: number;\n private readonly hasL1: boolean;\n private readonly hasL2: boolean;\n constructor(args?: L1L2Args) {\n super();\n\n assertObjectArgs(args);\n\n this.l1 = args == null || args.l1 == null ? 0.01 : args.l1;\n this.l2 = args == null || args.l2 == null ? 0.01 : args.l2;\n this.hasL1 = this.l1 !== 0;\n this.hasL2 = this.l2 !== 0;\n }\n\n /**\n * Porting note: Renamed from __call__.\n * @param x Variable of which to calculate the regularization score.\n */\n apply(x: Tensor): Scalar {\n return tidy(() => {\n let regularization: Tensor = zeros([1]);\n if (this.hasL1) {\n regularization = add(regularization, sum(tfc.mul(this.l1, abs(x))));\n }\n if (this.hasL2) {\n regularization =\n add(regularization, sum(tfc.mul(this.l2, K.square(x))));\n }\n return tfc.reshape(regularization, []);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n return {'l1': this.l1, 'l2': this.l2};\n }\n\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict): T {\n return new cls({l1: config['l1'] as number, l2: config['l2'] as number});\n }\n}\nserialization.registerClass(L1L2);\n\nexport function l1(args?: L1Args) {\n assertObjectArgs(args);\n return new L1L2({l1: args != null ? args.l1 : null, l2: 0});\n}\n\nexport function l2(args: L2Args) {\n assertObjectArgs(args);\n return new L1L2({l2: args != null ? args.l2 : null, l1: 0});\n}\n\n/** @docinline */\nexport type RegularizerIdentifier = 'l1l2'|string;\n\n// Maps the JavaScript-like identifier keys to the corresponding keras symbols.\nexport const REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP:\n {[identifier in RegularizerIdentifier]: string} = {\n 'l1l2': 'L1L2'\n };\n\nexport function serializeRegularizer(constraint: Regularizer):\n serialization.ConfigDictValue {\n return serializeKerasObject(constraint);\n}\n\nexport function deserializeRegularizer(\n config: serialization.ConfigDict,\n customObjects: serialization.ConfigDict = {}): Regularizer {\n return deserializeKerasObject(\n config, serialization.SerializationMap.getMap().classNameMap,\n customObjects, 'regularizer');\n}\n\nexport function getRegularizer(identifier: RegularizerIdentifier|\n serialization.ConfigDict|\n Regularizer): Regularizer {\n if (identifier == null) {\n return null;\n }\n if (typeof identifier === 'string') {\n const className = identifier in REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ?\n REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[identifier] :\n identifier;\n const config = {className, config: {}};\n return deserializeRegularizer(config);\n } else if (identifier instanceof Regularizer) {\n return identifier;\n } else {\n return deserializeRegularizer(identifier);\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Advanced activation layers.\n */\n\nimport {cast, clipByValue, elu, greater, leakyRelu, mul, prelu, relu, serialization, Tensor} from '@tensorflow/tfjs-core';\n\nimport {Softmax as softmaxActivation} from '../activations';\nimport {Constraint, getConstraint, serializeConstraint} from '../constraints';\nimport {InputSpec, Layer, LayerArgs} from '../engine/topology';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {getInitializer, Initializer, InitializerIdentifier, serializeInitializer} from '../initializers';\nimport {Shape} from '../keras_format/common';\nimport {getRegularizer, Regularizer, serializeRegularizer} from '../regularizers';\nimport {Kwargs} from '../types';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\nimport {LayerVariable} from '../variables';\n\nexport declare interface ReLULayerArgs extends LayerArgs {\n /**\n * Float, the maximum output value.\n */\n maxValue?: number;\n}\n\nexport class ReLU extends Layer {\n /** @nocollapse */\n static className = 'ReLU';\n maxValue: number;\n\n constructor(args?: ReLULayerArgs) {\n super(args == null ? {} : args);\n this.supportsMasking = true;\n if (args != null) {\n this.maxValue = args.maxValue;\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n inputs = getExactlyOneTensor(inputs);\n let output = relu(inputs);\n if (this.maxValue != null) {\n output = clipByValue(output, 0, this.maxValue);\n }\n return output;\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {maxValue: this.maxValue};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(ReLU);\n\nexport declare interface LeakyReLULayerArgs extends LayerArgs {\n /**\n * Float `>= 0`. Negative slope coefficient. Defaults to `0.3`.\n */\n alpha?: number;\n}\n\nexport class LeakyReLU extends Layer {\n /** @nocollapse */\n static className = 'LeakyReLU';\n readonly alpha: number;\n\n readonly DEFAULT_ALPHA = 0.3;\n\n constructor(args?: LeakyReLULayerArgs) {\n super(args == null ? {} : args);\n if (args == null) {\n args = {};\n }\n this.alpha = args.alpha == null ? this.DEFAULT_ALPHA : args.alpha;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n const x = getExactlyOneTensor(inputs);\n return leakyRelu(x, this.alpha);\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {alpha: this.alpha};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(LeakyReLU);\n\nexport declare interface PReLULayerArgs extends LayerArgs {\n /**\n * Initializer for the learnable alpha.\n */\n alphaInitializer?: Initializer|InitializerIdentifier;\n\n /**\n * Regularizer for the learnable alpha.\n */\n alphaRegularizer?: Regularizer;\n\n /**\n * Constraint for the learnable alpha.\n */\n alphaConstraint?: Constraint;\n\n /**\n * The axes along which to share learnable parameters for the activation\n * function. For example, if the incoming feature maps are from a 2D\n * convolution with output shape `[numExamples, height, width, channels]`,\n * and you wish to share parameters across space (height and width) so that\n * each filter channels has only one set of parameters, set\n * `shared_axes: [1, 2]`.\n */\n sharedAxes?: number|number[];\n}\n\nexport class PReLU extends Layer {\n /** @nocollapse */\n static className = 'PReLU';\n private readonly alphaInitializer: Initializer;\n private readonly alphaRegularizer: Regularizer;\n private readonly alphaConstraint: Constraint;\n private readonly sharedAxes: number[];\n private alpha: LayerVariable;\n\n readonly DEFAULT_ALPHA_INITIALIZER: InitializerIdentifier = 'zeros';\n\n constructor(args?: PReLULayerArgs) {\n super(args == null ? {} : args);\n if (args == null) {\n args = {};\n }\n\n this.supportsMasking = true;\n this.alphaInitializer =\n getInitializer(args.alphaInitializer || this.DEFAULT_ALPHA_INITIALIZER);\n this.alphaRegularizer = getRegularizer(args.alphaRegularizer);\n this.alphaConstraint = getConstraint(args.alphaConstraint);\n if (args.sharedAxes == null) {\n this.sharedAxes = null;\n } else if (Array.isArray(args.sharedAxes)) {\n this.sharedAxes = args.sharedAxes;\n } else if (typeof args.sharedAxes === 'number') {\n this.sharedAxes = [args.sharedAxes];\n } else {\n throw new ValueError(\n `Expected sharedAxes to be a number or an array of numbers, ` +\n `but got ${args.sharedAxes}`);\n }\n }\n\n build(inputShape: Shape|Shape[]) {\n inputShape = getExactlyOneShape(inputShape);\n const paramShape: Shape = inputShape.slice(1);\n if (this.sharedAxes != null) {\n for (const i of this.sharedAxes) {\n paramShape[i - 1] = 1;\n }\n }\n this.alpha = this.addWeight(\n 'alpha', paramShape, 'float32', this.alphaInitializer,\n this.alphaRegularizer, true, this.alphaConstraint);\n // Set input spec.\n const axes: {[axis: number]: number} = {};\n if (this.sharedAxes != null) {\n for (let i = 1; i < inputShape.length; ++i) {\n axes[i] = inputShape[i];\n }\n }\n this.inputSpec = [new InputSpec({\n ndim: inputShape.length,\n axes,\n })];\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n inputs = getExactlyOneTensor(inputs);\n return prelu(inputs, this.alpha.read());\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n alphaInitializer: serializeInitializer(this.alphaInitializer),\n alphaRegularizer: serializeRegularizer(this.alphaRegularizer),\n alphaConstraint: serializeConstraint(this.alphaConstraint),\n sharedAxes: this.sharedAxes\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(PReLU);\n\nexport declare interface ELULayerArgs extends LayerArgs {\n /**\n * Float `>= 0`. Negative slope coefficient. Defaults to `1.0`.\n */\n alpha?: number;\n}\n\nexport class ELU extends Layer {\n /** @nocollapse */\n static className = 'ELU';\n readonly alpha: number;\n\n readonly DEFAULT_ALPHA = 1.0;\n\n constructor(args?: ELULayerArgs) {\n super(args == null ? {} : args);\n if (args == null) {\n args = {};\n }\n\n if (args.alpha != null && args.alpha !== this.DEFAULT_ALPHA) {\n throw new NotImplementedError(\n `Non-default alpha value (${args.alpha}) is not supported by the ` +\n `ELU layer yet.`);\n }\n\n this.alpha = args.alpha == null ? this.DEFAULT_ALPHA : args.alpha;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n const x = getExactlyOneTensor(inputs);\n return elu(x);\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {alpha: this.alpha};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(ELU);\n\nexport declare interface ThresholdedReLULayerArgs extends LayerArgs {\n /**\n * Float >= 0. Threshold location of activation.\n */\n theta?: number;\n}\n\nexport class ThresholdedReLU extends Layer {\n /** @nocollapse */\n static className = 'ThresholdedReLU';\n readonly theta: number;\n\n readonly DEFAULT_THETA = 1.0;\n\n constructor(args?: ThresholdedReLULayerArgs) {\n super(args == null ? {} : args);\n if (args == null) {\n args = {};\n }\n\n this.theta = args.theta == null ? this.DEFAULT_THETA : args.theta;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n const x = getExactlyOneTensor(inputs);\n return mul(x, cast(greater(x, this.theta), 'float32'));\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {theta: this.theta};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(ThresholdedReLU);\n\nexport declare interface SoftmaxLayerArgs extends LayerArgs {\n /**\n * Integer, axis along which the softmax normalization is applied.\n * Defaults to `-1` (i.e., the last axis).\n */\n axis?: number;\n}\n\nexport class Softmax extends Layer {\n /** @nocollapse */\n static className = 'Softmax';\n readonly axis: number;\n readonly softmax: (t: Tensor, a?: number) => Tensor;\n readonly DEFAULT_AXIS = 1.0;\n\n constructor(args?: SoftmaxLayerArgs) {\n super(args == null ? {} : args);\n if (args == null) {\n args = {};\n }\n this.softmax = new softmaxActivation().apply;\n this.axis = args.axis == null ? this.DEFAULT_AXIS : args.axis;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n const x = getExactlyOneTensor(inputs);\n return this.softmax(x, this.axis);\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {axis: this.axis};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Softmax);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport {ValueError} from '../errors';\nimport {PaddingMode} from '../keras_format/common';\n\nimport {pyListRepeat} from './generic_utils';\nimport {isInteger, max} from './math_utils';\n\n/**\n * Transforms a single number of array of numbers into an array of numbers.\n * @param value\n * @param n: The size of the tuple to be returned.\n * @param name: Name of the parameter, used for generating error messages.\n * @returns An array of numbers.\n */\nexport function normalizeArray(\n value: number|number[], n: number, name: string): number[] {\n if (typeof value === 'number') {\n return pyListRepeat(value, n);\n } else {\n if (value.length !== n) {\n throw new ValueError(\n `The ${name} argument must be an integer or tuple of ${n} integers.` +\n ` Received: ${value.length} elements.`);\n }\n for (let i = 0; i < n; ++i) {\n const singleValue = value[i];\n if (!isInteger(singleValue)) {\n throw new ValueError(\n `The ${name} argument must be an integer or tuple of ${n}` +\n ` integers. Received: ${JSON.stringify(value)} including a` +\n ` non-integer number ${singleValue}`);\n }\n }\n return value;\n }\n}\n\n/**\n * Determines output length of a convolution given input length.\n * @param inputLength\n * @param filterSize\n * @param padding\n * @param stride\n * @param dilation: dilation rate.\n */\nexport function convOutputLength(\n inputLength: number, filterSize: number, padding: PaddingMode,\n stride: number, dilation = 1): number {\n if (inputLength == null) {\n return inputLength;\n }\n const dilatedFilterSize = filterSize + (filterSize - 1) * (dilation - 1);\n let outputLength: number;\n if (padding === 'same') {\n outputLength = inputLength;\n } else { // VALID\n outputLength = inputLength - dilatedFilterSize + 1;\n }\n return Math.floor((outputLength + stride - 1) / stride);\n}\n\nexport function deconvLength(\n dimSize: number, strideSize: number, kernelSize: number,\n padding: PaddingMode): number {\n if (dimSize == null) {\n return null;\n }\n\n if (padding === 'valid') {\n dimSize = dimSize * strideSize + max([kernelSize - strideSize, 0]);\n } else if (padding === 'same') {\n dimSize = dimSize * strideSize;\n } else {\n throw new ValueError(`Unsupport padding mode: ${padding}.`);\n }\n return dimSize;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * TensorFlow.js Layers: Convolutional Layers\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {fused, serialization, Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D, Tensor5D, tidy} from '@tensorflow/tfjs-core';\n\nimport {Activation, getActivation, serializeActivation} from '../activations';\nimport {imageDataFormat} from '../backend/common';\nimport * as K from '../backend/tfjs_backend';\nimport {checkDataFormat, checkInterpolationFormat, checkPaddingMode} from '../common';\nimport {Constraint, ConstraintIdentifier, getConstraint, serializeConstraint} from '../constraints';\nimport {InputSpec, Layer, LayerArgs} from '../engine/topology';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {getInitializer, Initializer, InitializerIdentifier, serializeInitializer} from '../initializers';\nimport {ActivationIdentifier} from '../keras_format/activation_config';\nimport {DataFormat, InterpolationFormat, PaddingMode, Shape} from '../keras_format/common';\nimport {getRegularizer, Regularizer, RegularizerIdentifier, serializeRegularizer} from '../regularizers';\nimport {Kwargs} from '../types';\nimport {convOutputLength, deconvLength, normalizeArray} from '../utils/conv_utils';\nimport * as generic_utils from '../utils/generic_utils';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\nimport {LayerVariable} from '../variables';\n\n/**\n * Transpose and cast the input before the conv2d.\n * @param x Input image tensor.\n * @param dataFormat\n */\nexport function preprocessConv2DInput(\n x: Tensor, dataFormat: DataFormat): Tensor {\n // TODO(cais): Cast type to float32 if not.\n return tidy(() => {\n checkDataFormat(dataFormat);\n if (dataFormat === 'channelsFirst') {\n return tfc.transpose(x, [0, 2, 3, 1]); // NCHW -> NHWC.\n } else {\n return x;\n }\n });\n}\n\n/**\n * Transpose and cast the input before the conv3d.\n * @param x Input image tensor.\n * @param dataFormat\n */\nexport function preprocessConv3DInput(\n x: Tensor, dataFormat: DataFormat): Tensor {\n return tidy(() => {\n checkDataFormat(dataFormat);\n if (dataFormat === 'channelsFirst') {\n return tfc.transpose(x, [0, 2, 3, 4, 1]); // NCDHW -> NDHWC.\n } else {\n return x;\n }\n });\n}\n\n/**\n * 1D-convolution with bias added.\n *\n * Porting Note: This function does not exist in the Python Keras backend.\n * It is exactly the same as `conv2d`, except the added `bias`.\n *\n * @param x Input tensor, rank-3, of shape `[batchSize, width, inChannels]`.\n * @param kernel Kernel, rank-3, of shape `[filterWidth, inDepth, outDepth]`.\n * @param bias Bias, rank-3, of shape `[outDepth]`.\n * @param strides\n * @param padding Padding mode.\n * @param dataFormat Data format.\n * @param dilationRate\n * @returns The result of the 1D convolution.\n * @throws ValueError, if `x`, `kernel` or `bias` is not of the correct rank.\n */\nexport function conv1dWithBias(\n x: Tensor, kernel: Tensor, bias: Tensor, strides = 1, padding = 'valid',\n dataFormat?: DataFormat, dilationRate = 1): Tensor {\n return tidy(() => {\n if (dataFormat == null) {\n dataFormat = imageDataFormat();\n }\n checkDataFormat(dataFormat);\n // Check the ranks of x, kernel and bias.\n if (x.shape.length !== 3) {\n throw new ValueError(\n `The input of a conv1dWithBias operation should be 3, but is ` +\n `${x.shape.length} instead.`);\n }\n if (kernel.shape.length !== 3) {\n throw new ValueError(\n `The kernel for a conv1dWithBias operation should be 3, but is ` +\n `${kernel.shape.length} instead`);\n }\n if (bias != null && bias.shape.length !== 1) {\n throw new ValueError(\n `The bias for a conv1dWithBias operation should be 1, but is ` +\n `${kernel.shape.length} instead`);\n }\n // TODO(cais): Support CAUSAL padding mode.\n if (dataFormat === 'channelsFirst') {\n x = tfc.transpose(x, [0, 2, 1]); // NCW -> NWC.\n }\n if (padding === 'causal') {\n throw new NotImplementedError(\n 'The support for CAUSAL padding mode in conv1dWithBias is not ' +\n 'implemented yet.');\n }\n let y: Tensor = tfc.conv1d(\n x as Tensor2D | Tensor3D, kernel as Tensor3D, strides,\n padding === 'same' ? 'same' : 'valid', 'NWC', dilationRate);\n if (bias != null) {\n y = K.biasAdd(y, bias);\n }\n return y;\n });\n}\n\n/**\n * 1D-convolution.\n *\n * @param x Input tensor, rank-3, of shape `[batchSize, width, inChannels]`.\n * @param kernel Kernel, rank-3, of shape `[filterWidth, inDepth, outDepth]`.s\n * @param strides\n * @param padding Padding mode.\n * @param dataFormat Data format.\n * @param dilationRate\n * @returns The result of the 1D convolution.\n * @throws ValueError, if `x`, `kernel` or `bias` is not of the correct rank.\n */\nexport function conv1d(\n x: Tensor, kernel: Tensor, strides = 1, padding = 'valid',\n dataFormat?: DataFormat, dilationRate = 1): Tensor {\n return tidy(() => {\n checkDataFormat(dataFormat);\n return conv1dWithBias(\n x, kernel, null, strides, padding, dataFormat, dilationRate);\n });\n}\n\n/**\n * 2D Convolution\n * @param x\n * @param kernel kernel of the convolution.\n * @param strides strides array.\n * @param padding padding mode. Default to 'valid'.\n * @param dataFormat data format. Defaults to 'channelsLast'.\n * @param dilationRate dilation rate array.\n * @returns Result of the 2D pooling.\n */\nexport function conv2d(\n x: Tensor, kernel: Tensor, strides = [1, 1], padding = 'valid',\n dataFormat?: DataFormat, dilationRate?: [number, number]): Tensor {\n return tidy(() => {\n checkDataFormat(dataFormat);\n return conv2dWithBiasActivation(\n x, kernel, null, strides, padding, dataFormat, dilationRate);\n });\n}\n\n/**\n * 2D Convolution with an added bias and optional activation.\n * Note: This function does not exist in the Python Keras Backend. This function\n * is exactly the same as `conv2d`, except the added `bias`.\n */\nexport function conv2dWithBiasActivation(\n x: Tensor, kernel: Tensor, bias: Tensor, strides = [1, 1],\n padding = 'valid', dataFormat?: DataFormat, dilationRate?: [number, number],\n activation: fused.Activation = null): Tensor {\n return tidy(() => {\n if (dataFormat == null) {\n dataFormat = imageDataFormat();\n }\n checkDataFormat(dataFormat);\n if (x.rank !== 3 && x.rank !== 4) {\n throw new ValueError(\n `conv2dWithBiasActivation expects input to be of rank 3 or 4, ` +\n `but received ${x.rank}.`);\n }\n if (kernel.rank !== 3 && kernel.rank !== 4) {\n throw new ValueError(\n `conv2dWithBiasActivation expects kernel to be of rank 3 or 4, ` +\n `but received ${x.rank}.`);\n }\n let y = preprocessConv2DInput(x, dataFormat);\n if (padding === 'causal') {\n throw new NotImplementedError(\n 'The support for CAUSAL padding mode in conv1dWithBias is not ' +\n 'implemented yet.');\n }\n y = tfc.fused.conv2d({\n x: y as Tensor3D | Tensor4D,\n filter: kernel as Tensor4D,\n strides: strides as [number, number],\n pad: padding === 'same' ? 'same' : 'valid',\n dilations: dilationRate,\n dataFormat: 'NHWC',\n bias,\n activation\n });\n if (dataFormat === 'channelsFirst') {\n y = tfc.transpose(y, [0, 3, 1, 2]);\n }\n return y;\n });\n}\n\n/**\n * 3D Convolution.\n * @param x\n * @param kernel kernel of the convolution.\n * @param strides strides array.\n * @param padding padding mode. Default to 'valid'.\n * @param dataFormat data format. Defaults to 'channelsLast'.\n * @param dilationRate dilation rate array.\n * @returns Result of the 3D convolution.\n */\nexport function conv3d(\n x: Tensor, kernel: Tensor, strides = [1, 1, 1], padding = 'valid',\n dataFormat?: DataFormat, dilationRate?: [number, number, number]): Tensor {\n return tidy(() => {\n checkDataFormat(dataFormat);\n return conv3dWithBias(\n x, kernel, null, strides, padding, dataFormat, dilationRate);\n });\n}\n\n/**\n * 3D Convolution with an added bias.\n * Note: This function does not exist in the Python Keras Backend. This function\n * is exactly the same as `conv3d`, except the added `bias`.\n */\nexport function conv3dWithBias(\n x: Tensor, kernel: Tensor, bias: Tensor, strides = [1, 1, 1],\n padding = 'valid', dataFormat?: DataFormat,\n dilationRate?: [number, number, number]): Tensor {\n return tidy(() => {\n if (dataFormat == null) {\n dataFormat = imageDataFormat();\n }\n checkDataFormat(dataFormat);\n if (x.rank !== 4 && x.rank !== 5) {\n throw new ValueError(\n `conv3dWithBias expects input to be of rank 4 or 5, but received ` +\n `${x.rank}.`);\n }\n if (kernel.rank !== 4 && kernel.rank !== 5) {\n throw new ValueError(\n `conv3dWithBias expects kernel to be of rank 4 or 5, but received ` +\n `${x.rank}.`);\n }\n let y = preprocessConv3DInput(x, dataFormat);\n if (padding === 'causal') {\n throw new NotImplementedError(\n 'The support for CAUSAL padding mode in conv3dWithBias is not ' +\n 'implemented yet.');\n }\n y = tfc.conv3d(\n y as Tensor4D | tfc.Tensor<tfc.Rank.R5>,\n kernel as tfc.Tensor<tfc.Rank.R5>, strides as [number, number, number],\n padding === 'same' ? 'same' : 'valid', 'NDHWC', dilationRate);\n if (bias != null) {\n y = K.biasAdd(y, bias as Tensor1D);\n }\n if (dataFormat === 'channelsFirst') {\n y = tfc.transpose(y, [0, 4, 1, 2, 3]);\n }\n return y;\n });\n}\n\n/**\n * Base LayerConfig for depthwise and non-depthwise convolutional layers.\n */\nexport declare interface BaseConvLayerArgs extends LayerArgs {\n /**\n * The dimensions of the convolution window. If kernelSize is a number, the\n * convolutional window will be square.\n */\n kernelSize: number|number[];\n\n /**\n * The strides of the convolution in each dimension. If strides is a number,\n * strides in both dimensions are equal.\n *\n * Specifying any stride value != 1 is incompatible with specifying any\n * `dilationRate` value != 1.\n */\n strides?: number|number[];\n\n /**\n * Padding mode.\n */\n padding?: PaddingMode;\n\n /**\n * Format of the data, which determines the ordering of the dimensions in\n * the inputs.\n *\n * `channels_last` corresponds to inputs with shape\n * `(batch, ..., channels)`\n *\n * `channels_first` corresponds to inputs with shape `(batch, channels,\n * ...)`.\n *\n * Defaults to `channels_last`.\n */\n dataFormat?: DataFormat;\n\n /**\n * The dilation rate to use for the dilated convolution in each dimension.\n * Should be an integer or array of two or three integers.\n *\n * Currently, specifying any `dilationRate` value != 1 is incompatible with\n * specifying any `strides` value != 1.\n */\n dilationRate?: number|[number]|[number, number]|[number, number, number];\n\n /**\n * Activation function of the layer.\n *\n * If you don't specify the activation, none is applied.\n */\n activation?: ActivationIdentifier;\n\n /**\n * Whether the layer uses a bias vector. Defaults to `true`.\n */\n useBias?: boolean;\n\n /**\n * Initializer for the convolutional kernel weights matrix.\n */\n kernelInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the bias vector.\n */\n biasInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Constraint for the convolutional kernel weights.\n */\n kernelConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Constraint for the bias vector.\n */\n biasConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Regularizer function applied to the kernel weights matrix.\n */\n kernelRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the bias vector.\n */\n biasRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the activation.\n */\n activityRegularizer?: RegularizerIdentifier|Regularizer;\n}\n\n/**\n * LayerConfig for non-depthwise convolutional layers.\n * Applies to non-depthwise convolution of all ranks (e.g, Conv1D, Conv2D,\n * Conv3D).\n */\nexport declare interface ConvLayerArgs extends BaseConvLayerArgs {\n /**\n * The dimensionality of the output space (i.e. the number of filters in the\n * convolution).\n */\n filters: number;\n}\n\n/**\n * Abstract convolution layer.\n */\nexport abstract class BaseConv extends Layer {\n protected readonly rank: number;\n protected readonly kernelSize: number[];\n protected readonly strides: number[];\n protected readonly padding: PaddingMode;\n protected readonly dataFormat: DataFormat;\n protected readonly activation: Activation;\n protected readonly useBias: boolean;\n protected readonly dilationRate: number[];\n\n // Bias-related members are here because all convolution subclasses use the\n // same configuration parmeters to control bias. Kernel-related members\n // are in subclass `Conv` because some subclasses use different parameters to\n // control kernel properties, for instance, `DepthwiseConv2D` uses\n // `depthwiseInitializer` instead of `kernelInitializer`.\n protected readonly biasInitializer?: Initializer;\n protected readonly biasConstraint?: Constraint;\n protected readonly biasRegularizer?: Regularizer;\n\n protected bias: LayerVariable = null;\n\n readonly DEFAULT_KERNEL_INITIALIZER: InitializerIdentifier = 'glorotNormal';\n readonly DEFAULT_BIAS_INITIALIZER: InitializerIdentifier = 'zeros';\n\n constructor(rank: number, args: BaseConvLayerArgs) {\n super(args as LayerArgs);\n BaseConv.verifyArgs(args);\n this.rank = rank;\n generic_utils.assertPositiveInteger(this.rank, 'rank');\n if (this.rank !== 1 && this.rank !== 2 && this.rank !== 3) {\n throw new NotImplementedError(\n `Convolution layer for rank other than 1, 2, or 3 (${\n this.rank}) is ` +\n `not implemented yet.`);\n }\n this.kernelSize = normalizeArray(args.kernelSize, rank, 'kernelSize');\n this.strides = normalizeArray(\n args.strides == null ? 1 : args.strides, rank, 'strides');\n this.padding = args.padding == null ? 'valid' : args.padding;\n checkPaddingMode(this.padding);\n this.dataFormat =\n args.dataFormat == null ? 'channelsLast' : args.dataFormat;\n checkDataFormat(this.dataFormat);\n this.activation = getActivation(args.activation);\n this.useBias = args.useBias == null ? true : args.useBias;\n this.biasInitializer =\n getInitializer(args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER);\n this.biasConstraint = getConstraint(args.biasConstraint);\n this.biasRegularizer = getRegularizer(args.biasRegularizer);\n this.activityRegularizer = getRegularizer(args.activityRegularizer);\n this.dilationRate = normalizeArray(\n args.dilationRate == null ? 1 : args.dilationRate, rank,\n 'dilationRate');\n if (this.rank === 1 &&\n (Array.isArray(this.dilationRate) && this.dilationRate.length !== 1)) {\n throw new ValueError(\n `dilationRate must be a number or an array of a single number ` +\n `for 1D convolution, but received ` +\n `${JSON.stringify(this.dilationRate)}`);\n } else if (this.rank === 2) {\n if (typeof this.dilationRate === 'number') {\n this.dilationRate = [this.dilationRate, this.dilationRate];\n } else if (this.dilationRate.length !== 2) {\n throw new ValueError(\n `dilationRate must be a number or array of two numbers for 2D ` +\n `convolution, but received ${JSON.stringify(this.dilationRate)}`);\n }\n } else if (this.rank === 3) {\n if (typeof this.dilationRate === 'number') {\n this.dilationRate =\n [this.dilationRate, this.dilationRate, this.dilationRate];\n } else if (this.dilationRate.length !== 3) {\n throw new ValueError(\n `dilationRate must be a number or array of three numbers for 3D ` +\n `convolution, but received ${JSON.stringify(this.dilationRate)}`);\n }\n }\n }\n\n protected static verifyArgs(args: BaseConvLayerArgs) {\n // Check config.kernelSize type and shape.\n generic_utils.assert(\n 'kernelSize' in args, `required key 'kernelSize' not in config`);\n if (typeof args.kernelSize !== 'number' &&\n !generic_utils.checkArrayTypeAndLength(\n args.kernelSize, 'number', 1, 3)) {\n throw new ValueError(\n `BaseConv expects config.kernelSize to be number or number[] with ` +\n `length 1, 2, or 3, but received ${\n JSON.stringify(args.kernelSize)}.`);\n }\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n kernelSize: this.kernelSize,\n strides: this.strides,\n padding: this.padding,\n dataFormat: this.dataFormat,\n dilationRate: this.dilationRate,\n activation: serializeActivation(this.activation),\n useBias: this.useBias,\n biasInitializer: serializeInitializer(this.biasInitializer),\n biasRegularizer: serializeRegularizer(this.biasRegularizer),\n activityRegularizer: serializeRegularizer(this.activityRegularizer),\n biasConstraint: serializeConstraint(this.biasConstraint)\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\n\n/**\n * Abstract nD convolution layer. Ancestor of convolution layers which reduce\n * across channels, i.e., Conv1D and Conv2D, but not DepthwiseConv2D.\n */\nexport abstract class Conv extends BaseConv {\n protected readonly filters: number;\n\n protected kernel: LayerVariable = null;\n\n // Bias-related properties are stored in the superclass `BaseConv` because all\n // convolution subclasses use the same configuration parameters to control\n // bias. Kernel-related properties are defined here rather than in the\n // superclass because some convolution subclasses use different names and\n // configuration parameters for their internal kernel state.\n protected readonly kernelInitializer?: Initializer;\n protected readonly kernelConstraint?: Constraint;\n protected readonly kernelRegularizer?: Regularizer;\n\n constructor(rank: number, args: ConvLayerArgs) {\n super(rank, args as BaseConvLayerArgs);\n Conv.verifyArgs(args);\n this.filters = args.filters;\n generic_utils.assertPositiveInteger(this.filters, 'filters');\n this.kernelInitializer = getInitializer(\n args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER);\n this.kernelConstraint = getConstraint(args.kernelConstraint);\n this.kernelRegularizer = getRegularizer(args.kernelRegularizer);\n }\n\n build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n const channelAxis =\n this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1;\n if (inputShape[channelAxis] == null) {\n throw new ValueError(\n `The channel dimension of the input should be defined. ` +\n `Found ${inputShape[channelAxis]}`);\n }\n const inputDim = inputShape[channelAxis];\n\n const kernelShape = this.kernelSize.concat([inputDim, this.filters]);\n\n this.kernel = this.addWeight(\n 'kernel', kernelShape, null, this.kernelInitializer,\n this.kernelRegularizer, true, this.kernelConstraint);\n if (this.useBias) {\n this.bias = this.addWeight(\n 'bias', [this.filters], null, this.biasInitializer,\n this.biasRegularizer, true, this.biasConstraint);\n }\n\n this.inputSpec = [{ndim: this.rank + 2, axes: {[channelAxis]: inputDim}}];\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = getExactlyOneTensor(inputs);\n let outputs: Tensor;\n const biasValue = this.bias == null ? null : this.bias.read();\n const fusedActivationName = generic_utils.mapActivationToFusedKernel(\n this.activation.getClassName());\n\n if (fusedActivationName != null && this.rank === 2) {\n outputs = conv2dWithBiasActivation(\n inputs, this.kernel.read(), biasValue, this.strides, this.padding,\n this.dataFormat, this.dilationRate as [number, number],\n fusedActivationName);\n } else {\n if (this.rank === 1) {\n outputs = conv1dWithBias(\n inputs, this.kernel.read(), biasValue, this.strides[0],\n this.padding, this.dataFormat, this.dilationRate[0]);\n } else if (this.rank === 2) {\n // TODO(cais): Move up to constructor.\n outputs = conv2dWithBiasActivation(\n inputs, this.kernel.read(), biasValue, this.strides, this.padding,\n this.dataFormat, this.dilationRate as [number, number]);\n } else if (this.rank === 3) {\n outputs = conv3dWithBias(\n inputs, this.kernel.read(), biasValue, this.strides, this.padding,\n this.dataFormat, this.dilationRate as [number, number, number]);\n } else {\n throw new NotImplementedError(\n 'convolutions greater than 3D are not implemented yet.');\n }\n\n if (this.activation != null) {\n outputs = this.activation.apply(outputs);\n }\n }\n\n return outputs;\n });\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const newSpace: number[] = [];\n const space = (this.dataFormat === 'channelsLast') ?\n inputShape.slice(1, inputShape.length - 1) :\n inputShape.slice(2);\n for (let i = 0; i < space.length; ++i) {\n const newDim = convOutputLength(\n space[i], this.kernelSize[i], this.padding, this.strides[i],\n typeof this.dilationRate === 'number' ? this.dilationRate :\n this.dilationRate[i]);\n newSpace.push(newDim);\n }\n\n let outputShape = [inputShape[0]];\n if (this.dataFormat === 'channelsLast') {\n outputShape = outputShape.concat(newSpace);\n outputShape.push(this.filters);\n } else {\n outputShape.push(this.filters);\n outputShape = outputShape.concat(newSpace);\n }\n return outputShape;\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n filters: this.filters,\n kernelInitializer: serializeInitializer(this.kernelInitializer),\n kernelRegularizer: serializeRegularizer(this.kernelRegularizer),\n kernelConstraint: serializeConstraint(this.kernelConstraint)\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n protected static verifyArgs(args: ConvLayerArgs) {\n // Check config.filters type, shape, and value.\n if (!('filters' in args) || typeof args.filters !== 'number' ||\n args.filters < 1) {\n throw new ValueError(\n `Convolution layer expected config.filters to be a 'number' > 0 ` +\n `but got ${JSON.stringify(args.filters)}`);\n }\n }\n}\n\nexport class Conv2D extends Conv {\n /** @nocollapse */\n static className = 'Conv2D';\n constructor(args: ConvLayerArgs) {\n super(2, args);\n Conv2D.verifyArgs(args);\n }\n\n getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['rank'];\n return config;\n }\n\n protected static verifyArgs(args: ConvLayerArgs) {\n // config.kernelSize must be a number or array of numbers.\n if ((typeof args.kernelSize !== 'number') &&\n !generic_utils.checkArrayTypeAndLength(\n args.kernelSize, 'number', 1, 2)) {\n throw new ValueError(\n `Conv2D expects config.kernelSize to be number or number[] with ` +\n `length 1 or 2, but received ${JSON.stringify(args.kernelSize)}.`);\n }\n }\n}\nserialization.registerClass(Conv2D);\n\nexport class Conv3D extends Conv {\n /** @nocollapse */\n static className = 'Conv3D';\n constructor(args: ConvLayerArgs) {\n super(3, args);\n Conv3D.verifyArgs(args);\n }\n\n getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['rank'];\n return config;\n }\n\n protected static verifyArgs(args: ConvLayerArgs) {\n // config.kernelSize must be a number or array of numbers.\n if (typeof args.kernelSize !== 'number') {\n if (!(Array.isArray(args.kernelSize) &&\n (args.kernelSize.length === 1 || args.kernelSize.length === 3))) {\n throw new ValueError(\n `Conv3D expects config.kernelSize to be number or` +\n ` [number, number, number], but received ${\n JSON.stringify(args.kernelSize)}.`);\n }\n }\n }\n}\nserialization.registerClass(Conv3D);\n\nexport class Conv2DTranspose extends Conv2D {\n /** @nocollapse */\n static className = 'Conv2DTranspose';\n inputSpec: InputSpec[];\n\n constructor(args: ConvLayerArgs) {\n super(args);\n this.inputSpec = [new InputSpec({ndim: 4})];\n\n if (this.padding !== 'same' && this.padding !== 'valid') {\n throw new ValueError(\n `Conv2DTranspose currently supports only padding modes 'same' ` +\n `and 'valid', but received padding mode ${this.padding}`);\n }\n }\n\n build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n\n if (inputShape.length !== 4) {\n throw new ValueError(\n 'Input should have rank 4; Received input shape: ' +\n JSON.stringify(inputShape));\n }\n\n const channelAxis =\n this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1;\n if (inputShape[channelAxis] == null) {\n throw new ValueError(\n 'The channel dimension of the inputs should be defined. ' +\n 'Found `None`.');\n }\n const inputDim = inputShape[channelAxis];\n const kernelShape = this.kernelSize.concat([this.filters, inputDim]);\n\n this.kernel = this.addWeight(\n 'kernel', kernelShape, 'float32', this.kernelInitializer,\n this.kernelRegularizer, true, this.kernelConstraint);\n if (this.useBias) {\n this.bias = this.addWeight(\n 'bias', [this.filters], 'float32', this.biasInitializer,\n this.biasRegularizer, true, this.biasConstraint);\n }\n\n // Set input spec.\n this.inputSpec =\n [new InputSpec({ndim: 4, axes: {[channelAxis]: inputDim}})];\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tfc.tidy(() => {\n let input = getExactlyOneTensor(inputs);\n if (input.shape.length !== 4) {\n throw new ValueError(\n `Conv2DTranspose.call() expects input tensor to be rank-4, but ` +\n `received a tensor of rank-${input.shape.length}`);\n }\n\n const inputShape = input.shape;\n const batchSize = inputShape[0];\n\n let hAxis: number;\n let wAxis: number;\n if (this.dataFormat === 'channelsFirst') {\n hAxis = 2;\n wAxis = 3;\n } else {\n hAxis = 1;\n wAxis = 2;\n }\n\n const height = inputShape[hAxis];\n const width = inputShape[wAxis];\n const kernelH = this.kernelSize[0];\n const kernelW = this.kernelSize[1];\n const strideH = this.strides[0];\n const strideW = this.strides[1];\n\n // Infer the dynamic output shape.\n const outHeight = deconvLength(height, strideH, kernelH, this.padding);\n const outWidth = deconvLength(width, strideW, kernelW, this.padding);\n\n // Porting Note: We don't branch based on `this.dataFormat` here,\n // because\n // the tjfs-core function `conv2dTranspose` called below always\n // assumes channelsLast.\n const outputShape: [number, number, number, number] =\n [batchSize, outHeight, outWidth, this.filters];\n\n if (this.dataFormat !== 'channelsLast') {\n input = tfc.transpose(input, [0, 2, 3, 1]);\n }\n let outputs = tfc.conv2dTranspose(\n input as Tensor4D, this.kernel.read() as Tensor4D, outputShape,\n this.strides as [number, number], this.padding as 'same' | 'valid');\n if (this.dataFormat !== 'channelsLast') {\n outputs = tfc.transpose(outputs, [0, 3, 1, 2]);\n }\n\n if (this.bias != null) {\n outputs =\n K.biasAdd(outputs, this.bias.read(), this.dataFormat) as Tensor4D;\n }\n if (this.activation != null) {\n outputs = this.activation.apply(outputs) as Tensor4D;\n }\n return outputs;\n });\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const outputShape = inputShape.slice();\n\n let channelAxis: number;\n let heightAxis: number;\n let widthAxis: number;\n if (this.dataFormat === 'channelsFirst') {\n channelAxis = 1;\n heightAxis = 2;\n widthAxis = 3;\n } else {\n channelAxis = 3;\n heightAxis = 1;\n widthAxis = 2;\n }\n\n const kernelH = this.kernelSize[0];\n const kernelW = this.kernelSize[1];\n const strideH = this.strides[0];\n const strideW = this.strides[1];\n\n outputShape[channelAxis] = this.filters;\n outputShape[heightAxis] =\n deconvLength(outputShape[heightAxis], strideH, kernelH, this.padding);\n outputShape[widthAxis] =\n deconvLength(outputShape[widthAxis], strideW, kernelW, this.padding);\n return outputShape;\n }\n\n getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['dilationRate'];\n return config;\n }\n}\nserialization.registerClass(Conv2DTranspose);\n\nexport class Conv3DTranspose extends Conv3D {\n /** @nocollapse */\n static className = 'Conv3DTranspose';\n inputSpec: InputSpec[];\n\n constructor(args: ConvLayerArgs) {\n super(args);\n this.inputSpec = [new InputSpec({ndim: 5})];\n\n if (this.padding !== 'same' && this.padding !== 'valid') {\n throw new ValueError(\n `Conv3DTranspose currently supports only padding modes 'same' ` +\n `and 'valid', but received padding mode ${this.padding}`);\n }\n }\n\n build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n\n if (inputShape.length !== 5) {\n throw new ValueError(\n 'Input should have rank 5; Received input shape: ' +\n JSON.stringify(inputShape));\n }\n\n const channelAxis =\n this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1;\n if (inputShape[channelAxis] == null) {\n throw new ValueError(\n 'The channel dimension of the inputs should be defined. ' +\n 'Found `None`.');\n }\n const inputDim = inputShape[channelAxis];\n const kernelShape = this.kernelSize.concat([this.filters, inputDim]);\n\n this.kernel = this.addWeight(\n 'kernel', kernelShape, 'float32', this.kernelInitializer,\n this.kernelRegularizer, true, this.kernelConstraint);\n if (this.useBias) {\n this.bias = this.addWeight(\n 'bias', [this.filters], 'float32', this.biasInitializer,\n this.biasRegularizer, true, this.biasConstraint);\n }\n\n // Set input spec.\n this.inputSpec =\n [new InputSpec({ndim: 5, axes: {[channelAxis]: inputDim}})];\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tfc.tidy<tfc.Tensor5D>(() => {\n let input = getExactlyOneTensor(inputs);\n if (input.shape.length !== 5) {\n throw new ValueError(\n `Conv3DTranspose.call() expects input tensor to be rank-4, but ` +\n `received a tensor of rank-${input.shape.length}`);\n }\n\n const inputShape = input.shape;\n const batchSize = inputShape[0];\n\n let hAxis: number;\n let wAxis: number;\n let dAxis: number;\n\n if (this.dataFormat === 'channelsFirst') {\n dAxis = 2;\n hAxis = 3;\n wAxis = 4;\n } else {\n dAxis = 1;\n hAxis = 2;\n wAxis = 3;\n }\n\n const depth = inputShape[dAxis];\n const height = inputShape[hAxis];\n const width = inputShape[wAxis];\n const kernelD = this.kernelSize[0];\n const kernelH = this.kernelSize[1];\n const kernelW = this.kernelSize[2];\n const strideD = this.strides[0];\n const strideH = this.strides[1];\n const strideW = this.strides[2];\n\n // Infer the dynamic output shape.\n const outDepth = deconvLength(depth, strideD, kernelD, this.padding);\n const outHeight = deconvLength(height, strideH, kernelH, this.padding);\n const outWidth = deconvLength(width, strideW, kernelW, this.padding);\n\n // Same as `conv2dTranspose`. We always assumes channelsLast.\n const outputShape: [number, number, number, number, number] =\n [batchSize, outDepth, outHeight, outWidth, this.filters];\n if (this.dataFormat !== 'channelsLast') {\n input = tfc.transpose(input, [0, 2, 3, 4, 1]);\n }\n let outputs = tfc.conv3dTranspose(\n input as Tensor5D, this.kernel.read() as Tensor5D, outputShape,\n this.strides as [number, number, number],\n this.padding as 'same' | 'valid');\n if (this.dataFormat !== 'channelsLast') {\n outputs = tfc.transpose(outputs, [0, 4, 1, 2, 3]);\n }\n\n if (this.bias !== null) {\n outputs =\n K.biasAdd(outputs, this.bias.read(), this.dataFormat) as Tensor5D;\n }\n if (this.activation !== null) {\n outputs = this.activation.apply(outputs) as Tensor5D;\n }\n return outputs;\n });\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const outputShape = inputShape.slice();\n\n let channelAxis: number;\n let depthAxis: number;\n let heightAxis: number;\n let widthAxis: number;\n if (this.dataFormat === 'channelsFirst') {\n channelAxis = 1;\n depthAxis = 2;\n heightAxis = 3;\n widthAxis = 4;\n } else {\n channelAxis = 4;\n depthAxis = 1;\n heightAxis = 2;\n widthAxis = 3;\n }\n\n const kernelD = this.kernelSize[0];\n const kernelH = this.kernelSize[1];\n const kernelW = this.kernelSize[2];\n const strideD = this.strides[0];\n const strideH = this.strides[1];\n const strideW = this.strides[2];\n\n outputShape[channelAxis] = this.filters;\n outputShape[depthAxis] =\n deconvLength(outputShape[depthAxis], strideD, kernelD, this.padding);\n outputShape[heightAxis] =\n deconvLength(outputShape[heightAxis], strideH, kernelH, this.padding);\n outputShape[widthAxis] =\n deconvLength(outputShape[widthAxis], strideW, kernelW, this.padding);\n return outputShape;\n }\n\n getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['dilationRate'];\n return config;\n }\n}\nserialization.registerClass(Conv3DTranspose);\n\nexport declare interface SeparableConvLayerArgs extends ConvLayerArgs {\n /**\n * The number of depthwise convolution output channels for each input\n * channel.\n * The total number of depthwise convolution output channels will be equal\n * to `filtersIn * depthMultiplier`. Default: 1.\n */\n depthMultiplier?: number;\n\n /**\n * Initializer for the depthwise kernel matrix.\n */\n depthwiseInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the pointwise kernel matrix.\n */\n pointwiseInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Regularizer function applied to the depthwise kernel matrix.\n */\n depthwiseRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the pointwise kernel matrix.\n */\n pointwiseRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Constraint function applied to the depthwise kernel matrix.\n */\n depthwiseConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Constraint function applied to the pointwise kernel matrix.\n */\n pointwiseConstraint?: ConstraintIdentifier|Constraint;\n}\n\nexport class SeparableConv extends Conv {\n /** @nocollapse */\n static className = 'SeparableConv';\n\n readonly depthMultiplier: number;\n\n protected readonly depthwiseInitializer?: Initializer;\n protected readonly depthwiseRegularizer?: Regularizer;\n protected readonly depthwiseConstraint?: Constraint;\n protected readonly pointwiseInitializer?: Initializer;\n protected readonly pointwiseRegularizer?: Regularizer;\n protected readonly pointwiseConstraint?: Constraint;\n\n readonly DEFAULT_DEPTHWISE_INITIALIZER: InitializerIdentifier =\n 'glorotUniform';\n readonly DEFAULT_POINTWISE_INITIALIZER: InitializerIdentifier =\n 'glorotUniform';\n\n protected depthwiseKernel: LayerVariable = null;\n protected pointwiseKernel: LayerVariable = null;\n\n constructor(rank: number, config?: SeparableConvLayerArgs) {\n super(rank, config);\n\n if (config.filters == null) {\n throw new ValueError(\n 'The `filters` configuration field is required by SeparableConv, ' +\n 'but is unspecified.');\n }\n if (config.kernelInitializer != null || config.kernelRegularizer != null ||\n config.kernelConstraint != null) {\n throw new ValueError(\n 'Fields kernelInitializer, kernelRegularizer and kernelConstraint ' +\n 'are invalid for SeparableConv2D. Use depthwiseInitializer, ' +\n 'depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, ' +\n 'pointwiseRegularizer and pointwiseConstraint instead.');\n }\n if (config.padding != null && config.padding !== 'same' &&\n config.padding !== 'valid') {\n throw new ValueError(\n `SeparableConv${this.rank}D supports only padding modes: ` +\n `'same' and 'valid', but received ${JSON.stringify(config.padding)}`);\n }\n\n this.depthMultiplier =\n config.depthMultiplier == null ? 1 : config.depthMultiplier;\n this.depthwiseInitializer = getInitializer(\n config.depthwiseInitializer || this.DEFAULT_DEPTHWISE_INITIALIZER);\n this.depthwiseRegularizer = getRegularizer(config.depthwiseRegularizer);\n this.depthwiseConstraint = getConstraint(config.depthwiseConstraint);\n this.pointwiseInitializer = getInitializer(\n config.depthwiseInitializer || this.DEFAULT_POINTWISE_INITIALIZER);\n this.pointwiseRegularizer = getRegularizer(config.pointwiseRegularizer);\n this.pointwiseConstraint = getConstraint(config.pointwiseConstraint);\n }\n\n build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n if (inputShape.length < this.rank + 2) {\n throw new ValueError(\n `Inputs to SeparableConv${this.rank}D should have rank ` +\n `${this.rank + 2}, but received input shape: ` +\n `${JSON.stringify(inputShape)}`);\n }\n const channelAxis =\n this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1;\n if (inputShape[channelAxis] == null || inputShape[channelAxis] < 0) {\n throw new ValueError(\n `The channel dimension of the inputs should be defined, ` +\n `but found ${JSON.stringify(inputShape[channelAxis])}`);\n }\n\n const inputDim = inputShape[channelAxis];\n const depthwiseKernelShape =\n this.kernelSize.concat([inputDim, this.depthMultiplier]);\n const pointwiseKernelShape = [];\n for (let i = 0; i < this.rank; ++i) {\n pointwiseKernelShape.push(1);\n }\n pointwiseKernelShape.push(inputDim * this.depthMultiplier, this.filters);\n\n const trainable = true;\n this.depthwiseKernel = this.addWeight(\n 'depthwise_kernel', depthwiseKernelShape, 'float32',\n this.depthwiseInitializer, this.depthwiseRegularizer, trainable,\n this.depthwiseConstraint);\n this.pointwiseKernel = this.addWeight(\n 'pointwise_kernel', pointwiseKernelShape, 'float32',\n this.pointwiseInitializer, this.pointwiseRegularizer, trainable,\n this.pointwiseConstraint);\n if (this.useBias) {\n this.bias = this.addWeight(\n 'bias', [this.filters], 'float32', this.biasInitializer,\n this.biasRegularizer, trainable, this.biasConstraint);\n } else {\n this.bias = null;\n }\n\n this.inputSpec =\n [new InputSpec({ndim: this.rank + 2, axes: {[channelAxis]: inputDim}})];\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = getExactlyOneTensor(inputs);\n\n let output: Tensor;\n if (this.rank === 1) {\n throw new NotImplementedError(\n '1D separable convolution is not implemented yet.');\n } else if (this.rank === 2) {\n if (this.dataFormat === 'channelsFirst') {\n inputs = tfc.transpose(inputs, [0, 2, 3, 1]); // NCHW -> NHWC.\n }\n\n output = tfc.separableConv2d(\n inputs as Tensor4D, this.depthwiseKernel.read() as Tensor4D,\n this.pointwiseKernel.read() as Tensor4D,\n this.strides as [number, number], this.padding as 'same' | 'valid',\n this.dilationRate as [number, number], 'NHWC');\n }\n\n if (this.useBias) {\n output = K.biasAdd(output, this.bias.read(), this.dataFormat);\n }\n if (this.activation != null) {\n output = this.activation.apply(output);\n }\n\n if (this.dataFormat === 'channelsFirst') {\n output = tfc.transpose(output, [0, 3, 1, 2]); // NHWC -> NCHW.\n }\n return output;\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['rank'];\n delete config['kernelInitializer'];\n delete config['kernelRegularizer'];\n delete config['kernelConstraint'];\n config['depthwiseInitializer'] =\n serializeInitializer(this.depthwiseInitializer);\n config['pointwiseInitializer'] =\n serializeInitializer(this.pointwiseInitializer);\n config['depthwiseRegularizer'] =\n serializeRegularizer(this.depthwiseRegularizer);\n config['pointwiseRegularizer'] =\n serializeRegularizer(this.pointwiseRegularizer);\n config['depthwiseConstraint'] =\n serializeConstraint(this.depthwiseConstraint);\n config['pointwiseConstraint'] =\n serializeConstraint(this.pointwiseConstraint);\n return config;\n }\n}\n\nexport class SeparableConv2D extends SeparableConv {\n /** @nocollapse */\n static className = 'SeparableConv2D';\n constructor(args?: SeparableConvLayerArgs) {\n super(2, args);\n }\n}\nserialization.registerClass(SeparableConv2D);\n\nexport class Conv1D extends Conv {\n /** @nocollapse */\n static className = 'Conv1D';\n constructor(args: ConvLayerArgs) {\n super(1, args);\n Conv1D.verifyArgs(args);\n this.inputSpec = [{ndim: 3}];\n }\n\n getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n delete config['rank'];\n delete config['dataFormat'];\n return config;\n }\n\n protected static verifyArgs(args: ConvLayerArgs) {\n // config.kernelSize must be a number or array of numbers.\n if (typeof args.kernelSize !== 'number' &&\n !generic_utils.checkArrayTypeAndLength(\n args.kernelSize, 'number', 1, 1)) {\n throw new ValueError(\n `Conv1D expects config.kernelSize to be number or number[] with ` +\n `length 1, but received ${JSON.stringify(args.kernelSize)}.`);\n }\n }\n}\nserialization.registerClass(Conv1D);\n\nexport declare interface Cropping2DLayerArgs extends LayerArgs {\n /**\n * Dimension of the cropping along the width and the height.\n * - If integer: the same symmetric cropping\n * is applied to width and height.\n * - If list of 2 integers:\n * interpreted as two different\n * symmetric cropping values for height and width:\n * `[symmetric_height_crop, symmetric_width_crop]`.\n * - If a list of 2 list of 2 integers:\n * interpreted as\n * `[[top_crop, bottom_crop], [left_crop, right_crop]]`\n */\n cropping: number|[number, number]|[[number, number], [number, number]];\n\n /**\n * Format of the data, which determines the ordering of the dimensions in\n * the inputs.\n *\n * `channels_last` corresponds to inputs with shape\n * `(batch, ..., channels)`\n *\n * `channels_first` corresponds to inputs with shape\n * `(batch, channels, ...)`\n *\n * Defaults to `channels_last`.\n */\n dataFormat?: DataFormat;\n}\n\nexport class Cropping2D extends Layer {\n /** @nocollapse */\n static className = 'Cropping2D';\n protected readonly cropping: [[number, number], [number, number]];\n protected readonly dataFormat: DataFormat;\n\n constructor(args: Cropping2DLayerArgs) {\n super(args);\n if (typeof args.cropping === 'number') {\n this.cropping =\n [[args.cropping, args.cropping], [args.cropping, args.cropping]];\n } else if (typeof args.cropping[0] === 'number') {\n this.cropping = [\n [args.cropping[0], args.cropping[0]],\n [args.cropping[1] as number, args.cropping[1] as number]\n ];\n } else {\n this.cropping = args.cropping as [[number, number], [number, number]];\n }\n this.dataFormat =\n args.dataFormat === undefined ? 'channelsLast' : args.dataFormat;\n this.inputSpec = [{ndim: 4}];\n }\n\n computeOutputShape(inputShape: Shape): Shape {\n if (this.dataFormat === 'channelsFirst') {\n return [\n inputShape[0], inputShape[1],\n inputShape[2] - this.cropping[0][0] - this.cropping[0][1],\n inputShape[3] - this.cropping[1][0] - this.cropping[1][1]\n ];\n } else {\n return [\n inputShape[0],\n inputShape[1] - this.cropping[0][0] - this.cropping[0][1],\n inputShape[2] - this.cropping[1][0] - this.cropping[1][1], inputShape[3]\n ];\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = getExactlyOneTensor(inputs);\n\n if (this.dataFormat === 'channelsLast') {\n const hSliced = K.sliceAlongAxis(\n inputs, this.cropping[0][0],\n inputs.shape[1] - this.cropping[0][0] - this.cropping[0][1], 2);\n return K.sliceAlongAxis(\n hSliced, this.cropping[1][0],\n inputs.shape[2] - this.cropping[1][1] - this.cropping[1][0], 3);\n } else {\n const hSliced = K.sliceAlongAxis(\n inputs, this.cropping[0][0],\n inputs.shape[2] - this.cropping[0][0] - this.cropping[0][1], 3);\n return K.sliceAlongAxis(\n hSliced, this.cropping[1][0],\n inputs.shape[3] - this.cropping[1][1] - this.cropping[1][0], 4);\n }\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {cropping: this.cropping, dataFormat: this.dataFormat};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Cropping2D);\n\nexport declare interface UpSampling2DLayerArgs extends LayerArgs {\n /**\n * The upsampling factors for rows and columns.\n *\n * Defaults to `[2, 2]`.\n */\n size?: number[];\n /**\n * Format of the data, which determines the ordering of the dimensions in\n * the inputs.\n *\n * `\"channelsLast\"` corresponds to inputs with shape\n * `[batch, ..., channels]`\n *\n * `\"channelsFirst\"` corresponds to inputs with shape `[batch, channels,\n * ...]`.\n *\n * Defaults to `\"channelsLast\"`.\n */\n dataFormat?: DataFormat;\n /**\n * The interpolation mechanism, one of `\"nearest\"` or `\"bilinear\"`, default\n * to `\"nearest\"`.\n */\n interpolation?: InterpolationFormat;\n}\n\nexport class UpSampling2D extends Layer {\n /** @nocollapse */\n static className = 'UpSampling2D';\n protected readonly DEFAULT_SIZE = [2, 2];\n protected readonly size: number[];\n protected readonly dataFormat: DataFormat;\n protected readonly interpolation: InterpolationFormat;\n\n constructor(args: UpSampling2DLayerArgs) {\n super(args);\n this.inputSpec = [{ndim: 4}];\n this.size = args.size == null ? this.DEFAULT_SIZE : args.size;\n this.dataFormat =\n args.dataFormat == null ? 'channelsLast' : args.dataFormat;\n checkDataFormat(this.dataFormat);\n this.interpolation =\n args.interpolation == null ? 'nearest' : args.interpolation;\n checkInterpolationFormat(this.interpolation);\n }\n\n computeOutputShape(inputShape: Shape): Shape {\n if (this.dataFormat === 'channelsFirst') {\n const height =\n inputShape[2] == null ? null : this.size[0] * inputShape[2];\n const width = inputShape[3] == null ? null : this.size[1] * inputShape[3];\n return [inputShape[0], inputShape[1], height, width];\n } else {\n const height =\n inputShape[1] == null ? null : this.size[0] * inputShape[1];\n const width = inputShape[2] == null ? null : this.size[1] * inputShape[2];\n return [inputShape[0], height, width, inputShape[3]];\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tfc.tidy(() => {\n let input = getExactlyOneTensor(inputs) as Tensor4D;\n const inputShape = input.shape;\n\n if (this.dataFormat === 'channelsFirst') {\n input = tfc.transpose(input, [0, 2, 3, 1]);\n const height = this.size[0] * inputShape[2];\n const width = this.size[1] * inputShape[3];\n\n const resized = this.interpolation === 'nearest' ?\n tfc.image.resizeNearestNeighbor(input, [height, width]) :\n tfc.image.resizeBilinear(input, [height, width]);\n return tfc.transpose(resized, [0, 3, 1, 2]);\n } else {\n const height = this.size[0] * inputShape[1];\n const width = this.size[1] * inputShape[2];\n return this.interpolation === 'nearest' ?\n tfc.image.resizeNearestNeighbor(input, [height, width]) :\n tfc.image.resizeBilinear(input, [height, width]);\n }\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {size: this.size, dataFormat: this.dataFormat};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(UpSampling2D);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * TensorFlow.js Layers: Depthwise Convolutional Layers\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {serialization, Tensor, Tensor4D, tidy} from '@tensorflow/tfjs-core';\n\nimport {imageDataFormat} from '../backend/common';\nimport * as K from '../backend/tfjs_backend';\nimport {checkDataFormat} from '../common';\nimport {Constraint, ConstraintIdentifier, getConstraint, serializeConstraint} from '../constraints';\nimport {ValueError} from '../errors';\nimport {getInitializer, Initializer, InitializerIdentifier, serializeInitializer} from '../initializers';\nimport {DataFormat, Shape} from '../keras_format/common';\nimport {getRegularizer, Regularizer, RegularizerIdentifier, serializeRegularizer} from '../regularizers';\nimport {Kwargs} from '../types';\nimport {convOutputLength} from '../utils/conv_utils';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\nimport {LayerVariable} from '../variables';\n\nimport {BaseConv, BaseConvLayerArgs, ConvLayerArgs, preprocessConv2DInput} from './convolutional';\n\n/**\n * 2D convolution with separable filters.\n * @param x Input tensor.\n * @param depthwiseKernel Convolution kernel for depthwise convolution.\n * @param strides Strides (Array of two integers).\n * @param padding Padding model.\n * @param dataFormat Data format.\n * @param dilationRate Array of two integers, dilation rates for the separable\n * convolution.\n * @returns Output tensor.\n * @throws ValueError If depthwiseKernel is not a 4D array.\n */\nexport function depthwiseConv2d(\n x: Tensor, depthwiseKernel: Tensor, strides: [number, number] = [1, 1],\n padding = 'valid', dataFormat?: DataFormat,\n dilationRate?: [number, number]): Tensor {\n return tidy(() => {\n if (dataFormat == null) {\n dataFormat = imageDataFormat();\n }\n checkDataFormat(dataFormat);\n let y = preprocessConv2DInput(x, dataFormat);\n if (x.rank !== 4) {\n throw new ValueError(\n `Input for depthwiseConv2d is required to be 4-D, but is instead ` +\n `${x.rank}-D`);\n }\n if (depthwiseKernel.rank !== 4) {\n throw new ValueError(\n `depthwiseKernel is required to be 4-D, but is instead ` +\n `${depthwiseKernel.rank}-D`);\n }\n y = tfc.depthwiseConv2d(\n y as Tensor4D, depthwiseKernel as Tensor4D, strides,\n padding === 'same' ? 'same' : 'valid', 'NHWC', dilationRate);\n if (dataFormat === 'channelsFirst') {\n y = tfc.transpose(y, [0, 3, 1, 2]);\n }\n return y;\n });\n}\n\nexport declare interface DepthwiseConv2DLayerArgs extends BaseConvLayerArgs {\n /**\n * An integer or Array of 2 integers, specifying the width and height of the\n * 2D convolution window. Can be a single integer to specify the same value\n * for all spatial dimensions.\n */\n kernelSize: number|[number, number];\n\n /**\n * The number of depthwise convolution output channels for each input\n * channel.\n * The total number of depthwise convolution output channels will be equal to\n * `filtersIn * depthMultiplier`.\n * Default: 1.\n */\n depthMultiplier?: number;\n\n /**\n * Initializer for the depthwise kernel matrix.\n * Default: GlorotNormal.\n */\n depthwiseInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Constraint for the depthwise kernel matrix.\n */\n depthwiseConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Regulzarizer function for the depthwise kernel matrix.\n */\n depthwiseRegularizer?: RegularizerIdentifier|Regularizer;\n}\n\nexport class DepthwiseConv2D extends BaseConv {\n /** @nocollapse */\n static className = 'DepthwiseConv2D';\n private readonly depthMultiplier: number;\n private readonly depthwiseInitializer: Initializer;\n private readonly depthwiseConstraint: Constraint;\n private readonly depthwiseRegularizer: Regularizer;\n\n private depthwiseKernel: LayerVariable = null;\n\n constructor(args: DepthwiseConv2DLayerArgs) {\n super(2, args as ConvLayerArgs);\n this.depthMultiplier =\n args.depthMultiplier == null ? 1 : args.depthMultiplier;\n this.depthwiseInitializer = getInitializer(\n args.depthwiseInitializer || this.DEFAULT_KERNEL_INITIALIZER);\n this.depthwiseConstraint = getConstraint(args.depthwiseConstraint);\n this.depthwiseRegularizer = getRegularizer(args.depthwiseRegularizer);\n }\n\n build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n if (inputShape.length < 4) {\n throw new ValueError(\n `Inputs to DepthwiseConv2D should have rank 4. ` +\n `Received input shape: ${JSON.stringify(inputShape)}.`);\n }\n const channelAxis = this.dataFormat === 'channelsFirst' ? 1 : 3;\n if (inputShape[channelAxis] == null || inputShape[channelAxis] < 0) {\n throw new ValueError(\n 'The channel dimension of the inputs to DepthwiseConv2D should ' +\n `be defined, but is not (${inputShape[channelAxis]}).`);\n }\n const inputDim = inputShape[channelAxis];\n const depthwiseKernelShape: Shape = [\n this.kernelSize[0], this.kernelSize[1], inputDim, this.depthMultiplier\n ];\n\n this.depthwiseKernel = this.addWeight(\n 'depthwise_kernel', depthwiseKernelShape, null,\n this.depthwiseInitializer, this.depthwiseRegularizer, true,\n this.depthwiseConstraint);\n if (this.useBias) {\n this.bias = this.addWeight(\n 'bias', [inputDim * this.depthMultiplier], null, this.biasInitializer,\n this.biasRegularizer, true, this.biasConstraint);\n } else {\n this.bias = null;\n }\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = getExactlyOneTensor(inputs);\n let outputs = depthwiseConv2d(\n inputs, this.depthwiseKernel.read(), this.strides as [number, number],\n this.padding, this.dataFormat, null);\n // TODO(cais): Add support for dilation.\n if (this.useBias) {\n outputs = K.biasAdd(outputs, this.bias.read(), this.dataFormat);\n }\n if (this.activation != null) {\n outputs = this.activation.apply(outputs);\n }\n return outputs;\n });\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const rows =\n this.dataFormat === 'channelsFirst' ? inputShape[2] : inputShape[1];\n const cols =\n this.dataFormat === 'channelsFirst' ? inputShape[3] : inputShape[2];\n const outFilters = this.dataFormat === 'channelsFirst' ?\n inputShape[1] * this.depthMultiplier :\n inputShape[3] * this.depthMultiplier;\n const outRows = convOutputLength(\n rows, this.kernelSize[0], this.padding, this.strides[0]);\n const outCols = convOutputLength(\n cols, this.kernelSize[1], this.padding, this.strides[1]);\n if (this.dataFormat === 'channelsFirst') {\n return [inputShape[0], outFilters, outRows, outCols];\n } else {\n // In this case, assume 'channelsLast'.\n return [inputShape[0], outRows, outCols, outFilters];\n }\n }\n\n getConfig(): serialization.ConfigDict {\n const config = super.getConfig();\n config['depthMultiplier'] = this.depthMultiplier;\n config['depthwiseInitializer'] =\n serializeInitializer(this.depthwiseInitializer);\n config['depthwiseRegularizer'] =\n serializeRegularizer(this.depthwiseRegularizer);\n config['depthwiseConstraint'] =\n serializeConstraint(this.depthwiseRegularizer);\n return config;\n }\n}\nserialization.registerClass(DepthwiseConv2D);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * TensorFlow.js Layers: Recurrent Neural Network Layers.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {DataType, serialization, Tensor, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {Activation, getActivation, serializeActivation} from '../activations';\nimport * as K from '../backend/tfjs_backend';\nimport {nameScope} from '../common';\nimport {Constraint, ConstraintIdentifier, getConstraint, serializeConstraint} from '../constraints';\nimport {InputSpec, SymbolicTensor} from '../engine/topology';\nimport {Layer, LayerArgs} from '../engine/topology';\nimport {AttributeError, NotImplementedError, ValueError} from '../errors';\nimport {getInitializer, Initializer, InitializerIdentifier, Ones, serializeInitializer} from '../initializers';\nimport {ActivationIdentifier} from '../keras_format/activation_config';\nimport {Shape} from '../keras_format/common';\nimport {getRegularizer, Regularizer, RegularizerIdentifier, serializeRegularizer} from '../regularizers';\nimport {Kwargs, RnnStepFunction} from '../types';\nimport {assertPositiveInteger} from '../utils/generic_utils';\nimport * as math_utils from '../utils/math_utils';\nimport {getExactlyOneShape, getExactlyOneTensor, isArrayOfShapes} from '../utils/types_utils';\nimport {batchGetValue, batchSetValue, LayerVariable} from '../variables';\nimport {deserialize} from './serialization';\n\n/**\n * Standardize `apply()` args to a single list of tensor inputs.\n *\n * When running a model loaded from file, the input tensors `initialState` and\n * `constants` are passed to `RNN.apply()` as part of `inputs` instead of the\n * dedicated kwargs fields. `inputs` consists of\n * `[inputs, initialState0, initialState1, ..., constant0, constant1]` in this\n * case.\n * This method makes sure that arguments are\n * separated and that `initialState` and `constants` are `Array`s of tensors\n * (or None).\n *\n * @param inputs Tensor or `Array` of tensors.\n * @param initialState Tensor or `Array` of tensors or `null`/`undefined`.\n * @param constants Tensor or `Array` of tensors or `null`/`undefined`.\n * @returns An object consisting of\n * inputs: A tensor.\n * initialState: `Array` of tensors or `null`.\n * constants: `Array` of tensors or `null`.\n * @throws ValueError, if `inputs` is an `Array` but either `initialState` or\n * `constants` is provided.\n */\nexport function standardizeArgs(\n inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],\n initialState: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],\n constants: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],\n numConstants?: number): {\n inputs: Tensor|SymbolicTensor,\n initialState: Tensor[]|SymbolicTensor[],\n constants: Tensor[]|SymbolicTensor[]\n} {\n if (Array.isArray(inputs)) {\n if (initialState != null || constants != null) {\n throw new ValueError(\n 'When inputs is an array, neither initialState or constants ' +\n 'should be provided');\n }\n if (numConstants != null) {\n constants = inputs.slice(inputs.length - numConstants, inputs.length);\n inputs = inputs.slice(0, inputs.length - numConstants);\n }\n if (inputs.length > 1) {\n initialState = inputs.slice(1, inputs.length);\n }\n inputs = inputs[0];\n }\n\n function toListOrNull(x: Tensor|Tensor[]|SymbolicTensor|\n SymbolicTensor[]): Tensor[]|SymbolicTensor[] {\n if (x == null || Array.isArray(x)) {\n return x as Tensor[] | SymbolicTensor[];\n } else {\n return [x] as Tensor[] | SymbolicTensor[];\n }\n }\n\n initialState = toListOrNull(initialState);\n constants = toListOrNull(constants);\n\n return {inputs, initialState, constants};\n}\n\n/**\n * Iterates over the time dimension of a tensor.\n *\n * @param stepFunction RNN step function.\n * Parameters:\n * inputs: tensor with shape `[samples, ...]` (no time dimension),\n * representing input for the batch of samples at a certain time step.\n * states: an Array of tensors.\n * Returns:\n * outputs: tensor with shape `[samples, outputDim]` (no time dimension).\n * newStates: list of tensors, same length and shapes as `states`. The first\n * state in the list must be the output tensor at the previous timestep.\n * @param inputs Tensor of temporal data of shape `[samples, time, ...]` (at\n * least 3D).\n * @param initialStates Tensor with shape `[samples, outputDim]` (no time\n * dimension), containing the initial values of the states used in the step\n * function.\n * @param goBackwards If `true`, do the iteration over the time dimension in\n * reverse order and return the reversed sequence.\n * @param mask Binary tensor with shape `[sample, time, 1]`, with a zero for\n * every element that is masked.\n * @param constants An Array of constant values passed at each step.\n * @param unroll Whether to unroll the RNN or to use a symbolic loop. *Not*\n * applicable to this imperative deeplearn.js backend. Its value is ignored.\n * @param needPerStepOutputs Whether the per-step outputs are to be\n * concatenated into a single tensor and returned (as the second return\n * value). Default: `false`. This arg is included so that the relatively\n * expensive concatenation of the stepwise outputs can be omitted unless\n * the stepwise outputs need to be kept (e.g., for an LSTM layer of which\n * `returnSequence` is `true`.)\n * @returns An Array: `[lastOutput, outputs, newStates]`.\n * lastOutput: the lastest output of the RNN, of shape `[samples, ...]`.\n * outputs: tensor with shape `[samples, time, ...]` where each entry\n * `output[s, t]` is the output of the step function at time `t` for sample\n * `s`. This return value is provided if and only if the\n * `needPerStepOutputs` is set as `true`. If it is set as `false`, this\n * return value will be `undefined`.\n * newStates: Array of tensors, latest states returned by the step function,\n * of shape `(samples, ...)`.\n * @throws ValueError If input dimension is less than 3.\n *\n * TODO(nielsene): This needs to be tidy-ed.\n */\nexport function rnn(\n stepFunction: RnnStepFunction, inputs: Tensor, initialStates: Tensor[],\n goBackwards = false, mask?: Tensor, constants?: Tensor[], unroll = false,\n needPerStepOutputs = false): [Tensor, Tensor, Tensor[]] {\n return tfc.tidy(() => {\n const ndim = inputs.shape.length;\n if (ndim < 3) {\n throw new ValueError(`Input should be at least 3D, but is ${ndim}D.`);\n }\n\n // Transpose to time-major, i.e., from [batch, time, ...] to [time, batch,\n // ...].\n const axes = [1, 0].concat(math_utils.range(2, ndim));\n inputs = tfc.transpose(inputs, axes);\n\n if (constants != null) {\n throw new NotImplementedError(\n 'The rnn() functoin of the deeplearn.js backend does not support ' +\n 'constants yet.');\n }\n\n // Porting Note: the unroll option is ignored by the imperative backend.\n if (unroll) {\n console.warn(\n 'Backend rnn(): the unroll = true option is not applicable to the ' +\n 'imperative deeplearn.js backend.');\n }\n\n if (mask != null) {\n mask = tfc.cast(tfc.cast(mask, 'bool'), 'float32');\n if (mask.rank === ndim - 1) {\n mask = tfc.expandDims(mask, -1);\n }\n mask = tfc.transpose(mask, axes);\n }\n\n if (goBackwards) {\n inputs = tfc.reverse(inputs, 0);\n if (mask != null) {\n mask = tfc.reverse(mask, 0);\n }\n }\n\n // Porting Note: PyKeras with TensorFlow backend uses a symbolic loop\n // (tf.while_loop). But for the imperative deeplearn.js backend, we just\n // use the usual TypeScript control flow to iterate over the time steps in\n // the inputs.\n // Porting Note: PyKeras patches a \"_use_learning_phase\" attribute to\n // outputs.\n // This is not idiomatic in TypeScript. The info regarding whether we are\n // in a learning (i.e., training) phase for RNN is passed in a different\n // way.\n\n const perStepOutputs: Tensor[] = [];\n let lastOutput: Tensor;\n let states = initialStates;\n const timeSteps = inputs.shape[0];\n const perStepInputs = tfc.unstack(inputs);\n let perStepMasks: Tensor[];\n if (mask != null) {\n perStepMasks = tfc.unstack(mask);\n }\n\n for (let t = 0; t < timeSteps; ++t) {\n const currentInput = perStepInputs[t];\n const stepOutputs = tfc.tidy(() => stepFunction(currentInput, states));\n\n if (mask == null) {\n lastOutput = stepOutputs[0];\n states = stepOutputs[1];\n } else {\n const maskedOutputs = tfc.tidy(() => {\n const stepMask = perStepMasks[t];\n const negStepMask = tfc.sub(tfc.onesLike(stepMask), stepMask);\n // TODO(cais): Would tfc.where() be better for performance?\n const output = tfc.add(\n tfc.mul(stepOutputs[0], stepMask),\n tfc.mul(states[0], negStepMask));\n const newStates = states.map((state, i) => {\n return tfc.add(\n tfc.mul(stepOutputs[1][i], stepMask),\n tfc.mul(state, negStepMask));\n });\n return {output, newStates};\n });\n lastOutput = maskedOutputs.output;\n states = maskedOutputs.newStates;\n }\n\n if (needPerStepOutputs) {\n perStepOutputs.push(lastOutput);\n }\n }\n let outputs: Tensor;\n if (needPerStepOutputs) {\n const axis = 1;\n outputs = tfc.stack(perStepOutputs, axis);\n }\n return [lastOutput, outputs, states] as [Tensor, Tensor, Tensor[]];\n });\n}\n\nexport declare interface BaseRNNLayerArgs extends LayerArgs {\n /**\n * A RNN cell instance. A RNN cell is a class that has:\n * - a `call()` method, which takes `[Tensor, Tensor]` as the\n * first input argument. The first item is the input at time t, and\n * second item is the cell state at time t.\n * The `call()` method returns `[outputAtT, statesAtTPlus1]`.\n * The `call()` method of the cell can also take the argument `constants`,\n * see section \"Note on passing external constants\" below.\n * Porting Node: PyKeras overrides the `call()` signature of RNN cells,\n * which are Layer subtypes, to accept two arguments. tfjs-layers does\n * not do such overriding. Instead we preseve the `call()` signature,\n * which due to its `Tensor|Tensor[]` argument and return value, is\n * flexible enough to handle the inputs and states.\n * - a `stateSize` attribute. This can be a single integer (single state)\n * in which case it is the size of the recurrent state (which should be\n * the same as the size of the cell output). This can also be an Array of\n * integers (one size per state). In this case, the first entry\n * (`stateSize[0]`) should be the same as the size of the cell output.\n * It is also possible for `cell` to be a list of RNN cell instances, in which\n * case the cells get stacked on after the other in the RNN, implementing an\n * efficient stacked RNN.\n */\n cell?: RNNCell|RNNCell[];\n\n /**\n * Whether to return the last output in the output sequence, or the full\n * sequence.\n */\n returnSequences?: boolean;\n\n /**\n * Whether to return the last state in addition to the output.\n */\n returnState?: boolean;\n\n /**\n * If `true`, process the input sequence backwards and return the reversed\n * sequence (default: `false`).\n */\n goBackwards?: boolean;\n\n /**\n * If `true`, the last state for each sample at index i in a batch will be\n * used as initial state of the sample of index i in the following batch\n * (default: `false`).\n *\n * You can set RNN layers to be \"stateful\", which means that the states\n * computed for the samples in one batch will be reused as initial states\n * for the samples in the next batch. This assumes a one-to-one mapping\n * between samples in different successive batches.\n *\n * To enable \"statefulness\":\n * - specify `stateful: true` in the layer constructor.\n * - specify a fixed batch size for your model, by passing\n * - if sequential model:\n * `batchInputShape: [...]` to the first layer in your model.\n * - else for functional model with 1 or more Input layers:\n * `batchShape: [...]` to all the first layers in your model.\n * This is the expected shape of your inputs\n * *including the batch size*.\n * It should be a tuple of integers, e.g., `[32, 10, 100]`.\n * - specify `shuffle: false` when calling `LayersModel.fit()`.\n *\n * To reset the state of your model, call `resetStates()` on either the\n * specific layer or on the entire model.\n */\n stateful?: boolean;\n // TODO(cais): Explore whether we can warn users when they fail to set\n // `shuffle: false` when training a model consisting of stateful RNNs\n // and any stateful Layers in general.\n\n /**\n * If `true`, the network will be unrolled, else a symbolic loop will be\n * used. Unrolling can speed-up a RNN, although it tends to be more memory-\n * intensive. Unrolling is only suitable for short sequences (default:\n * `false`).\n * Porting Note: tfjs-layers has an imperative backend. RNNs are executed with\n * normal TypeScript control flow. Hence this property is inapplicable and\n * ignored in tfjs-layers.\n */\n unroll?: boolean;\n\n /**\n * Dimensionality of the input (integer).\n * This option (or alternatively, the option `inputShape`) is required when\n * this layer is used as the first layer in a model.\n */\n inputDim?: number;\n\n /**\n * Length of the input sequences, to be specified when it is constant.\n * This argument is required if you are going to connect `Flatten` then\n * `Dense` layers upstream (without it, the shape of the dense outputs cannot\n * be computed). Note that if the recurrent layer is not the first layer in\n * your model, you would need to specify the input length at the level of the\n * first layer (e.g., via the `inputShape` option).\n */\n inputLength?: number;\n}\n\nexport class RNN extends Layer {\n /** @nocollapse */\n static className = 'RNN';\n public readonly cell: RNNCell;\n public readonly returnSequences: boolean;\n public readonly returnState: boolean;\n public readonly goBackwards: boolean;\n public readonly unroll: boolean;\n\n public stateSpec: InputSpec[];\n protected states_: Tensor[];\n\n // NOTE(cais): For stateful RNNs, the old states cannot be disposed right\n // away when new states are set, because the old states may need to be used\n // later for backpropagation through time (BPTT) and other purposes. So we\n // keep them here for final disposal when the state is reset completely\n // (i.e., through no-arg call to `resetStates()`).\n protected keptStates: Tensor[][];\n\n private numConstants: number;\n\n constructor(args: RNNLayerArgs) {\n super(args);\n let cell: RNNCell;\n if (args.cell == null) {\n throw new ValueError(\n 'cell property is missing for the constructor of RNN.');\n } else if (Array.isArray(args.cell)) {\n cell = new StackedRNNCells({cells: args.cell});\n } else {\n cell = args.cell;\n }\n if (cell.stateSize == null) {\n throw new ValueError(\n 'The RNN cell should have an attribute `stateSize` (tuple of ' +\n 'integers, one integer per RNN state).');\n }\n this.cell = cell;\n this.returnSequences =\n args.returnSequences == null ? false : args.returnSequences;\n this.returnState = args.returnState == null ? false : args.returnState;\n this.goBackwards = args.goBackwards == null ? false : args.goBackwards;\n this._stateful = args.stateful == null ? false : args.stateful;\n this.unroll = args.unroll == null ? false : args.unroll;\n\n this.supportsMasking = true;\n this.inputSpec = [new InputSpec({ndim: 3})];\n this.stateSpec = null;\n this.states_ = null;\n // TODO(cais): Add constantsSpec and numConstants.\n this.numConstants = null;\n // TODO(cais): Look into the use of initial_state in the kwargs of the\n // constructor.\n\n this.keptStates = [];\n }\n\n // Porting Note: This is the equivalent of `RNN.states` property getter in\n // PyKeras.\n getStates(): Tensor[] {\n if (this.states_ == null) {\n const numStates =\n Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;\n return math_utils.range(0, numStates).map(x => null);\n } else {\n return this.states_;\n }\n }\n\n // Porting Note: This is the equivalent of the `RNN.states` property setter in\n // PyKeras.\n setStates(states: Tensor[]): void {\n this.states_ = states;\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n if (isArrayOfShapes(inputShape)) {\n inputShape = (inputShape as Shape[])[0];\n }\n inputShape = inputShape as Shape;\n\n // TODO(cais): Remove the casting once stacked RNN cells become supported.\n let stateSize = this.cell.stateSize;\n if (!Array.isArray(stateSize)) {\n stateSize = [stateSize];\n }\n const outputDim = stateSize[0];\n let outputShape: Shape|Shape[];\n if (this.returnSequences) {\n outputShape = [inputShape[0], inputShape[1], outputDim];\n } else {\n outputShape = [inputShape[0], outputDim];\n }\n\n if (this.returnState) {\n const stateShape: Shape[] = [];\n for (const dim of stateSize) {\n stateShape.push([inputShape[0], dim]);\n }\n return [outputShape].concat(stateShape);\n } else {\n return outputShape;\n }\n }\n\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor\n |Tensor[] {\n return tfc.tidy(() => {\n if (Array.isArray(mask)) {\n mask = mask[0];\n }\n const outputMask = this.returnSequences ? mask : null;\n\n if (this.returnState) {\n const stateMask = this.states.map(s => null);\n return [outputMask].concat(stateMask);\n } else {\n return outputMask;\n }\n });\n }\n\n /**\n * Get the current state tensors of the RNN.\n *\n * If the state hasn't been set, return an array of `null`s of the correct\n * length.\n */\n get states(): Tensor[] {\n if (this.states_ == null) {\n const numStates =\n Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;\n const output: Tensor[] = [];\n for (let i = 0; i < numStates; ++i) {\n output.push(null);\n }\n return output;\n } else {\n return this.states_;\n }\n }\n\n set states(s: Tensor[]) {\n this.states_ = s;\n }\n\n public build(inputShape: Shape|Shape[]): void {\n // Note inputShape will be an Array of Shapes of initial states and\n // constants if these are passed in apply().\n const constantShape: Shape[] = null;\n if (this.numConstants != null) {\n throw new NotImplementedError(\n 'Constants support is not implemented in RNN yet.');\n }\n\n if (isArrayOfShapes(inputShape)) {\n inputShape = (inputShape as Shape[])[0];\n }\n inputShape = inputShape as Shape;\n\n const batchSize: number = this.stateful ? inputShape[0] : null;\n const inputDim = inputShape.slice(2);\n this.inputSpec[0] = new InputSpec({shape: [batchSize, null, ...inputDim]});\n\n // Allow cell (if RNNCell Layer) to build before we set or validate\n // stateSpec.\n const stepInputShape = [inputShape[0]].concat(inputShape.slice(2));\n if (constantShape != null) {\n throw new NotImplementedError(\n 'Constants support is not implemented in RNN yet.');\n } else {\n this.cell.build(stepInputShape);\n }\n\n // Set or validate stateSpec.\n let stateSize: number[];\n if (Array.isArray(this.cell.stateSize)) {\n stateSize = this.cell.stateSize;\n } else {\n stateSize = [this.cell.stateSize];\n }\n\n if (this.stateSpec != null) {\n if (!util.arraysEqual(\n this.stateSpec.map(spec => spec.shape[spec.shape.length - 1]),\n stateSize)) {\n throw new ValueError(\n `An initialState was passed that is not compatible with ` +\n `cell.stateSize. Received stateSpec=${this.stateSpec}; ` +\n `However cell.stateSize is ${this.cell.stateSize}`);\n }\n } else {\n this.stateSpec =\n stateSize.map(dim => new InputSpec({shape: [null, dim]}));\n }\n if (this.stateful) {\n this.resetStates();\n }\n }\n\n /**\n * Reset the state tensors of the RNN.\n *\n * If the `states` argument is `undefined` or `null`, will set the\n * state tensor(s) of the RNN to all-zero tensors of the appropriate\n * shape(s).\n *\n * If `states` is provided, will set the state tensors of the RNN to its\n * value.\n *\n * @param states Optional externally-provided initial states.\n * @param training Whether this call is done during training. For stateful\n * RNNs, this affects whether the old states are kept or discarded. In\n * particular, if `training` is `true`, the old states will be kept so\n * that subsequent backpropgataion through time (BPTT) may work properly.\n * Else, the old states will be discarded.\n */\n resetStates(states?: Tensor|Tensor[], training = false): void {\n tidy(() => {\n if (!this.stateful) {\n throw new AttributeError(\n 'Cannot call resetStates() on an RNN Layer that is not stateful.');\n }\n const batchSize = this.inputSpec[0].shape[0];\n if (batchSize == null) {\n throw new ValueError(\n 'If an RNN is stateful, it needs to know its batch size. Specify ' +\n 'the batch size of your input tensors: \\n' +\n '- If using a Sequential model, specify the batch size by ' +\n 'passing a `batchInputShape` option to your first layer.\\n' +\n '- If using the functional API, specify the batch size by ' +\n 'passing a `batchShape` option to your Input layer.');\n }\n // Initialize state if null.\n if (this.states_ == null) {\n if (Array.isArray(this.cell.stateSize)) {\n this.states_ =\n this.cell.stateSize.map(dim => tfc.zeros([batchSize, dim]));\n } else {\n this.states_ = [tfc.zeros([batchSize, this.cell.stateSize])];\n }\n } else if (states == null) {\n // Dispose old state tensors.\n tfc.dispose(this.states_);\n // For stateful RNNs, fully dispose kept old states.\n if (this.keptStates != null) {\n tfc.dispose(this.keptStates);\n this.keptStates = [];\n }\n\n if (Array.isArray(this.cell.stateSize)) {\n this.states_ =\n this.cell.stateSize.map(dim => tfc.zeros([batchSize, dim]));\n } else {\n this.states_[0] = tfc.zeros([batchSize, this.cell.stateSize]);\n }\n } else {\n if (!Array.isArray(states)) {\n states = [states];\n }\n if (states.length !== this.states_.length) {\n throw new ValueError(\n `Layer ${this.name} expects ${this.states_.length} state(s), ` +\n `but it received ${states.length} state value(s). Input ` +\n `received: ${states}`);\n }\n\n if (training === true) {\n // Store old state tensors for complete disposal later, i.e., during\n // the next no-arg call to this method. We do not dispose the old\n // states immediately because that BPTT (among other things) require\n // them.\n this.keptStates.push(this.states_.slice());\n } else {\n tfc.dispose(this.states_);\n }\n\n for (let index = 0; index < this.states_.length; ++index) {\n const value = states[index];\n const dim = Array.isArray(this.cell.stateSize) ?\n this.cell.stateSize[index] :\n this.cell.stateSize;\n const expectedShape = [batchSize, dim];\n if (!util.arraysEqual(value.shape, expectedShape)) {\n throw new ValueError(\n `State ${index} is incompatible with layer ${this.name}: ` +\n `expected shape=${expectedShape}, received shape=${\n value.shape}`);\n }\n this.states_[index] = value;\n }\n }\n this.states_ = this.states_.map(state => tfc.keep(state.clone()));\n });\n }\n\n apply(\n inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],\n kwargs?: Kwargs): Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[] {\n // TODO(cais): Figure out whether initialState is in kwargs or inputs.\n let initialState: Tensor[]|SymbolicTensor[] =\n kwargs == null ? null : kwargs['initialState'];\n let constants: Tensor[]|SymbolicTensor[] =\n kwargs == null ? null : kwargs['constants'];\n if (kwargs == null) {\n kwargs = {};\n }\n\n const standardized =\n standardizeArgs(inputs, initialState, constants, this.numConstants);\n inputs = standardized.inputs;\n initialState = standardized.initialState;\n constants = standardized.constants;\n\n // If any of `initial_state` or `constants` are specified and are\n // `tf.SymbolicTensor`s, then add them to the inputs and temporarily modify\n // the input_spec to include them.\n\n let additionalInputs: Array<Tensor|SymbolicTensor> = [];\n let additionalSpecs: InputSpec[] = [];\n if (initialState != null) {\n kwargs['initialState'] = initialState;\n additionalInputs = additionalInputs.concat(initialState);\n this.stateSpec = [];\n for (const state of initialState) {\n this.stateSpec.push(new InputSpec({shape: state.shape}));\n }\n // TODO(cais): Use the following instead.\n // this.stateSpec = initialState.map(state => new InputSpec({shape:\n // state.shape}));\n additionalSpecs = additionalSpecs.concat(this.stateSpec);\n }\n if (constants != null) {\n kwargs['constants'] = constants;\n additionalInputs = additionalInputs.concat(constants);\n // TODO(cais): Add this.constantsSpec.\n this.numConstants = constants.length;\n }\n\n const isTensor = additionalInputs[0] instanceof SymbolicTensor;\n if (isTensor) {\n // Compute full input spec, including state and constants.\n const fullInput =\n [inputs].concat(additionalInputs) as Tensor[] | SymbolicTensor[];\n const fullInputSpec = this.inputSpec.concat(additionalSpecs);\n // Perform the call with temporarily replaced inputSpec.\n const originalInputSpec = this.inputSpec;\n this.inputSpec = fullInputSpec;\n const output = super.apply(fullInput, kwargs);\n this.inputSpec = originalInputSpec;\n return output;\n } else {\n return super.apply(inputs, kwargs);\n }\n }\n\n // tslint:disable-next-line:no-any\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n // Input shape: `[samples, time (padded with zeros), input_dim]`.\n // Note that the .build() method of subclasses **must** define\n // this.inputSpec and this.stateSpec owith complete input shapes.\n return tidy(() => {\n const mask = kwargs == null ? null : kwargs['mask'] as Tensor;\n const training = kwargs == null ? null : kwargs['training'];\n let initialState: Tensor[] =\n kwargs == null ? null : kwargs['initialState'];\n\n inputs = getExactlyOneTensor(inputs);\n if (initialState == null) {\n if (this.stateful) {\n initialState = this.states_;\n } else {\n initialState = this.getInitialState(inputs);\n }\n }\n\n const numStates =\n Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1;\n if (initialState.length !== numStates) {\n throw new ValueError(\n `RNN Layer has ${numStates} state(s) but was passed ` +\n `${initialState.length} initial state(s).`);\n }\n if (this.unroll) {\n console.warn(\n 'Ignoring unroll = true for RNN layer, due to imperative backend.');\n }\n\n const cellCallKwargs: Kwargs = {training};\n\n // TODO(cais): Add support for constants.\n const step = (inputs: Tensor, states: Tensor[]) => {\n // `inputs` and `states` are concatenated to form a single `Array` of\n // `tf.Tensor`s as the input to `cell.call()`.\n const outputs =\n this.cell.call([inputs].concat(states), cellCallKwargs) as Tensor[];\n // Marshall the return value into output and new states.\n return [outputs[0], outputs.slice(1)] as [Tensor, Tensor[]];\n };\n\n // TODO(cais): Add support for constants.\n\n const rnnOutputs =\n rnn(step, inputs, initialState, this.goBackwards, mask, null,\n this.unroll, this.returnSequences);\n const lastOutput = rnnOutputs[0];\n const outputs = rnnOutputs[1];\n const states = rnnOutputs[2];\n\n if (this.stateful) {\n this.resetStates(states, training);\n }\n\n const output = this.returnSequences ? outputs : lastOutput;\n\n // TODO(cais): Porperty set learning phase flag.\n\n if (this.returnState) {\n return [output].concat(states);\n } else {\n return output;\n }\n });\n }\n\n getInitialState(inputs: Tensor): Tensor[] {\n return tidy(() => {\n // Build an all-zero tensor of shape [samples, outputDim].\n // [Samples, timeSteps, inputDim].\n let initialState = tfc.zeros(inputs.shape);\n // [Samples].\n initialState = tfc.sum(initialState, [1, 2]);\n initialState = K.expandDims(initialState); // [Samples, 1].\n\n if (Array.isArray(this.cell.stateSize)) {\n return this.cell.stateSize.map(\n dim => dim > 1 ? K.tile(initialState, [1, dim]) : initialState);\n } else {\n return this.cell.stateSize > 1 ?\n [K.tile(initialState, [1, this.cell.stateSize])] :\n [initialState];\n }\n });\n }\n\n get trainableWeights(): LayerVariable[] {\n if (!this.trainable) {\n return [];\n }\n // Porting Note: In TypeScript, `this` is always an instance of `Layer`.\n return this.cell.trainableWeights;\n }\n\n get nonTrainableWeights(): LayerVariable[] {\n // Porting Note: In TypeScript, `this` is always an instance of `Layer`.\n if (!this.trainable) {\n return this.cell.weights;\n }\n return this.cell.nonTrainableWeights;\n }\n\n setFastWeightInitDuringBuild(value: boolean) {\n super.setFastWeightInitDuringBuild(value);\n if (this.cell != null) {\n this.cell.setFastWeightInitDuringBuild(value);\n }\n }\n\n getConfig(): serialization.ConfigDict {\n const baseConfig = super.getConfig();\n\n const config: serialization.ConfigDict = {\n returnSequences: this.returnSequences,\n returnState: this.returnState,\n goBackwards: this.goBackwards,\n stateful: this.stateful,\n unroll: this.unroll,\n };\n\n if (this.numConstants != null) {\n config['numConstants'] = this.numConstants;\n }\n\n const cellConfig = this.cell.getConfig();\n\n if (this.getClassName() === RNN.className) {\n config['cell'] = {\n 'className': this.cell.getClassName(),\n 'config': cellConfig,\n } as serialization.ConfigDictValue;\n }\n\n // this order is necessary, to prevent cell name from replacing layer name\n return {...cellConfig, ...baseConfig, ...config};\n }\n\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict,\n customObjects = {} as serialization.ConfigDict): T {\n const cellConfig = config['cell'] as serialization.ConfigDict;\n const cell = deserialize(cellConfig, customObjects) as RNNCell;\n return new cls(Object.assign(config, {cell}));\n }\n}\nserialization.registerClass(RNN);\n\n// Porting Note: This is a common parent class for RNN cells. There is no\n// equivalent of this in PyKeras. Having a common parent class forgoes the\n// need for `has_attr(cell, ...)` checks or its TypeScript equivalent.\n/**\n * An RNNCell layer.\n *\n * @doc {heading: 'Layers', subheading: 'Classes'}\n */\nexport abstract class RNNCell extends Layer {\n /**\n * Size(s) of the states.\n * For RNN cells with only a single state, this is a single integer.\n */\n // See\n // https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#properties-overriding-accessors-and-vice-versa-is-an-error\n public abstract stateSize: number|number[];\n public dropoutMask: Tensor|Tensor[];\n public recurrentDropoutMask: Tensor|Tensor[];\n}\n\nexport declare interface SimpleRNNCellLayerArgs extends LayerArgs {\n /**\n * units: Positive integer, dimensionality of the output space.\n */\n units: number;\n\n /**\n * Activation function to use.\n * Default: hyperbolic tangent ('tanh').\n * If you pass `null`, 'linear' activation will be applied.\n */\n activation?: ActivationIdentifier;\n\n /**\n * Whether the layer uses a bias vector.\n */\n useBias?: boolean;\n\n /**\n * Initializer for the `kernel` weights matrix, used for the linear\n * transformation of the inputs.\n */\n kernelInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the `recurrentKernel` weights matrix, used for\n * linear transformation of the recurrent state.\n */\n recurrentInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the bias vector.\n */\n biasInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Regularizer function applied to the `kernel` weights matrix.\n */\n kernelRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the `recurrent_kernel` weights matrix.\n */\n recurrentRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the bias vector.\n */\n biasRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Constraint function applied to the `kernel` weights matrix.\n */\n kernelConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Constraint function applied to the `recurrentKernel` weights matrix.\n */\n recurrentConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Constraintfunction applied to the bias vector.\n */\n biasConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Float number between 0 and 1. Fraction of the units to drop for the linear\n * transformation of the inputs.\n */\n dropout?: number;\n\n /**\n * Float number between 0 and 1. Fraction of the units to drop for the linear\n * transformation of the recurrent state.\n */\n recurrentDropout?: number;\n}\n\nexport class SimpleRNNCell extends RNNCell {\n /** @nocollapse */\n static className = 'SimpleRNNCell';\n readonly units: number;\n readonly activation: Activation;\n readonly useBias: boolean;\n\n readonly kernelInitializer: Initializer;\n readonly recurrentInitializer: Initializer;\n readonly biasInitializer: Initializer;\n\n readonly kernelConstraint: Constraint;\n readonly recurrentConstraint: Constraint;\n readonly biasConstraint: Constraint;\n\n readonly kernelRegularizer: Regularizer;\n readonly recurrentRegularizer: Regularizer;\n readonly biasRegularizer: Regularizer;\n\n readonly dropout: number;\n readonly recurrentDropout: number;\n\n readonly stateSize: number;\n\n kernel: LayerVariable;\n recurrentKernel: LayerVariable;\n bias: LayerVariable;\n\n readonly DEFAULT_ACTIVATION = 'tanh';\n readonly DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';\n readonly DEFAULT_RECURRENT_INITIALIZER = 'orthogonal';\n readonly DEFAULT_BIAS_INITIALIZER: InitializerIdentifier = 'zeros';\n\n constructor(args: SimpleRNNCellLayerArgs) {\n super(args);\n this.units = args.units;\n assertPositiveInteger(this.units, `units`);\n this.activation = getActivation(\n args.activation == null ? this.DEFAULT_ACTIVATION : args.activation);\n this.useBias = args.useBias == null ? true : args.useBias;\n\n this.kernelInitializer = getInitializer(\n args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER);\n this.recurrentInitializer = getInitializer(\n args.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER);\n\n this.biasInitializer =\n getInitializer(args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER);\n\n this.kernelRegularizer = getRegularizer(args.kernelRegularizer);\n this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);\n this.biasRegularizer = getRegularizer(args.biasRegularizer);\n\n this.kernelConstraint = getConstraint(args.kernelConstraint);\n this.recurrentConstraint = getConstraint(args.recurrentConstraint);\n this.biasConstraint = getConstraint(args.biasConstraint);\n\n this.dropout = math_utils.min(\n [1, math_utils.max([0, args.dropout == null ? 0 : args.dropout])]);\n this.recurrentDropout = math_utils.min([\n 1,\n math_utils.max(\n [0, args.recurrentDropout == null ? 0 : args.recurrentDropout])\n ]);\n this.stateSize = this.units;\n this.dropoutMask = null;\n this.recurrentDropoutMask = null;\n }\n\n build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n // TODO(cais): Use regularizer.\n this.kernel = this.addWeight(\n 'kernel', [inputShape[inputShape.length - 1], this.units], null,\n this.kernelInitializer, this.kernelRegularizer, true,\n this.kernelConstraint);\n this.recurrentKernel = this.addWeight(\n 'recurrent_kernel', [this.units, this.units], null,\n this.recurrentInitializer, this.recurrentRegularizer, true,\n this.recurrentConstraint);\n if (this.useBias) {\n this.bias = this.addWeight(\n 'bias', [this.units], null, this.biasInitializer,\n this.biasRegularizer, true, this.biasConstraint);\n } else {\n this.bias = null;\n }\n this.built = true;\n }\n\n // Porting Note: PyKeras' equivalent of this method takes two tensor inputs:\n // `inputs` and `states`. Here, the two tensors are combined into an\n // `Tensor[]` Array as the first input argument.\n // Similarly, PyKeras' equivalent of this method returns two values:\n // `output` and `[output]`. Here the two are combined into one length-2\n // `Tensor[]`, consisting of `output` repeated.\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = inputs as Tensor[];\n if (inputs.length !== 2) {\n throw new ValueError(\n `SimpleRNNCell expects 2 input Tensors, got ${inputs.length}.`);\n }\n let prevOutput = inputs[1];\n inputs = inputs[0];\n const training = kwargs['training'] == null ? false : kwargs['training'];\n\n if (0 < this.dropout && this.dropout < 1 && this.dropoutMask == null) {\n this.dropoutMask = generateDropoutMask({\n ones: () => tfc.onesLike(inputs as Tensor),\n rate: this.dropout,\n training\n }) as Tensor;\n }\n if (0 < this.recurrentDropout && this.recurrentDropout < 1 &&\n this.recurrentDropoutMask == null) {\n this.recurrentDropoutMask = generateDropoutMask({\n ones: () => tfc.onesLike(prevOutput),\n rate: this.recurrentDropout,\n training\n }) as Tensor;\n }\n let h: Tensor;\n const dpMask: Tensor = this.dropoutMask as Tensor;\n const recDpMask: Tensor = this.recurrentDropoutMask as Tensor;\n if (dpMask != null) {\n h = K.dot(tfc.mul(inputs, dpMask), this.kernel.read());\n } else {\n h = K.dot(inputs, this.kernel.read());\n }\n if (this.bias != null) {\n h = K.biasAdd(h, this.bias.read());\n }\n if (recDpMask != null) {\n prevOutput = tfc.mul(prevOutput, recDpMask);\n }\n let output = tfc.add(h, K.dot(prevOutput, this.recurrentKernel.read()));\n if (this.activation != null) {\n output = this.activation.apply(output);\n }\n\n // TODO(cais): Properly set learning phase on output tensor?\n return [output, output];\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const baseConfig = super.getConfig();\n\n const config: serialization.ConfigDict = {\n units: this.units,\n activation: serializeActivation(this.activation),\n useBias: this.useBias,\n kernelInitializer: serializeInitializer(this.kernelInitializer),\n recurrentInitializer: serializeInitializer(this.recurrentInitializer),\n biasInitializer: serializeInitializer(this.biasInitializer),\n kernelRegularizer: serializeRegularizer(this.kernelRegularizer),\n recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),\n biasRegularizer: serializeRegularizer(this.biasRegularizer),\n activityRegularizer: serializeRegularizer(this.activityRegularizer),\n kernelConstraint: serializeConstraint(this.kernelConstraint),\n recurrentConstraint: serializeConstraint(this.recurrentConstraint),\n biasConstraint: serializeConstraint(this.biasConstraint),\n dropout: this.dropout,\n recurrentDropout: this.recurrentDropout,\n };\n\n return {...baseConfig, ...config};\n }\n}\nserialization.registerClass(SimpleRNNCell);\n\nexport declare interface SimpleRNNLayerArgs extends BaseRNNLayerArgs {\n /**\n * Positive integer, dimensionality of the output space.\n */\n units: number;\n\n /**\n * Activation function to use.\n *\n * Defaults to hyperbolic tangent (`tanh`)\n *\n * If you pass `null`, no activation will be applied.\n */\n activation?: ActivationIdentifier;\n\n /**\n * Whether the layer uses a bias vector.\n */\n useBias?: boolean;\n\n /**\n * Initializer for the `kernel` weights matrix, used for the linear\n * transformation of the inputs.\n */\n kernelInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the `recurrentKernel` weights matrix, used for\n * linear transformation of the recurrent state.\n */\n recurrentInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the bias vector.\n */\n biasInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Regularizer function applied to the kernel weights matrix.\n */\n kernelRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the recurrentKernel weights matrix.\n */\n recurrentRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the bias vector.\n */\n biasRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Constraint function applied to the kernel weights matrix.\n */\n kernelConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Constraint function applied to the recurrentKernel weights matrix.\n */\n recurrentConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Constraint function applied to the bias vector.\n */\n biasConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Number between 0 and 1. Fraction of the units to drop for the linear\n * transformation of the inputs.\n */\n dropout?: number;\n\n /**\n * Number between 0 and 1. Fraction of the units to drop for the linear\n * transformation of the recurrent state.\n */\n recurrentDropout?: number;\n}\n\n/**\n * RNNLayerConfig is identical to BaseRNNLayerConfig, except it makes the\n * `cell` property required. This interface is to be used with constructors\n * of concrete RNN layer subtypes.\n */\nexport declare interface RNNLayerArgs extends BaseRNNLayerArgs {\n cell: RNNCell|RNNCell[];\n}\n\nexport class SimpleRNN extends RNN {\n /** @nocollapse */\n static className = 'SimpleRNN';\n constructor(args: SimpleRNNLayerArgs) {\n args.cell = new SimpleRNNCell(args);\n super(args as RNNLayerArgs);\n // TODO(cais): Add activityRegularizer.\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n if (this.cell.dropoutMask != null) {\n tfc.dispose(this.cell.dropoutMask);\n this.cell.dropoutMask = null;\n }\n if (this.cell.recurrentDropoutMask != null) {\n tfc.dispose(this.cell.recurrentDropoutMask);\n this.cell.recurrentDropoutMask = null;\n }\n const mask = kwargs == null ? null : kwargs['mask'];\n const training = kwargs == null ? null : kwargs['training'];\n const initialState: Tensor[] =\n kwargs == null ? null : kwargs['initialState'];\n return super.call(inputs, {mask, training, initialState});\n });\n }\n\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict): T {\n return new cls(config);\n }\n}\nserialization.registerClass(SimpleRNN);\n\n// Porting Note: Since this is a superset of SimpleRNNLayerConfig, we extend\n// that interface instead of repeating the fields.\nexport declare interface GRUCellLayerArgs extends SimpleRNNCellLayerArgs {\n /**\n * Activation function to use for the recurrent step.\n *\n * Defaults to hard sigmoid (`hardSigmoid`).\n *\n * If `null`, no activation is applied.\n */\n recurrentActivation?: ActivationIdentifier;\n\n /**\n * Implementation mode, either 1 or 2.\n *\n * Mode 1 will structure its operations as a larger number of\n * smaller dot products and additions.\n *\n * Mode 2 will batch them into fewer, larger operations. These modes will\n * have different performance profiles on different hardware and\n * for different applications.\n *\n * Note: For superior performance, TensorFlow.js always uses implementation\n * 2, regardless of the actual value of this configuration field.\n */\n implementation?: number;\n\n /**\n * GRU convention (whether to apply reset gate after or before matrix\n * multiplication). false = \"before\", true = \"after\" (only false is\n * supported).\n */\n resetAfter?: boolean;\n}\n\nexport class GRUCell extends RNNCell {\n /** @nocollapse */\n static className = 'GRUCell';\n readonly units: number;\n readonly activation: Activation;\n readonly recurrentActivation: Activation;\n readonly useBias: boolean;\n\n readonly kernelInitializer: Initializer;\n readonly recurrentInitializer: Initializer;\n readonly biasInitializer: Initializer;\n\n readonly kernelRegularizer: Regularizer;\n readonly recurrentRegularizer: Regularizer;\n readonly biasRegularizer: Regularizer;\n\n readonly kernelConstraint: Constraint;\n readonly recurrentConstraint: Constraint;\n readonly biasConstraint: Constraint;\n\n readonly dropout: number;\n readonly recurrentDropout: number;\n\n readonly stateSize: number;\n readonly implementation: number;\n\n readonly DEFAULT_ACTIVATION = 'tanh';\n readonly DEFAULT_RECURRENT_ACTIVATION: ActivationIdentifier = 'hardSigmoid';\n\n readonly DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';\n readonly DEFAULT_RECURRENT_INITIALIZER = 'orthogonal';\n readonly DEFAULT_BIAS_INITIALIZER: InitializerIdentifier = 'zeros';\n\n kernel: LayerVariable;\n recurrentKernel: LayerVariable;\n bias: LayerVariable;\n\n constructor(args: GRUCellLayerArgs) {\n super(args);\n if (args.resetAfter) {\n throw new ValueError(\n `GRUCell does not support reset_after parameter set to true.`);\n }\n this.units = args.units;\n assertPositiveInteger(this.units, 'units');\n this.activation = getActivation(\n args.activation === undefined ? this.DEFAULT_ACTIVATION :\n args.activation);\n this.recurrentActivation = getActivation(\n args.recurrentActivation === undefined ?\n this.DEFAULT_RECURRENT_ACTIVATION :\n args.recurrentActivation);\n this.useBias = args.useBias == null ? true : args.useBias;\n\n this.kernelInitializer = getInitializer(\n args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER);\n this.recurrentInitializer = getInitializer(\n args.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER);\n\n this.biasInitializer =\n getInitializer(args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER);\n\n this.kernelRegularizer = getRegularizer(args.kernelRegularizer);\n this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);\n this.biasRegularizer = getRegularizer(args.biasRegularizer);\n\n this.kernelConstraint = getConstraint(args.kernelConstraint);\n this.recurrentConstraint = getConstraint(args.recurrentConstraint);\n this.biasConstraint = getConstraint(args.biasConstraint);\n\n this.dropout = math_utils.min(\n [1, math_utils.max([0, args.dropout == null ? 0 : args.dropout])]);\n this.recurrentDropout = math_utils.min([\n 1,\n math_utils.max(\n [0, args.recurrentDropout == null ? 0 : args.recurrentDropout])\n ]);\n this.implementation = args.implementation;\n this.stateSize = this.units;\n this.dropoutMask = null;\n this.recurrentDropoutMask = null;\n }\n\n public build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n const inputDim = inputShape[inputShape.length - 1];\n this.kernel = this.addWeight(\n 'kernel', [inputDim, this.units * 3], null, this.kernelInitializer,\n this.kernelRegularizer, true, this.kernelConstraint);\n this.recurrentKernel = this.addWeight(\n 'recurrent_kernel', [this.units, this.units * 3], null,\n this.recurrentInitializer, this.recurrentRegularizer, true,\n this.recurrentConstraint);\n if (this.useBias) {\n this.bias = this.addWeight(\n 'bias', [this.units * 3], null, this.biasInitializer,\n this.biasRegularizer, true, this.biasConstraint);\n } else {\n this.bias = null;\n }\n // Porting Notes: Unlike the PyKeras implementation, we perform slicing\n // of the weights and bias in the call() method, at execution time.\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = inputs as Tensor[];\n if (inputs.length !== 2) {\n throw new ValueError(\n `GRUCell expects 2 input Tensors (inputs, h, c), got ` +\n `${inputs.length}.`);\n }\n\n const training = kwargs['training'] == null ? false : kwargs['training'];\n let hTMinus1 = inputs[1]; // Previous memory state.\n inputs = inputs[0];\n\n // Note: For superior performance, TensorFlow.js always uses\n // implementation 2, regardless of the actual value of\n // config.implementation.\n if (0 < this.dropout && this.dropout < 1 && this.dropoutMask == null) {\n this.dropoutMask = generateDropoutMask({\n ones: () => tfc.onesLike(inputs as Tensor),\n rate: this.dropout,\n training,\n count: 3\n }) as Tensor[];\n }\n if (0 < this.recurrentDropout && this.recurrentDropout < 1 &&\n this.recurrentDropoutMask == null) {\n this.recurrentDropoutMask = generateDropoutMask({\n ones: () => tfc.onesLike(hTMinus1),\n rate: this.recurrentDropout,\n training,\n count: 3\n }) as Tensor[];\n }\n const dpMask = this.dropoutMask as [Tensor, Tensor, Tensor];\n const recDpMask = this.recurrentDropoutMask as [Tensor, Tensor, Tensor];\n let z: Tensor;\n let r: Tensor;\n let hh: Tensor;\n\n if (0 < this.dropout && this.dropout < 1) {\n inputs = tfc.mul(inputs, dpMask[0]);\n }\n let matrixX = K.dot(inputs, this.kernel.read());\n if (this.useBias) {\n matrixX = K.biasAdd(matrixX, this.bias.read());\n }\n if (0 < this.recurrentDropout && this.recurrentDropout < 1) {\n hTMinus1 = tfc.mul(hTMinus1, recDpMask[0]);\n }\n\n const recurrentKernelValue = this.recurrentKernel.read();\n const [rk1, rk2] = tfc.split(\n recurrentKernelValue, [2 * this.units, this.units],\n recurrentKernelValue.rank - 1);\n const matrixInner = K.dot(hTMinus1, rk1);\n\n const [xZ, xR, xH] = tfc.split(matrixX, 3, matrixX.rank - 1);\n const [recurrentZ, recurrentR] =\n tfc.split(matrixInner, 2, matrixInner.rank - 1);\n z = this.recurrentActivation.apply(tfc.add(xZ, recurrentZ));\n r = this.recurrentActivation.apply(tfc.add(xR, recurrentR));\n\n const recurrentH = K.dot(tfc.mul(r, hTMinus1), rk2);\n hh = this.activation.apply(tfc.add(xH, recurrentH));\n\n const h =\n tfc.add(tfc.mul(z, hTMinus1), tfc.mul(tfc.add(1, tfc.neg(z)), hh));\n // TODO(cais): Add use_learning_phase flag properly.\n return [h, h];\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const baseConfig = super.getConfig();\n\n const config: serialization.ConfigDict = {\n units: this.units,\n activation: serializeActivation(this.activation),\n recurrentActivation: serializeActivation(this.recurrentActivation),\n useBias: this.useBias,\n kernelInitializer: serializeInitializer(this.kernelInitializer),\n recurrentInitializer: serializeInitializer(this.recurrentInitializer),\n biasInitializer: serializeInitializer(this.biasInitializer),\n kernelRegularizer: serializeRegularizer(this.kernelRegularizer),\n recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),\n biasRegularizer: serializeRegularizer(this.biasRegularizer),\n activityRegularizer: serializeRegularizer(this.activityRegularizer),\n kernelConstraint: serializeConstraint(this.kernelConstraint),\n recurrentConstraint: serializeConstraint(this.recurrentConstraint),\n biasConstraint: serializeConstraint(this.biasConstraint),\n dropout: this.dropout,\n recurrentDropout: this.recurrentDropout,\n implementation: this.implementation,\n resetAfter: false\n };\n\n return {...baseConfig, ...config};\n }\n}\nserialization.registerClass(GRUCell);\n\n// Porting Note: Since this is a superset of SimpleRNNLayerConfig, we inherit\n// from that interface instead of repeating the fields here.\nexport declare interface GRULayerArgs extends SimpleRNNLayerArgs {\n /**\n * Activation function to use for the recurrent step.\n *\n * Defaults to hard sigmoid (`hardSigmoid`).\n *\n * If `null`, no activation is applied.\n */\n recurrentActivation?: ActivationIdentifier;\n\n /**\n * Implementation mode, either 1 or 2.\n *\n * Mode 1 will structure its operations as a larger number of\n * smaller dot products and additions.\n *\n * Mode 2 will batch them into fewer, larger operations. These modes will\n * have different performance profiles on different hardware and\n * for different applications.\n *\n * Note: For superior performance, TensorFlow.js always uses implementation\n * 2, regardless of the actual value of this configuration field.\n */\n implementation?: number;\n}\n\nexport class GRU extends RNN {\n /** @nocollapse */\n static className = 'GRU';\n constructor(args: GRULayerArgs) {\n if (args.implementation === 0) {\n console.warn(\n '`implementation=0` has been deprecated, and now defaults to ' +\n '`implementation=1`. Please update your layer call.');\n }\n args.cell = new GRUCell(args);\n super(args as RNNLayerArgs);\n // TODO(cais): Add activityRegularizer.\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n if (this.cell.dropoutMask != null) {\n tfc.dispose(this.cell.dropoutMask);\n this.cell.dropoutMask = null;\n }\n if (this.cell.recurrentDropoutMask != null) {\n tfc.dispose(this.cell.recurrentDropoutMask);\n this.cell.recurrentDropoutMask = null;\n }\n const mask = kwargs == null ? null : kwargs['mask'];\n const training = kwargs == null ? null : kwargs['training'];\n const initialState: Tensor[] =\n kwargs == null ? null : kwargs['initialState'];\n return super.call(inputs, {mask, training, initialState});\n });\n }\n\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict): T {\n if (config['implmentation'] === 0) {\n config['implementation'] = 1;\n }\n return new cls(config);\n }\n}\nserialization.registerClass(GRU);\n\n// Porting Note: Since this is a superset of SimpleRNNLayerConfig, we extend\n// that interface instead of repeating the fields.\nexport declare interface LSTMCellLayerArgs extends SimpleRNNCellLayerArgs {\n /**\n * Activation function to use for the recurrent step.\n *\n * Defaults to hard sigmoid (`hardSigmoid`).\n *\n * If `null`, no activation is applied.\n */\n recurrentActivation?: ActivationIdentifier;\n\n /**\n * If `true`, add 1 to the bias of the forget gate at initialization.\n * Setting it to `true` will also force `biasInitializer = 'zeros'`.\n * This is recommended in\n * [Jozefowicz et\n * al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).\n */\n unitForgetBias?: boolean;\n\n /**\n * Implementation mode, either 1 or 2.\n *\n * Mode 1 will structure its operations as a larger number of\n * smaller dot products and additions.\n *\n * Mode 2 will batch them into fewer, larger operations. These modes will\n * have different performance profiles on different hardware and\n * for different applications.\n *\n * Note: For superior performance, TensorFlow.js always uses implementation\n * 2, regardless of the actual value of this configuration field.\n */\n implementation?: number;\n}\n\nexport class LSTMCell extends RNNCell {\n /** @nocollapse */\n static className = 'LSTMCell';\n readonly units: number;\n readonly activation: Activation;\n readonly recurrentActivation: Activation;\n readonly useBias: boolean;\n\n readonly kernelInitializer: Initializer;\n readonly recurrentInitializer: Initializer;\n readonly biasInitializer: Initializer;\n readonly unitForgetBias: boolean;\n\n readonly kernelConstraint: Constraint;\n readonly recurrentConstraint: Constraint;\n readonly biasConstraint: Constraint;\n\n readonly kernelRegularizer: Regularizer;\n readonly recurrentRegularizer: Regularizer;\n readonly biasRegularizer: Regularizer;\n\n readonly dropout: number;\n readonly recurrentDropout: number;\n\n readonly stateSize: number[];\n readonly implementation: number;\n\n readonly DEFAULT_ACTIVATION = 'tanh';\n readonly DEFAULT_RECURRENT_ACTIVATION = 'hardSigmoid';\n readonly DEFAULT_KERNEL_INITIALIZER = 'glorotNormal';\n readonly DEFAULT_RECURRENT_INITIALIZER = 'orthogonal';\n\n readonly DEFAULT_BIAS_INITIALIZER = 'zeros';\n\n kernel: LayerVariable;\n recurrentKernel: LayerVariable;\n bias: LayerVariable;\n\n constructor(args: LSTMCellLayerArgs) {\n super(args);\n\n this.units = args.units;\n assertPositiveInteger(this.units, 'units');\n this.activation = getActivation(\n args.activation === undefined ? this.DEFAULT_ACTIVATION :\n args.activation);\n this.recurrentActivation = getActivation(\n args.recurrentActivation === undefined ?\n this.DEFAULT_RECURRENT_ACTIVATION :\n args.recurrentActivation);\n this.useBias = args.useBias == null ? true : args.useBias;\n\n this.kernelInitializer = getInitializer(\n args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER);\n this.recurrentInitializer = getInitializer(\n args.recurrentInitializer || this.DEFAULT_RECURRENT_INITIALIZER);\n\n this.biasInitializer =\n getInitializer(args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER);\n this.unitForgetBias = args.unitForgetBias;\n\n this.kernelRegularizer = getRegularizer(args.kernelRegularizer);\n this.recurrentRegularizer = getRegularizer(args.recurrentRegularizer);\n this.biasRegularizer = getRegularizer(args.biasRegularizer);\n\n this.kernelConstraint = getConstraint(args.kernelConstraint);\n this.recurrentConstraint = getConstraint(args.recurrentConstraint);\n this.biasConstraint = getConstraint(args.biasConstraint);\n\n this.dropout = math_utils.min(\n [1, math_utils.max([0, args.dropout == null ? 0 : args.dropout])]);\n this.recurrentDropout = math_utils.min([\n 1,\n math_utils.max(\n [0, args.recurrentDropout == null ? 0 : args.recurrentDropout])\n ]);\n this.implementation = args.implementation;\n this.stateSize = [this.units, this.units];\n this.dropoutMask = null;\n this.recurrentDropoutMask = null;\n }\n\n public build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n const inputDim = inputShape[inputShape.length - 1];\n this.kernel = this.addWeight(\n 'kernel', [inputDim, this.units * 4], null, this.kernelInitializer,\n this.kernelRegularizer, true, this.kernelConstraint);\n this.recurrentKernel = this.addWeight(\n 'recurrent_kernel', [this.units, this.units * 4], null,\n this.recurrentInitializer, this.recurrentRegularizer, true,\n this.recurrentConstraint);\n let biasInitializer: Initializer;\n if (this.useBias) {\n if (this.unitForgetBias) {\n const capturedBiasInit = this.biasInitializer;\n const capturedUnits = this.units;\n biasInitializer = new (class CustomInit extends Initializer {\n /** @nocollapse */\n static className = 'CustomInit';\n\n apply(shape: Shape, dtype?: DataType): Tensor {\n // TODO(cais): More informative variable names?\n const bI = capturedBiasInit.apply([capturedUnits]);\n const bF = (new Ones()).apply([capturedUnits]);\n const bCAndH = capturedBiasInit.apply([capturedUnits * 2]);\n return K.concatAlongFirstAxis(\n K.concatAlongFirstAxis(bI, bF), bCAndH);\n }\n })();\n } else {\n biasInitializer = this.biasInitializer;\n }\n this.bias = this.addWeight(\n 'bias', [this.units * 4], null, biasInitializer, this.biasRegularizer,\n true, this.biasConstraint);\n } else {\n this.bias = null;\n }\n // Porting Notes: Unlike the PyKeras implementation, we perform slicing\n // of the weights and bias in the call() method, at execution time.\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n const training = kwargs['training'] == null ? false : kwargs['training'];\n inputs = inputs as Tensor[];\n if (inputs.length !== 3) {\n throw new ValueError(\n `LSTMCell expects 3 input Tensors (inputs, h, c), got ` +\n `${inputs.length}.`);\n }\n let hTMinus1 = inputs[1]; // Previous memory state.\n const cTMinus1 = inputs[2]; // Previous carry state.\n inputs = inputs[0];\n if (0 < this.dropout && this.dropout < 1 && this.dropoutMask == null) {\n this.dropoutMask = generateDropoutMask({\n ones: () => tfc.onesLike(inputs as Tensor),\n rate: this.dropout,\n training,\n count: 4\n }) as Tensor[];\n }\n if (0 < this.recurrentDropout && this.recurrentDropout < 1 &&\n this.recurrentDropoutMask == null) {\n this.recurrentDropoutMask = generateDropoutMask({\n ones: () => tfc.onesLike(hTMinus1),\n rate: this.recurrentDropout,\n training,\n count: 4\n }) as Tensor[];\n }\n const dpMask = this.dropoutMask as [Tensor, Tensor, Tensor, Tensor];\n const recDpMask =\n this.recurrentDropoutMask as [Tensor, Tensor, Tensor, Tensor];\n\n // Note: For superior performance, TensorFlow.js always uses\n // implementation 2 regardless of the actual value of\n // config.implementation.\n let i: Tensor;\n let f: Tensor;\n let c: Tensor;\n let o: Tensor;\n if (0 < this.dropout && this.dropout < 1) {\n inputs = tfc.mul(inputs, dpMask[0]);\n }\n let z = K.dot(inputs, this.kernel.read());\n if (0 < this.recurrentDropout && this.recurrentDropout < 1) {\n hTMinus1 = tfc.mul(hTMinus1, recDpMask[0]);\n }\n z = tfc.add(z, K.dot(hTMinus1, this.recurrentKernel.read()));\n if (this.useBias) {\n z = K.biasAdd(z, this.bias.read());\n }\n\n const [z0, z1, z2, z3] = tfc.split(z, 4, z.rank - 1);\n\n i = this.recurrentActivation.apply(z0);\n f = this.recurrentActivation.apply(z1);\n c = tfc.add(tfc.mul(f, cTMinus1), tfc.mul(i, this.activation.apply(z2)));\n o = this.recurrentActivation.apply(z3);\n\n const h = tfc.mul(o, this.activation.apply(c));\n // TODO(cais): Add use_learning_phase flag properly.\n return [h, h, c];\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const baseConfig = super.getConfig();\n\n const config: serialization.ConfigDict = {\n units: this.units,\n activation: serializeActivation(this.activation),\n recurrentActivation: serializeActivation(this.recurrentActivation),\n useBias: this.useBias,\n kernelInitializer: serializeInitializer(this.kernelInitializer),\n recurrentInitializer: serializeInitializer(this.recurrentInitializer),\n biasInitializer: serializeInitializer(this.biasInitializer),\n unitForgetBias: this.unitForgetBias,\n kernelRegularizer: serializeRegularizer(this.kernelRegularizer),\n recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer),\n biasRegularizer: serializeRegularizer(this.biasRegularizer),\n activityRegularizer: serializeRegularizer(this.activityRegularizer),\n kernelConstraint: serializeConstraint(this.kernelConstraint),\n recurrentConstraint: serializeConstraint(this.recurrentConstraint),\n biasConstraint: serializeConstraint(this.biasConstraint),\n dropout: this.dropout,\n recurrentDropout: this.recurrentDropout,\n implementation: this.implementation,\n };\n\n return {...baseConfig, ...config};\n }\n}\nserialization.registerClass(LSTMCell);\n\n// Porting Note: Since this is a superset of SimpleRNNLayerConfig, we inherit\n// from that interface instead of repeating the fields here.\nexport declare interface LSTMLayerArgs extends SimpleRNNLayerArgs {\n /**\n * Activation function to use for the recurrent step.\n *\n * Defaults to hard sigmoid (`hardSigmoid`).\n *\n * If `null`, no activation is applied.\n */\n recurrentActivation?: ActivationIdentifier;\n\n /**\n * If `true`, add 1 to the bias of the forget gate at initialization.\n * Setting it to `true` will also force `biasInitializer = 'zeros'`.\n * This is recommended in\n * [Jozefowicz et\n * al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).\n */\n unitForgetBias?: boolean;\n\n /**\n * Implementation mode, either 1 or 2.\n * Mode 1 will structure its operations as a larger number of\n * smaller dot products and additions, whereas mode 2 will\n * batch them into fewer, larger operations. These modes will\n * have different performance profiles on different hardware and\n * for different applications.\n *\n * Note: For superior performance, TensorFlow.js always uses implementation\n * 2, regardless of the actual value of this config field.\n */\n implementation?: number;\n}\n\nexport class LSTM extends RNN {\n /** @nocollapse */\n static className = 'LSTM';\n constructor(args: LSTMLayerArgs) {\n if (args.implementation === 0) {\n console.warn(\n '`implementation=0` has been deprecated, and now defaults to ' +\n '`implementation=1`. Please update your layer call.');\n }\n args.cell = new LSTMCell(args);\n super(args as RNNLayerArgs);\n // TODO(cais): Add activityRegularizer.\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n if (this.cell.dropoutMask != null) {\n tfc.dispose(this.cell.dropoutMask);\n this.cell.dropoutMask = null;\n }\n if (this.cell.recurrentDropoutMask != null) {\n tfc.dispose(this.cell.recurrentDropoutMask);\n this.cell.recurrentDropoutMask = null;\n }\n const mask = kwargs == null ? null : kwargs['mask'];\n const training = kwargs == null ? null : kwargs['training'];\n const initialState: Tensor[] =\n kwargs == null ? null : kwargs['initialState'];\n return super.call(inputs, {mask, training, initialState});\n });\n }\n\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict): T {\n if (config['implmentation'] === 0) {\n config['implementation'] = 1;\n }\n return new cls(config);\n }\n}\nserialization.registerClass(LSTM);\n\nexport declare interface StackedRNNCellsArgs extends LayerArgs {\n /**\n * A `Array` of `RNNCell` instances.\n */\n cells: RNNCell[];\n}\n\nexport class StackedRNNCells extends RNNCell {\n /** @nocollapse */\n static className = 'StackedRNNCells';\n protected cells: RNNCell[];\n\n constructor(args: StackedRNNCellsArgs) {\n super(args);\n this.cells = args.cells;\n }\n\n get stateSize(): number[] {\n // States are a flat list in reverse order of the cell stack.\n // This allows perserving the requirement `stack.statesize[0] ===\n // outputDim`. E.g., states of a 2-layer LSTM would be `[h2, c2, h1, c1]`,\n // assuming one LSTM has states `[h, c]`.\n const stateSize: number[] = [];\n for (const cell of this.cells.slice().reverse()) {\n if (Array.isArray(cell.stateSize)) {\n stateSize.push(...cell.stateSize);\n } else {\n stateSize.push(cell.stateSize);\n }\n }\n return stateSize;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = inputs as Tensor[];\n let states = inputs.slice(1);\n\n // Recover per-cell states.\n const nestedStates: Tensor[][] = [];\n for (const cell of this.cells.slice().reverse()) {\n if (Array.isArray(cell.stateSize)) {\n nestedStates.push(states.splice(0, cell.stateSize.length));\n } else {\n nestedStates.push(states.splice(0, 1));\n }\n }\n nestedStates.reverse();\n\n // Call the cells in order and store the returned states.\n const newNestedStates: Tensor[][] = [];\n let callInputs: Tensor[];\n for (let i = 0; i < this.cells.length; ++i) {\n const cell = this.cells[i];\n states = nestedStates[i];\n // TODO(cais): Take care of constants.\n if (i === 0) {\n callInputs = [inputs[0]].concat(states);\n } else {\n callInputs = [callInputs[0]].concat(states);\n }\n callInputs = cell.call(callInputs, kwargs) as Tensor[];\n newNestedStates.push(callInputs.slice(1));\n }\n\n // Format the new states as a flat list in reverse cell order.\n states = [];\n for (const cellStates of newNestedStates.slice().reverse()) {\n states.push(...cellStates);\n }\n return [callInputs[0]].concat(states);\n });\n }\n\n public build(inputShape: Shape|Shape[]): void {\n if (isArrayOfShapes(inputShape)) {\n // TODO(cais): Take care of input constants.\n // const constantShape = inputShape.slice(1);\n inputShape = (inputShape as Shape[])[0];\n }\n inputShape = inputShape as Shape;\n let outputDim: number;\n this.cells.forEach((cell, i) => {\n nameScope(`RNNCell_${i}`, () => {\n // TODO(cais): Take care of input constants.\n\n cell.build(inputShape);\n if (Array.isArray(cell.stateSize)) {\n outputDim = cell.stateSize[0];\n } else {\n outputDim = cell.stateSize;\n }\n inputShape = [inputShape[0], outputDim] as Shape;\n });\n });\n this.built = true;\n }\n\n getConfig(): serialization.ConfigDict {\n const baseConfig = super.getConfig();\n\n const getCellConfig = (cell: RNNCell) => {\n return {\n 'className': cell.getClassName(),\n 'config': cell.getConfig(),\n };\n };\n\n const cellConfigs = this.cells.map(getCellConfig);\n\n const config = {'cells': cellConfigs};\n\n return {...baseConfig, ...config};\n }\n\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict,\n customObjects = {} as serialization.ConfigDict): T {\n const cells: RNNCell[] = [];\n for (const cellConfig of (config['cells'] as serialization.ConfigDict[])) {\n cells.push(deserialize(cellConfig, customObjects) as RNNCell);\n }\n return new cls({cells});\n }\n\n get trainableWeights(): LayerVariable[] {\n if (!this.trainable) {\n return [];\n }\n const weights: LayerVariable[] = [];\n for (const cell of this.cells) {\n weights.push(...cell.trainableWeights);\n }\n return weights;\n }\n\n get nonTrainableWeights(): LayerVariable[] {\n const weights: LayerVariable[] = [];\n for (const cell of this.cells) {\n weights.push(...cell.nonTrainableWeights);\n }\n if (!this.trainable) {\n const trainableWeights: LayerVariable[] = [];\n for (const cell of this.cells) {\n trainableWeights.push(...cell.trainableWeights);\n }\n return trainableWeights.concat(weights);\n }\n return weights;\n }\n\n /**\n * Retrieve the weights of a the model.\n *\n * @returns A flat `Array` of `tf.Tensor`s.\n */\n getWeights(): Tensor[] {\n const weights: LayerVariable[] = [];\n for (const cell of this.cells) {\n weights.push(...cell.weights);\n }\n return batchGetValue(weights);\n }\n\n /**\n * Set the weights of the model.\n *\n * @param weights An `Array` of `tf.Tensor`s with shapes and types matching\n * the output of `getWeights()`.\n */\n setWeights(weights: Tensor[]): void {\n const tuples: Array<[LayerVariable, Tensor]> = [];\n for (const cell of this.cells) {\n const numParams = cell.weights.length;\n const inputWeights = weights.splice(numParams);\n for (let i = 0; i < cell.weights.length; ++i) {\n tuples.push([cell.weights[i], inputWeights[i]]);\n }\n }\n batchSetValue(tuples);\n }\n\n // TODO(cais): Maybe implemnt `losses` and `getLossesFor`.\n}\nserialization.registerClass(StackedRNNCells);\n\nexport function generateDropoutMask(args: {\n ones: () => tfc.Tensor,\n rate: number,\n training?: boolean,\n count?: number,\n}): tfc.Tensor|tfc.Tensor[] {\n const {ones, rate, training = false, count = 1} = args;\n\n const droppedInputs = () => K.dropout(ones(), rate);\n\n const createMask = () => K.inTrainPhase(droppedInputs, ones, training);\n\n // just in case count is provided with null or undefined\n if (!count || count <= 1) {\n return tfc.keep(createMask().clone());\n }\n\n const masks = Array(count).fill(undefined).map(createMask);\n\n return masks.map(m => tfc.keep(m.clone()));\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {Tensor, util} from '@tensorflow/tfjs-core';\n\nimport {Activation} from '../activations';\nimport * as K from '../backend/tfjs_backend';\nimport {checkDataFormat, checkPaddingMode} from '../common';\nimport {Constraint} from '../constraints';\nimport {InputSpec} from '../engine/topology';\nimport {AttributeError, NotImplementedError, ValueError} from '../errors';\nimport {Initializer} from '../initializers';\nimport {DataFormat, DataType, PaddingMode, Shape} from '../keras_format/common';\nimport {Regularizer} from '../regularizers';\nimport {Kwargs} from '../types';\nimport {convOutputLength, normalizeArray} from '../utils/conv_utils';\nimport {assertPositiveInteger} from '../utils/generic_utils';\nimport {getExactlyOneShape} from '../utils/types_utils';\n\nimport {BaseRNNLayerArgs, generateDropoutMask, LSTMCell, LSTMCellLayerArgs, LSTMLayerArgs, RNN, RNNCell, RNNLayerArgs, SimpleRNNCellLayerArgs} from './recurrent';\n\ndeclare interface ConvRNN2DCellArgs extends\n Omit<SimpleRNNCellLayerArgs, 'units'> {\n /**\n * The dimensionality of the output space (i.e. the number of filters in the\n * convolution).\n */\n filters: number;\n\n /**\n * The dimensions of the convolution window. If kernelSize is a number, the\n * convolutional window will be square.\n */\n kernelSize: number|number[];\n\n /**\n * The strides of the convolution in each dimension. If strides is a number,\n * strides in both dimensions are equal.\n *\n * Specifying any stride value != 1 is incompatible with specifying any\n * `dilationRate` value != 1.\n */\n strides?: number|number[];\n\n /**\n * Padding mode.\n */\n padding?: PaddingMode;\n\n /**\n * Format of the data, which determines the ordering of the dimensions in\n * the inputs.\n *\n * `channels_last` corresponds to inputs with shape\n * `(batch, ..., channels)`\n *\n * `channels_first` corresponds to inputs with shape `(batch, channels,\n * ...)`.\n *\n * Defaults to `channels_last`.\n */\n dataFormat?: DataFormat;\n\n /**\n * The dilation rate to use for the dilated convolution in each dimension.\n * Should be an integer or array of two or three integers.\n *\n * Currently, specifying any `dilationRate` value != 1 is incompatible with\n * specifying any `strides` value != 1.\n */\n dilationRate?: number|[number]|[number, number];\n}\n\nabstract class ConvRNN2DCell extends RNNCell {\n readonly filters: number;\n readonly kernelSize: number[];\n readonly strides: number[];\n readonly padding: PaddingMode;\n readonly dataFormat: DataFormat;\n readonly dilationRate: number[];\n\n readonly activation: Activation;\n readonly useBias: boolean;\n\n readonly kernelInitializer: Initializer;\n readonly recurrentInitializer: Initializer;\n readonly biasInitializer: Initializer;\n\n readonly kernelConstraint: Constraint;\n readonly recurrentConstraint: Constraint;\n readonly biasConstraint: Constraint;\n\n readonly kernelRegularizer: Regularizer;\n readonly recurrentRegularizer: Regularizer;\n readonly biasRegularizer: Regularizer;\n\n readonly dropout: number;\n readonly recurrentDropout: number;\n}\n\ndeclare interface ConvRNN2DLayerArgs extends BaseRNNLayerArgs,\n ConvRNN2DCellArgs {}\n\n/**\n * Base class for convolutional-recurrent layers.\n */\nclass ConvRNN2D extends RNN {\n /** @nocollapse */\n static className = 'ConvRNN2D';\n\n readonly cell: ConvRNN2DCell;\n\n constructor(args: ConvRNN2DLayerArgs) {\n if (args.unroll) {\n throw new NotImplementedError(\n 'Unrolling is not possible with convolutional RNNs.');\n }\n\n if (Array.isArray(args.cell)) {\n throw new NotImplementedError(\n 'It is not possible at the moment to stack convolutional cells.');\n }\n\n super(args as RNNLayerArgs);\n\n this.inputSpec = [new InputSpec({ndim: 5})];\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tfc.tidy(() => {\n if (this.cell.dropoutMask != null) {\n tfc.dispose(this.cell.dropoutMask);\n\n this.cell.dropoutMask = null;\n }\n\n if (this.cell.recurrentDropoutMask != null) {\n tfc.dispose(this.cell.recurrentDropoutMask);\n\n this.cell.recurrentDropoutMask = null;\n }\n\n if (kwargs && kwargs['constants']) {\n throw new ValueError('ConvRNN2D cell does not support constants');\n }\n\n const mask = kwargs == null ? null : kwargs['mask'];\n\n const training = kwargs == null ? null : kwargs['training'];\n\n const initialState: Tensor[] =\n kwargs == null ? null : kwargs['initialState'];\n\n return super.call(inputs, {mask, training, initialState});\n });\n }\n\n computeOutputShape(inputShape: Shape): Shape|Shape[] {\n let outShape: Shape = this.computeSingleOutputShape(inputShape);\n\n if (!this.returnSequences) {\n outShape = [outShape[0], ...outShape.slice(2)];\n }\n\n if (this.returnState) {\n outShape =\n [outShape, ...Array(2).fill([inputShape[0], ...outShape.slice(-3)])];\n }\n\n return outShape;\n }\n\n getInitialState(inputs: tfc.Tensor): tfc.Tensor[] {\n return tfc.tidy(() => {\n const {stateSize} = this.cell;\n\n const inputShape = inputs.shape;\n\n const outputShape = this.computeSingleOutputShape(inputShape);\n\n const stateShape = [outputShape[0], ...outputShape.slice(2)];\n\n const initialState = tfc.zeros(stateShape);\n\n if (Array.isArray(stateSize)) {\n return Array(stateSize.length).fill(initialState);\n }\n\n return [initialState];\n });\n }\n\n resetStates(states?: Tensor|Tensor[], training = false): void {\n tfc.tidy(() => {\n if (!this.stateful) {\n throw new AttributeError(\n 'Cannot call resetStates() on an RNN Layer that is not stateful.');\n }\n\n const inputShape = this.inputSpec[0].shape;\n\n const outputShape = this.computeSingleOutputShape(inputShape);\n\n const stateShape = [outputShape[0], ...outputShape.slice(2)];\n\n const batchSize = inputShape[0];\n\n if (batchSize == null) {\n throw new ValueError(\n 'If an RNN is stateful, it needs to know its batch size. Specify ' +\n 'the batch size of your input tensors: \\n' +\n '- If using a Sequential model, specify the batch size by ' +\n 'passing a `batchInputShape` option to your first layer.\\n' +\n '- If using the functional API, specify the batch size by ' +\n 'passing a `batchShape` option to your Input layer.');\n }\n\n // Initialize state if null.\n if (this.getStates() == null) {\n if (Array.isArray(this.cell.stateSize)) {\n this.states_ = this.cell.stateSize.map(() => tfc.zeros(stateShape));\n } else {\n this.states_ = [tfc.zeros(stateShape)];\n }\n } else if (states == null) {\n // Dispose old state tensors.\n tfc.dispose(this.states_);\n\n // For stateful RNNs, fully dispose kept old states.\n if (this.keptStates != null) {\n tfc.dispose(this.keptStates);\n this.keptStates = [];\n }\n\n if (Array.isArray(this.cell.stateSize)) {\n this.states_ = this.cell.stateSize.map(() => tfc.zeros(stateShape));\n } else {\n this.states_[0] = tfc.zeros(stateShape);\n }\n } else {\n if (!Array.isArray(states)) {\n states = [states];\n }\n\n if (states.length !== this.states_.length) {\n throw new ValueError(\n `Layer ${this.name} expects ${this.states_.length} state(s), ` +\n `but it received ${states.length} state value(s). Input ` +\n `received: ${states}`);\n }\n\n if (training) {\n // Store old state tensors for complete disposal later, i.e., during\n // the next no-arg call to this method. We do not dispose the old\n // states immediately because that BPTT (among other things) require\n // them.\n this.keptStates.push(this.states_.slice());\n } else {\n tfc.dispose(this.states_);\n }\n\n for (let index = 0; index < this.states_.length; ++index) {\n const value = states[index];\n\n const expectedShape = stateShape;\n\n if (!util.arraysEqual(value.shape, expectedShape)) {\n throw new ValueError(\n `State ${index} is incompatible with layer ${this.name}: ` +\n `expected shape=${expectedShape}, received shape=${\n value.shape}`);\n }\n\n this.states_[index] = value;\n }\n }\n\n this.states_ = this.states_.map(state => tfc.keep(state.clone()));\n });\n }\n\n protected computeSingleOutputShape(inputShape: Shape): Shape {\n const {dataFormat, filters, kernelSize, padding, strides, dilationRate} =\n this.cell;\n\n const isChannelsFirst = dataFormat === 'channelsFirst';\n\n const h = inputShape[isChannelsFirst ? 3 : 2];\n const w = inputShape[isChannelsFirst ? 4 : 3];\n\n const hOut = convOutputLength(\n h, kernelSize[0], padding, strides[0], dilationRate[0]);\n const wOut = convOutputLength(\n w, kernelSize[1], padding, strides[1], dilationRate[1]);\n\n const outShape: Shape = [\n ...inputShape.slice(0, 2),\n ...(isChannelsFirst ? [filters, hOut, wOut] : [hOut, wOut, filters])\n ];\n\n return outShape;\n }\n}\n\nexport declare interface ConvLSTM2DCellArgs extends\n Omit<LSTMCellLayerArgs, 'units'>, ConvRNN2DCellArgs {}\n\nexport class ConvLSTM2DCell extends LSTMCell implements ConvRNN2DCell {\n /** @nocollapse */\n static className = 'ConvLSTM2DCell';\n\n readonly filters: number;\n readonly kernelSize: number[];\n readonly strides: number[];\n readonly padding: PaddingMode;\n readonly dataFormat: DataFormat;\n readonly dilationRate: number[];\n\n constructor(args: ConvLSTM2DCellArgs) {\n const {\n filters,\n kernelSize,\n strides,\n padding,\n dataFormat,\n dilationRate,\n } = args;\n\n super({...args, units: filters});\n\n this.filters = filters;\n assertPositiveInteger(this.filters, 'filters');\n\n this.kernelSize = normalizeArray(kernelSize, 2, 'kernelSize');\n this.kernelSize.forEach(size => assertPositiveInteger(size, 'kernelSize'));\n\n this.strides = normalizeArray(strides || 1, 2, 'strides');\n this.strides.forEach(stride => assertPositiveInteger(stride, 'strides'));\n\n this.padding = padding || 'valid';\n checkPaddingMode(this.padding);\n\n this.dataFormat = dataFormat || 'channelsLast';\n checkDataFormat(this.dataFormat);\n\n this.dilationRate = normalizeArray(dilationRate || 1, 2, 'dilationRate');\n this.dilationRate.forEach(\n rate => assertPositiveInteger(rate, 'dilationRate'));\n }\n\n public build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n\n const channelAxis =\n this.dataFormat === 'channelsFirst' ? 1 : inputShape.length - 1;\n\n if (inputShape[channelAxis] == null) {\n throw new ValueError(\n `The channel dimension of the input should be defined. ` +\n `Found ${inputShape[channelAxis]}`);\n }\n\n const inputDim = inputShape[channelAxis];\n\n const numOfKernels = 4;\n\n const kernelShape =\n this.kernelSize.concat([inputDim, this.filters * numOfKernels]);\n\n this.kernel = this.addWeight(\n 'kernel', kernelShape, null, this.kernelInitializer,\n this.kernelRegularizer, true, this.kernelConstraint);\n\n const recurrentKernelShape =\n this.kernelSize.concat([this.filters, this.filters * numOfKernels]);\n\n this.recurrentKernel = this.addWeight(\n 'recurrent_kernel', recurrentKernelShape, null,\n this.recurrentInitializer, this.recurrentRegularizer, true,\n this.recurrentConstraint);\n\n if (this.useBias) {\n let biasInitializer: Initializer;\n\n if (this.unitForgetBias) {\n const init = this.biasInitializer;\n\n const filters = this.filters;\n\n biasInitializer = new (class CustomInit extends Initializer {\n /** @nocollapse */\n static className = 'CustomInit';\n\n apply(shape: Shape, dtype?: DataType): tfc.Tensor {\n const biasI = init.apply([filters]);\n const biasF = tfc.ones([filters]);\n const biasCAndO = init.apply([filters * 2]);\n return K.concatenate([biasI, biasF, biasCAndO]);\n }\n })();\n } else {\n biasInitializer = this.biasInitializer;\n }\n\n this.bias = this.addWeight(\n 'bias', [this.filters * numOfKernels], null, biasInitializer,\n this.biasRegularizer, true, this.biasConstraint);\n }\n\n this.built = true;\n }\n\n call(inputs: tfc.Tensor[], kwargs: Kwargs): tfc.Tensor[] {\n return tfc.tidy(() => {\n if (inputs.length !== 3) {\n throw new ValueError(\n `ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ` +\n `${inputs.length}.`);\n }\n\n const training = kwargs['training'] || false;\n\n const x = inputs[0]; // Current input\n const hTMinus1 = inputs[1]; // Previous memory state.\n const cTMinus1 = inputs[2]; // Previous carry state.\n\n const numOfKernels = 4;\n\n type DropoutMasks = [tfc.Tensor, tfc.Tensor, tfc.Tensor, tfc.Tensor];\n\n if (0 < this.dropout && this.dropout < 1 && this.dropoutMask == null) {\n this.dropoutMask = generateDropoutMask({\n ones: () => tfc.onesLike(x),\n rate: this.dropout,\n training,\n count: numOfKernels\n }) as tfc.Tensor[];\n }\n\n const dropoutMask = this.dropoutMask as DropoutMasks;\n\n const applyDropout =\n (x: tfc.Tensor, mask: tfc.Tensor[], index: number) => {\n if (!mask || !mask[index]) {\n return x;\n }\n\n return tfc.mul(mask[index], x);\n };\n\n let xI = applyDropout(x, dropoutMask, 0);\n let xF = applyDropout(x, dropoutMask, 1);\n let xC = applyDropout(x, dropoutMask, 2);\n let xO = applyDropout(x, dropoutMask, 3);\n\n if (0 < this.recurrentDropout && this.recurrentDropout < 1 &&\n this.recurrentDropoutMask == null) {\n this.recurrentDropoutMask = generateDropoutMask({\n ones: () => tfc.onesLike(hTMinus1),\n rate: this.recurrentDropout,\n training,\n count: numOfKernels\n }) as tfc.Tensor[];\n }\n\n const recDropoutMask = this.recurrentDropoutMask as DropoutMasks;\n\n let hI = applyDropout(hTMinus1, recDropoutMask, 0);\n let hF = applyDropout(hTMinus1, recDropoutMask, 1);\n let hC = applyDropout(hTMinus1, recDropoutMask, 2);\n let hO = applyDropout(hTMinus1, recDropoutMask, 3);\n\n const kernelChannelAxis = 3;\n\n const [kernelI, kernelF, kernelC, kernelO]: tfc.Tensor[] =\n tfc.split(this.kernel.read(), numOfKernels, kernelChannelAxis);\n\n const [biasI, biasF, biasC, biasO]: tfc.Tensor[] = this.useBias ?\n tfc.split(this.bias.read(), numOfKernels) :\n [null, null, null, null];\n\n xI = this.inputConv(xI, kernelI, biasI, this.padding);\n xF = this.inputConv(xF, kernelF, biasF, this.padding);\n xC = this.inputConv(xC, kernelC, biasC, this.padding);\n xO = this.inputConv(xO, kernelO, biasO, this.padding);\n\n const [recKernelI, recKernelF, recKernelC, recKernelO]: tfc.Tensor[] =\n tfc.split(\n this.recurrentKernel.read(), numOfKernels, kernelChannelAxis);\n\n hI = this.recurrentConv(hI, recKernelI);\n hF = this.recurrentConv(hF, recKernelF);\n hC = this.recurrentConv(hC, recKernelC);\n hO = this.recurrentConv(hO, recKernelO);\n\n const i = this.recurrentActivation.apply(tfc.add(xI, hI));\n const f = this.recurrentActivation.apply(tfc.add(xF, hF));\n const c = tfc.add(\n tfc.mul(f, cTMinus1),\n tfc.mul(i, this.activation.apply(tfc.add(xC, hC))));\n const h = tfc.mul(\n this.recurrentActivation.apply(tfc.add(xO, hO)),\n this.activation.apply(c));\n\n return [h, h, c];\n });\n }\n\n getConfig(): tfc.serialization.ConfigDict {\n const {'units': _, ...baseConfig} = super.getConfig();\n\n const config: tfc.serialization.ConfigDict = {\n filters: this.filters,\n kernelSize: this.kernelSize,\n padding: this.padding,\n dataFormat: this.dataFormat,\n dilationRate: this.dilationRate,\n strides: this.strides,\n };\n\n return {...baseConfig, ...config};\n }\n\n inputConv(x: Tensor, w: Tensor, b?: Tensor, padding?: PaddingMode) {\n const out = tfc.conv2d(\n x as tfc.Tensor3D, w as tfc.Tensor4D, this.strides as [number, number],\n (padding || 'valid') as 'same' | 'valid',\n this.dataFormat === 'channelsFirst' ? 'NCHW' : 'NHWC',\n this.dilationRate as [number, number]);\n\n if (b) {\n return K.biasAdd(out, b, this.dataFormat) as tfc.Tensor3D;\n }\n\n return out;\n }\n\n recurrentConv(x: Tensor, w: Tensor) {\n const strides = 1;\n\n return tfc.conv2d(\n x as tfc.Tensor3D, w as tfc.Tensor4D, strides, 'same',\n this.dataFormat === 'channelsFirst' ? 'NCHW' : 'NHWC');\n }\n}\n\ntfc.serialization.registerClass(ConvLSTM2DCell);\n\nexport declare interface ConvLSTM2DArgs extends\n Omit<LSTMLayerArgs, 'units'|'cell'>, ConvRNN2DLayerArgs {}\n\nexport class ConvLSTM2D extends ConvRNN2D {\n /** @nocollapse */\n static className = 'ConvLSTM2D';\n\n constructor(args: ConvLSTM2DArgs) {\n const cell = new ConvLSTM2DCell(args);\n\n super({...args, cell} as ConvRNN2DLayerArgs);\n }\n\n /** @nocollapse */\n static fromConfig<T extends tfc.serialization.Serializable>(\n cls: tfc.serialization.SerializableConstructor<T>,\n config: tfc.serialization.ConfigDict): T {\n return new cls(config);\n }\n}\n\ntfc.serialization.registerClass(ConvLSTM2D);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * TensorFlow.js Layers: Basic Layers.\n */\n\nimport {any, cast, mul, notEqual, reshape, serialization, Tensor, tidy, transpose, util} from '@tensorflow/tfjs-core';\n\nimport {Activation as ActivationFn, getActivation, serializeActivation} from '../activations';\nimport * as K from '../backend/tfjs_backend';\nimport {Constraint, ConstraintIdentifier, getConstraint, serializeConstraint} from '../constraints';\nimport {DisposeResult, InputSpec, Layer, LayerArgs} from '../engine/topology';\nimport {ValueError} from '../errors';\nimport {getInitializer, Initializer, InitializerIdentifier, serializeInitializer} from '../initializers';\nimport {ActivationIdentifier} from '../keras_format/activation_config';\nimport {DataFormat, Shape} from '../keras_format/common';\nimport {LayerConfig} from '../keras_format/topology_config';\nimport {getRegularizer, Regularizer, RegularizerIdentifier, serializeRegularizer} from '../regularizers';\nimport {Kwargs} from '../types';\nimport {assertPositiveInteger, mapActivationToFusedKernel} from '../utils/generic_utils';\nimport {arrayProd, range} from '../utils/math_utils';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\nimport {LayerVariable} from '../variables';\n\nexport declare interface DropoutLayerArgs extends LayerArgs {\n /** Float between 0 and 1. Fraction of the input units to drop. */\n rate: number;\n\n /**\n * Integer array representing the shape of the binary dropout mask that will\n * be multiplied with the input.\n *\n * For instance, if your inputs have shape `(batchSize, timesteps, features)`\n * and you want the dropout mask to be the same for all timesteps, you can use\n * `noise_shape=(batch_size, 1, features)`.\n */\n noiseShape?: number[];\n\n /** An integer to use as random seed. */\n seed?: number;\n}\n\nexport class Dropout extends Layer {\n /** @nocollapse */\n static className = 'Dropout';\n private readonly rate: number;\n private readonly noiseShape: number[];\n private readonly seed: number;\n\n constructor(args: DropoutLayerArgs) {\n super(args);\n this.rate = Math.max(Math.min(args.rate, 1), 0);\n // So that the scalar doesn't get tidied up between executions.\n this.noiseShape = args.noiseShape;\n this.seed = args.seed;\n this.supportsMasking = true;\n }\n\n protected getNoiseShape(input: Tensor): Shape {\n if (this.noiseShape == null) {\n return this.noiseShape;\n }\n const inputShape = input.shape;\n const noiseShape: Shape = [];\n for (let i = 0; i < this.noiseShape.length; ++i) {\n noiseShape.push(\n this.noiseShape[i] == null ? inputShape[i] : this.noiseShape[i]);\n }\n return noiseShape;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n const input = getExactlyOneTensor(inputs);\n if (0 < this.rate && this.rate < 1) {\n const training =\n kwargs['training'] == null ? false : kwargs['training'];\n const noiseShape = this.getNoiseShape(input);\n const output = K.inTrainPhase(\n () => K.dropout(input, this.rate, noiseShape, this.seed),\n () => input, training);\n return output;\n }\n return inputs;\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n rate: this.rate,\n noiseShape: this.noiseShape,\n seed: this.seed,\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n dispose(): DisposeResult {\n return super.dispose();\n }\n}\nserialization.registerClass(Dropout);\n\nexport declare interface DenseLayerArgs extends LayerArgs {\n /** Positive integer, dimensionality of the output space. */\n units: number;\n /**\n * Activation function to use.\n *\n * If unspecified, no activation is applied.\n */\n activation?: ActivationIdentifier;\n /** Whether to apply a bias. */\n useBias?: boolean;\n /**\n * Initializer for the dense kernel weights matrix.\n */\n kernelInitializer?: InitializerIdentifier|Initializer;\n /**\n * Initializer for the bias vector.\n */\n biasInitializer?: InitializerIdentifier|Initializer;\n /**\n * If specified, defines inputShape as `[inputDim]`.\n */\n inputDim?: number;\n\n /**\n * Constraint for the kernel weights.\n */\n kernelConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Constraint for the bias vector.\n */\n biasConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Regularizer function applied to the dense kernel weights matrix.\n */\n kernelRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the bias vector.\n */\n biasRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer function applied to the activation.\n */\n activityRegularizer?: RegularizerIdentifier|Regularizer;\n}\n\nexport interface SpatialDropout1DLayerConfig extends LayerConfig {\n /** Float between 0 and 1. Fraction of the input units to drop. */\n rate: number;\n\n /** An integer to use as random seed. */\n seed?: number;\n}\n\nexport class SpatialDropout1D extends Dropout {\n /** @nocollapse */\n static className = 'SpatialDropout1D';\n\n constructor(args: SpatialDropout1DLayerConfig) {\n super(args);\n this.inputSpec = [{ndim: 3}];\n }\n\n protected getNoiseShape(input: Tensor): Shape {\n const inputShape = input.shape;\n return [inputShape[0], 1, inputShape[2]];\n }\n}\nserialization.registerClass(SpatialDropout1D);\n\nexport class Dense extends Layer {\n /** @nocollapse */\n static className = 'Dense';\n private units: number;\n // Default activation: Linear (none).\n private activation: ActivationFn = null;\n private useBias = true;\n private kernelInitializer: Initializer;\n private biasInitializer: Initializer;\n private kernel: LayerVariable = null;\n private bias: LayerVariable = null;\n\n readonly DEFAULT_KERNEL_INITIALIZER: InitializerIdentifier = 'glorotNormal';\n readonly DEFAULT_BIAS_INITIALIZER: InitializerIdentifier = 'zeros';\n private readonly kernelConstraint?: Constraint;\n private readonly biasConstraint?: Constraint;\n private readonly kernelRegularizer?: Regularizer;\n private readonly biasRegularizer?: Regularizer;\n\n constructor(args: DenseLayerArgs) {\n super(args);\n if (args.batchInputShape == null && args.inputShape == null &&\n args.inputDim != null) {\n // This logic is copied from Layer's constructor, since we can't\n // do exactly what the Python constructor does for Dense().\n let batchSize: number = null;\n if (args.batchSize != null) {\n batchSize = args.batchSize;\n }\n this.batchInputShape = [batchSize, args.inputDim];\n }\n\n this.units = args.units;\n assertPositiveInteger(this.units, 'units');\n this.activation = getActivation(args.activation);\n if (args.useBias != null) {\n this.useBias = args.useBias;\n }\n this.kernelInitializer = getInitializer(\n args.kernelInitializer || this.DEFAULT_KERNEL_INITIALIZER);\n this.biasInitializer =\n getInitializer(args.biasInitializer || this.DEFAULT_BIAS_INITIALIZER);\n this.kernelConstraint = getConstraint(args.kernelConstraint);\n this.biasConstraint = getConstraint(args.biasConstraint);\n this.kernelRegularizer = getRegularizer(args.kernelRegularizer);\n this.biasRegularizer = getRegularizer(args.biasRegularizer);\n this.activityRegularizer = getRegularizer(args.activityRegularizer);\n this.supportsMasking = true;\n\n this.inputSpec = [{minNDim: 2}];\n }\n\n public build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n const inputLastDim = inputShape[inputShape.length - 1];\n if (this.kernel == null) {\n this.kernel = this.addWeight(\n 'kernel', [inputLastDim, this.units], null, this.kernelInitializer,\n this.kernelRegularizer, true, this.kernelConstraint);\n if (this.useBias) {\n this.bias = this.addWeight(\n 'bias', [this.units], null, this.biasInitializer,\n this.biasRegularizer, true, this.biasConstraint);\n }\n }\n\n this.inputSpec = [{minNDim: 2, axes: {[-1]: inputLastDim}}];\n this.built = true;\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const outputShape = inputShape.slice();\n outputShape[outputShape.length - 1] = this.units;\n return outputShape;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n // Dense layer accepts only a single input.\n const input = getExactlyOneTensor(inputs);\n const fusedActivationName =\n mapActivationToFusedKernel(this.activation.getClassName());\n let output: Tensor;\n\n if (fusedActivationName != null) {\n output = K.dot(\n input, this.kernel.read(), fusedActivationName,\n this.bias ? this.bias.read() : null);\n } else {\n output = K.dot(input, this.kernel.read());\n if (this.bias != null) {\n output = K.biasAdd(output, this.bias.read());\n }\n if (this.activation != null) {\n output = this.activation.apply(output);\n }\n }\n\n return output;\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n units: this.units,\n activation: serializeActivation(this.activation),\n useBias: this.useBias,\n kernelInitializer: serializeInitializer(this.kernelInitializer),\n biasInitializer: serializeInitializer(this.biasInitializer),\n kernelRegularizer: serializeRegularizer(this.kernelRegularizer),\n biasRegularizer: serializeRegularizer(this.biasRegularizer),\n activityRegularizer: serializeRegularizer(this.activityRegularizer),\n kernelConstraint: serializeConstraint(this.kernelConstraint),\n biasConstraint: serializeConstraint(this.biasConstraint)\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Dense);\n\nexport declare interface FlattenLayerArgs extends LayerArgs {\n /** Image data format: channeLast (default) or channelFirst. */\n dataFormat?: DataFormat;\n}\n\nexport class Flatten extends Layer {\n private dataFormat: DataFormat;\n\n /** @nocollapse */\n static className = 'Flatten';\n constructor(args?: FlattenLayerArgs) {\n args = args || {};\n super(args);\n this.inputSpec = [{minNDim: 3}];\n this.dataFormat = args.dataFormat;\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n for (const dim of inputShape.slice(1)) {\n if (dim == null) {\n throw new ValueError(\n `The shape of the input to \"Flatten\" is not fully defined ` +\n `(got ${inputShape.slice(1)}). Make sure to pass a complete ` +\n `\"input_shape\" or \"batch_input_shape\" argument to the first ` +\n `layer in your model.`);\n }\n }\n return [inputShape[0], arrayProd(inputShape, 1)];\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n\n let input = getExactlyOneTensor(inputs);\n if (this.dataFormat === 'channelsFirst' && input.rank > 1) {\n const permutation: number[] = [0];\n for (let i = 2; i < input.rank; ++i) {\n permutation.push(i);\n }\n permutation.push(1);\n input = transpose(input, permutation);\n }\n\n return K.batchFlatten(input);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {};\n if (this.dataFormat != null) {\n config['dataFormat'] = this.dataFormat;\n }\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Flatten);\n\nexport declare interface ActivationLayerArgs extends LayerArgs {\n /**\n * Name of the activation function to use.\n */\n activation: ActivationIdentifier;\n}\n\nexport class Activation extends Layer {\n /** @nocollapse */\n static className = 'Activation';\n activation: ActivationFn;\n\n constructor(args: ActivationLayerArgs) {\n super(args);\n this.supportsMasking = true;\n this.activation = getActivation(args.activation);\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n const input = getExactlyOneTensor(inputs);\n return this.activation.apply(input);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {activation: serializeActivation(this.activation)};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Activation);\n\nexport declare interface ReshapeLayerArgs extends LayerArgs {\n /** The target shape. Does not include the batch axis. */\n targetShape: Shape;\n}\n\nexport declare interface RepeatVectorLayerArgs extends LayerArgs {\n /**\n * The integer number of times to repeat the input.\n */\n n: number;\n}\n\nexport class RepeatVector extends Layer {\n /** @nocollapse */\n static className = 'RepeatVector';\n readonly n: number;\n\n constructor(args: RepeatVectorLayerArgs) {\n super(args);\n this.n = args.n;\n this.inputSpec = [{ndim: 2}];\n }\n\n computeOutputShape(inputShape: Shape): Shape {\n return [inputShape[0], this.n, inputShape[1]];\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = getExactlyOneTensor(inputs);\n return K.repeat(inputs, this.n);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n n: this.n,\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(RepeatVector);\n\nexport class Reshape extends Layer {\n /** @nocollapse */\n static className = 'Reshape';\n private targetShape: Shape;\n\n constructor(args: ReshapeLayerArgs) {\n super(args);\n this.targetShape = args.targetShape;\n\n // Make sure that all unknown dimensions are represented as `null`.\n for (let i = 0; i < this.targetShape.length; ++i) {\n if (this.isUnknown(this.targetShape[i])) {\n this.targetShape[i] = null;\n }\n }\n }\n\n private isUnknown(dim: number): boolean {\n return dim < 0 || dim == null;\n }\n\n /**\n * Finds and replaces a missing dimension in output shape.\n *\n * This is a near direct port of the internal Numpy function\n * `_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c`.\n *\n * @param inputShape: Original shape of array begin reshape.\n * @param outputShape: Target shape of the array, with at most a single\n * `null` or negative number, which indicates an underdetermined dimension\n * that should be derived from `inputShape` and the known dimensions of\n * `outputShape`.\n * @returns: The output shape with `null` replaced with its computed value.\n * @throws: ValueError: If `inputShape` and `outputShape` do not match.\n */\n private fixUnknownDimension(inputShape: Shape, outputShape: Shape): Shape {\n const errorMsg = 'Total size of new array must be unchanged.';\n const finalShape = outputShape.slice();\n let known = 1;\n let unknown = null;\n for (let i = 0; i < finalShape.length; ++i) {\n const dim = finalShape[i];\n if (this.isUnknown(dim)) {\n if (unknown === null) {\n unknown = i;\n } else {\n throw new ValueError('Can only specifiy one unknown dimension.');\n }\n } else {\n known *= dim;\n }\n }\n\n const originalSize = arrayProd(inputShape);\n if (unknown !== null) {\n if (known === 0 || originalSize % known !== 0) {\n throw new ValueError(errorMsg);\n }\n finalShape[unknown] = originalSize / known;\n } else if (originalSize !== known) {\n throw new ValueError(errorMsg);\n }\n\n return finalShape;\n }\n\n computeOutputShape(inputShape: Shape): Shape {\n let anyUnknownDims = false;\n for (let i = 0; i < inputShape.length; ++i) {\n if (this.isUnknown(inputShape[i])) {\n anyUnknownDims = true;\n break;\n }\n }\n\n if (anyUnknownDims) {\n return inputShape.slice(0, 1).concat(this.targetShape);\n } else {\n return inputShape.slice(0, 1).concat(\n this.fixUnknownDimension(inputShape.slice(1), this.targetShape));\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n const input = getExactlyOneTensor(inputs);\n const inputShape = input.shape;\n const outputShape = inputShape.slice(0, 1).concat(\n this.fixUnknownDimension(inputShape.slice(1), this.targetShape));\n return reshape(input, outputShape);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n targetShape: this.targetShape,\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Reshape);\n\nexport declare interface PermuteLayerArgs extends LayerArgs {\n /**\n * Array of integers. Permutation pattern. Does not include the\n * sample (batch) dimension. Index starts at 1.\n * For instance, `[2, 1]` permutes the first and second dimensions\n * of the input.\n */\n dims: number[];\n}\n\nexport class Permute extends Layer {\n /** @nocollapse */\n static className = 'Permute';\n readonly dims: number[];\n private readonly dimsIncludingBatch: number[];\n\n constructor(args: PermuteLayerArgs) {\n super(args);\n if (args.dims == null) {\n throw new Error(\n 'Required configuration field `dims` is missing during Permute ' +\n 'constructor call.');\n }\n if (!Array.isArray(args.dims)) {\n throw new Error(\n 'Permute constructor requires `dims` to be an Array, but received ' +\n `${args.dims} instead.`);\n }\n\n // Check the validity of the permutation indices.\n const expectedSortedIndices = range(1, args.dims.length + 1);\n if (!util.arraysEqual(args.dims.slice().sort(), expectedSortedIndices)) {\n throw new Error(\n 'Invalid permutation `dims`: ' + JSON.stringify(args.dims) +\n ' `dims` must contain consecutive integers starting from 1.');\n }\n\n this.dims = args.dims;\n this.dimsIncludingBatch = [0].concat(this.dims);\n this.inputSpec = [new InputSpec({ndim: this.dims.length + 1})];\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const outputShape = inputShape.slice();\n this.dims.forEach((dim: number, i: number) => {\n outputShape[i + 1] = (inputShape as Shape)[dim];\n });\n return outputShape;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return transpose(getExactlyOneTensor(inputs), this.dimsIncludingBatch);\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n dims: this.dims,\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Permute);\n\nexport declare interface MaskingArgs extends LayerArgs {\n /**\n * Masking Value. Defaults to `0.0`.\n */\n maskValue?: number;\n}\n\nexport class Masking extends Layer {\n /** @nocollapse */\n static className = 'Masking';\n maskValue: number;\n\n constructor(args?: MaskingArgs) {\n super(args == null ? {} : args);\n this.supportsMasking = true;\n if (args != null) {\n this.maskValue = args.maskValue == null ? 0 : args.maskValue;\n } else {\n this.maskValue = 0;\n }\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n return inputShape;\n }\n\n getConfig() {\n const baseConfig = super.getConfig();\n const config = {maskValue: this.maskValue};\n Object.assign(config, baseConfig);\n return config;\n }\n\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor {\n const input = getExactlyOneTensor(inputs);\n const axis = -1;\n return any(notEqual(input, this.maskValue), axis);\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n const input = getExactlyOneTensor(inputs);\n const axis = -1;\n const keepDims = true;\n const booleanMask = any(notEqual(input, this.maskValue), axis, keepDims);\n const output = mul(input, cast(booleanMask, input.dtype));\n return output;\n });\n }\n}\nserialization.registerClass(Masking);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * TensorFlow.js Layers: Embedding Layer.\n *\n * Original source: keras/constraints.py\n */\nimport {notEqual, reshape, serialization, Tensor, tidy, zerosLike} from '@tensorflow/tfjs-core';\n\nimport * as K from '../backend/tfjs_backend';\nimport {Constraint, ConstraintIdentifier, getConstraint, serializeConstraint} from '../constraints';\nimport {Layer, LayerArgs} from '../engine/topology';\nimport {ValueError} from '../errors';\nimport {getInitializer, Initializer, InitializerIdentifier, serializeInitializer} from '../initializers';\nimport {Shape} from '../keras_format/common';\nimport {getRegularizer, Regularizer, RegularizerIdentifier, serializeRegularizer} from '../regularizers';\nimport {Kwargs} from '../types';\nimport * as generic_utils from '../utils/generic_utils';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\nimport {LayerVariable} from '../variables';\n\nexport declare interface EmbeddingLayerArgs extends LayerArgs {\n /**\n * Integer > 0. Size of the vocabulary, i.e. maximum integer index + 1.\n */\n inputDim: number;\n /**\n * Integer >= 0. Dimension of the dense embedding.\n */\n outputDim: number;\n /**\n * Initializer for the `embeddings` matrix.\n */\n embeddingsInitializer?: InitializerIdentifier|Initializer;\n /**\n * Regularizer function applied to the `embeddings` matrix.\n */\n embeddingsRegularizer?: RegularizerIdentifier|Regularizer;\n /**\n * Regularizer function applied to the activation.\n */\n activityRegularizer?: RegularizerIdentifier|Regularizer;\n /**\n * Constraint function applied to the `embeddings` matrix.\n */\n embeddingsConstraint?: ConstraintIdentifier|Constraint;\n /**\n * Whether the input value 0 is a special \"padding\" value that should be\n * masked out. This is useful when using recurrent layers which may take\n * variable length input.\n *\n * If this is `True` then all subsequent layers in the model need to support\n * masking or an exception will be raised. If maskZero is set to `True`, as a\n * consequence, index 0 cannot be used in the vocabulary (inputDim should\n * equal size of vocabulary + 1).\n */\n maskZero?: boolean;\n /**\n * Length of input sequences, when it is constant.\n *\n * This argument is required if you are going to connect `flatten` then\n * `dense` layers upstream (without it, the shape of the dense outputs cannot\n * be computed).\n */\n inputLength?: number|number[];\n}\n\nexport class Embedding extends Layer {\n /** @nocollapse */\n static className = 'Embedding';\n private inputDim: number;\n private outputDim: number;\n private embeddingsInitializer: Initializer;\n private maskZero: boolean;\n private inputLength: number|number[];\n\n private embeddings: LayerVariable = null;\n\n readonly DEFAULT_EMBEDDINGS_INITIALIZER: InitializerIdentifier =\n 'randomUniform';\n private readonly embeddingsRegularizer?: Regularizer;\n private readonly embeddingsConstraint?: Constraint;\n\n constructor(args: EmbeddingLayerArgs) {\n super(args);\n if (args.batchInputShape == null && args.inputShape == null) {\n // Porting Note: This logic is copied from Layer's constructor, since we\n // can't do exactly what the Python constructor does for Embedding().\n // Specifically, the super constructor can not be called after the\n // mutation of the `config` argument.\n let batchSize: number = null;\n if (args.batchSize != null) {\n batchSize = args.batchSize;\n }\n if (args.inputLength == null) {\n // Fix super-constructor to what it would have done if\n // 'config.inputShape' were (None, )\n this.batchInputShape = [batchSize, null];\n } else {\n // Fix super-constructor to what it would have done if\n // 'config.inputShape' were (config.inputLength, )\n this.batchInputShape =\n [batchSize].concat(generic_utils.toList(args.inputLength));\n }\n }\n this.inputDim = args.inputDim;\n generic_utils.assertPositiveInteger(this.inputDim, 'inputDim');\n this.outputDim = args.outputDim;\n generic_utils.assertPositiveInteger(this.outputDim, 'outputDim');\n this.embeddingsInitializer = getInitializer(\n args.embeddingsInitializer || this.DEFAULT_EMBEDDINGS_INITIALIZER);\n this.embeddingsRegularizer = getRegularizer(args.embeddingsRegularizer);\n this.activityRegularizer = getRegularizer(args.activityRegularizer);\n this.embeddingsConstraint = getConstraint(args.embeddingsConstraint);\n this.maskZero = args.maskZero;\n this.supportsMasking = args.maskZero;\n this.inputLength = args.inputLength;\n }\n\n public build(inputShape: Shape|Shape[]): void {\n this.embeddings = this.addWeight(\n 'embeddings', [this.inputDim, this.outputDim], this.dtype,\n this.embeddingsInitializer, this.embeddingsRegularizer, true,\n this.embeddingsConstraint);\n this.built = true;\n }\n\n // Override warnOnIncompatibleInputShape because an embedding layer allows\n // the input to have varying ranks.\n protected warnOnIncompatibleInputShape(inputShape: Shape) {}\n\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor {\n return tidy(() => {\n if (!this.maskZero) {\n return null;\n } else {\n inputs = getExactlyOneTensor(inputs);\n return notEqual(inputs, zerosLike(inputs));\n }\n });\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n if (this.inputLength == null) {\n return [...inputShape, this.outputDim];\n }\n // inputLength can be an array if input is 3D or higher.\n const inLens: number[] = generic_utils.toList(this.inputLength);\n if (inLens.length !== inputShape.length - 1) {\n throw new ValueError(\n `\"inputLength\" is ${this.inputLength}, but received ` +\n `input shape has shape ${inputShape}`);\n } else {\n let i = 0;\n for (let k = 0; k < inLens.length; ++k) {\n const s1 = inLens[k];\n const s2 = inputShape[k + 1];\n if ((s1 != null) && (s2 != null) && (s1 !== s2)) {\n throw new ValueError(\n `\"inputLength\" is ${this.inputLength}, but received ` +\n `input shape has shape ${inputShape}`);\n } else if (s1 == null) {\n inLens[i] = s2;\n }\n i++;\n }\n }\n return [inputShape[0], ...inLens, this.outputDim];\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n // Embedding layer accepts only a single input.\n let input = getExactlyOneTensor(inputs);\n if (input.dtype !== 'int32') {\n input = K.cast(input, 'int32');\n }\n const output =\n K.gather(this.embeddings.read(), reshape(input, [input.size]));\n return reshape(\n output, getExactlyOneShape(this.computeOutputShape(input.shape)));\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n inputDim: this.inputDim,\n outputDim: this.outputDim,\n embeddingsInitializer: serializeInitializer(this.embeddingsInitializer),\n embeddingsRegularizer: serializeRegularizer(this.embeddingsRegularizer),\n activityRegularizer: serializeRegularizer(this.activityRegularizer),\n embeddingsConstraint: serializeConstraint(this.embeddingsConstraint),\n maskZero: this.maskZero,\n inputLength: this.inputLength\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Embedding);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * TensorFlow.js Layers: Merge Layers.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {serialization, Tensor, tidy, util} from '@tensorflow/tfjs-core';\nimport * as K from '../backend/tfjs_backend';\nimport {Layer, LayerArgs, SymbolicTensor} from '../engine/topology';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {Shape} from '../keras_format/common';\nimport {l2Normalize} from '../losses';\nimport {Kwargs} from '../types';\nimport * as generic_utils from '../utils/generic_utils';\nimport * as mathUtils from '../utils/math_utils';\nimport {getExactlyOneShape} from '../utils/types_utils';\n\n/**\n * Generic Merge layer for element-wise merge functions.\n *\n * Used to implement `Sum`, `Average`, `Concatenate`, etc.\n */\nexport abstract class Merge extends Layer {\n protected reshapeRequired: boolean;\n\n constructor(args?: LayerArgs) {\n super(args || {});\n this.supportsMasking = true;\n }\n\n /**\n * Logic for merging multiple tensors, to be overridden by subclasses.\n * @param inputs\n */\n protected mergeFunction(inputs: Tensor[]): Tensor {\n throw new NotImplementedError();\n }\n\n /**\n * Computes the shape of the result of an elementwise operation.\n *\n * @param shape1: Shape of the first tensor.\n * @param shape2: Shape of the second tensor.\n * @returns Expected output shape when an elementwise operation is carried\n * out on 2 tensors with shapes `shape1` and `shape2`.\n * @throws ValueError: If `shape1` and `shape2` are not compatible for\n * element-wise operations.\n */\n private computeElementwiseOpOutputShape(shape1: Shape, shape2: Shape): Shape {\n if (shape1 == null || shape2 == null) {\n return null;\n } else if (shape1.length < shape2.length) {\n return this.computeElementwiseOpOutputShape(shape2, shape1);\n } else if (shape2.length === 0) {\n return shape1;\n }\n const outputShape: Shape = shape1.slice(0, shape1.length - shape2.length);\n for (let k = 0; k < shape2.length; ++k) {\n const i = shape1[shape1.length - shape2.length + k];\n const j = shape2[k];\n if (i == null || j == null || i < 0 || j < 0) {\n outputShape.push(null);\n } else if (i === 1) {\n outputShape.push(j);\n } else if (j === 1) {\n outputShape.push(i);\n } else {\n if (i !== j) {\n throw new ValueError(\n 'Operands could not be broadcast together with shapes ' +\n JSON.stringify(shape1) + ' ' + JSON.stringify(shape2));\n }\n outputShape.push(i);\n }\n }\n return outputShape;\n }\n\n build(inputShape: Shape|Shape[]): void {\n // Used purely for shape validation.\n if (Array.isArray(inputShape) && !Array.isArray(inputShape[0])) {\n // Make sure that inputShape is an Array of shape.\n inputShape = [getExactlyOneShape(inputShape)];\n }\n inputShape = inputShape as Shape[];\n if (inputShape.length < 2) {\n throw new ValueError(\n 'A merge layer should be called on an Array of at least 2 inputs.' +\n ` Got ${inputShape.length} input(s).`);\n }\n\n // Make sure that there is at most one unique batch size among the input\n // shapes.\n let batchSizes: number[] = [];\n for (const shape of inputShape) {\n if (shape != null && shape[0] !== null) {\n batchSizes.push(shape[0]);\n }\n }\n batchSizes = generic_utils.unique(batchSizes);\n if (batchSizes.length > 1) {\n throw new ValueError(\n `Can not merge tensors with different batch sizes. ` +\n `Got tensors with shapes: ${JSON.stringify(inputShape)}.`);\n }\n\n let outputShape: Shape =\n inputShape[0] == null ? null : inputShape[0].slice(1);\n for (let i = 1; i < inputShape.length; ++i) {\n const shape = inputShape[i] == null ? null : inputShape[i].slice(1);\n outputShape = this.computeElementwiseOpOutputShape(outputShape, shape);\n }\n // If the inputs have different ranks, we have to reshape them to make them\n // broadcastable.\n const allRanks = inputShape.map(shape => shape.length);\n if (inputShape.indexOf(null) === -1 &&\n generic_utils.unique(allRanks).length === 1) {\n this.reshapeRequired = false;\n } else {\n this.reshapeRequired = true;\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n inputs = inputs as Tensor[];\n if (this.reshapeRequired) {\n const reshapedInputs: Tensor[] = [];\n const inputDims = inputs.map(input => input.rank);\n if (inputDims.indexOf(null) === -1) {\n // If ranks of all inputs are available, we simply expand each of them\n // at axis=1 until all of them have the same rank.\n const maxNDim = mathUtils.max(inputDims);\n for (let x of inputs) {\n const xNDim = x.rank;\n for (let k = 0; k < maxNDim - xNDim; ++k) {\n x = K.expandDims(x, 1);\n }\n reshapedInputs.push(x);\n }\n return this.mergeFunction(reshapedInputs);\n } else {\n // Transpose all inputs so that batch size is the last dimension.\n // [batchSize, dim1, dim2, ...] -> [dim1, dim2, ..., batchSize]\n let transposed = false;\n for (const x of inputs) {\n const xNDim = x.rank;\n if (xNDim == null) {\n const xShape = x.shape;\n const batchSize = xShape[0];\n const newShape = xShape.slice(1).concat([batchSize]);\n let xTransposed = tfc.reshape(\n x, [batchSize].concat(mathUtils.arrayProd(xShape.slice(1))));\n xTransposed = tfc.transpose(xTransposed, [1, 0]);\n xTransposed = tfc.reshape(xTransposed, newShape);\n reshapedInputs.push(xTransposed);\n transposed = true;\n } else if (xNDim > 1) {\n const dims = mathUtils.range(1, xNDim).concat([0]);\n reshapedInputs.push(tfc.transpose(x, dims));\n transposed = true;\n } else {\n // We don't transpose inputs if they are 1D vectors or scalars.\n reshapedInputs.push(x);\n }\n }\n let y = this.mergeFunction(reshapedInputs);\n const yNDim = y.rank;\n if (transposed) {\n // If inputs have been transposed, we have to transpose the output\n // too.\n if (yNDim == null) {\n const yShape = y.shape;\n const yNDim = yShape.length;\n const batchSize = yShape[yNDim - 1];\n const newShape =\n [batchSize].concat(yShape.slice(0, yShape.length - 1));\n y = tfc.reshape(\n tfc.transpose(tfc.reshape(y, [-1, batchSize]), [1, 0]),\n newShape);\n } else if (yNDim > 1) {\n const dims = [yNDim - 1].concat(mathUtils.range(0, yNDim - 1));\n y = tfc.transpose(y, dims);\n }\n }\n return y;\n }\n } else {\n return this.mergeFunction(inputs);\n }\n });\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = inputShape as Shape[];\n let outputShape: Shape;\n if (inputShape[0] == null) {\n outputShape = null;\n } else {\n outputShape = inputShape[0].slice(1);\n }\n for (let i = 1; i < inputShape.length; ++i) {\n const shape = inputShape[i] == null ? null : inputShape[i].slice(1);\n outputShape = this.computeElementwiseOpOutputShape(outputShape, shape);\n }\n\n let batchSizes: number[] = [];\n for (const shape of inputShape) {\n if (shape != null && shape[0] !== null) {\n batchSizes.push(shape[0]);\n }\n }\n batchSizes = generic_utils.unique(batchSizes);\n if (batchSizes.length === 1) {\n outputShape = batchSizes.concat(outputShape);\n } else {\n outputShape = [null].concat(outputShape);\n }\n return outputShape;\n }\n\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor {\n return tfc.tidy(() => {\n if (mask == null) {\n return null;\n }\n if (!Array.isArray(mask)) {\n throw new ValueError('`mask` should be an Array');\n }\n if (!Array.isArray(inputs)) {\n throw new ValueError('`inputs` should be an Array');\n }\n if (mask.length !== inputs.length) {\n throw new ValueError(\n `The Array 'inputs' and 'mask' are expected to have the same ` +\n `length, but have different lengths ` +\n `(${inputs.length} vs ${mask.length})`);\n }\n if (mask.every(m => m == null)) {\n return null;\n }\n mask = mask.map(m => m == null ? m : tfc.expandDims(m, 0));\n let output = mask[0];\n for (let i = 1; i < mask.length - 1; ++i) {\n output = tfc.logicalAnd(output, mask[i]);\n }\n return output;\n });\n }\n}\n\nexport class Add extends Merge {\n /** @nocollapse */\n static className = 'Add';\n constructor(args?: LayerArgs) {\n super(args);\n }\n\n protected mergeFunction(inputs: Tensor[]): Tensor {\n return tidy(() => {\n let output = inputs[0].clone();\n for (let i = 1; i < inputs.length; ++i) {\n output = tfc.add(output, inputs[i]);\n }\n return output;\n });\n }\n}\nserialization.registerClass(Add);\n\n/**\n * Calculate the element-wise sum of inputs, which all have the same shape.\n *\n * This function can be invoked in three ways.\n *\n * 1. Construct an instance of `Add` layer, by using no input argument\n * or a single configuration argument. The resultant `Add` layer can then\n * be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:\n *\n * ```js\n * const addLayer = tf.layers.add();\n *\n * // The layer can be applied to inputs.\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = addLayer.apply([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.SymbolicTensor`. For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = tf.layers.add([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.Tensor` as the result of the computation. For\n * example:\n *\n * ```js\n * const input1 = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const input2 = tf.tensor2d([10, 20, 30, 40], [2, 2]);\n * tf.layers.add([input1, input2]).print();\n * // Gives [[11, 22], [33, 44]].\n *\n */\nexport function add(config?: SymbolicTensor[]|Tensor[]|LayerArgs): Layer|\n SymbolicTensor|Tensor {\n if (Array.isArray(config)) {\n const layer = new Add({});\n return layer.apply(config) as SymbolicTensor | Tensor;\n } else {\n return new Add(config);\n }\n}\n\nexport class Multiply extends Merge {\n /** @nocollapse */\n static className = 'Multiply';\n constructor(args?: LayerArgs) {\n super(args);\n }\n\n protected mergeFunction(inputs: Tensor[]): Tensor {\n return tidy(() => {\n let output = inputs[0].clone();\n for (let i = 1; i < inputs.length; ++i) {\n output = tfc.mul(output, inputs[i]);\n }\n return output;\n });\n }\n}\nserialization.registerClass(Multiply);\n\n/**\n * Calculate the element-wise product of inputs, which all have the same shape.\n *\n * This function can be invoked in three ways.\n *\n * 1. Construct an instance of `Multiply` layer, by using no input argument\n * or a single configuration argument. The resultant `Multiply` layer can\n * then be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:\n *\n * ```js\n * const multiplyLayer = tf.layers.multiply();\n *\n * // The layer can be applied to inputs.\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = multiplyLayer.apply([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.SymbolicTensor`. For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = tf.layers.multiply([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.Tensor` as the result of the computation. For\n * example:\n *\n * ```js\n * const input1 = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const input2 = tf.tensor2d([10, 20, 30, 40], [2, 2]);\n * tf.layers.multiply([input1, input2]).print();\n * // Gives [[10, 40], [90, 160]].\n *\n */\nexport function multiply(config?: SymbolicTensor[]|Tensor[]|LayerArgs): Layer|\n SymbolicTensor|Tensor {\n if (Array.isArray(config)) {\n const layer = new Multiply({});\n return layer.apply(config) as SymbolicTensor | Tensor;\n } else {\n return new Multiply(config);\n }\n}\n\nexport class Average extends Merge {\n /** @nocollapse */\n static className = 'Average';\n constructor(args?: LayerArgs) {\n super(args);\n }\n\n protected mergeFunction(inputs: Tensor[]): Tensor {\n return tidy(() => {\n let output = inputs[0].clone();\n for (let i = 1; i < inputs.length; ++i) {\n output = tfc.add(output, inputs[i]);\n }\n return tfc.mul(1 / inputs.length, output);\n });\n }\n}\nserialization.registerClass(Average);\n\n/**\n * Calculate the element-wise arithmetic mean of inputs, which all have the same\n * shape.\n *\n * This function can be invoked in three ways.\n *\n * 1. Construct an instance of `Average` layer, by using no input argument\n * or a single configuration argument. The resultant `Average` layer can then\n * be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:\n *\n * ```js\n * const averageLayer = tf.layers.average();\n *\n * // The layer can be applied to inputs.\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = averageLayer.apply([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.SymbolicTensor`. For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = tf.layers.average([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.Tensor` as the result of the computation. For\n * example:\n *\n * ```js\n * const input1 = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const input2 = tf.tensor2d([10, 20, 30, 40], [2, 2]);\n * tf.layers.average([input1, input2]).print();\n * // Gives [[5.5, 11], [16.5, 22]].\n *\n */\nexport function average(config?: SymbolicTensor[]|Tensor[]|LayerArgs): Layer|\n SymbolicTensor|Tensor {\n if (Array.isArray(config)) {\n const layer = new Average({});\n return layer.apply(config) as SymbolicTensor | Tensor;\n } else {\n return new Average(config);\n }\n}\n\nexport class Maximum extends Merge {\n /** @nocollapse */\n static className = 'Maximum';\n constructor(args?: LayerArgs) {\n super(args);\n }\n\n protected mergeFunction(inputs: Tensor[]): Tensor {\n return tidy(() => {\n let output = inputs[0];\n for (let i = 1; i < inputs.length; ++i) {\n output = tfc.maximum(output, inputs[i]);\n }\n return output;\n });\n }\n}\nserialization.registerClass(Maximum);\n\n/**\n * Calculate the element-wise maximum of inputs, which all have the same shape.\n *\n * This function can be invoked in three ways.\n *\n * 1. Construct an instance of `Maximum` layer, by using no input argument\n * or a single configuration argument. The resultant `Maximum` layer can then\n * be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:\n *\n * ```js\n * const maximumLayer = tf.layers.maximum();\n *\n * // The layer can be applied to inputs.\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = maximumLayer.apply([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.SymbolicTensor`. For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = tf.layers.maximum([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.Tensor` as the result of the computation. For\n * example:\n *\n * ```js\n * const input1 = tf.tensor2d([1, 20, 3, 40], [2, 2]);\n * const input2 = tf.tensor2d([10, 2, 30, 4], [2, 2]);\n * tf.layers.maximum([input1, input2]).print();\n * // Gives [[10, 20], [30, 40]].\n *\n */\nexport function maximum(config?: SymbolicTensor[]|Tensor[]|LayerArgs): Layer|\n SymbolicTensor|Tensor {\n if (Array.isArray(config)) {\n const layer = new Maximum({});\n return layer.apply(config) as SymbolicTensor | Tensor;\n } else {\n return new Maximum(config);\n }\n}\n\nexport class Minimum extends Merge {\n /** @nocollapse */\n static className = 'Minimum';\n constructor(args?: LayerArgs) {\n super(args);\n }\n\n protected mergeFunction(inputs: Tensor[]): Tensor {\n return tidy(() => {\n let output = inputs[0];\n for (let i = 1; i < inputs.length; ++i) {\n output = tfc.minimum(output, inputs[i]);\n }\n return output;\n });\n }\n}\nserialization.registerClass(Minimum);\n\n/**\n * Calculate the element-wise minimum of inputs, which all have the same shape.\n *\n * This function can be invoked in three ways.\n *\n * 1. Construct an instance of `Minimum` layer, by using no input argument\n * or a single configuration argument. The resultant `Minimum` layer can then\n * be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:\n *\n * ```js\n * const minimumLayer = tf.layers.minimum();\n *\n * // The layer can be applied to inputs.\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = minimumLayer.apply([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.SymbolicTensor`. For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 2]});\n * const input2 = tf.input({shape: [2, 2]});\n * const output = tf.layers.minimum([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension.\n * ```\n *\n * 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.Tensor` as the result of the computation. For\n * example:\n *\n * ```js\n * const input1 = tf.tensor2d([1, 20, 3, 40], [2, 2]);\n * const input2 = tf.tensor2d([10, 2, 30, 4], [2, 2]);\n * tf.layers.minimum([input1, input2]).print();\n * // Gives [[1, 2], [3, 4]].\n *\n */\nexport function minimum(config?: SymbolicTensor[]|Tensor[]|LayerArgs): Layer|\n SymbolicTensor|Tensor {\n if (Array.isArray(config)) {\n const layer = new Minimum({});\n return layer.apply(config) as SymbolicTensor | Tensor;\n } else {\n return new Minimum(config);\n }\n}\n\nexport declare interface ConcatenateLayerArgs extends LayerArgs {\n /**\n * Axis along which to concatenate.\n */\n axis?: number;\n}\n\nexport class Concatenate extends Merge {\n /** @nocollapse */\n static className = 'Concatenate';\n readonly DEFAULT_AXIS = -1;\n private readonly axis: number;\n\n constructor(args?: ConcatenateLayerArgs) {\n super(args);\n if (args == null) {\n args = {};\n }\n this.axis = args.axis == null ? this.DEFAULT_AXIS : args.axis;\n this.supportsMasking = true;\n this.reshapeRequired = false;\n }\n\n build(inputShape: Shape|Shape[]): void {\n // Used purely for shape validation.]\n if (!(Array.isArray(inputShape) && Array.isArray(inputShape[0])) ||\n inputShape.length === 1) {\n throw new ValueError(\n 'A `Concatenate` layer should be called on a list of at least 2 ' +\n 'inputs');\n }\n inputShape = inputShape as Shape[];\n\n let allNoneShape = true;\n for (const shape of inputShape) {\n if (shape != null) {\n allNoneShape = false;\n break;\n }\n }\n if (allNoneShape) {\n return;\n }\n\n const shapeSet: Shape[] = [];\n for (let i = 0; i < inputShape.length; ++i) {\n const shapeWithoutConcatAxis = inputShape[i].slice();\n shapeWithoutConcatAxis.splice(this.axis, 1);\n let exists = false;\n for (const shape of shapeSet) {\n if (util.arraysEqual(shape, shapeWithoutConcatAxis)) {\n exists = true;\n break;\n }\n }\n if (!exists) {\n shapeSet.push(shapeWithoutConcatAxis);\n }\n }\n if (shapeSet.length > 1) {\n throw new ValueError(\n 'A `Concatenate` layer requires inputs with matching shapes ' +\n 'except for the concat axis. Got input shapes: ' +\n JSON.stringify(inputShape));\n }\n }\n\n protected mergeFunction(inputs: Tensor[]): Tensor {\n return tidy(() => {\n return K.concatenate(inputs, this.axis);\n });\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n if (!(Array.isArray(inputShape) && Array.isArray(inputShape[0]))) {\n throw new ValueError(\n 'A `Concatenate` layer should be called on a list of inputs.');\n }\n const inputShapes = inputShape as Shape[];\n const outputShape = inputShapes[0].slice();\n const axis = this.axis < 0 ? outputShape.length + this.axis : this.axis;\n // Porting Note: the line above is because TypeScript doesn't support\n // negative indices.\n for (const shape of inputShapes.slice(1)) {\n if (outputShape[axis] == null || shape[axis] == null) {\n outputShape[axis] = null;\n break;\n }\n outputShape[axis] += shape[axis];\n }\n return outputShape;\n }\n\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor {\n if (mask == null) {\n return null;\n }\n if (!Array.isArray(mask)) {\n throw new ValueError('`mask` should be an array for Concatenate');\n }\n if (!Array.isArray(inputs)) {\n throw new ValueError('`inputs` should be an array for Concatenate');\n }\n if (mask.length !== inputs.length) {\n throw new ValueError(\n `Mismatch in the length of mask (${mask.length}) ` +\n `and the legnth of inputs (${inputs.length})`);\n }\n return tfc.tidy(() => {\n let allNullMasks = true;\n mask.forEach(m => {\n if (m != null) {\n allNullMasks = false;\n return;\n }\n });\n if (allNullMasks) {\n return null;\n }\n const outputMasks: Tensor[] = [];\n for (let i = 0; i < inputs.length; ++i) {\n if (mask[i] == null) {\n // Input is unmasked. Append all 1's to masks.\n outputMasks.push(tfc.cast(tfc.onesLike(inputs[i]), 'bool'));\n } else if (mask[i].rank < inputs[i].rank) {\n // Mask is smaller than the input, expand it.\n outputMasks.push(tfc.expandDims(mask[i], -1));\n } else {\n outputMasks.push(mask[i]);\n }\n }\n const concatenatedMasks = tfc.concat(outputMasks, this.axis);\n return tfc.all(concatenatedMasks, -1, false);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'axis': this.axis,\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Concatenate);\n\n/**\n * Concatenate an `Array` of inputs.\n *\n * This function can be invoked in three ways.\n *\n * 1. Construct an instance of `Concatenate` layer, by using no input argument\n * or a single configuration argument. The resultant `Concatenate` layer can\n * then be used on `tf.SymbolicTensor`s or `tf.Tensor`s. For example:\n *\n * ```js\n * const concatLayer = tf.layers.concatenate();\n *\n * // The layer can be applied to inputs.\n * const input1 = tf.input({shape: [2, 3]});\n * const input2 = tf.input({shape: [2, 4]});\n * const output = concatLayer.apply([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 7], with the first dimension as the undetermined batch\n * // dimension and the last dimension as the result of concatenating the\n * // last dimensions of the two inputs.\n * ```\n *\n * 2. Invoke directly on an `Array` of `tf.SymbolicTensor`s. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.SymbolicTensor`. For example:\n *\n * ```js\n * const input1 = tf.input({shape: [2, 3]});\n * const input2 = tf.input({shape: [2, 4]});\n * const output = tf.layers.concatenate([input1, input2]);\n * console.log(output.shape);\n * // You get [null, 2, 2], with the first dimension as the undetermined batch\n * // dimension and the last dimension as the result of concatenating the\n * // last dimensions of the two inputs.\n * ```\n *\n * 3. Invoke directly on `tf.Tensor`s, i.e., concrete values. This constructs\n * an `Layer` object internally and calls its `apply` method on the inputs,\n * generating a new `tf.Tensor` as the result of the computation. For\n * example:\n *\n * ```js\n * const input1 = tf.tensor2d([[1, 2], [3, 4]], [2, 2]);\n * const input2 = tf.tensor2d([[10, 20], [30, 40]], [2, 2]);\n * tf.layers.concatenate([input1, input2]).print();\n * // Gives [[1, 2, 10, 20], [3, 4, 30, 40]].\n *\n */\nexport function concatenate(config?: SymbolicTensor[]|Tensor[]|\n ConcatenateLayerArgs): Layer|SymbolicTensor|Tensor {\n if (Array.isArray(config)) {\n const layer = new Concatenate({});\n return layer.apply(config) as SymbolicTensor | Tensor;\n } else {\n return new Concatenate(config);\n }\n}\n\nexport declare interface DotLayerArgs extends LayerArgs {\n /**\n * Axis or axes along which the dot product will be taken.\n *\n * Integer or an Array of integers.\n */\n axes: number|[number, number];\n\n /**\n * Whether to L2-normalize samples along the dot product axis\n * before taking the dot product.\n *\n * If set to `true`, the output of the dot product isthe cosine\n * proximity between the two samples.\n */\n normalize?: boolean;\n}\n\n/**\n * Interpretable potentially negative axis index.\n *\n * For example, given axis = -1, and dim = 3, this function will return 2.\n *\n * @param axis The axis index, may be a positive, zero or negative integer.\n * @param dim Total number of dimensions, a positive integer.\n * @returns A non-negative axis index equivalent to the input `axis`.\n */\nfunction interpretAxis(axis: number, dim: number): number {\n while (axis < 0) {\n axis += dim;\n }\n return axis;\n}\n\nfunction batchDot(x: Tensor, y: Tensor, axes: number|[number, number]): Tensor {\n if (x.shape.length > 3 || y.shape.length > 3) {\n throw new NotImplementedError(\n 'batchDot is not implemented for tensors of 4D or higher rank yet');\n }\n tfc.util.assert(\n x.shape.length >= 2,\n () => `batchDot requires the rank of x to be >= 2, ` +\n `but got ${x.shape.length}`);\n tfc.util.assert(\n x.shape.length >= 2,\n () => `batchDot requires the rank of y to be >= 2, ` +\n `but got ${y.shape.length}`);\n\n if (typeof axes === 'number') {\n axes = [axes, axes];\n }\n\n if (x.dtype === 'complex64' || y.dtype === 'complex64') {\n throw new NotImplementedError(\n 'batchDot is not implemented for complex64-type Tensors yet.');\n }\n\n const xNDim = x.shape.length;\n const yNDim = y.shape.length;\n if (axes == null) {\n // Behave like batchMatmul by default.\n axes = [xNDim - 1, yNDim - 2];\n }\n const axesArray = axes as [number, number];\n\n return tfc.tidy(() => {\n let diff: number;\n if (xNDim > yNDim) {\n diff = xNDim - yNDim;\n const diffShape: Shape = [];\n for (let i = 0; i < diff; ++i) {\n diffShape.push(1);\n }\n y = tfc.reshape(y, y.shape.concat(diffShape));\n } else if (yNDim > xNDim) {\n diff = yNDim - xNDim;\n const diffShape: Shape = [];\n for (let i = 0; i < diff; ++i) {\n diffShape.push(1);\n }\n x = tfc.reshape(x, x.shape.concat(diffShape));\n } else {\n diff = 0;\n }\n\n let out: Tensor;\n if (x.shape.length === 2 && y.shape.length === 2) {\n if (axesArray[0] === axesArray[1]) {\n out = tfc.sum(tfc.mul(x, y), axesArray[0]);\n } else {\n out = tfc.sum(tfc.mul(tfc.transpose(x, [1, 0]), y), axesArray[1]);\n }\n } else {\n const adjX = axesArray[0] !== x.shape.length - 1;\n const adjY = axesArray[1] === y.shape.length - 1;\n out = tfc.matMul(x, y, adjX, adjY);\n }\n\n if (diff > 0) {\n let idx: number;\n if (xNDim > yNDim) {\n idx = xNDim + yNDim - 3;\n } else {\n idx = xNDim - 1;\n }\n const squeezeAxes: number[] = [];\n for (let i = idx; i < idx + diff; ++i) {\n squeezeAxes.push(i);\n }\n out = tfc.squeeze(out, squeezeAxes);\n }\n if (out.shape.length === 1) {\n out = tfc.expandDims(out, 1);\n }\n return out;\n });\n}\n\nexport class Dot extends Merge {\n /** @nocollapse */\n static className = 'Dot';\n\n private axes: number|[number, number];\n private normalize: boolean;\n\n constructor(args: DotLayerArgs) {\n super(args);\n this.axes = args.axes;\n this.normalize = args.normalize == null ? false : args.normalize;\n this.supportsMasking = true;\n this.reshapeRequired = false;\n }\n\n build(inputShape: Shape|Shape[]): void {\n tfc.util.assert(\n Array.isArray(inputShape) && inputShape.length === 2 &&\n Array.isArray(inputShape[0]) && Array.isArray(inputShape[1]),\n () => 'A `Dot` layer should be called on a list of exactly 2 inputs.');\n const shape1 = inputShape[0] as Shape;\n const shape2 = inputShape[1] as Shape;\n if (shape1.length > 3 || shape2.length > 3) {\n throw new NotImplementedError(\n 'Dot layer does not support tensors of 4D or higher rank yet.');\n }\n\n const axes = this.interpretAxes(shape1, shape2);\n if (shape1[axes[0]] !== shape2[axes[1]]) {\n throw new ValueError(\n `Dimension incompatibility: ` +\n `${shape1[axes[0]]} !== ${shape2[axes[1]]}`);\n }\n }\n\n protected mergeFunction(inputs: Tensor[]): Tensor {\n if (inputs.length !== 2) {\n throw new ValueError(\n 'A `Dot` layer must be called on exactly 2 inputs, ' +\n `but received ${inputs.length} input(s).`);\n }\n\n let x1 = inputs[0];\n let x2 = inputs[1];\n let axes: [number, number];\n if (!Array.isArray(this.axes)) {\n axes = [\n interpretAxis(this.axes, x1.shape.length),\n interpretAxis(this.axes, x2.shape.length)\n ];\n } else {\n axes = this.axes.map(\n (axis, i) => interpretAxis(\n axis, inputs[i].shape.length)) as [number, number];\n }\n if (this.normalize) {\n x1 = l2Normalize(x1, axes[0]);\n x2 = l2Normalize(x2, axes[1]);\n }\n return batchDot(x1, x2, axes);\n }\n\n private interpretAxes(shape1: Shape, shape2: Shape): number[] {\n let axes: number[];\n if (!Array.isArray(this.axes)) {\n // `this.axes` is a single integer.\n axes = [\n interpretAxis(this.axes, shape1.length),\n interpretAxis(this.axes, shape2.length)\n ];\n } else {\n // `this.axes` is an Array of integers.\n axes = this.axes;\n }\n return axes;\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n tfc.util.assert(\n Array.isArray(inputShape) && inputShape.length === 2 &&\n Array.isArray(inputShape[0]) && Array.isArray(inputShape[1]),\n () => 'A `Dot` layer should be called on a list of exactly 2 inputs.');\n const shape1 = (inputShape[0] as Shape).slice();\n const shape2 = (inputShape[1] as Shape).slice();\n if (shape1.length > 3 || shape2.length > 3) {\n throw new NotImplementedError(\n 'Dot layer does not support tensors of 4D or higher rank yet.');\n }\n\n const axes = this.interpretAxes(shape1, shape2);\n shape1.splice(axes[0], 1);\n shape2.splice(axes[1], 1);\n shape2.splice(0, 1);\n const outputShape = shape1.concat(shape2);\n if (outputShape.length === 1) {\n outputShape.push(1);\n }\n return outputShape;\n }\n\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor {\n return null;\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'axes': this.axes,\n 'normalize': this.normalize\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(Dot);\n\n// TODO(cais): Add functional interfaces for the merge layers.\n", "/**\r\n * @license\r\n * Copyright 2018 Google LLC\r\n *\r\n * Use of this source code is governed by an MIT-style\r\n * license that can be found in the LICENSE file or at\r\n * https://opensource.org/licenses/MIT.\r\n * =============================================================================\r\n */\r\n\r\n/**\r\n * TensorFlow.js Layers: Noise Layers.\r\n */\r\n\r\nimport {add, greaterEqual, mul, randomUniform, serialization, Tensor, tidy} from '@tensorflow/tfjs-core';\r\n\r\nimport * as K from '../backend/tfjs_backend';\r\nimport {Layer, LayerArgs} from '../engine/topology';\r\nimport {Shape} from '../keras_format/common';\r\nimport {Kwargs} from '../types';\r\nimport {getExactlyOneTensor} from '../utils/types_utils';\r\n\r\nexport declare interface GaussianNoiseArgs extends LayerArgs {\r\n /** Standard Deviation. */\r\n stddev: number;\r\n}\r\n\r\nexport class GaussianNoise extends Layer {\r\n /** @nocollapse */\r\n static className = 'GaussianNoise';\r\n readonly stddev: number;\r\n\r\n constructor(args: GaussianNoiseArgs) {\r\n super(args);\r\n this.supportsMasking = true;\r\n this.stddev = args.stddev;\r\n }\r\n\r\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\r\n return inputShape;\r\n }\r\n\r\n getConfig() {\r\n const baseConfig = super.getConfig();\r\n const config = {stddev: this.stddev};\r\n Object.assign(config, baseConfig);\r\n return config;\r\n }\r\n\r\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\r\n return tidy(() => {\r\n this.invokeCallHook(inputs, kwargs);\r\n const input = getExactlyOneTensor(inputs);\r\n const noised = () =>\r\n add(K.randomNormal(input.shape, 0, this.stddev), input);\r\n const output =\r\n K.inTrainPhase(noised, () => input, kwargs['training'] || false);\r\n return output;\r\n });\r\n }\r\n}\r\nserialization.registerClass(GaussianNoise);\r\n\r\nexport declare interface GaussianDropoutArgs extends LayerArgs {\r\n /** drop probability. */\r\n rate: number;\r\n}\r\n\r\nexport class GaussianDropout extends Layer {\r\n /** @nocollapse */\r\n static className = 'GaussianDropout';\r\n readonly rate: number;\r\n\r\n constructor(args: GaussianDropoutArgs) {\r\n super(args);\r\n this.supportsMasking = true;\r\n this.rate = args.rate;\r\n }\r\n\r\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\r\n return inputShape;\r\n }\r\n\r\n getConfig() {\r\n const baseConfig = super.getConfig();\r\n const config = {rate: this.rate};\r\n Object.assign(config, baseConfig);\r\n return config;\r\n }\r\n\r\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\r\n return tidy(() => {\r\n this.invokeCallHook(inputs, kwargs);\r\n const input = getExactlyOneTensor(inputs);\r\n if (this.rate > 0 && this.rate < 1) {\r\n const noised = () => {\r\n const stddev = Math.sqrt(this.rate / (1 - this.rate));\r\n return mul(input, K.randomNormal(input.shape, 1, stddev));\r\n };\r\n return K.inTrainPhase(noised, () => input, kwargs['training'] || false);\r\n }\r\n return input;\r\n });\r\n }\r\n}\r\nserialization.registerClass(GaussianDropout);\r\n\r\nexport declare interface AlphaDropoutArgs extends LayerArgs {\r\n /** drop probability. */\r\n rate: number;\r\n /**\r\n * A 1-D `Tensor` of type `int32`, representing the\r\n * shape for randomly generated keep/drop flags.\r\n */\r\n noiseShape?: Shape;\r\n}\r\n\r\n/**\r\n * Applies Alpha Dropout to the input.\r\n *\r\n * As it is a regularization layer, it is only active at training time.\r\n *\r\n * Alpha Dropout is a `Dropout` that keeps mean and variance of inputs\r\n * to their original values, in order to ensure the self-normalizing property\r\n * even after this dropout.\r\n * Alpha Dropout fits well to Scaled Exponential Linear Units\r\n * by randomly setting activations to the negative saturation value.\r\n *\r\n * Arguments:\r\n * - `rate`: float, drop probability (as with `Dropout`).\r\n * The multiplicative noise will have\r\n * standard deviation `sqrt(rate / (1 - rate))`.\r\n * - `noise_shape`: A 1-D `Tensor` of type `int32`, representing the\r\n * shape for randomly generated keep/drop flags.\r\n *\r\n * Input shape:\r\n * Arbitrary. Use the keyword argument `inputShape`\r\n * (tuple of integers, does not include the samples axis)\r\n * when using this layer as the first layer in a model.\r\n *\r\n * Output shape:\r\n * Same shape as input.\r\n *\r\n * References:\r\n * - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515)\r\n */\r\nexport class AlphaDropout extends Layer {\r\n /** @nocollapse */\r\n static className = 'AlphaDropout';\r\n readonly rate: number;\r\n readonly noiseShape: Shape;\r\n\r\n constructor(args: AlphaDropoutArgs) {\r\n super(args);\r\n this.supportsMasking = true;\r\n this.rate = args.rate;\r\n this.noiseShape = args.noiseShape;\r\n }\r\n\r\n _getNoiseShape(inputs: Tensor|Tensor[]) {\r\n return this.noiseShape || getExactlyOneTensor(inputs).shape;\r\n }\r\n\r\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\r\n return inputShape;\r\n }\r\n\r\n getConfig() {\r\n const baseConfig = super.getConfig();\r\n const config = {rate: this.rate};\r\n Object.assign(config, baseConfig);\r\n return config;\r\n }\r\n\r\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\r\n return tidy(() => {\r\n if (this.rate < 1 && this.rate > 0) {\r\n const noiseShape = this._getNoiseShape(inputs);\r\n\r\n const droppedInputs = () => {\r\n const input = getExactlyOneTensor(inputs);\r\n\r\n const alpha = 1.6732632423543772848170429916717;\r\n const scale = 1.0507009873554804934193349852946;\r\n\r\n const alphaP = -alpha * scale;\r\n\r\n let keptIdx = greaterEqual(randomUniform(noiseShape), this.rate);\r\n\r\n keptIdx = K.cast(keptIdx, 'float32'); // get default dtype.\r\n\r\n // Get affine transformation params.\r\n const a = ((1 - this.rate) * (1 + this.rate * alphaP ** 2)) ** -0.5;\r\n const b = -a * alphaP * this.rate;\r\n\r\n // Apply mask.\r\n const x = add(mul(input, keptIdx), mul(add(keptIdx, -1), alphaP));\r\n\r\n return add(mul(x, a), b);\r\n };\r\n return K.inTrainPhase(\r\n droppedInputs, () => getExactlyOneTensor(inputs),\r\n kwargs['training'] || false);\r\n }\r\n return inputs;\r\n });\r\n }\r\n}\r\nserialization.registerClass(AlphaDropout);\r\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Normalization layers.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {moments, reshape, serialization, Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D, tidy, util} from '@tensorflow/tfjs-core';\n\nimport {Constraint, ConstraintIdentifier, getConstraint, serializeConstraint} from '../constraints';\nimport {InputSpec, Layer, LayerArgs} from '../engine/topology';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {getInitializer, Initializer, InitializerIdentifier, serializeInitializer} from '../initializers';\nimport {Shape} from '../keras_format/common';\nimport {getRegularizer, Regularizer, RegularizerIdentifier, serializeRegularizer} from '../regularizers';\nimport {Kwargs} from '../types';\nimport * as generic_utils from '../utils/generic_utils';\nimport * as math_utils from '../utils/math_utils';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\nimport {LayerVariable} from '../variables';\n\n/**\n * Applies batch normalization on x given mean, var, beta and gamma.\n *\n * I.e. returns:\n * `output = (x - mean) / (sqrt(var) + epsilon) * gamma + beta`\n *\n * @param x Input tensor.\n * @param mean Mean of batch.\n * @param variance Variance of batch.\n * @param beta Tensor with which to center the input.\n * @param gamma Tensor by which to scale the input.\n * @param epsilon Fuzz factor.\n * @returns The result of the batch normalization.\n */\nexport function batchNormalization(\n x: Tensor, mean: Tensor, variance: Tensor, beta?: Tensor, gamma?: Tensor,\n epsilon = 1e-3): Tensor {\n let out: Tensor;\n if (x.rank === 2) {\n out = tfc.batchNorm2d(\n x as Tensor2D, mean as Tensor2D | Tensor1D,\n variance as Tensor2D | Tensor1D, beta as Tensor2D | Tensor1D,\n gamma as Tensor2D | Tensor1D, epsilon);\n } else if (x.rank === 3) {\n // TODO(cais): Check rank; give proper error message.\n out = tfc.batchNorm3d(\n x as Tensor3D, mean as Tensor3D | Tensor1D,\n variance as Tensor3D | Tensor1D, beta as Tensor3D | Tensor1D,\n gamma as Tensor3D | Tensor1D, epsilon);\n } else if (x.rank === 4) {\n out = tfc.batchNorm4d(\n x as Tensor4D, mean as Tensor4D | Tensor1D,\n variance as Tensor4D | Tensor1D, beta as Tensor4D | Tensor1D,\n gamma as Tensor4D | Tensor1D, epsilon);\n } else {\n throw new NotImplementedError(\n `batchNormalization is not implemented for array of rank ${x.rank} ` +\n `yet`);\n }\n return out;\n}\n\n/**\n * Non-broadcasting batch normalization for use in training (not inference).\n *\n * The input is normalized to zero mean and unit variance along the\n * `reductionAxes`, followed by scaling with `gamma` and shifted by `beta`.\n * The result of that is returned as the first element\n * of the returned `Array`. The other two elements are the mean and variance,\n * respectively.\n *\n * @param x Input tensor to be normalized.\n * @param gamma Tensor by which to scale the input.\n * @param beta Tensor by which to center the input.\n * @param reductionAxes Axes over which to normalize.\n * @param epsilon Fuzz factor.\n * @returns An `Array` of three `Tensors`:\n * [normalized tensor, mean of input, variance of input].\n */\nfunction regularNormalizeBatchInTraining(\n x: Tensor, gamma: Tensor, beta: Tensor, reductionAxes: number[],\n epsilon = 1e-3): [Tensor, Tensor, Tensor] {\n return tidy(() => {\n const meanAndVariance = tfc.moments(x, reductionAxes);\n const mean = meanAndVariance.mean;\n const variance = meanAndVariance.variance;\n const normed =\n batchNormalization(x, mean, variance, beta, gamma, epsilon);\n return [normed, mean, variance];\n }) as [Tensor, Tensor, Tensor];\n}\n\n/**\n * Broadcasting batch normalization for use in training (not inference).\n *\n * The input is normalized to zero mean and unit variance along the\n * `reductionAxes`, followed by scaling with `gamma` and shifted by `beta`.\n * The result of that is returned as the first element\n * of the returned `Array`. The other two elements are the mean and variance,\n * respectively.\n *\n * @param x Input tensor to be normalized.\n * @param gamma Tensor by which to scale the input.\n * @param beta Tensor by which to center the input.\n * @param reductionAxes Axes over which to normalize.\n * @param epsilon Fuzz factor.\n * @returns An `Array` of three `Tensors`:\n * [normalized tensor, mean of input, variance of input].\n */\nfunction broadcastNormalizeBatchInTraining(\n x: Tensor, gamma: Tensor, beta: Tensor, reductionAxes: number[],\n epsilon = 1e-3): [Tensor, Tensor, Tensor] {\n return tidy(() => {\n const meanAndVariance = tfc.moments(x, reductionAxes);\n const mean = meanAndVariance.mean;\n const variance = meanAndVariance.variance;\n const targetShape: number[] = [];\n for (const axis of math_utils.range(0, x.rank)) {\n if (reductionAxes.indexOf(axis) !== -1) {\n targetShape.push(1);\n } else {\n targetShape.push(x.shape[axis]);\n }\n }\n const broadcastMean = reshape(mean, targetShape);\n const broadcastVariance = reshape(variance, targetShape);\n const broadcastGamma =\n gamma == null ? null : reshape(gamma, targetShape);\n const broadcastBeta =\n beta == null ? null : reshape(beta, targetShape);\n const normed = batchNormalization(\n x, broadcastMean, broadcastVariance, broadcastBeta,\n broadcastGamma, epsilon);\n return [normed, mean, variance];\n }) as [Tensor, Tensor, Tensor];\n}\n\n/**\n * Batch normalization for use in training (not inference).\n *\n * @param x Input tensor to be normalized.\n * @param gamma Tensor by which to scale the input.\n * @param beta Tensor by which to center the input.\n * @param reductionAxes Axes over which to normalize.\n * @param epsilon Fuzz factor.\n * @returns An `Array` of three `Tensors`:\n * [normalized tensor, mean of input, variance of input].\n */\nexport function normalizeBatchInTraining(\n x: Tensor, gamma: Tensor, beta: Tensor, reductionAxes: number[],\n epsilon = 1e-3): [Tensor, Tensor, Tensor] {\n if (util.arraysEqual(\n reductionAxes.slice().sort(), math_utils.range(0, x.rank - 1))) {\n return regularNormalizeBatchInTraining(\n x, gamma, beta, reductionAxes, epsilon);\n } else {\n return broadcastNormalizeBatchInTraining(\n x, gamma, beta, reductionAxes, epsilon);\n }\n}\n\nexport declare interface BatchNormalizationLayerArgs extends LayerArgs {\n /**\n * The integer axis that should be normalized (typically the features axis).\n * Defaults to -1.\n *\n * For instance, after a `Conv2D` layer with `data_format=\"channels_first\"`,\n * set `axis=1` in `batchNormalization`.\n */\n axis?: number;\n\n /**\n * Momentum of the moving average. Defaults to 0.99.\n */\n momentum?: number;\n\n /**\n * Small float added to the variance to avoid dividing by zero. Defaults to\n * 1e-3.\n */\n epsilon?: number;\n\n /**\n * If `true`, add offset of `beta` to normalized tensor.\n * If `false`, `beta` is ignored.\n * Defaults to `true`.\n */\n center?: boolean;\n\n /**\n * If `true`, multiply by `gamma`.\n * If `false`, `gamma` is not used.\n * When the next layer is linear (also e.g. `nn.relu`),\n * this can be disabled since the scaling will be done by the next layer.\n * Defaults to `true`.\n */\n scale?: boolean;\n\n /**\n * Initializer for the beta weight.\n * Defaults to 'zeros'.\n */\n betaInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the gamma weight.\n * Defaults to `ones`.\n */\n gammaInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the moving mean.\n * Defaults to `zeros`\n */\n movingMeanInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the moving variance.\n * Defaults to 'Ones'.\n */\n movingVarianceInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Constraint for the beta weight.\n */\n betaConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Constraint for gamma weight.\n */\n gammaConstraint?: ConstraintIdentifier|Constraint;\n\n /**\n * Regularizer for the beta weight.\n */\n betaRegularizer?: RegularizerIdentifier|Regularizer;\n\n /**\n * Regularizer for the gamma weight.\n */\n gammaRegularizer?: RegularizerIdentifier|Regularizer;\n}\n\nexport class BatchNormalization extends Layer {\n /** @nocollapse */\n static className = 'BatchNormalization';\n private readonly axis: number;\n private readonly momentum: number;\n private readonly epsilon: number;\n private readonly center: boolean;\n private readonly scale: boolean;\n private readonly betaInitializer: Initializer;\n private readonly gammaInitializer: Initializer;\n private readonly movingMeanInitializer: Initializer;\n private readonly movingVarianceInitializer: Initializer;\n private readonly betaConstraint: Constraint;\n private readonly gammaConstraint: Constraint;\n private readonly betaRegularizer: Regularizer;\n private readonly gammaRegularizer: Regularizer;\n private gamma: LayerVariable;\n private beta: LayerVariable;\n private movingMean: LayerVariable;\n private movingVariance: LayerVariable;\n\n constructor(args?: BatchNormalizationLayerArgs) {\n if (args == null) {\n args = {};\n }\n super(args);\n\n this.supportsMasking = true;\n this.axis = args.axis == null ? -1 : args.axis;\n this.momentum = args.momentum == null ? 0.99 : args.momentum;\n this.epsilon = args.epsilon == null ? 1e-3 : args.epsilon;\n this.center = args.center == null ? true : args.center;\n this.scale = args.scale == null ? true : args.scale;\n this.betaInitializer = getInitializer(args.betaInitializer || 'zeros');\n this.gammaInitializer = getInitializer(args.gammaInitializer || 'ones');\n this.movingMeanInitializer =\n getInitializer(args.movingMeanInitializer || 'zeros');\n this.movingVarianceInitializer =\n getInitializer(args.movingVarianceInitializer || 'ones');\n this.betaConstraint = getConstraint(args.betaConstraint);\n this.gammaConstraint = getConstraint(args.gammaConstraint);\n this.betaRegularizer = getRegularizer(args.betaRegularizer);\n this.gammaRegularizer = getRegularizer(args.gammaRegularizer);\n }\n\n public build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n const axis = this.axis >= 0 ? this.axis : (this.axis + inputShape.length);\n const dim = inputShape[axis];\n if (dim == null) {\n throw new ValueError(\n `Axis ${axis} of input tensor should have a defined dimension but ` +\n `the layer received an input with shape ` +\n `${JSON.stringify(inputShape)}.`);\n }\n this.inputSpec =\n [new InputSpec({ndim: inputShape.length, axes: {[axis]: dim}})];\n const shape = [dim];\n if (this.scale) {\n this.gamma = this.addWeight(\n 'gamma', shape, null, this.gammaInitializer, this.gammaRegularizer,\n true, this.gammaConstraint);\n }\n if (this.center) {\n this.beta = this.addWeight(\n 'beta', shape, null, this.betaInitializer, this.betaRegularizer, true,\n this.betaConstraint);\n }\n this.movingMean = this.addWeight(\n 'moving_mean', shape, null, this.movingMeanInitializer, null, false);\n this.movingVariance = this.addWeight(\n 'moving_variance', shape, null, this.movingVarianceInitializer, null,\n false);\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n const training = kwargs['training'] == null ? false : kwargs['training'];\n const input = getExactlyOneTensor(inputs);\n const inputShape = input.shape;\n const ndim = inputShape.length;\n const reductionAxes = math_utils.range(0, ndim);\n const axis = this.axis >= 0 ? this.axis : (this.axis + ndim);\n reductionAxes.splice(axis, 1);\n const broadcastShape = generic_utils.pyListRepeat(1, ndim);\n broadcastShape[axis] = inputShape[axis];\n\n const sortedReductionAxes = reductionAxes.slice();\n sortedReductionAxes.sort();\n const needsBroadcasting = !util.arraysEqual(\n sortedReductionAxes, math_utils.range(0, ndim).slice(0, ndim - 1));\n\n const normalizeInference: () => Tensor = () => {\n if (needsBroadcasting) {\n const broadcastMovingMean =\n reshape(this.movingMean.read(), broadcastShape);\n const broadcastMovingVariance =\n reshape(this.movingVariance.read(), broadcastShape);\n const broadcastBeta =\n this.center ? reshape(this.beta.read(), broadcastShape) : null;\n const broadcastGamma =\n this.scale ? reshape(this.gamma.read(), broadcastShape) : null;\n return batchNormalization(\n input, broadcastMovingMean, broadcastMovingVariance,\n broadcastBeta, broadcastGamma, this.epsilon);\n } else {\n return batchNormalization(\n input, this.movingMean.read(), this.movingVariance.read(),\n this.beta == null ? null : this.beta.read(),\n this.gamma == null ? null : this.gamma.read(), this.epsilon);\n }\n };\n\n if (!training) {\n return normalizeInference();\n }\n\n const [normedTraining, mean, variance] = normalizeBatchInTraining(\n input, this.gamma.read(), this.beta.read(), reductionAxes,\n this.epsilon);\n\n const doMovingAverage =\n (variable: LayerVariable, value: Tensor, momentum: number): void => {\n tfc.tidy(() => {\n const decay = 1 - momentum;\n const origValue = variable.read();\n const updateDelta = tfc.mul(tfc.sub(origValue, value), decay);\n variable.write(tfc.sub(origValue, updateDelta));\n });\n };\n\n // Perform updates to moving mean and moving variance for training.\n // Porting Note: In PyKeras, these updates to `movingMean` and\n // `movingAverage` are done as a deferred Graph, added to the `Layer`'s\n // `update`s using the `add_update()` method. Here we do it imperatively\n // and encapsulate the updates in a function that is invoked\n // immediately.\n const updateMovingMeanAndVariance = () => {\n doMovingAverage(this.movingMean, mean, this.momentum);\n doMovingAverage(this.movingVariance, variance, this.momentum);\n };\n updateMovingMeanAndVariance();\n\n return normedTraining;\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n axis: this.axis,\n momentum: this.momentum,\n epsilon: this.epsilon,\n center: this.center,\n scale: this.scale,\n betaInitializer: serializeInitializer(this.betaInitializer),\n gammaInitializer: serializeInitializer(this.gammaInitializer),\n movingMeanInitializer: serializeInitializer(this.movingMeanInitializer),\n movingVarianceInitializer:\n serializeInitializer(this.movingVarianceInitializer),\n betaRegularizer: serializeRegularizer(this.betaRegularizer),\n gammaRegularizer: serializeRegularizer(this.gammaRegularizer),\n betaConstraint: serializeConstraint(this.betaConstraint),\n gammaConstraint: serializeConstraint(this.gammaConstraint)\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(BatchNormalization);\n\nexport interface LayerNormalizationLayerArgs extends LayerArgs {\n /**\n * The axis or axes that should be normalized (typically, the feature axis.)\n * Defaults to -1 (the last axis.)\n */\n axis?: number|number[];\n\n /**\n * A small positive float added to variance to avoid divison by zero.\n * Defaults to 1e-3.\n */\n epsilon?: number;\n\n /**\n * If `true`, add offset of `beta` to normalized tensor.\n * If `false`, `beta` is ignored.\n * Default: `true`.\n */\n center?: boolean;\n\n /**\n * If `true`, multiply output by `gamma`.\n * If `false`, `gamma` is not used.\n * When the next layer is linear, this can be disabled since scaling will\n * be done by the next layer.\n * Default: `true`.\n */\n scale?: boolean;\n\n /**\n * Initializer for the beta weight.\n * Default: `'zeros'`.\n */\n betaInitializer?: InitializerIdentifier|Initializer;\n\n /**\n * Initializer for the gamma weight.\n * Default: `'ones'`.\n */\n gammaInitializer?: InitializerIdentifier|Initializer;\n\n /** Regularizer for the beta weight. */\n betaRegularizer?: RegularizerIdentifier|Regularizer;\n\n /** Regularizer for the gamma weight. */\n gammaRegularizer?: RegularizerIdentifier|Regularizer;\n}\n\nexport class LayerNormalization extends Layer {\n /** @nocollapse */\n static className = 'LayerNormalization';\n\n private axis: number|number[];\n readonly epsilon: number;\n readonly center: boolean;\n readonly scale: boolean;\n readonly betaInitializer: Initializer;\n readonly gammaInitializer: Initializer;\n readonly betaRegularizer: Regularizer;\n readonly gammaRegularizer: Regularizer;\n\n private gamma: LayerVariable;\n private beta: LayerVariable;\n\n constructor(args?: LayerNormalizationLayerArgs) {\n if (args == null) {\n args = {};\n }\n super(args);\n\n this.axis = args.axis == null ? -1 : args.axis;\n if (typeof this.axis === 'number') {\n if (!Number.isInteger(this.axis)) {\n throw new Error(\n `Expected axis to be an integer, but received ${this.axis}`);\n }\n } else if (Array.isArray(this.axis)) {\n for (const axis of this.axis) {\n if (!Number.isInteger(axis)) {\n throw new Error(\n `Expected axis to be an array of integers, ` +\n `but received ${JSON.stringify(this.axis)}`);\n }\n }\n } else {\n throw new Error(\n `Expected axis to be an integer or an array of integers, ` +\n `but received ${JSON.stringify(this.axis)}`);\n }\n\n this.epsilon = args.epsilon == null ? 1e-3 : args.epsilon;\n this.center = args.center == null ? true : args.center;\n this.scale = args.scale == null ? true : args.scale;\n this.betaInitializer = getInitializer(args.betaInitializer || 'zeros');\n this.gammaInitializer = getInitializer(args.gammaInitializer || 'ones');\n this.betaRegularizer = getRegularizer(args.betaRegularizer);\n this.gammaRegularizer = getRegularizer(args.gammaRegularizer);\n\n this.supportsMasking = true;\n }\n\n public build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n const nDims = inputShape.length;\n\n // Convert axis to array and resolve negatives.\n if (typeof this.axis === 'number') {\n this.axis = [this.axis];\n }\n for (let i = 0; i < this.axis.length; ++i) {\n if (this.axis[i] < 0) {\n this.axis[i] += nDims;\n }\n }\n\n // Further validate axes.\n for (const axis of this.axis) {\n if (axis < 0 || axis >= nDims) {\n throw new Error(`Invalid axis: ${axis}`);\n }\n }\n if (this.axis.length !== generic_utils.unique(this.axis).length) {\n throw new Error(`Found duplicate axes in: ${this.axis}`);\n }\n\n const paramShape = this.axis.map(axis => inputShape[axis]) as number[];\n\n const trainable = true;\n if (this.scale) {\n this.gamma = this.addWeight(\n 'gamma', paramShape, 'float32', this.gammaInitializer,\n this.gammaRegularizer, trainable);\n } else {\n this.gamma = null;\n }\n if (this.center) {\n this.beta = this.addWeight(\n 'beta', paramShape, 'float32', this.betaInitializer,\n this.betaRegularizer, trainable);\n } else {\n this.beta = null;\n }\n\n this.built = true;\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n const input = getExactlyOneTensor(inputs);\n const inputShape = input.shape;\n const nDims = inputShape.length;\n\n return tidy(() => {\n const keepDims = true;\n let {mean, variance} = moments(input, this.axis, keepDims);\n const broadcastShape = generic_utils.pyListRepeat(1, nDims);\n for (const dim of this.axis as number[]) {\n broadcastShape[dim] = inputShape[dim];\n }\n\n const broadcast = (v: Tensor) => {\n if (v != null && v.shape.length !== nDims &&\n this.axis !== [nDims - 1]) {\n return tfc.reshape(v, broadcastShape);\n } else {\n return v;\n }\n };\n\n let scale = broadcast(this.gamma.read());\n let offset = broadcast(this.beta.read());\n\n // TODO(https://github.com/tensorflow/tfjs/issues/2120): The tiling below\n // is a workaround for the limitation of core's batchNormalization?d don't\n // support broadcasting in their gradients. In addition, the tiling is\n // necessary to ensure correctness on the browser CPU backend regardless\n // of forward or backward computation. Remove this workaround once the\n // limitation is addressed. See .\n const momentsTiling: number[] = [];\n const scaleOffsetTiling: number[] = [];\n for (let i = 0; i < nDims; ++i) {\n if ((this.axis as number[]).indexOf(i) !== -1) {\n momentsTiling.push(inputShape[i]);\n scaleOffsetTiling.push(1);\n } else {\n momentsTiling.push(1);\n scaleOffsetTiling.push(inputShape[i]);\n }\n }\n mean = tfc.tile(mean, momentsTiling);\n variance = tfc.tile(variance, momentsTiling);\n scale = tfc.tile(scale, scaleOffsetTiling);\n offset = tfc.tile(offset, scaleOffsetTiling);\n\n return batchNormalization(\n input, mean, variance, offset, scale, this.epsilon);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n axis: this.axis,\n epsilon: this.epsilon,\n center: this.center,\n scale: this.scale,\n betaInitializer: serializeInitializer(this.betaInitializer),\n gammaInitializer: serializeInitializer(this.gammaInitializer),\n betaRegularizer: serializeRegularizer(this.betaRegularizer),\n gammaRegularizer: serializeRegularizer(this.gammaRegularizer)\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(LayerNormalization);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Padding Layers.\n */\n\n// Porting Note: In Python Keras, the padding layers are in convolutional.py,\n// but we decided to put them in a separate file (padding.ts) for clarity.\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {serialization, Tensor, tidy} from '@tensorflow/tfjs-core';\n\nimport {imageDataFormat} from '../backend/common';\nimport {InputSpec, Layer, LayerArgs} from '../engine/topology';\nimport {ValueError} from '../errors';\nimport {DataFormat, Shape} from '../keras_format/common';\nimport {Kwargs} from '../types';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\n\n/**\n * Pads the middle dimension of a 3D tensor.\n *\n * @param x Input `tf.Tensor` to be padded.\n * @param padding `Array` of 2 integers, how many zeros to add at the start and\n * end of the middle dimension (i.e., dimension 1).\n * @return A padded 3D `tf.Tensor`.\n */\nexport function temporalPadding(x: Tensor, padding?: [number, number]): Tensor {\n return tidy(() => {\n if (x.rank !== 3) {\n throw new ValueError(\n `temporalPadding expects input tensor to be 3-D, but received a ` +\n `${x.rank}-D tensor.`);\n }\n\n if (padding == null) {\n padding = [1, 1];\n }\n if (padding.length !== 2) {\n throw new ValueError(\n `temporalPadding expects input padding pattern to be a length-2 ` +\n `array, but received a length-${padding.length} array.`);\n }\n\n const pattern: Array<[number, number]> = [[0, 0], padding, [0, 0]];\n return tfc.pad(x, pattern);\n });\n}\n\n/**\n * Pads the 2nd and 3rd dimensions of a 4D tensor.\n *\n * @param x Input `tf.Tensor` to be padded.\n * @param padding `Array` of two `Array`s, each of which is an `Array` of two\n * integers. The amount of padding at the beginning and end of the 2nd and 3rd\n * dimensions, respectively.\n * @param dataFormat 'channelsLast' (default) or 'channelsFirst'.\n * @return Padded 4D `tf.Tensor`.\n */\nexport function spatial2dPadding(\n x: Tensor, padding?: [[number, number], [number, number]],\n dataFormat?: DataFormat): Tensor {\n return tidy(() => {\n if (x.rank !== 4) {\n throw new ValueError(\n `temporalPadding expects input tensor to be 4-D, but received a ` +\n `${x.rank}-D tensor.`);\n }\n\n if (padding == null) {\n padding = [[1, 1], [1, 1]];\n }\n if (padding.length !== 2 || padding[0].length !== 2 ||\n padding[1].length !== 2) {\n throw new ValueError(\n 'spatial2dPadding expects `padding` to be an Array of two Arrays, ' +\n 'each of which is an Array of two integers.');\n }\n\n if (dataFormat == null) {\n dataFormat = imageDataFormat();\n }\n if (dataFormat !== 'channelsLast' && dataFormat !== 'channelsFirst') {\n throw new ValueError(\n `Unknown data format: ${dataFormat}. ` +\n `Supported data formats are 'channelsLast' and 'channelsFirst.`);\n }\n\n let pattern: Array<[number, number]>;\n if (dataFormat === 'channelsFirst') {\n pattern = [[0, 0], [0, 0], padding[0], padding[1]];\n } else {\n pattern = [[0, 0], padding[0], padding[1], [0, 0]];\n }\n\n return tfc.pad(x, pattern);\n });\n}\n\nexport declare interface ZeroPadding2DLayerArgs extends LayerArgs {\n /**\n * Integer, or `Array` of 2 integers, or `Array` of 2 `Array`s, each of\n * which is an `Array` of 2 integers.\n * - If integer, the same symmetric padding is applied to width and height.\n * - If Array` of 2 integers, interpreted as two different symmetric values\n * for height and width:\n * `[symmetricHeightPad, symmetricWidthPad]`.\n * - If `Array` of 2 `Array`s, interpreted as:\n * `[[topPad, bottomPad], [leftPad, rightPad]]`.\n */\n padding?: number|[number, number]|[[number, number], [number, number]];\n\n /**\n * One of `'channelsLast'` (default) and `'channelsFirst'`.\n *\n * The ordering of the dimensions in the inputs.\n * `channelsLast` corresponds to inputs with shape\n * `[batch, height, width, channels]` while `channelsFirst`\n * corresponds to inputs with shape\n * `[batch, channels, height, width]`.\n */\n dataFormat?: DataFormat;\n}\n\nexport class ZeroPadding2D extends Layer {\n /** @nocollapse */\n static className = 'ZeroPadding2D';\n readonly dataFormat: DataFormat;\n readonly padding: [[number, number], [number, number]];\n\n constructor(args?: ZeroPadding2DLayerArgs) {\n if (args == null) {\n args = {};\n }\n super(args);\n\n this.dataFormat =\n args.dataFormat == null ? imageDataFormat() : args.dataFormat;\n // TODO(cais): Maybe refactor the following logic surrounding `padding`\n // into a helper method.\n if (args.padding == null) {\n this.padding = [[1, 1], [1, 1]];\n } else if (typeof args.padding === 'number') {\n this.padding =\n [[args.padding, args.padding], [args.padding, args.padding]];\n } else {\n args.padding = args.padding;\n if (args.padding.length !== 2) {\n throw new ValueError(\n `ZeroPadding2D expects padding to be a length-2 array, but ` +\n `received a length-${args.padding.length} array.`);\n }\n\n let heightPadding: [number, number];\n let widthPadding: [number, number];\n if (typeof args.padding[0] === 'number') {\n heightPadding = [args.padding[0], args.padding[0]];\n widthPadding = [args.padding[1] as number, args.padding[1] as number];\n } else {\n args.padding = args.padding as [[number, number], [number, number]];\n\n if (args.padding[0].length !== 2) {\n throw new ValueError(\n `ZeroPadding2D expects height padding to be a length-2 array, ` +\n `but received a length-${args.padding[0].length} array.`);\n }\n heightPadding = args.padding[0] as [number, number];\n\n if (args.padding[1].length !== 2) {\n throw new ValueError(\n `ZeroPadding2D expects width padding to be a length-2 array, ` +\n `but received a length-${args.padding[1].length} array.`);\n }\n widthPadding = args.padding[1] as [number, number];\n }\n this.padding = [heightPadding, widthPadding];\n }\n this.inputSpec = [new InputSpec({ndim: 4})];\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n\n let rows: number;\n let cols: number;\n if (this.dataFormat === 'channelsFirst') {\n if (inputShape[2] != null && inputShape[2] >= 0) {\n rows = inputShape[2] + this.padding[0][0] + this.padding[0][1];\n } else {\n rows = null;\n }\n if (inputShape[3] != null && inputShape[3] >= 0) {\n cols = inputShape[3] + this.padding[1][0] + this.padding[1][1];\n } else {\n cols = null;\n }\n return [inputShape[0], inputShape[1], rows, cols];\n } else {\n if (inputShape[1] != null && inputShape[1] >= 0) {\n rows = inputShape[1] + this.padding[0][0] + this.padding[0][1];\n } else {\n rows = null;\n }\n if (inputShape[2] != null && inputShape[2] >= 0) {\n cols = inputShape[2] + this.padding[1][0] + this.padding[1][1];\n } else {\n cols = null;\n }\n return [inputShape[0], rows, cols, inputShape[3]];\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(\n () => spatial2dPadding(\n getExactlyOneTensor(inputs), this.padding, this.dataFormat));\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n padding: this.padding,\n dataFormat: this.dataFormat,\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\nserialization.registerClass(ZeroPadding2D);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * TensorFlow.js Layers: Pooling Layers.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {serialization, Tensor, Tensor3D, Tensor4D, Tensor5D, tidy} from '@tensorflow/tfjs-core';\n\nimport {imageDataFormat} from '../backend/common';\nimport * as K from '../backend/tfjs_backend';\nimport {checkDataFormat, checkPaddingMode, checkPoolMode} from '../common';\nimport {InputSpec} from '../engine/topology';\nimport {Layer, LayerArgs} from '../engine/topology';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {DataFormat, PaddingMode, PoolMode, Shape} from '../keras_format/common';\nimport {Kwargs} from '../types';\nimport {convOutputLength} from '../utils/conv_utils';\nimport {assertPositiveInteger} from '../utils/generic_utils';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\n\nimport {preprocessConv2DInput, preprocessConv3DInput} from './convolutional';\n\n/**\n * 2D pooling.\n * @param x\n * @param poolSize\n * @param stridesdes strides. Defaults to [1, 1].\n * @param padding padding. Defaults to 'valid'.\n * @param dataFormat data format. Defaults to 'channelsLast'.\n * @param poolMode Mode of pooling. Defaults to 'max'.\n * @returns Result of the 2D pooling.\n */\nexport function pool2d(\n x: Tensor, poolSize: [number, number], strides?: [number, number],\n padding?: PaddingMode, dataFormat?: DataFormat,\n poolMode?: PoolMode): Tensor {\n return tidy(() => {\n checkDataFormat(dataFormat);\n checkPoolMode(poolMode);\n checkPaddingMode(padding);\n if (strides == null) {\n strides = [1, 1];\n }\n if (padding == null) {\n padding = 'valid';\n }\n if (dataFormat == null) {\n dataFormat = imageDataFormat();\n }\n if (poolMode == null) {\n poolMode = 'max';\n }\n\n // TODO(cais): Remove the preprocessing step once deeplearn.js supports\n // dataFormat as an input argument.\n x = preprocessConv2DInput(x, dataFormat); // x is NHWC after preprocessing.\n let y: Tensor;\n const paddingString = (padding === 'same') ? 'same' : 'valid';\n if (poolMode === 'max') {\n // TODO(cais): Rank check?\n y = tfc.maxPool(x as Tensor4D, poolSize, strides, paddingString);\n } else { // 'avg'\n // TODO(cais): Check the dtype and rank of x and give clear error message\n // if those are incorrect.\n y = tfc.avgPool(\n // TODO(cais): Rank check?\n x as Tensor3D | Tensor4D, poolSize, strides, paddingString);\n }\n if (dataFormat === 'channelsFirst') {\n y = tfc.transpose(y, [0, 3, 1, 2]); // NHWC -> NCHW.\n }\n return y;\n });\n}\n\n/**\n * 3D pooling.\n * @param x\n * @param poolSize. Default to [1, 1, 1].\n * @param strides strides. Defaults to [1, 1, 1].\n * @param padding padding. Defaults to 'valid'.\n * @param dataFormat data format. Defaults to 'channelsLast'.\n * @param poolMode Mode of pooling. Defaults to 'max'.\n * @returns Result of the 3D pooling.\n */\nexport function pool3d(\n x: Tensor5D, poolSize: [number, number, number],\n strides?: [number, number, number], padding?: PaddingMode,\n dataFormat?: DataFormat, poolMode?: PoolMode): Tensor {\n return tidy(() => {\n checkDataFormat(dataFormat);\n checkPoolMode(poolMode);\n checkPaddingMode(padding);\n if (strides == null) {\n strides = [1, 1, 1];\n }\n if (padding == null) {\n padding = 'valid';\n }\n if (dataFormat == null) {\n dataFormat = imageDataFormat();\n }\n if (poolMode == null) {\n poolMode = 'max';\n }\n\n // x is NDHWC after preprocessing.\n x = preprocessConv3DInput(x as Tensor, dataFormat) as Tensor5D;\n let y: Tensor;\n const paddingString = (padding === 'same') ? 'same' : 'valid';\n if (poolMode === 'max') {\n y = tfc.maxPool3d(x, poolSize, strides, paddingString);\n } else { // 'avg'\n y = tfc.avgPool3d(x, poolSize, strides, paddingString);\n }\n if (dataFormat === 'channelsFirst') {\n y = tfc.transpose(y, [0, 4, 1, 2, 3]); // NDHWC -> NCDHW.\n }\n return y;\n });\n}\n\nexport declare interface Pooling1DLayerArgs extends LayerArgs {\n /**\n * Size of the window to pool over, should be an integer.\n */\n poolSize?: number|[number];\n /**\n * Period at which to sample the pooled values.\n *\n * If `null`, defaults to `poolSize`.\n */\n strides?: number|[number];\n /** How to fill in data that's not an integer multiple of poolSize. */\n padding?: PaddingMode;\n}\n\n/**\n * Abstract class for different pooling 1D layers.\n */\nexport abstract class Pooling1D extends Layer {\n protected readonly poolSize: [number];\n protected readonly strides: [number];\n protected readonly padding: PaddingMode;\n\n /**\n *\n * @param args Parameters for the Pooling layer.\n *\n * config.poolSize defaults to 2.\n */\n constructor(args: Pooling1DLayerArgs) {\n if (args.poolSize == null) {\n args.poolSize = 2;\n }\n super(args);\n if (typeof args.poolSize === 'number') {\n this.poolSize = [args.poolSize];\n } else if (\n Array.isArray(args.poolSize) &&\n (args.poolSize as number[]).length === 1 &&\n typeof (args.poolSize as number[])[0] === 'number') {\n this.poolSize = args.poolSize;\n } else {\n throw new ValueError(\n `poolSize for 1D convolutional layer must be a number or an ` +\n `Array of a single number, but received ` +\n `${JSON.stringify(args.poolSize)}`);\n }\n assertPositiveInteger(this.poolSize, 'poolSize');\n if (args.strides == null) {\n this.strides = this.poolSize;\n } else {\n if (typeof args.strides === 'number') {\n this.strides = [args.strides];\n } else if (\n Array.isArray(args.strides) &&\n (args.strides as number[]).length === 1 &&\n typeof (args.strides as number[])[0] === 'number') {\n this.strides = args.strides;\n } else {\n throw new ValueError(\n `strides for 1D convolutional layer must be a number or an ` +\n `Array of a single number, but received ` +\n `${JSON.stringify(args.strides)}`);\n }\n }\n assertPositiveInteger(this.strides, 'strides');\n\n this.padding = args.padding == null ? 'valid' : args.padding;\n checkPaddingMode(this.padding);\n this.inputSpec = [new InputSpec({ndim: 3})];\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const length = convOutputLength(\n inputShape[1], this.poolSize[0], this.padding, this.strides[0]);\n return [inputShape[0], length, inputShape[2]];\n }\n\n protected abstract poolingFunction(\n inputs: Tensor, poolSize: [number, number], strides: [number, number],\n padding: PaddingMode, dataFormat: DataFormat): Tensor;\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n // Add dummy last dimension.\n inputs = K.expandDims(getExactlyOneTensor(inputs), 2);\n const output = this.poolingFunction(\n getExactlyOneTensor(inputs), [this.poolSize[0], 1],\n [this.strides[0], 1], this.padding, 'channelsLast');\n // Remove dummy last dimension.\n return tfc.squeeze(output, [2]);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n poolSize: this.poolSize,\n padding: this.padding,\n strides: this.strides,\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\n\nexport class MaxPooling1D extends Pooling1D {\n /** @nocollapse */\n static className = 'MaxPooling1D';\n constructor(args: Pooling1DLayerArgs) {\n super(args);\n }\n\n protected poolingFunction(\n inputs: Tensor, poolSize: [number, number], strides: [number, number],\n padding: PaddingMode, dataFormat: DataFormat): Tensor {\n checkDataFormat(dataFormat);\n checkPaddingMode(padding);\n return pool2d(inputs, poolSize, strides, padding, dataFormat, 'max');\n }\n}\nserialization.registerClass(MaxPooling1D);\n\nexport class AveragePooling1D extends Pooling1D {\n /** @nocollapse */\n static className = 'AveragePooling1D';\n constructor(args: Pooling1DLayerArgs) {\n super(args);\n }\n\n protected poolingFunction(\n inputs: Tensor, poolSize: [number, number], strides: [number, number],\n padding: PaddingMode, dataFormat: DataFormat): Tensor {\n checkDataFormat(dataFormat);\n checkPaddingMode(padding);\n return pool2d(inputs, poolSize, strides, padding, dataFormat, 'avg');\n }\n}\nserialization.registerClass(AveragePooling1D);\n\nexport declare interface Pooling2DLayerArgs extends LayerArgs {\n /**\n * Factors by which to downscale in each dimension [vertical, horizontal].\n * Expects an integer or an array of 2 integers.\n *\n * For example, `[2, 2]` will halve the input in both spatial dimension.\n * If only one integer is specified, the same window length\n * will be used for both dimensions.\n */\n poolSize?: number|[number, number];\n\n /**\n * The size of the stride in each dimension of the pooling window. Expects\n * an integer or an array of 2 integers. Integer, tuple of 2 integers, or\n * None.\n *\n * If `null`, defaults to `poolSize`.\n */\n strides?: number|[number, number];\n\n /** The padding type to use for the pooling layer. */\n padding?: PaddingMode;\n /** The data format to use for the pooling layer. */\n dataFormat?: DataFormat;\n}\n\n/**\n * Abstract class for different pooling 2D layers.\n */\nexport abstract class Pooling2D extends Layer {\n protected readonly poolSize: [number, number];\n protected readonly strides: [number, number];\n protected readonly padding: PaddingMode;\n protected readonly dataFormat: DataFormat;\n\n constructor(args: Pooling2DLayerArgs) {\n if (args.poolSize == null) {\n args.poolSize = [2, 2];\n }\n super(args);\n this.poolSize = Array.isArray(args.poolSize) ?\n args.poolSize :\n [args.poolSize, args.poolSize];\n if (args.strides == null) {\n this.strides = this.poolSize;\n } else if (Array.isArray(args.strides)) {\n if (args.strides.length !== 2) {\n throw new ValueError(\n `If the strides property of a 2D pooling layer is an Array, ` +\n `it is expected to have a length of 2, but received length ` +\n `${args.strides.length}.`);\n }\n this.strides = args.strides;\n } else {\n // `config.strides` is a number.\n this.strides = [args.strides, args.strides];\n }\n assertPositiveInteger(this.poolSize, 'poolSize');\n assertPositiveInteger(this.strides, 'strides');\n this.padding = args.padding == null ? 'valid' : args.padding;\n this.dataFormat =\n args.dataFormat == null ? 'channelsLast' : args.dataFormat;\n checkDataFormat(this.dataFormat);\n checkPaddingMode(this.padding);\n\n this.inputSpec = [new InputSpec({ndim: 4})];\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n let rows =\n this.dataFormat === 'channelsFirst' ? inputShape[2] : inputShape[1];\n let cols =\n this.dataFormat === 'channelsFirst' ? inputShape[3] : inputShape[2];\n rows =\n convOutputLength(rows, this.poolSize[0], this.padding, this.strides[0]);\n cols =\n convOutputLength(cols, this.poolSize[1], this.padding, this.strides[1]);\n if (this.dataFormat === 'channelsFirst') {\n return [inputShape[0], inputShape[1], rows, cols];\n } else {\n return [inputShape[0], rows, cols, inputShape[3]];\n }\n }\n\n protected abstract poolingFunction(\n inputs: Tensor, poolSize: [number, number], strides: [number, number],\n padding: PaddingMode, dataFormat: DataFormat): Tensor;\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n return this.poolingFunction(\n getExactlyOneTensor(inputs), this.poolSize, this.strides,\n this.padding, this.dataFormat);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n poolSize: this.poolSize,\n padding: this.padding,\n strides: this.strides,\n dataFormat: this.dataFormat\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\n\nexport class MaxPooling2D extends Pooling2D {\n /** @nocollapse */\n static className = 'MaxPooling2D';\n constructor(args: Pooling2DLayerArgs) {\n super(args);\n }\n\n protected poolingFunction(\n inputs: Tensor, poolSize: [number, number], strides: [number, number],\n padding: PaddingMode, dataFormat: DataFormat): Tensor {\n checkDataFormat(dataFormat);\n checkPaddingMode(padding);\n return pool2d(inputs, poolSize, strides, padding, dataFormat, 'max');\n }\n}\nserialization.registerClass(MaxPooling2D);\n\nexport class AveragePooling2D extends Pooling2D {\n /** @nocollapse */\n static className = 'AveragePooling2D';\n constructor(args: Pooling2DLayerArgs) {\n super(args);\n }\n\n protected poolingFunction(\n inputs: Tensor, poolSize: [number, number], strides: [number, number],\n padding: PaddingMode, dataFormat: DataFormat): Tensor {\n checkDataFormat(dataFormat);\n checkPaddingMode(padding);\n return pool2d(inputs, poolSize, strides, padding, dataFormat, 'avg');\n }\n}\nserialization.registerClass(AveragePooling2D);\n\nexport declare interface Pooling3DLayerArgs extends LayerArgs {\n /**\n * Factors by which to downscale in each dimension [depth, height, width].\n * Expects an integer or an array of 3 integers.\n *\n * For example, `[2, 2, 2]` will halve the input in three dimensions.\n * If only one integer is specified, the same window length\n * will be used for all dimensions.\n */\n poolSize?: number|[number, number, number];\n\n /**\n * The size of the stride in each dimension of the pooling window. Expects\n * an integer or an array of 3 integers. Integer, tuple of 3 integers, or\n * None.\n *\n * If `null`, defaults to `poolSize`.\n */\n strides?: number|[number, number, number];\n\n /** The padding type to use for the pooling layer. */\n padding?: PaddingMode;\n /** The data format to use for the pooling layer. */\n dataFormat?: DataFormat;\n}\n\n/**\n * Abstract class for different pooling 3D layers.\n */\nexport abstract class Pooling3D extends Layer {\n protected readonly poolSize: [number, number, number];\n protected readonly strides: [number, number, number];\n protected readonly padding: PaddingMode;\n protected readonly dataFormat: DataFormat;\n\n constructor(args: Pooling3DLayerArgs) {\n if (args.poolSize == null) {\n args.poolSize = [2, 2, 2];\n }\n super(args);\n this.poolSize = Array.isArray(args.poolSize) ?\n args.poolSize :\n [args.poolSize, args.poolSize, args.poolSize];\n if (args.strides == null) {\n this.strides = this.poolSize;\n } else if (Array.isArray(args.strides)) {\n if (args.strides.length !== 3) {\n throw new ValueError(\n `If the strides property of a 3D pooling layer is an Array, ` +\n `it is expected to have a length of 3, but received length ` +\n `${args.strides.length}.`);\n }\n this.strides = args.strides;\n } else {\n // `config.strides` is a number.\n this.strides = [args.strides, args.strides, args.strides];\n }\n assertPositiveInteger(this.poolSize, 'poolSize');\n assertPositiveInteger(this.strides, 'strides');\n this.padding = args.padding == null ? 'valid' : args.padding;\n this.dataFormat =\n args.dataFormat == null ? 'channelsLast' : args.dataFormat;\n checkDataFormat(this.dataFormat);\n checkPaddingMode(this.padding);\n\n this.inputSpec = [new InputSpec({ndim: 5})];\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n let depths =\n this.dataFormat === 'channelsFirst' ? inputShape[2] : inputShape[1];\n let rows =\n this.dataFormat === 'channelsFirst' ? inputShape[3] : inputShape[2];\n let cols =\n this.dataFormat === 'channelsFirst' ? inputShape[4] : inputShape[3];\n depths = convOutputLength(\n depths, this.poolSize[0], this.padding, this.strides[0]);\n rows =\n convOutputLength(rows, this.poolSize[1], this.padding, this.strides[1]);\n cols =\n convOutputLength(cols, this.poolSize[2], this.padding, this.strides[2]);\n if (this.dataFormat === 'channelsFirst') {\n return [inputShape[0], inputShape[1], depths, rows, cols];\n } else {\n return [inputShape[0], depths, rows, cols, inputShape[4]];\n }\n }\n\n protected abstract poolingFunction(\n inputs: Tensor, poolSize: [number, number, number],\n strides: [number, number, number], padding: PaddingMode,\n dataFormat: DataFormat): Tensor;\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n this.invokeCallHook(inputs, kwargs);\n return this.poolingFunction(\n getExactlyOneTensor(inputs), this.poolSize, this.strides,\n this.padding, this.dataFormat);\n });\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {\n poolSize: this.poolSize,\n padding: this.padding,\n strides: this.strides,\n dataFormat: this.dataFormat\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\n\nexport class MaxPooling3D extends Pooling3D {\n /** @nocollapse */\n static className = 'MaxPooling3D';\n constructor(args: Pooling3DLayerArgs) {\n super(args);\n }\n\n protected poolingFunction(\n inputs: Tensor, poolSize: [number, number, number],\n strides: [number, number, number], padding: PaddingMode,\n dataFormat: DataFormat): Tensor {\n checkDataFormat(dataFormat);\n checkPaddingMode(padding);\n return pool3d(\n inputs as Tensor5D, poolSize, strides, padding, dataFormat, 'max');\n }\n}\nserialization.registerClass(MaxPooling3D);\n\nexport class AveragePooling3D extends Pooling3D {\n /** @nocollapse */\n static className = 'AveragePooling3D';\n constructor(args: Pooling3DLayerArgs) {\n super(args);\n }\n\n protected poolingFunction(\n inputs: Tensor, poolSize: [number, number, number],\n strides: [number, number, number], padding: PaddingMode,\n dataFormat: DataFormat): Tensor {\n checkDataFormat(dataFormat);\n checkPaddingMode(padding);\n return pool3d(\n inputs as Tensor5D, poolSize, strides, padding, dataFormat, 'avg');\n }\n}\nserialization.registerClass(AveragePooling3D);\n\n/**\n * Abstract class for different global pooling 1D layers.\n */\nexport abstract class GlobalPooling1D extends Layer {\n constructor(args: LayerArgs) {\n super(args);\n this.inputSpec = [new InputSpec({ndim: 3})];\n }\n\n computeOutputShape(inputShape: Shape): Shape {\n return [inputShape[0], inputShape[2]];\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n throw new NotImplementedError();\n }\n}\n\nexport class GlobalAveragePooling1D extends GlobalPooling1D {\n /** @nocollapse */\n static className = 'GlobalAveragePooling1D';\n constructor(args?: LayerArgs) {\n super(args || {});\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n const input = getExactlyOneTensor(inputs);\n return tfc.mean(input, 1);\n });\n }\n}\nserialization.registerClass(GlobalAveragePooling1D);\n\nexport class GlobalMaxPooling1D extends GlobalPooling1D {\n /** @nocollapse */\n static className = 'GlobalMaxPooling1D';\n constructor(args: LayerArgs) {\n super(args || {});\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n const input = getExactlyOneTensor(inputs);\n return tfc.max(input, 1);\n });\n }\n}\nserialization.registerClass(GlobalMaxPooling1D);\n\nexport declare interface GlobalPooling2DLayerArgs extends LayerArgs {\n /**\n * One of `CHANNEL_LAST` (default) or `CHANNEL_FIRST`.\n *\n * The ordering of the dimensions in the inputs. `CHANNEL_LAST` corresponds\n * to inputs with shape `[batch, height, width, channels[` while\n * `CHANNEL_FIRST` corresponds to inputs with shape\n * `[batch, channels, height, width]`.\n */\n dataFormat?: DataFormat;\n}\n\n/**\n * Abstract class for different global pooling 2D layers.\n */\nexport abstract class GlobalPooling2D extends Layer {\n protected dataFormat: DataFormat;\n constructor(args: GlobalPooling2DLayerArgs) {\n super(args);\n this.dataFormat =\n args.dataFormat == null ? 'channelsLast' : args.dataFormat;\n checkDataFormat(this.dataFormat);\n this.inputSpec = [new InputSpec({ndim: 4})];\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = inputShape as Shape;\n if (this.dataFormat === 'channelsLast') {\n return [inputShape[0], inputShape[3]];\n } else {\n return [inputShape[0], inputShape[1]];\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n throw new NotImplementedError();\n }\n\n getConfig(): serialization.ConfigDict {\n const config = {dataFormat: this.dataFormat};\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n}\n\nexport class GlobalAveragePooling2D extends GlobalPooling2D {\n /** @nocollapse */\n static className = 'GlobalAveragePooling2D';\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n const input = getExactlyOneTensor(inputs);\n if (this.dataFormat === 'channelsLast') {\n return tfc.mean(input, [1, 2]);\n } else {\n return tfc.mean(input, [2, 3]);\n }\n });\n }\n}\nserialization.registerClass(GlobalAveragePooling2D);\n\nexport class GlobalMaxPooling2D extends GlobalPooling2D {\n /** @nocollapse */\n static className = 'GlobalMaxPooling2D';\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n const input = getExactlyOneTensor(inputs);\n if (this.dataFormat === 'channelsLast') {\n return tfc.max(input, [1, 2]);\n } else {\n return tfc.max(input, [2, 3]);\n }\n });\n }\n}\nserialization.registerClass(GlobalMaxPooling2D);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/**\n * Layers that augment the functionality of a base layer.\n */\n\nimport * as tfc from '@tensorflow/tfjs-core';\nimport {serialization, Tensor, tidy} from '@tensorflow/tfjs-core';\nimport * as K from '../backend/tfjs_backend';\nimport {nameScope} from '../common';\nimport {InputSpec, Layer, LayerArgs, SymbolicTensor} from '../engine/topology';\nimport {NotImplementedError, ValueError} from '../errors';\nimport {BidirectionalMergeMode, Shape, VALID_BIDIRECTIONAL_MERGE_MODES} from '../keras_format/common';\nimport {Kwargs} from '../types';\nimport {RegularizerFn, RnnStepFunction} from '../types';\nimport * as generic_utils from '../utils/generic_utils';\nimport {getExactlyOneShape, getExactlyOneTensor} from '../utils/types_utils';\nimport {LayerVariable} from '../variables';\n\nimport {rnn, RNN, standardizeArgs} from './recurrent';\nimport {deserialize} from './serialization';\n\nexport declare interface WrapperLayerArgs extends LayerArgs {\n /**\n * The layer to be wrapped.\n */\n layer: Layer;\n}\n\n/**\n * Abstract wrapper base class.\n *\n * Wrappers take another layer and augment it in various ways.\n * Do not use this class as a layer, it is only an abstract base class.\n * Two usable wrappers are the `TimeDistributed` and `Bidirectional` wrappers.\n */\nexport abstract class Wrapper extends Layer {\n readonly layer: Layer;\n\n constructor(args: WrapperLayerArgs) {\n // Porting Note: In PyKeras, `self.layer` is set prior to the calling\n // `super()`. But we can't do that here due to TypeScript's restriction.\n // See: https://github.com/Microsoft/TypeScript/issues/8277\n // As a result, we have to add checks in `get trainable()` and\n // `set trainable()` below in order to prevent using `this.layer` when\n // its value is `undefined`. The super constructor does use the getter\n // and the setter of `this.layer`.\n super(args);\n this.layer = args.layer;\n }\n\n build(inputShape: Shape|Shape[]): void {\n this.built = true;\n }\n\n // TODO(cais): Implement activityRegularizer getter.\n\n get trainable(): boolean {\n // Porting Note: the check of `this.layer` here is necessary due to the\n // way the `constructor` of this class is written (see Porting Note\n // above).\n if (this.layer != null) {\n return this.layer.trainable;\n } else {\n return false;\n }\n }\n\n set trainable(value: boolean) {\n // Porting Note: the check of `this.layer` here is necessary due to the\n // way the `constructor` of this class is written (see Porting Note\n // above).\n if (this.layer != null) {\n this.layer.trainable = value;\n }\n }\n\n get trainableWeights(): LayerVariable[] {\n return this.layer.trainableWeights;\n }\n // TODO(cais): Implement setter for trainableWeights.\n\n get nonTrainableWeights(): LayerVariable[] {\n return this.layer.nonTrainableWeights;\n }\n // TODO(cais): Implement setter for nonTrainableWeights.\n\n get updates(): Tensor[] {\n // tslint:disable-next-line:no-any\n return (this.layer as any)._updates;\n }\n\n // TODO(cais): Implement getUpdatesFor().\n\n get losses(): RegularizerFn[] {\n return this.layer.losses;\n }\n\n // TODO(cais): Implement getLossesFor().\n\n getWeights(): Tensor[] {\n return this.layer.getWeights();\n }\n\n setWeights(weights: Tensor[]): void {\n this.layer.setWeights(weights);\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'layer': {\n 'className': this.layer.getClassName(),\n 'config': this.layer.getConfig(),\n }\n };\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n setFastWeightInitDuringBuild(value: boolean) {\n super.setFastWeightInitDuringBuild(value);\n if (this.layer != null) {\n this.layer.setFastWeightInitDuringBuild(value);\n }\n }\n\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict,\n customObjects = {} as serialization.ConfigDict): T {\n const layerConfig = config['layer'] as serialization.ConfigDict;\n const layer = deserialize(layerConfig, customObjects) as Layer;\n delete config['layer'];\n const newConfig = {layer};\n Object.assign(newConfig, config);\n return new cls(newConfig);\n }\n}\n\nexport class TimeDistributed extends Wrapper {\n /** @nocollapse */\n static className = 'TimeDistributed';\n constructor(args: WrapperLayerArgs) {\n super(args);\n this.supportsMasking = true;\n }\n\n build(inputShape: Shape|Shape[]): void {\n inputShape = getExactlyOneShape(inputShape);\n if (inputShape.length < 3) {\n throw new ValueError(\n `TimeDistributed layer expects an input shape >= 3D, but received ` +\n `input shape ${JSON.stringify(inputShape)}`);\n }\n this.inputSpec = [{shape: inputShape}];\n const childInputShape = [inputShape[0]].concat(inputShape.slice(2));\n if (!this.layer.built) {\n this.layer.build(childInputShape);\n this.layer.built = true;\n }\n super.build(inputShape);\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n inputShape = getExactlyOneShape(inputShape);\n const childInputShape = [inputShape[0]].concat(inputShape.slice(2));\n const childOutputShape =\n this.layer.computeOutputShape(childInputShape) as Shape;\n const timesteps = inputShape[1];\n return [childOutputShape[0], timesteps].concat(childOutputShape.slice(1));\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n // TODO(cais): Add 'training' and 'useLearningPhase' to kwargs.\n inputs = getExactlyOneTensor(inputs);\n // Porting Note: In tfjs-layers, `inputs` are always concrete tensor\n // values. Hence the inputs can't have an undetermined first (batch)\n // dimension, which is why we always use the K.rnn approach here.\n const step: RnnStepFunction = (inputs: Tensor, states: Tensor[]) => {\n // TODO(cais): Add useLearningPhase.\n // NOTE(cais): `layer.call` may return a length-1 array of Tensor in\n // some cases (e.g., `layer` is a `Sequential` instance), which is\n // why `getExactlyOneTensor` is used below.\n const output = getExactlyOneTensor(this.layer.call(inputs, kwargs));\n return [output, []];\n };\n const rnnOutputs =\n rnn(step, inputs, [], false /* goBackwards */, null /* mask */,\n null /* constants */, false /* unroll */,\n true /* needPerStepOutputs */);\n const y = rnnOutputs[1];\n // TODO(cais): Add activity regularization.\n // TODO(cais): Add useLearningPhase.\n return y;\n });\n }\n\n // TODO(cais): Implement detailed computeMask() logic.\n}\nserialization.registerClass(TimeDistributed);\n\nexport function checkBidirectionalMergeMode(value?: string): void {\n generic_utils.checkStringTypeUnionValue(\n VALID_BIDIRECTIONAL_MERGE_MODES, 'BidirectionalMergeMode', value);\n}\n\nexport declare interface BidirectionalLayerArgs extends WrapperLayerArgs {\n /**\n * The instance of an `RNN` layer to be wrapped.\n */\n layer: RNN;\n\n /**\n * Mode by which outputs of the forward and backward RNNs are\n * combined. If `null` or `undefined`, the output will not be\n * combined, they will be returned as an `Array`.\n *\n * If `undefined` (i.e., not provided), defaults to `'concat'`.\n */\n mergeMode?: BidirectionalMergeMode;\n}\n\nconst DEFAULT_BIDIRECTIONAL_MERGE_MODE: BidirectionalMergeMode = 'concat';\n\nexport class Bidirectional extends Wrapper {\n /** @nocollapse */\n static className = 'Bidirectional';\n mergeMode: BidirectionalMergeMode;\n private forwardLayer: RNN;\n private backwardLayer: RNN;\n private returnSequences: boolean;\n private returnState: boolean;\n private numConstants?: number;\n private _trainable: boolean;\n\n constructor(args: BidirectionalLayerArgs) {\n super(args);\n\n // Note: When creating `this.forwardLayer`, the original Layer object\n // (`config.layer`) ought to be cloned. This is why we call\n // `getConfig()` followed by `deserialize()`. Without this cloning,\n // the layer names saved during serialization will incorrectly contain\n // the 'forward_' prefix. In Python Keras, this is done using\n // `copy.copy` (shallow copy), which does not have a simple equivalent\n // in JavaScript. JavaScript's `Object.assign()` does not copy\n // methods.\n const layerConfig = args.layer.getConfig();\n const forwDict: serialization.ConfigDict = {};\n forwDict['className'] = args.layer.getClassName();\n forwDict['config'] = layerConfig;\n this.forwardLayer = deserialize(forwDict) as RNN;\n layerConfig['goBackwards'] =\n layerConfig['goBackwards'] === true ? false : true;\n const backDict: serialization.ConfigDict = {};\n backDict['className'] = args.layer.getClassName();\n backDict['config'] = layerConfig;\n this.backwardLayer = deserialize(backDict) as RNN;\n this.forwardLayer.name = 'forward_' + this.forwardLayer.name;\n this.backwardLayer.name = 'backward_' + this.backwardLayer.name;\n\n this.mergeMode = args.mergeMode === undefined ?\n DEFAULT_BIDIRECTIONAL_MERGE_MODE :\n args.mergeMode;\n checkBidirectionalMergeMode(this.mergeMode);\n if (args.weights) {\n throw new NotImplementedError(\n 'weights support is not implemented for Bidirectional layer yet.');\n }\n this._stateful = args.layer.stateful;\n this.returnSequences = args.layer.returnSequences;\n this.returnState = args.layer.returnState;\n this.supportsMasking = true;\n this._trainable = true;\n this.inputSpec = args.layer.inputSpec;\n this.numConstants = null;\n }\n\n get trainable(): boolean {\n return this._trainable;\n }\n\n set trainable(value: boolean) {\n // Porting Note: the check of `this.layer` here is necessary due to the\n // way the `constructor` of this class is written (see Porting Note\n // above).\n this._trainable = value;\n if (this.forwardLayer != null) {\n this.forwardLayer.trainable = value;\n }\n if (this.backwardLayer != null) {\n this.backwardLayer.trainable = value;\n }\n }\n\n getWeights(): Tensor[] {\n return this.forwardLayer.getWeights().concat(\n this.backwardLayer.getWeights());\n }\n\n setWeights(weights: Tensor[]): void {\n const numWeights = weights.length;\n const numeightsOver2 = Math.floor(numWeights / 2);\n this.forwardLayer.setWeights(weights.slice(0, numeightsOver2));\n this.backwardLayer.setWeights(weights.slice(numeightsOver2));\n }\n\n computeOutputShape(inputShape: Shape|Shape[]): Shape|Shape[] {\n let layerShapes: Shape|Shape[] =\n this.forwardLayer.computeOutputShape(inputShape);\n if (!(Array.isArray(layerShapes) && Array.isArray(layerShapes[0]))) {\n layerShapes = [layerShapes as Shape];\n }\n layerShapes = layerShapes as Shape[];\n\n let outputShape: Shape;\n let outputShapes: Shape[];\n let stateShape: Shape[];\n if (this.returnState) {\n stateShape = layerShapes.slice(1);\n outputShape = layerShapes[0];\n } else {\n outputShape = layerShapes[0];\n }\n outputShape = outputShape;\n if (this.mergeMode === 'concat') {\n outputShape[outputShape.length - 1] *= 2;\n outputShapes = [outputShape];\n } else if (this.mergeMode == null) {\n outputShapes = [outputShape, outputShape.slice()];\n } else {\n outputShapes = [outputShape];\n }\n\n if (this.returnState) {\n if (this.mergeMode == null) {\n return outputShapes.concat(stateShape).concat(stateShape.slice());\n }\n return [outputShape].concat(stateShape).concat(stateShape.slice());\n }\n return generic_utils.singletonOrArray(outputShapes);\n }\n\n apply(\n inputs: Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[],\n kwargs?: Kwargs): Tensor|Tensor[]|SymbolicTensor|SymbolicTensor[] {\n let initialState: Tensor[]|SymbolicTensor[] =\n kwargs == null ? null : kwargs['initialState'];\n let constants: Tensor[]|SymbolicTensor[] =\n kwargs == null ? null : kwargs['constants'];\n if (kwargs == null) {\n kwargs = {};\n }\n const standardized =\n standardizeArgs(inputs, initialState, constants, this.numConstants);\n inputs = standardized.inputs;\n initialState = standardized.initialState;\n constants = standardized.constants;\n\n if (Array.isArray(inputs)) {\n initialState = (inputs as Tensor[] | SymbolicTensor[]).slice(1);\n inputs = (inputs as Tensor[] | SymbolicTensor[])[0];\n }\n\n if ((initialState == null || initialState.length === 0) &&\n constants == null) {\n return super.apply(inputs, kwargs);\n }\n const additionalInputs: Array<Tensor|SymbolicTensor> = [];\n const additionalSpecs: InputSpec[] = [];\n if (initialState != null) {\n const numStates = initialState.length;\n if (numStates % 2 > 0) {\n throw new ValueError(\n 'When passing `initialState` to a Bidrectional RNN, ' +\n 'the state should be an Array containing the states of ' +\n 'the underlying RNNs.');\n }\n kwargs['initialState'] = initialState;\n additionalInputs.push(...initialState);\n const stateSpecs = (initialState as Array<Tensor|SymbolicTensor>)\n .map(state => new InputSpec({shape: state.shape}));\n this.forwardLayer.stateSpec = stateSpecs.slice(0, numStates / 2);\n this.backwardLayer.stateSpec = stateSpecs.slice(numStates / 2);\n additionalSpecs.push(...stateSpecs);\n }\n if (constants != null) {\n throw new NotImplementedError(\n 'Support for constants in Bidirectional layers is not ' +\n 'implemented yet.');\n }\n\n const isSymbolicTensor = additionalInputs[0] instanceof SymbolicTensor;\n for (const tensor of additionalInputs) {\n if (tensor instanceof SymbolicTensor !== isSymbolicTensor) {\n throw new ValueError(\n 'The initial state of a Bidirectional layer cannot be ' +\n 'specified as a mix of symbolic and non-symbolic tensors');\n }\n }\n\n if (isSymbolicTensor) {\n // Compute the full input and specs, including the states.\n const fullInput = [inputs].concat(additionalInputs);\n const fullInputSpec = this.inputSpec.concat(additionalSpecs);\n // Perform the call temporarily and replace inputSpec.\n // Note: with initial states symbolic calls and non-symbolic calls to\n // this method differ in how the initial states are passed. For\n // symbolic calls, the initial states are passed in the first arg, as\n // an Array of SymbolicTensors; for non-symbolic calls, they are\n // passed in the second arg as a part of the kwargs. Hence the need to\n // temporarily modify inputSpec here.\n // TODO(cais): Make refactoring so that this hacky code below is no\n // longer needed.\n const originalInputSpec = this.inputSpec;\n this.inputSpec = fullInputSpec;\n const output =\n super.apply(fullInput as Tensor[] | SymbolicTensor[], kwargs);\n this.inputSpec = originalInputSpec;\n return output;\n } else {\n return super.apply(inputs, kwargs);\n }\n }\n\n call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] {\n return tidy(() => {\n const initialState = kwargs['initialState'];\n\n let y: Tensor|Tensor[];\n let yRev: Tensor|Tensor[];\n if (initialState == null) {\n y = this.forwardLayer.call(inputs, kwargs);\n yRev = this.backwardLayer.call(inputs, kwargs);\n } else {\n const forwardState = initialState.slice(0, initialState.length / 2);\n const backwardState = initialState.slice(initialState.length / 2);\n y = this.forwardLayer.call(\n inputs, Object.assign(kwargs, {initialState: forwardState}));\n yRev = this.backwardLayer.call(\n inputs, Object.assign(kwargs, {initialState: backwardState}));\n }\n\n let states: Tensor[];\n if (this.returnState) {\n if (Array.isArray(y)) {\n states = y.slice(1).concat((yRev as Tensor[]).slice(1));\n } else {\n }\n y = (y as Tensor[])[0];\n yRev = (yRev as Tensor[])[0];\n }\n\n if (this.returnSequences) {\n yRev = tfc.reverse(yRev as Tensor, 1);\n }\n\n let output: Tensor|Tensor[];\n if (this.mergeMode === 'concat') {\n output = K.concatenate([y as Tensor, yRev as Tensor]);\n } else if (this.mergeMode === 'sum') {\n output = tfc.add(y as Tensor, yRev as Tensor);\n } else if (this.mergeMode === 'ave') {\n output = tfc.mul(.5, tfc.add(y as Tensor, yRev as Tensor));\n } else if (this.mergeMode === 'mul') {\n output = tfc.mul(y as Tensor, yRev as Tensor);\n } else if (this.mergeMode == null) {\n output = [y as Tensor, yRev as Tensor];\n }\n\n // TODO(cais): Properly set learning phase.\n if (this.returnState) {\n if (this.mergeMode == null) {\n return (output as Tensor[]).concat(states);\n }\n return [output as Tensor].concat(states);\n }\n return output;\n });\n }\n\n resetStates(states?: Tensor|Tensor[]): void {\n this.forwardLayer.resetStates();\n this.backwardLayer.resetStates();\n }\n\n build(inputShape: Shape|Shape[]): void {\n nameScope(this.forwardLayer.name, () => {\n this.forwardLayer.build(inputShape);\n });\n nameScope(this.backwardLayer.name, () => {\n this.backwardLayer.build(inputShape);\n });\n this.built = true;\n }\n\n computeMask(inputs: Tensor|Tensor[], mask?: Tensor|Tensor[]): Tensor\n |Tensor[] {\n if (Array.isArray(mask)) {\n mask = mask[0];\n }\n let outputMask: Tensor|Tensor[];\n if (this.returnSequences) {\n if (this.mergeMode == null) {\n outputMask = [mask, mask];\n } else {\n outputMask = mask;\n }\n } else {\n if (this.mergeMode == null) {\n outputMask = [null, null];\n } else {\n outputMask = null;\n }\n }\n if (this.returnState) {\n const states = this.forwardLayer.states;\n const stateMask: Tensor[] = states.map(state => null);\n if (Array.isArray(outputMask)) {\n return outputMask.concat(stateMask).concat(stateMask);\n } else {\n return [outputMask].concat(stateMask).concat(stateMask);\n }\n } else {\n return outputMask;\n }\n }\n\n get trainableWeights(): LayerVariable[] {\n return this.forwardLayer.trainableWeights.concat(\n this.backwardLayer.trainableWeights);\n }\n\n get nonTrainableWeights(): LayerVariable[] {\n return this.forwardLayer.nonTrainableWeights.concat(\n this.backwardLayer.nonTrainableWeights);\n }\n\n // TODO(cais): Implement constraints().\n\n setFastWeightInitDuringBuild(value: boolean) {\n super.setFastWeightInitDuringBuild(value);\n if (this.forwardLayer != null) {\n this.forwardLayer.setFastWeightInitDuringBuild(value);\n }\n if (this.backwardLayer != null) {\n this.backwardLayer.setFastWeightInitDuringBuild(value);\n }\n }\n\n getConfig(): serialization.ConfigDict {\n const config: serialization.ConfigDict = {\n 'mergeMode': this.mergeMode,\n };\n // TODO(cais): Add logic for `numConstants` once the property is added.\n const baseConfig = super.getConfig();\n Object.assign(config, baseConfig);\n return config;\n }\n\n /** @nocollapse */\n static fromConfig<T extends serialization.Serializable>(\n cls: serialization.SerializableConstructor<T>,\n config: serialization.ConfigDict): T {\n const rnnLayer =\n deserialize(config['layer'] as serialization.ConfigDict) as RNN;\n delete config['layer'];\n // TODO(cais): Add logic for `numConstants` once the property is added.\n if (config['numConstants'] != null) {\n throw new NotImplementedError(\n `Deserialization of a Bidirectional layer with numConstants ` +\n `present is not supported yet.`);\n }\n // tslint:disable-next-line:no-any\n const newConfig: {[key: string]: any} = config;\n newConfig['layer'] = rnnLayer;\n return new cls(newConfig);\n }\n}\nserialization.registerClass(Bidirectional);\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\nimport {Tensor} from '@tensorflow/tfjs-core';\n\nimport * as losses from './losses';\nimport * as metrics from './metrics';\n\n/**\n * Binary accuracy metric function.\n *\n * `yTrue` and `yPred` can have 0-1 values. Example:\n * ```js\n * const x = tf.tensor2d([[1, 1, 1, 1], [0, 0, 0, 0]], [2, 4]);\n * const y = tf.tensor2d([[1, 0, 1, 0], [0, 0, 0, 1]], [2, 4]);\n * const accuracy = tf.metrics.binaryAccuracy(x, y);\n * accuracy.print();\n * ```\n *\n * `yTrue` and `yPred` can also have floating-number values between 0 and 1, in\n * which case the values will be thresholded at 0.5 to yield 0-1 values (i.e.,\n * a value >= 0.5 and <= 1.0 is interpreted as 1.\n * )\n * Example:\n * ```js\n * const x = tf.tensor1d([1, 1, 1, 1, 0, 0, 0, 0]);\n * const y = tf.tensor1d([0.2, 0.4, 0.6, 0.8, 0.2, 0.3, 0.4, 0.7]);\n * const accuracy = tf.metrics.binaryAccuracy(x, y);\n * accuracy.print();\n * ```\n *\n * @param yTrue Binary Tensor of truth.\n * @param yPred Binary Tensor of prediction.\n * @return Accuracy Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function binaryAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.binaryAccuracy(yTrue, yPred);\n}\n\n/**\n * Binary crossentropy metric function.\n *\n * Example:\n * ```js\n * const x = tf.tensor2d([[0], [1], [1], [1]]);\n * const y = tf.tensor2d([[0], [0], [0.5], [1]]);\n * const crossentropy = tf.metrics.binaryCrossentropy(x, y);\n * crossentropy.print();\n * ```\n *\n * @param yTrue Binary Tensor of truth.\n * @param yPred Binary Tensor of prediction, probabilities for the `1` case.\n * @return Accuracy Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function binaryCrossentropy(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.binaryCrossentropy(yTrue, yPred);\n}\n\n/**\n * Sparse categorical accuracy metric function.\n *\n * Example:\n * ```js\n *\n * const yTrue = tf.tensor1d([1, 1, 2, 2, 0]);\n * const yPred = tf.tensor2d(\n * [[0, 1, 0], [1, 0, 0], [0, 0.4, 0.6], [0, 0.6, 0.4], [0.7, 0.3, 0]]);\n * const crossentropy = tf.metrics.sparseCategoricalAccuracy(yTrue, yPred);\n * crossentropy.print();\n * ```\n *\n * @param yTrue True labels: indices.\n * @param yPred Predicted probabilities or logits.\n * @returns Accuracy tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function sparseCategoricalAccuracy(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.sparseCategoricalAccuracy(yTrue, yPred);\n}\n\n/**\n * Categorical accuracy metric function.\n *\n * Example:\n * ```js\n * const x = tf.tensor2d([[0, 0, 0, 1], [0, 0, 0, 1]]);\n * const y = tf.tensor2d([[0.1, 0.8, 0.05, 0.05], [0.1, 0.05, 0.05, 0.8]]);\n * const accuracy = tf.metrics.categoricalAccuracy(x, y);\n * accuracy.print();\n * ```\n *\n * @param yTrue Binary Tensor of truth: one-hot encoding of categories.\n * @param yPred Binary Tensor of prediction: probabilities or logits for the\n * same categories as in `yTrue`.\n * @return Accuracy Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function categoricalAccuracy(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.categoricalAccuracy(yTrue, yPred);\n}\n\n/**\n * Categorical crossentropy between an output tensor and a target tensor.\n *\n * @param target A tensor of the same shape as `output`.\n * @param output A tensor resulting from a softmax (unless `fromLogits` is\n * `true`, in which case `output` is expected to be the logits).\n * @param fromLogits Boolean, whether `output` is the result of a softmax, or is\n * a tensor of logits.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function categoricalCrossentropy(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.categoricalCrossentropy(yTrue, yPred);\n}\n\n/**\n * Computes the precision of the predictions with respect to the labels.\n *\n * Example:\n * ```js\n * const x = tf.tensor2d(\n * [\n * [0, 0, 0, 1],\n * [0, 1, 0, 0],\n * [0, 0, 0, 1],\n * [1, 0, 0, 0],\n * [0, 0, 1, 0]\n * ]\n * );\n *\n * const y = tf.tensor2d(\n * [\n * [0, 0, 1, 0],\n * [0, 1, 0, 0],\n * [0, 0, 0, 1],\n * [0, 1, 0, 0],\n * [0, 1, 0, 0]\n * ]\n * );\n *\n * const precision = tf.metrics.precision(x, y);\n * precision.print();\n * ```\n *\n * @param yTrue The ground truth values. Expected to be contain only 0-1 values.\n * @param yPred The predicted values. Expected to be contain only 0-1 values.\n * @return Precision Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function precision(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.precision(yTrue, yPred);\n}\n\n/**\n * Computes the recall of the predictions with respect to the labels.\n *\n * Example:\n * ```js\n * const x = tf.tensor2d(\n * [\n * [0, 0, 0, 1],\n * [0, 1, 0, 0],\n * [0, 0, 0, 1],\n * [1, 0, 0, 0],\n * [0, 0, 1, 0]\n * ]\n * );\n *\n * const y = tf.tensor2d(\n * [\n * [0, 0, 1, 0],\n * [0, 1, 0, 0],\n * [0, 0, 0, 1],\n * [0, 1, 0, 0],\n * [0, 1, 0, 0]\n * ]\n * );\n *\n * const recall = tf.metrics.recall(x, y);\n * recall.print();\n * ```\n *\n * @param yTrue The ground truth values. Expected to be contain only 0-1 values.\n * @param yPred The predicted values. Expected to be contain only 0-1 values.\n * @return Recall Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function recall(yTrue: Tensor, yPred: Tensor): Tensor {\n return metrics.recall(yTrue, yPred);\n}\n\n/**\n * Loss or metric function: Cosine proximity.\n *\n * Mathematically, cosine proximity is defined as:\n * `-sum(l2Normalize(yTrue) * l2Normalize(yPred))`,\n * wherein `l2Normalize()` normalizes the L2 norm of the input to 1 and `*`\n * represents element-wise multiplication.\n *\n * ```js\n * const yTrue = tf.tensor2d([[1, 0], [1, 0]]);\n * const yPred = tf.tensor2d([[1 / Math.sqrt(2), 1 / Math.sqrt(2)], [0, 1]]);\n * const proximity = tf.metrics.cosineProximity(yTrue, yPred);\n * proximity.print();\n * ```\n *\n * @param yTrue Truth Tensor.\n * @param yPred Prediction Tensor.\n * @return Cosine proximity Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function cosineProximity(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.cosineProximity(yTrue, yPred);\n}\n\n/**\n * Loss or metric function: Mean absolute error.\n *\n * Mathematically, mean absolute error is defined as:\n * `mean(abs(yPred - yTrue))`,\n * wherein the `mean` is applied over feature dimensions.\n *\n * ```js\n * const yTrue = tf.tensor2d([[0, 1], [0, 0], [2, 3]]);\n * const yPred = tf.tensor2d([[0, 1], [0, 1], [-2, -3]]);\n * const mse = tf.metrics.meanAbsoluteError(yTrue, yPred);\n * mse.print();\n * ```\n *\n * @param yTrue Truth Tensor.\n * @param yPred Prediction Tensor.\n * @return Mean absolute error Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function meanAbsoluteError(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanAbsoluteError(yTrue, yPred);\n}\n\n/**\n * Loss or metric function: Mean absolute percentage error.\n *\n * ```js\n * const yTrue = tf.tensor2d([[0, 1], [10, 20]]);\n * const yPred = tf.tensor2d([[0, 1], [11, 24]]);\n * const mse = tf.metrics.meanAbsolutePercentageError(yTrue, yPred);\n * mse.print();\n * ```\n *\n * Aliases: `tf.metrics.MAPE`, `tf.metrics.mape`.\n *\n * @param yTrue Truth Tensor.\n * @param yPred Prediction Tensor.\n * @return Mean absolute percentage error Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function meanAbsolutePercentageError(\n yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanAbsolutePercentageError(yTrue, yPred);\n}\n\nexport function MAPE(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanAbsolutePercentageError(yTrue, yPred);\n}\n\nexport function mape(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanAbsolutePercentageError(yTrue, yPred);\n}\n\n/**\n * Loss or metric function: Mean squared error.\n *\n * ```js\n * const yTrue = tf.tensor2d([[0, 1], [3, 4]]);\n * const yPred = tf.tensor2d([[0, 1], [-3, -4]]);\n * const mse = tf.metrics.meanSquaredError(yTrue, yPred);\n * mse.print();\n * ```\n *\n * Aliases: `tf.metrics.MSE`, `tf.metrics.mse`.\n *\n * @param yTrue Truth Tensor.\n * @param yPred Prediction Tensor.\n * @return Mean squared error Tensor.\n *\n * @doc {heading: 'Metrics', namespace: 'metrics'}\n */\nexport function meanSquaredError(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanSquaredError(yTrue, yPred);\n}\n\nexport function MSE(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanSquaredError(yTrue, yPred);\n}\n\nexport function mse(yTrue: Tensor, yPred: Tensor): Tensor {\n return losses.meanSquaredError(yTrue, yPred);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nexport {modelFromJSON} from './models';\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\nimport * as regularizers from './regularizers';\n// tslint:disable-next-line:max-line-length\nimport {L1Args, L1L2, L1L2Args, L2Args, Regularizer} from './regularizers';\n\n/**\n * Regularizer for L1 and L2 regularization.\n *\n * Adds a term to the loss to penalize large weights:\n * loss += sum(l1 * abs(x)) + sum(l2 * x^2)\n *\n * @doc {heading: 'Regularizers', namespace: 'regularizers'}\n */\nexport function l1l2(config?: L1L2Args): Regularizer {\n return new L1L2(config);\n}\n\n/**\n * Regularizer for L1 regularization.\n *\n * Adds a term to the loss to penalize large weights:\n * loss += sum(l1 * abs(x))\n * @param args l1 config.\n *\n * @doc {heading: 'Regularizers', namespace: 'regularizers'}\n */\nexport function l1(config?: L1Args): Regularizer {\n return regularizers.l1(config);\n}\n\n/**\n * Regularizer for L2 regularization.\n *\n * Adds a term to the loss to penalize large weights:\n * loss += sum(l2 * x^2)\n * @param args l2 config.\n *\n * @doc {heading: 'Regularizers', namespace: 'regularizers'}\n */\nexport function l2(config?: L2Args): Regularizer {\n return regularizers.l2(config);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\n/* Original source: keras/callbacks.py */\n\nimport {BaseCallback} from './base_callbacks';\nimport {Container} from './engine/container';\nimport {LayersModel} from './engine/training';\nimport {NotImplementedError} from './errors';\nimport {Logs, resolveScalarsInLogs} from './logs';\n\nexport abstract class Callback extends BaseCallback {\n /** Instance of `keras.models.Model`. Reference of the model being trained. */\n model: LayersModel = null;\n\n setModel(model: Container): void {\n if (!(model instanceof LayersModel)) {\n throw new Error('model must be a LayersModel, not some other Container');\n }\n this.model = model;\n }\n}\n\nexport interface EarlyStoppingCallbackArgs {\n /**\n * Quantity to be monitored.\n *\n * Defaults to 'val_loss'.\n */\n monitor?: string;\n\n /**\n * Minimum change in the monitored quantity to qualify as improvement,\n * i.e., an absolute change of less than `minDelta` will count as no\n * improvement.\n *\n * Defaults to 0.\n */\n minDelta?: number;\n\n /**\n * Number of epochs with no improvement after which training will be stopped.\n *\n * Defaults to 0.\n */\n patience?: number;\n\n /** Verbosity mode. */\n verbose?: number;\n\n /**\n * Mode: one of 'min', 'max', and 'auto'.\n * - In 'min' mode, training will be stopped when the quantity monitored has\n * stopped decreasing.\n * - In 'max' mode, training will be stopped when the quantity monitored has\n * stopped increasing.\n * - In 'auto' mode, the direction is inferred automatically from the name of\n * the monitored quantity.\n *\n * Defaults to 'auto'.\n */\n mode?: 'auto'|'min'|'max';\n\n /**\n * Baseline value of the monitored quantity.\n *\n * If specified, training will be stopped if the model doesn't show\n * improvement over the baseline.\n */\n baseline?: number;\n\n /**\n * Whether to restore model weights from the epoch with the best value\n * of the monitored quantity. If `False`, the model weights obtained at the\n * at the last step of training are used.\n *\n * **`True` is not supported yet.**\n */\n restoreBestWeights?: boolean;\n}\n\nfunction less(currVal: number, prevVal: number) {\n return currVal < prevVal;\n}\n\nfunction greater(currVal: number, prevVal: number) {\n return currVal > prevVal;\n}\n\n/**\n * A Callback that stops training when a monitored quantity has stopped\n * improving.\n */\nexport class EarlyStopping extends Callback {\n protected readonly monitor: string;\n protected readonly minDelta: number;\n protected readonly patience: number;\n protected readonly baseline: number;\n protected readonly verbose: number;\n protected readonly mode: 'auto'|'min'|'max';\n\n protected monitorFunc: (currVal: number, prevVal: number) => boolean;\n\n private wait: number;\n private stoppedEpoch: number;\n private best: number;\n\n constructor(args?: EarlyStoppingCallbackArgs) {\n super();\n if (args == null) {\n args = {};\n }\n if (args.restoreBestWeights) {\n throw new NotImplementedError(\n 'restoreBestWeights = True is not implemented in EarlyStopping yet.');\n }\n\n this.monitor = args.monitor || 'val_loss';\n this.minDelta = Math.abs(args.minDelta || 0);\n this.patience = args.patience || 0;\n this.verbose = args.verbose || 0;\n this.mode = args.mode || 'auto';\n this.baseline = args.baseline;\n\n if (['auto', 'min', 'max'].indexOf(this.mode) === -1) {\n console.warn(\n `EarlyStopping mode '${this.mode}' is invalid. ` +\n `Falling back to mode 'auto'.`);\n this.mode = 'auto';\n }\n\n if (this.mode === 'min') {\n this.monitorFunc = less;\n } else if (this.mode === 'max') {\n this.monitorFunc = greater;\n } else {\n // For mode === 'auto'.\n if (this.monitor.indexOf('acc') !== -1) {\n this.monitorFunc = greater;\n } else {\n this.monitorFunc = less;\n }\n }\n\n if (this.monitorFunc === less) {\n this.minDelta *= -1;\n }\n }\n\n async onTrainBegin(logs?: Logs) {\n this.wait = 0;\n this.stoppedEpoch = 0;\n if (this.baseline != null) {\n this.best = this.baseline;\n } else {\n this.best = this.monitorFunc === less ? Infinity : -Infinity;\n }\n }\n\n async onEpochEnd(epoch: number, logs?: Logs) {\n await resolveScalarsInLogs(logs);\n const current = this.getMonitorValue(logs);\n if (current == null) {\n return;\n }\n\n if (this.monitorFunc(current - this.minDelta, this.best)) {\n this.best = current;\n this.wait = 0;\n // TODO(cais): Logic for restoreBestWeights.\n } else {\n this.wait++;\n if (this.wait >= this.patience) {\n this.stoppedEpoch = epoch;\n this.model.stopTraining = true;\n }\n // TODO(cais): Logic for restoreBestWeights.\n }\n }\n\n async onTrainEnd(logs?: Logs) {\n if (this.stoppedEpoch > 0 && this.verbose) {\n console.log(`Epoch ${this.stoppedEpoch}: early stopping.`);\n }\n }\n\n private getMonitorValue(logs: Logs) {\n if (logs == null) {\n logs = {};\n }\n const monitorValue = logs[this.monitor];\n if (monitorValue == null) {\n console.warn(\n `Metric for EarlyStopping ${this.monitor} is not available. ` +\n `Available metrics are: ${Object.keys(logs)}`);\n }\n return monitorValue;\n }\n}\n\n/**\n * Factory function for a Callback that stops training when a monitored\n * quantity has stopped improving.\n *\n * Early stopping is a type of regularization, and protects model against\n * overfitting.\n *\n * The following example based on fake data illustrates how this callback\n * can be used during `tf.LayersModel.fit()`:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.dense({\n * units: 3,\n * activation: 'softmax',\n * kernelInitializer: 'ones',\n * inputShape: [2]\n * }));\n * const xs = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n * const ys = tf.tensor2d([[1, 0, 0], [0, 1, 0]], [2, 3]);\n * const xsVal = tf.tensor2d([4, 3, 2, 1], [2, 2]);\n * const ysVal = tf.tensor2d([[0, 0, 1], [0, 1, 0]], [2, 3]);\n * model.compile(\n * {loss: 'categoricalCrossentropy', optimizer: 'sgd', metrics: ['acc']});\n *\n * // Without the EarlyStopping callback, the val_acc value would be:\n * // 0.5, 0.5, 0.5, 0.5, ...\n * // With val_acc being monitored, training should stop after the 2nd epoch.\n * const history = await model.fit(xs, ys, {\n * epochs: 10,\n * validationData: [xsVal, ysVal],\n * callbacks: tf.callbacks.earlyStopping({monitor: 'val_acc'})\n * });\n *\n * // Expect to see a length-2 array.\n * console.log(history.history.val_acc);\n * ```\n *\n * @doc {\n * heading: 'Callbacks',\n * namespace: 'callbacks'\n * }\n */\nexport function earlyStopping(args?: EarlyStoppingCallbackArgs) {\n return new EarlyStopping(args);\n}\n\nexport const callbacks = {earlyStopping};\n", "/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Use of this source code is governed by an MIT-style\n * license that can be found in the LICENSE file or at\n * https://opensource.org/licenses/MIT.\n * =============================================================================\n */\n\nimport '@tensorflow/tfjs-core';\n// tslint:disable-next-line: no-imports-from-dist\nimport '@tensorflow/tfjs-core/dist/register_all_gradients';\n\n// This file lists all exports of TensorFlow.js Layers\n\nimport * as constraints from './exports_constraints';\nimport * as initializers from './exports_initializers';\nimport * as layers from './exports_layers';\nimport * as metrics from './exports_metrics';\nimport * as models from './exports_models';\nimport * as regularizers from './exports_regularizers';\n\nexport {CallbackList, CustomCallback, CustomCallbackArgs, History} from './base_callbacks';\nexport {Callback, callbacks, EarlyStopping, EarlyStoppingCallbackArgs} from './callbacks';\nexport {InputSpec, SymbolicTensor} from './engine/topology';\nexport {LayersModel, ModelCompileArgs, ModelEvaluateArgs} from './engine/training';\nexport {ModelFitDatasetArgs} from './engine/training_dataset';\nexport {ModelFitArgs} from './engine/training_tensors';\nexport {ClassWeight, ClassWeightMap} from './engine/training_utils';\nexport {input, loadLayersModel, model, registerCallbackConstructor, sequential} from './exports';\nexport {Shape} from './keras_format/common';\nexport {GRUCellLayerArgs, GRULayerArgs, LSTMCellLayerArgs, LSTMLayerArgs, RNN, RNNLayerArgs, SimpleRNNCellLayerArgs, SimpleRNNLayerArgs} from './layers/recurrent';\nexport {Logs} from './logs';\nexport {ModelAndWeightsConfig, Sequential, SequentialArgs} from './models';\nexport {LayerVariable} from './variables';\nexport {version as version_layers} from './version';\nexport {constraints, initializers, layers, metrics, models, regularizers};\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 'DT_INVALID' = 0,\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,\n 'DT_INT64' = 9,\n 'DT_BOOL' = 10,\n 'DT_QINT8' = 11,\n 'DT_QUINT8' = 12,\n 'DT_QINT32' = 13,\n 'DT_BFLOAT16' = 14,\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}\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|null);\n\n /** TensorInfo tensorShape */\n tensorShape?: (ITensorShape|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 allow 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 is 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 if (inputParam.type === 'tensor') {\n return getTensor(\n node.inputNames[inputParam.inputIndexStart], tensorMap, context,\n resourceManager);\n }\n if (inputParam.type === 'tensors') {\n const inputs = node.inputNames.slice(start, end);\n\n return inputs.map(\n name => getTensor(name, tensorMap, context, resourceManager));\n }\n const tensor = getTensor(\n node.inputNames.slice(start)[0], 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);\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 getTensorsForCurrentContenxt(\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);\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(name: string): [string, number, string] {\n const parts = name.split(':');\n if (parts.length === 1) {\n return [name, 0, undefined];\n }\n\n const nodeName = parts[0];\n const outputName = parts.length === 3 ? parts[1] : undefined;\n const index = Number(parts[parts.length - 1]);\n return [nodeName, index, outputName];\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 * @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 {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'Add',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'AddV2',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'AddN',\n 'category': 'arithmetic',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors'}]\n },\n {\n 'tfOpName': 'BiasAdd',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'RealDiv',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Div',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'DivNoNan',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'FloorDiv',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Mul',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Maximum',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Minimum',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Pow',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'SquaredDifference',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Mod',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'FloorMod',\n 'category': 'arithmetic',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'Abs',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Acos',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Asin',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Atan',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Atan2',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'y', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Ceil',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'ClipByValue',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'clipValueMin', 'type': 'number'},\n {'start': 2, 'name': 'clipValueMax', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Complex',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'real', 'type': 'tensor'},\n {'start': 1, 'name': 'imag', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'ComplexAbs',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Cos',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Cosh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Elu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Exp',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Floor',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Log',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Imag',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Real',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'alpha', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Relu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Relu6',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Selu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sigmoid',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sin',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sinh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sqrt',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Rsqrt',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Square',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Tan',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Tanh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Sign',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Round',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Expm1',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Log1p',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Reciprocal',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Softplus',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Asinh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Acosh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Atanh',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Erf',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Prod',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axes', 'type': 'number[]'},\n ],\n 'attrs': [\n {\n 'tfName': 'keep_dims',\n 'name': 'keepDims',\n 'type': 'bool',\n 'notSupported': true\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LeakyRelu',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'alpha',\n 'name': 'alpha',\n 'type': 'number',\n 'defaultValue': 0.2\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'IsNan',\n 'category': 'basic_math',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\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 */\nimport {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'EmptyTensorList',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'elementShape', 'type': 'shape'},\n {'start': 1, 'name': 'maxNumElements', 'type': 'number'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'LoopCond',\n 'category': 'control',\n 'inputs': [{'start': 0, 'name': 'pred', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'Switch',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'data', 'type': 'tensor'},\n {'start': 1, 'name': 'pred', 'type': 'tensor'}\n ]\n },\n {\n 'tfOpName': 'Merge',\n 'category': 'control',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors'}]\n },\n {\n 'tfOpName': 'Enter',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true},\n {'tfName': 'frame_name', 'name': 'frameName', 'type': 'string'},\n {'tfName': 'is_constant', 'name': 'isConstant', 'type': 'bool'}\n ]\n },\n {\n 'tfOpName': 'Exit',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'NextIteration',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'TensorArrayV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'size', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape'},\n {'tfName': 'dynamic_size', 'name': 'dynamicSize', 'type': 'bool'},\n {'tfName': 'clear_after_read', 'name': 'clearAfterRead', 'type': 'bool'},\n {\n 'tfName': 'identical_element_shapes',\n 'name': 'identicalElementShapes',\n 'type': 'bool'\n },\n {'tfName': 'tensor_array_name', 'name': 'name', 'type': 'string'}\n ]\n },\n {\n 'tfOpName': 'TensorArrayWriteV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'index', 'type': 'number'},\n {'start': 2, 'name': 'tensor', 'type': 'tensor'},\n {'start': 3, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'TensorArrayReadV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'index', 'type': 'number'},\n {'start': 2, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [{\n 'tfName': 'dtype',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }]\n },\n {\n 'tfOpName': 'TensorArrayGatherV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape'}\n ]\n },\n {\n 'tfOpName': 'TensorArrayScatterV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'tensor', 'type': 'tensor'},\n {'start': 3, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorArrayConcatV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'}, {\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 {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'tensor', 'type': 'tensor'},\n {'start': 2, 'name': 'lengths', 'type': 'number[]'},\n {'start': 3, 'name': 'flowIn', 'type': 'number'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorArraySizeV3',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'},\n {'start': 1, 'name': 'flowIn', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'TensorArrayCloseV3',\n 'category': 'control',\n 'inputs': [{'start': 0, 'name': 'tensorArrayId', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'StatelessIf',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'cond', 'type': 'tensor'},\n {'start': 1, 'end': 0, 'name': 'args', 'type': 'tensors'}\n ],\n 'attrs': [\n {'tfName': 'then_branch', 'name': 'thenBranch', 'type': 'func'},\n {'tfName': 'else_branch', 'name': 'elseBranch', 'type': 'func'}\n ]\n },\n {\n 'tfOpName': 'If',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'cond', 'type': 'tensor'},\n {'start': 1, 'end': 0, 'name': 'args', 'type': 'tensors'}\n ],\n 'attrs': [\n {'tfName': 'then_branch', 'name': 'thenBranch', 'type': 'func'},\n {'tfName': 'else_branch', 'name': 'elseBranch', 'type': 'func'}\n ]\n },\n {\n 'tfOpName': 'StatelessWhile',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'end': 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'cond', 'name': 'cond', 'type': 'func'},\n {'tfName': 'body', 'name': 'body', 'type': 'func'}\n ]\n },\n {\n 'tfOpName': 'While',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'end': 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'cond', 'name': 'cond', 'type': 'func'},\n {'tfName': 'body', 'name': 'body', 'type': 'func'}\n ]\n },\n {\n 'tfOpName': 'TensorListScatter',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'elementShape', 'type': 'shape'}\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListScatterV2',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'elementShape', 'type': 'shape'},\n {'start': 3, 'name': 'numElements', 'type': 'number'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListGather',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'number[]'},\n {'start': 2, 'name': 'elementShape', 'type': 'shape'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListGetItem',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'index', 'type': 'number'},\n {'start': 2, 'name': 'elementShape', 'type': 'shape'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListSetItem',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'index', 'type': 'number'},\n {'start': 2, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListReserve',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'elementShape', 'type': 'shape'},\n {'start': 1, 'name': 'numElements', 'type': 'number'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListFromTensor',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n {'start': 1, 'name': 'elementShape', 'type': 'shape'}\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListStack',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'elementShape', 'type': 'shape'},\n ],\n 'attrs': [\n {'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'},\n {'tfName': 'num_elements', 'name': 'numElements', 'type': 'dtype'}\n ]\n },\n {\n 'tfOpName': 'TensorListSplit',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n {'start': 1, 'name': 'elementShape', 'type': 'shape'},\n {'start': 2, 'name': 'lengths', 'type': 'number[]'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListConcat',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'element_shape', 'name': 'elementShape', 'type': 'shape'},\n {'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}\n ]\n },\n {\n 'tfOpName': 'TensorListPopBack',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'elementShape', 'type': 'shape'},\n ],\n 'attrs':\n [{'tfName': 'element_dtype', 'name': 'elementDType', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TensorListPushBack',\n 'category': 'control',\n 'inputs': [\n {'start': 0, 'name': 'tensorListId', 'type': 'tensor'},\n {'start': 1, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'element_dtype', 'name': 'elementDType', 'type': '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 {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'AvgPool',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'MaxPool',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'}, {\n 'tfName': 'explicit_paddings',\n 'name': 'explicitPaddings',\n 'type': 'number[]',\n 'defaultValue': [],\n 'notSupported': true\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'MaxPoolWithArgmax',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'},\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'}, {\n 'tfName': 'include_batch_in_index',\n 'name': 'includeBatchInIndex',\n 'type': 'bool'\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'AvgPool3D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'MaxPool3D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'notSupported': true\n },\n {'tfName': 'ksize', 'name': 'kernelSize', 'type': 'number[]'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Conv1D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'stride', 'name': 'stride', 'type': 'number'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NWC'\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true},\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'},\n {'tfName': 'useCudnnOnGpu', 'name': 'useCudnnOnGpu', 'type': 'bool'}, {\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 {'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': '_FusedConv2D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n {'start': 2, end: 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'num_args', 'name': 'numArgs', 'type': 'number'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true},\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\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': [1, 1, 1, 1]\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 }\n ]\n },\n {\n 'tfOpName': 'Conv2DBackpropInput',\n 'category': 'convolution',\n 'inputs': [\n {'start': 2, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n {'start': 0, 'name': 'outputShape', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\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 {'start': 0, 'name': 'input', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\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 {'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'DepthwiseConv2dNative',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'input', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\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 {'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'FusedDepthwiseConv2dNative',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n {'start': 2, end: 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'num_args', 'name': 'numArgs', 'type': 'number'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true},\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\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': [1, 1, 1, 1]\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}, {\n 'tfName': 'data_format',\n 'name': 'dataFormat',\n 'type': 'string',\n 'defaultValue': 'NHWC'\n },\n {'tfName': 'dilations', 'name': 'dilations', 'type': 'number[]'}\n ],\n },\n {\n 'tfOpName': 'Dilation2D',\n 'category': 'convolution',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'filter', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'strides', 'name': 'strides', 'type': 'number[]'},\n {'tfName': 'rates', 'name': 'dilations', 'type': 'number[]'},\n {'tfName': 'padding', 'name': 'pad', 'type': 'string'}\n ]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'Fill',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n {'start': 1, 'name': 'value', 'type': 'number'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'LinSpace',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'start', 'type': 'number'},\n {'start': 1, 'name': 'stop', 'type': 'number'},\n {'start': 2, 'name': 'num', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'OneHot',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'indices', 'type': 'tensor'},\n {'start': 1, 'name': 'depth', 'type': 'number'},\n {'start': 2, 'name': 'onValue', 'type': 'number', 'defaultValue': 1},\n {'start': 3, 'name': 'offValue', 'type': 'number', 'defaultValue': 0},\n ],\n 'attrs': [\n {\n 'tfName': 'axis',\n 'name': 'axis',\n 'type': 'number',\n 'notSupported': true\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Ones',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'OnesLike',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'RandomUniform',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\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 {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'seed', 'name': 'seed', 'type': 'number', 'defaultValue': 0}, {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {'tfName': 'T', 'name': 'T', 'type': 'number', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Range',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'start', 'type': 'number'},\n {'start': 1, 'name': 'stop', 'type': 'number'},\n {'start': 2, 'name': 'step', 'type': 'number', 'defaultValue': 0},\n ],\n 'attrs': [{'tfName': 'Tidx', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'TruncatedNormal',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': [\n {\n 'tfName': 'means',\n 'name': 'mean',\n 'type': 'number',\n 'defaultValue': 0.0\n },\n {\n 'tfName': 'stddev',\n 'name': 'stdDev',\n 'type': 'number',\n 'defaultValue': 1.0\n },\n {'tfName': 'seed', 'name': 'seed', 'type': 'number'}, {\n 'tfName': 'seed2',\n 'name': 'seed2',\n 'type': 'number',\n 'defaultValue': 0,\n 'notSupported': true\n },\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'T', 'name': 'T', 'type': 'number', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Zeros',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'ZerosLike',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}]\n },\n {\n 'tfOpName': 'Multinomial',\n 'category': 'creation',\n 'inputs': [\n {'start': 0, 'name': 'logits', 'type': 'tensor'},\n {'start': 1, 'name': 'numSamples', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'seed', 'name': 'seed', 'type': 'number'},\n {'tfName': 'seed2', 'name': 'seed2', 'type': 'number'},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype'},\n {'tfName': 'output_dtype', 'name': 'output_dtype', 'type': 'dtype'}\n ]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'NonMaxSuppressionV2',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'boxes', 'type': 'tensor'},\n {'start': 1, 'name': 'scores', 'type': 'tensor'},\n {'start': 2, 'name': 'maxOutputSize', 'type': 'number'},\n {'start': 3, 'name': 'iouThreshold', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV3',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'boxes', 'type': 'tensor'},\n {'start': 1, 'name': 'scores', 'type': 'tensor'},\n {'start': 2, 'name': 'maxOutputSize', 'type': 'number'},\n {'start': 3, 'name': 'iouThreshold', 'type': 'number'},\n {'start': 4, 'name': 'scoreThreshold', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'NonMaxSuppressionV4',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'boxes', 'type': 'tensor'},\n {'start': 1, 'name': 'scores', 'type': 'tensor'},\n {'start': 2, 'name': 'maxOutputSize', 'type': 'number'},\n {'start': 3, 'name': 'iouThreshold', 'type': 'number'},\n {'start': 4, 'name': 'scoreThreshold', 'type': 'number'}\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'boxes', 'type': 'tensor'},\n {'start': 1, 'name': 'scores', 'type': 'tensor'},\n {'start': 2, 'name': 'maxOutputSize', 'type': 'number'},\n {'start': 3, 'name': 'iouThreshold', 'type': 'number'},\n {'start': 4, 'name': 'scoreThreshold', 'type': 'number'},\n {'start': 5, 'name': 'softNmsSigma', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'Where',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'condition', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'ListDiff',\n 'category': 'dynamic',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'y', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\n }]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'TopKV2',\n 'category': 'evaluation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'k', 'type': 'number'},\n ],\n 'attrs': [{'tfName': 'sorted', 'name': 'sorted', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Unique',\n 'category': 'evaluation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n },\n {\n 'tfOpName': 'UniqueV2',\n 'category': 'evaluation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'},\n ],\n },\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'PlaceholderWithDefault',\n 'category': 'graph',\n 'inputs': [\n {'start': 0, 'name': 'default', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'shape', 'name': 'shape', 'type': 'shape'},\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'}\n ]\n },\n {\n 'tfOpName': 'Placeholder',\n 'category': 'graph',\n 'attrs': [\n {'tfName': 'shape', 'name': 'shape', 'type': 'shape'},\n {'tfName': 'dtype', 'name': 'dtype', 'type': 'dtype'}\n ]\n },\n {'tfOpName': 'Const', 'category': 'graph'}, {\n 'tfOpName': 'Identity',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'IdentityN',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'x', 'type': 'tensors'}]\n },\n {\n 'tfOpName': 'Snapshot',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'Rank',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'Size',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'Shape',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'ShapeN',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'x', 'type': 'tensors'}]\n },\n {\n 'tfOpName': 'Print',\n 'category': 'graph',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'data', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'message', 'name': 'message', 'type': 'string'}, {\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 {'tfOpName': 'NoOp', 'category': 'graph', 'inputs': []}, {\n 'tfOpName': 'StopGradient',\n 'category': 'graph',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'FakeQuantWithMinMaxVars',\n 'category': 'graph',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'min', 'name': 'min', 'type': 'number'},\n {'tfName': 'max', 'name': 'max', 'type': 'number'}\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 {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'HashTable',\n 'category': 'hash_table',\n 'inputs': [],\n 'attrs': [\n {'tfName': 'shared_name', 'name': 'sharedName', 'type': 'string'},\n {\n 'tfName': 'use_node_name_sharing',\n 'name': 'useNodeNameSharing',\n 'type': 'bool'\n },\n {'tfName': 'key_dtype', 'name': 'keyDType', 'type': 'dtype'},\n {'tfName': 'value_dtype', 'name': 'valueDType', 'type': 'dtype'},\n ]\n },\n {\n 'tfOpName': 'HashTableV2',\n 'category': 'hash_table',\n 'inputs': [],\n 'attrs': [\n {'tfName': 'shared_name', 'name': 'sharedName', 'type': 'string'},\n {\n 'tfName': 'use_node_name_sharing',\n 'name': 'useNodeNameSharing',\n 'type': 'bool'\n },\n {'tfName': 'key_dtype', 'name': 'keyDType', 'type': 'dtype'},\n {'tfName': 'value_dtype', 'name': 'valueDType', 'type': 'dtype'},\n ]\n },\n {\n 'tfOpName': 'LookupTableImport',\n 'category': 'hash_table',\n 'inputs': [\n {'start': 0, 'name': 'tableHandle', 'type': 'tensor'},\n {'start': 1, 'name': 'keys', 'type': 'tensor'},\n {'start': 2, 'name': 'values', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'tableHandle', 'type': 'tensor'},\n {'start': 1, 'name': 'keys', 'type': 'tensor'},\n {'start': 2, 'name': 'values', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'tableHandle', 'type': 'tensor'},\n {'start': 1, 'name': 'keys', 'type': 'tensor'},\n {'start': 2, 'name': 'defaultValue', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'tableHandle', 'type': 'tensor'},\n {'start': 1, 'name': 'keys', 'type': 'tensor'},\n {'start': 2, 'name': 'defaultValue', 'type': 'tensor'}\n ],\n 'attrs': [\n {'tfName': 'Tin', 'name': 'tIn', 'type': 'dtype', 'notSupported': true}, {\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 {'start': 0, 'name': 'tableHandle', 'type': 'tensor'}\n ]\n },\n {\n 'tfOpName': 'LookupTableSizeV2',\n 'category': 'hash_table',\n 'inputs': [\n {'start': 0, 'name': 'tableHandle', 'type': 'tensor'}\n ]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'ResizeBilinear',\n 'category': 'image',\n 'inputs': [\n {'start': 0, 'name': 'images', 'type': 'tensor'},\n {'start': 1, 'name': 'size', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'align_corners', 'name': 'alignCorners', 'type': 'bool'}, {\n 'tfName': 'half_pixel_centers',\n 'name': 'halfPixelCenters',\n 'type': 'bool'\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'ResizeNearestNeighbor',\n 'category': 'image',\n 'inputs': [\n {'start': 0, 'name': 'images', 'type': 'tensor'},\n {'start': 1, 'name': 'size', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'align_corners', 'name': 'alignCorners', 'type': 'bool'}, {\n 'tfName': 'half_pixel_centers',\n 'name': 'halfPixelCenters',\n 'type': 'bool'\n },\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'CropAndResize',\n 'category': 'image',\n 'inputs': [\n {'start': 0, 'name': 'image', 'type': 'tensor'},\n {'start': 1, 'name': 'boxes', 'type': 'tensor'},\n {'start': 2, 'name': 'boxInd', 'type': 'tensor'},\n {'start': 3, 'name': 'cropSize', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'method', 'name': 'method', 'type': 'string'}, {\n 'tfName': 'extrapolation_value',\n 'name': 'extrapolationValue',\n 'type': 'number'\n }\n ]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'Equal',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'NotEqual',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Greater',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'GreaterEqual',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Less',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LessEqual',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LogicalAnd',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LogicalNot',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'LogicalOr',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Select',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'condition', 'type': 'tensor'},\n {'start': 1, 'name': 'a', 'type': 'tensor'},\n {'start': 2, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'SelectV2',\n 'category': 'logical',\n 'inputs': [\n {'start': 0, 'name': 'condition', 'type': 'tensor'},\n {'start': 1, 'name': 'a', 'type': 'tensor'},\n {'start': 2, 'name': 'b', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'T',\n 'name': 'dtype',\n 'type': 'dtype',\n 'notSupported': true\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 {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': '_FusedMatMul',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\n {'start': 2, end: 0, 'name': 'args', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'num_args', 'name': 'numArgs', 'type': 'number'}, {\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 {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'MatMul',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\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 {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'BatchMatMul',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\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 {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'BatchMatMulV2',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'a', 'type': 'tensor'},\n {'start': 1, 'name': 'b', 'type': 'tensor'},\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 {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Transpose',\n 'category': 'matrices',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'perm', 'type': 'number[]'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'Einsum',\n 'category': 'matrices',\n 'inputs': [{'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors'}],\n 'attrs': [\n {'tfName': 'equation', 'name': 'equation', 'type': 'string'},\n {'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2},\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype'}\n ]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'FusedBatchNorm',\n 'category': 'normalization',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'scale', 'type': 'tensor'},\n {'start': 2, 'name': 'offset', 'type': 'tensor'},\n {'start': 3, 'name': 'mean', 'type': 'tensor'},\n {'start': 4, 'name': 'variance', 'type': 'tensor'},\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'scale', 'type': 'tensor'},\n {'start': 2, 'name': 'offset', 'type': 'tensor'},\n {'start': 3, 'name': 'mean', 'type': 'tensor'},\n {'start': 4, 'name': 'variance', 'type': 'tensor'},\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'scale', 'type': 'tensor'},\n {'start': 2, 'name': 'offset', 'type': 'tensor'},\n {'start': 3, 'name': 'mean', 'type': 'tensor'},\n {'start': 4, 'name': 'variance', 'type': 'tensor'},\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'depth_radius',\n 'name': 'radius',\n 'type': 'number',\n 'defaultValue': 5\n },\n {'tfName': 'bias', 'name': 'bias', 'type': 'number', 'defaultValue': 1.0},\n {\n 'tfName': 'alpha',\n 'name': 'alpha',\n 'type': 'number',\n 'defaultValue': 1.0\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': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'LogSoftmax',\n 'category': 'normalization',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'SparseToDense',\n 'category': 'normalization',\n 'inputs': [\n {'start': 0, 'name': 'sparseIndices', 'type': 'tensor'},\n {'start': 1, 'name': 'outputShape', 'type': 'number[]'},\n {'start': 2, 'name': 'sparseValues', 'type': 'tensor'},\n {'start': 3, 'name': 'defaultValue', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'defaultValue': true,\n 'notSupported': true\n }]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'Bincount',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'size', 'type': 'number'},\n {'start': 2, 'name': 'weights', 'type': 'tensor'}\n ]\n },\n {\n 'tfOpName': 'DenseBincount',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'size', 'type': 'number'},\n {'start': 2, 'name': 'weights', 'type': 'tensor'}\n ],\n 'attrs':\n [{'tfName': 'binary_output', 'name': 'binaryOutput', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Max',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Mean',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Min',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Sum',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'All',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Any',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'ArgMax',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'ArgMin',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'Prod',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'keep_dims', 'name': 'keepDims', 'type': 'bool'}]\n },\n {\n 'tfOpName': 'Cumsum',\n 'category': 'reduction',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'},\n ],\n 'attrs': [\n {'tfName': 'exclusive', 'name': 'exclusive', 'type': 'bool'},\n {'tfName': 'reverse', 'name': 'reverse', 'type': 'bool'}\n ]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'ConcatV2',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'end': -1, 'name': 'tensors', 'type': 'tensors'},\n {'start': -1, 'name': 'axis', 'type': 'number'}\n ],\n 'attrs':\n [{'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2}]\n },\n {\n 'tfOpName': 'Concat',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 1, 'end': 0, 'name': 'tensors', 'type': 'tensors'},\n {'start': 0, 'name': 'axis', 'type': 'number'}\n ],\n 'attrs': [{'tfName': 'N', 'name': 'n', 'type': 'number', 'defaultValue': 2}]\n\n },\n {\n 'tfOpName': 'GatherV2',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'},\n {'start': 2, 'name': 'axis', 'type': 'number', 'defaultValue': 0}\n ],\n 'attrs': [{\n 'tfName': 'batch_dims',\n 'name': 'batchDims',\n 'type': 'number',\n 'defaultValue': 0\n }]\n },\n {\n 'tfOpName': 'Gather',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'notSupported': true\n }]\n },\n {\n 'tfOpName': 'Reverse',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'dims', 'type': 'bool[]'}\n ]\n },\n {\n 'tfOpName': 'ReverseV2',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'Slice',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'begin', 'type': 'number[]'},\n {'start': 2, 'name': 'size', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'StridedSlice',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'begin', 'type': 'number[]'},\n {'start': 2, 'name': 'end', 'type': 'number[]'},\n {'start': 3, 'name': 'strides', 'type': 'number[]'},\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 {'start': 0, 'end': 0, 'name': 'tensors', 'type': 'tensors'},\n ],\n 'attrs': [\n {'tfName': 'axis', 'name': 'axis', 'type': 'number', 'defaultValue': 0}\n ]\n },\n {\n 'tfOpName': 'Unpack',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'tensor', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'axis', 'name': 'axis', 'type': 'number', 'defaultValue': 0}, {\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'reps', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'Split',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'axis', 'type': 'number', 'defaultValue': 0},\n {'start': 1, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'num_split',\n 'name': 'numOrSizeSplits',\n 'type': 'number',\n 'defaultValue': 1\n }]\n },\n {\n 'tfOpName': 'SplitV',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'numOrSizeSplits', 'type': 'number[]'},\n {'start': 2, 'name': 'axis', 'type': 'number', 'defaultValue': 0}\n ]\n },\n {\n 'tfOpName': 'ScatterNd',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'indices', 'type': 'tensor'},\n {'start': 1, 'name': 'values', 'type': 'tensor'},\n {'start': 2, 'name': 'shape', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'GatherNd',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'}\n ]\n },\n {\n 'tfOpName': 'SparseToDense',\n 'category': 'slice_join',\n 'inputs': [\n {'start': 0, 'name': 'sparseIndices', 'type': 'tensor'},\n {'start': 1, 'name': 'outputShape', 'type': 'number[]'},\n {'start': 2, 'name': 'sparseValues', 'type': 'tensor'},\n {'start': 3, 'name': 'defaultValue', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'validate_indices',\n 'name': 'validateIndices',\n 'type': 'bool',\n 'defaultValue': false,\n 'notSupported': true\n }]\n }\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 {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'SparseFillEmptyRows',\n 'category': 'sparse',\n 'inputs': [\n {'start': 0, 'name': 'indices', 'type': 'tensor'},\n {'start': 1, 'name': 'values', 'type': 'tensor'},\n {'start': 2, 'name': 'denseShape', 'type': 'tensor'},\n {'start': 3, 'name': 'defaultValue', 'type': 'tensor'},\n ]\n },\n {\n 'tfOpName': 'SparseReshape',\n 'category': 'sparse',\n 'inputs': [\n {'start': 0, 'name': 'inputIndices', 'type': 'tensor'},\n {'start': 1, 'name': 'inputShape', 'type': 'tensor'},\n {'start': 2, 'name': 'newShape', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'T', 'name': 'dtype', 'type': 'dtype', 'notSupported': true}\n ]\n },\n {\n 'tfOpName': 'SparseSegmentMean',\n 'category': 'sparse',\n 'inputs': [\n {'start': 0, 'name': 'data', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'},\n {'start': 2, 'name': 'segmentIds', 'type': 'tensor'},\n ]\n },\n {\n 'tfOpName': 'SparseSegmentSum',\n 'category': 'sparse',\n 'inputs': [\n {'start': 0, 'name': 'data', 'type': 'tensor'},\n {'start': 1, 'name': 'indices', 'type': 'tensor'},\n {'start': 2, 'name': 'segmentIds', 'type': 'tensor'},\n ]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'FFT',\n 'category': 'spectral',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'IFFT',\n 'category': 'spectral',\n 'inputs': [{'start': 0, 'name': 'x', 'type': 'tensor'}]\n },\n {\n 'tfOpName': 'RFFT',\n 'category': 'spectral',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'}, {\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 {'start': 0, 'name': 'x', 'type': 'tensor'}, {\n 'start': 1,\n 'name': 'fft_length',\n 'type': 'number',\n 'notSupported': true\n }\n ]\n }\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 {OpMapper} from '../types';\n\nexport const json: OpMapper[] = [\n {\n 'tfOpName': 'StringNGrams',\n 'category': 'string',\n 'inputs': [\n {'start': 0, 'name': 'data', 'type': 'tensor'},\n {'start': 1, 'name': 'dataSplits', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'separator', 'name': 'separator', 'type': 'string'},\n {'tfName': 'ngram_widths', 'name': 'nGramWidths', 'type': 'number[]'},\n {'tfName': 'left_pad', 'name': 'leftPad', 'type': 'string'},\n {'tfName': 'right_pad', 'name': 'rightPad', 'type': 'string'},\n {'tfName': 'pad_width', 'name': 'padWidth', 'type': 'number'}, {\n 'tfName': 'preserve_short_sequences',\n 'name': 'preserveShortSequences',\n 'type': 'bool'\n }\n ],\n 'outputs': ['ngrams', 'ngrams_splits']\n },\n {\n 'tfOpName': 'StringSplit',\n 'category': 'string',\n 'inputs': [\n {'start': 0, 'name': 'input', 'type': 'tensor'},\n {'start': 1, 'name': 'delimiter', 'type': 'tensor'},\n ],\n 'attrs': [{'tfName': 'skip_empty', 'name': 'skipEmpty', 'type': 'bool'}],\n 'outputs': ['indices', 'values', 'shape']\n },\n {\n 'tfOpName': 'StringToHashBucketFast',\n 'category': 'string',\n 'inputs': [\n {'start': 0, 'name': 'input', 'type': 'tensor'},\n ],\n 'attrs': [{'tfName': 'num_buckets', 'name': 'numBuckets', 'type': 'number'}]\n }\n];\n", "import {OpMapper} from '../types';\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 json: OpMapper[] = [\n {\n 'tfOpName': 'Cast',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {\n 'tfName': 'SrcT',\n 'name': 'sdtype',\n 'type': 'dtype',\n 'notSupported': true\n },\n {'tfName': 'DstT', 'name': 'dtype', 'type': 'dtype'}\n ]\n },\n {\n 'tfOpName': 'ExpandDims',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'axis', 'type': 'number'}\n ]\n },\n {\n 'tfOpName': 'MirrorPad',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'padding', 'type': 'number[]'},\n ],\n 'attrs': [{'tfName': 'mode', 'name': 'mode', 'type': 'string'}]\n },\n {\n 'tfOpName': 'Pad',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'padding', 'type': 'number[]'},\n ],\n 'attrs': [{\n 'tfName': 'constant_value',\n 'name': 'constantValue',\n 'type': 'number',\n 'defaultValue': 0\n }]\n },\n {\n 'tfOpName': 'PadV2',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'padding', 'type': 'number[]'}, {\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 {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'shape', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'Squeeze',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [{\n 'tfName': 'axis',\n 'tfDeprecatedName': 'squeeze_dims',\n 'name': 'axis',\n 'type': 'number[]'\n }]\n },\n {\n 'tfOpName': 'SpaceToBatchND',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'blockShape', 'type': 'number[]'},\n {'start': 2, 'name': 'paddings', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'BatchToSpaceND',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'blockShape', 'type': 'number[]'},\n {'start': 2, 'name': 'crops', 'type': 'number[]'}\n ]\n },\n {\n 'tfOpName': 'DepthToSpace',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n ],\n 'attrs': [\n {'tfName': 'block_size', 'name': 'blockSize', 'type': 'number'},\n {'tfName': 'data_format', 'name': 'dataFormat', 'type': 'string'}\n ]\n },\n {\n 'tfOpName': 'BroadcastTo',\n 'category': 'transformation',\n 'inputs': [\n {'start': 0, 'name': 'x', 'type': 'tensor'},\n {'start': 1, 'name': 'shape', 'type': 'number[]'},\n ],\n 'attrs': []\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.substr(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 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 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 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): Tensor[] => {\n switch (node.op) {\n case 'BiasAdd':\n case 'AddV2':\n case 'Add': {\n return [tfOps.add(\n (getParamValue('a', node, tensorMap, context) as Tensor),\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'AddN': {\n return [tfOps.addN((\n getParamValue('tensors', node, tensorMap, context) as Tensor[]))];\n }\n case 'FloorMod':\n case 'Mod':\n return [tfOps.mod(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n case 'Mul':\n return [tfOps.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 [tfOps.div(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'DivNoNan': {\n return [tfOps.divNoNan(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'FloorDiv': {\n return [tfOps.floorDiv(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Sub': {\n return [tfOps.sub(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Minimum': {\n return [tfOps.minimum(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Maximum': {\n return [tfOps.maximum(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Pow': {\n return [tfOps.pow(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'SquaredDifference': {\n return [tfOps.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,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Abs':\n case 'ComplexAbs':\n return [tfOps.abs(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Acos':\n return [tfOps.acos(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Acosh':\n return [tfOps.acosh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Asin':\n return [tfOps.asin(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Asinh':\n return [tfOps.asinh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Atan':\n return [tfOps.atan(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Atan2':\n return [tfOps.atan2(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('y', node, tensorMap, context) as Tensor)];\n case 'Atanh':\n return [tfOps.atanh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Ceil':\n return [tfOps.ceil(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Complex':\n return [tfOps.complex(\n getParamValue('real', node, tensorMap, context) as Tensor,\n getParamValue('imag', node, tensorMap, context) as Tensor)];\n case 'Cos':\n return [tfOps.cos(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Cosh':\n return [tfOps.cosh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Elu':\n return [tfOps.elu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Erf':\n return [tfOps.erf(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Exp':\n return [tfOps.exp(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Expm1': {\n return [tfOps.expm1(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Floor':\n return [tfOps.floor(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Log':\n return [tfOps.log(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Log1p': {\n return [tfOps.log1p(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Imag':\n return [tfOps.imag(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n\n case 'Neg':\n return [tfOps.neg(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Reciprocal': {\n return [tfOps.reciprocal(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Real':\n return [tfOps.real(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Relu':\n return [tfOps.relu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Round': {\n return [tfOps.round(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Selu':\n return [tfOps.selu(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sigmoid':\n return [tfOps.sigmoid(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sin':\n return [tfOps.sin(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Sign': {\n return [tfOps.sign(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Sinh': {\n return [tfOps.sinh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Softplus': {\n return [tfOps.softplus(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Sqrt': {\n return [tfOps.sqrt(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Square': {\n return [tfOps.square(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Tanh': {\n return [tfOps.tanh(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'Tan':\n return [tfOps.tan(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'ClipByValue':\n return [tfOps.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 [tfOps.relu6(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n case 'Rsqrt':\n return [tfOps.rsqrt(\n getTensor(node.inputNames[0], tensorMap, context))];\n case 'Prod':\n return [tfOps.prod(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('axes', node, tensorMap, context) as number[])];\n case 'LeakyRelu':\n return [tfOps.leakyRelu(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('alpha', node, tensorMap, context) as number)];\n case 'Prelu':\n return [tfOps.prelu(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('alpha', node, tensorMap, context) as Tensor)];\n case 'IsNan':\n return [tfOps.isNaN(\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 nummber[] 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\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 this.tensors.length = size;\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 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 */\nexport function reserve(\n elementShape: number[], elementDtype: DataType, numElements: number) {\n return new TensorList([], elementShape, elementDtype, numElements);\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\n const tensorList = reserve(elementShape, elementDtype, numElements);\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 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 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): 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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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} = tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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,\n context: ExecutionContext): 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 [tfOps.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 [tfOps.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 [tfOps.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 return [tfOps.oneHot(indices, depth, onValue, offValue)];\n }\n case 'Ones': {\n return [tfOps.ones(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'OnesLike': {\n return [tfOps.onesLike(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'RandomUniform': {\n return [tfOps.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 '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 [tfOps.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 [tfOps.truncatedNormal(\n shape, mean, stdDev,\n getParamValue('dtype', node, tensorMap, context) as 'float32' |\n 'int32',\n seed)];\n }\n case 'Zeros': {\n return [tfOps.zeros(\n getParamValue('shape', node, tensorMap, context) as number[],\n getParamValue('dtype', node, tensorMap, context) as DataType)];\n }\n case 'ZerosLike': {\n return [tfOps.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 {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): 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 tfOps.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 tfOps.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 tfOps.image.nonMaxSuppressionAsync(\n boxes as Tensor2D, scores as Tensor1D, maxOutputSize, iouThreshold,\n scoreThreshold)];\n }\n case 'Where': {\n const condition = tfOps.cast(\n (getParamValue('condition', node, tensorMap, context) as Tensor),\n 'bool');\n const result = [await tfOps.whereAsync(condition)];\n condition.dispose();\n return result;\n }\n case 'ListDiff': {\n return tfOps.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 Tensor[] => {\n switch (node.op) {\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 = tfOps.topk(x, k, sorted);\n return [result.values, result.indices];\n }\n case 'Unique': {\n const x = getParamValue('x', node, tensorMap, context) as Tensor;\n const result = tfOps.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 = tfOps.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): 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 [tfOps.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) => tfOps.tensor1d(t.shape));\n case 'Size':\n return [tfOps.scalar(\n (getParamValue('x', node, tensorMap, context) as Tensor).size,\n 'int32')];\n case 'Rank':\n return [tfOps.scalar(\n (getParamValue('x', node, tensorMap, context) as Tensor).rank,\n 'int32')];\n case 'NoOp':\n return [tfOps.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 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 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): 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 [tfOps.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 [tfOps.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 [tfOps.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 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,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Equal': {\n return [tfOps.equal(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'NotEqual': {\n return [tfOps.notEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Greater': {\n return [tfOps.greater(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'GreaterEqual': {\n return [tfOps.greaterEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'Less': {\n return [tfOps.less(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LessEqual': {\n return [tfOps.lessEqual(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalAnd': {\n return [tfOps.logicalAnd(\n getParamValue('a', node, tensorMap, context) as Tensor,\n getParamValue('b', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalNot': {\n return [tfOps.logicalNot(\n getParamValue('a', node, tensorMap, context) as Tensor)];\n }\n case 'LogicalOr': {\n return [tfOps.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 [tfOps.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 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 {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,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'BatchMatMul':\n case 'BatchMatMulV2':\n case 'MatMul':\n return [tfOps.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 [tfOps.einsum(\n getParamValue('equation', node, tensorMap, context) as string,\n ...getParamValue('tensors', node, tensorMap, context) as\n Tensor[])];\n\n case 'Transpose':\n return [tfOps.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 [tfOps.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 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 {Scalar, 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): Tensor[] => {\n switch (node.op) {\n case 'FusedBatchNorm':\n case 'FusedBatchNormV2': {\n return [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.softmax(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'LogSoftmax': {\n return [tfOps.logSoftmax(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'SparseToDense': {\n return [tfOps.sparseToDense(\n getParamValue('sparseIndices', node, tensorMap, context) as\n Tensor,\n getParamValue('outputShape', node, tensorMap, context) as Tensor,\n getParamValue('sparseValues', node, tensorMap, context) as\n number[],\n getParamValue('defaultValue', node, tensorMap, context) as\n Scalar)];\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 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): 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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.prod(\n getParamValue('x', node, tensorMap, context) as Tensor, axis,\n keepDims)];\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 [tfOps.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 [tfOps.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 [tfOps.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,\n context: ExecutionContext): 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 [tfOps.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 [tfOps.gather(input, tfOps.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 [tfOps.gather(\n input, tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 = tfOps.squeeze(tensors[0]).shape;\n const mapped = tensors.map(tensor => {\n const sameShape = util.arraysEqual(tensor.shape, shape);\n if (!sameShape &&\n !util.arraysEqual(\n tfOps.squeeze(tensor).shape, squeezedShape)) {\n throw new Error('the input tensors shape does not match');\n }\n return sameShape ? tensor : tfOps.reshape(tensor, shape);\n });\n return [tfOps.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 tfOps.unstack(tensor, axis);\n }\n case 'Tile': {\n const reps =\n getParamValue('reps', node, tensorMap, context) as number[];\n return [tfOps.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 tfOps.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 [tfOps.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 [tfOps.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 [tfOps.sparseToDense(\n indices, sparseValues, shape,\n sparseValues.dtype === defaultValue.dtype ?\n defaultValue :\n tfOps.cast(defaultValue, sparseValues.dtype))];\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): Tensor[] => {\n switch (node.op) {\n case 'SparseFillEmptyRows': {\n const {\n outputIndices,\n outputValues,\n emptyRowIndicator,\n reverseIndexMap\n } =\n tfOps.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} = tfOps.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 = tfOps.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 = tfOps.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 Tensor[] => {\n switch (node.op) {\n case 'FFT': {\n return [tfOps.fft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'IFFT': {\n return [tfOps.ifft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'RFFT': {\n return [tfOps.rfft(\n getParamValue('x', node, tensorMap, context) as Tensor)];\n }\n case 'IRFFT': {\n return [tfOps.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): Tensor[] => {\n switch (node.op) {\n case 'StringNGrams': {\n const {nGrams, nGramsSplits} = tfOps.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} = tfOps.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 = tfOps.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,\n context: ExecutionContext): Tensor[] => {\n switch (node.op) {\n case 'Cast': {\n return [tfOps.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 [tfOps.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 [tfOps.squeeze(\n getParamValue('x', node, tensorMap, context) as Tensor, axis)];\n }\n\n case 'Reshape': {\n return [tfOps.reshape(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\n }\n case 'MirrorPad': {\n return [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.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 [tfOps.depthToSpace(\n getParamValue('x', node, tensorMap, context) as Tensor4D,\n blockSize, dataFormat)];\n }\n case 'BroadcastTo': {\n return [tfOps.broadcastTo(\n getParamValue('x', node, tensorMap, context) as Tensor,\n getParamValue('shape', node, tensorMap, context) as number[])];\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 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): tfc.Tensor[]|Promise<tfc.Tensor[]> {\n const value =\n ((node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) => {\n switch (node.category) {\n case 'arithmetic':\n return tfc.tidy(\n () => arithmetic.executeOp(node, tensorMap, context));\n case 'basic_math':\n return tfc.tidy(\n () => basicMath.executeOp(node, tensorMap, context));\n case 'control':\n return control.executeOp(node, tensorMap, context);\n case 'convolution':\n return tfc.tidy(\n () => convolution.executeOp(node, tensorMap, context));\n case 'creation':\n return tfc.tidy(() => creation.executeOp(node, tensorMap, context));\n case 'dynamic':\n return dynamic.executeOp(node, tensorMap, context);\n case 'evaluation':\n return tfc.tidy(\n () => evaluation.executeOp(node, tensorMap, context));\n case 'image':\n return tfc.tidy(() => image.executeOp(node, tensorMap, context));\n case 'graph':\n return tfc.tidy(() => graph.executeOp(node, tensorMap, context));\n case 'logical':\n return tfc.tidy(() => logical.executeOp(node, tensorMap, context));\n case 'matrices':\n return tfc.tidy(() => matrices.executeOp(node, tensorMap, context));\n case 'normalization':\n return tfc.tidy(\n () => normalization.executeOp(node, tensorMap, context));\n case 'reduction':\n return tfc.tidy(\n () => reduction.executeOp(node, tensorMap, context));\n case 'slice_join':\n return tfc.tidy(\n () => sliceJoin.executeOp(node, tensorMap, context));\n case 'sparse':\n return tfc.tidy(() => sparse.executeOp(node, tensorMap, context));\n case 'spectral':\n return tfc.tidy(() => spectral.executeOp(node, tensorMap, context));\n case 'string':\n return tfc.tidy(() => string.executeOp(node, tensorMap, context));\n case 'transformation':\n return tfc.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 as Promise<tfc.Tensor>).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 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 Object.keys(inputs).map(name => parseNodeName(name)[0]);\n\n let initNodeNames: string[] = [];\n if (initNodes != null) {\n initNodeNames = initNodes.map(node => parseNodeName(node.name)[0]);\n }\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.indexOf(node.name) !== -1) {\n continue;\n }\n // This node is a dead end since it doesn't have any inputs.\n if (initNodeNames.indexOf(node.name) !== -1) {\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, weightMap: NamedTensorsMap,\n executionInfo: ExecutionInfo): Node[] {\n const {usedNodes, inputs} = executionInfo;\n const frontier: Node[] = [];\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 inputNodes.forEach(input => {\n if (usedNodes.has(input.name)) {\n frontier.push(input);\n }\n });\n graph.weights.forEach(weight => {\n if (usedNodes.has(weight.name)) {\n frontier.push(weight);\n }\n });\n if (initNodes != null) {\n initNodes.forEach(node => {\n if (usedNodes.has(node.name)) {\n frontier.push(node);\n }\n });\n }\n const seen = new Set<string>();\n const orderedNodes: Node[] = [];\n while (frontier.length > 0) {\n const node = frontier.pop();\n seen.add(node.name);\n if (!weightMap[node.name]) {\n orderedNodes.push(node);\n }\n node.children.forEach(child => {\n if (!seen.has(child.name) && usedNodes.has(child.name) &&\n child.inputs.every(input => seen.has(input.name))) {\n frontier.push(child);\n }\n });\n }\n return orderedNodes;\n}\n\nconst CONTROL_FLOW_OPS = [\n 'Switch', 'Merge', 'Enter', 'Exit', 'NextIteration', 'StatelessIf',\n 'StatelessWhile', 'if', 'While'\n];\nconst DYNAMIC_SHAPE_OPS = [\n 'NonMaxSuppressionV2', 'NonMaxSuppressionV3', 'NonMaxSuppressionV5', 'Where'\n];\nconst HASH_TABLE_OPS = [\n 'HashTable', 'HashTableV2', 'LookupTableImport', 'LookupTableImportV2',\n 'LookupTableFind', 'LookupTableFindV2', 'LookupTableSize', 'LookupTableSizeV2'\n];\n\nexport function isControlFlow(node: Node) {\n return CONTROL_FLOW_OPS.indexOf(node.op) >= 0;\n}\n\nexport function isDynamicShape(node: Node) {\n return DYNAMIC_SHAPE_OPS.indexOf(node.op) >= 0;\n}\n\nexport function isHashTable(node: Node) {\n return HASH_TABLE_OPS.indexOf(node.op) >= 0;\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, 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, getTensorsForCurrentContenxt, 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, 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: Map<string, Node[]> = new Map();\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 SEPERATOR = ',';\n private _functions: {[key: string]: Graph} = {};\n private _functionExecutorMap: {[key: string]: FunctionExecutor} = {};\n private _resourceManager: ResourceManager;\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.SEPERATOR) + '--' +\n sortedOutputs.join(this.SEPERATOR);\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 */\n private compile(inputs: NamedTensorMap, outputs: Node[]): 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 return getNodesInTopologicalOrder(\n this.graph, this.weightMap, executionInfo);\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 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 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 compilationKey = this.getCompilationKey(inputNodes, outputNodes);\n\n // Do nothing if the compiled graph cache contains the input.\n let orderedNodes = this.compiledMap.get(compilationKey);\n if (orderedNodes == null) {\n orderedNodes = this.compile(inputs, outputNodes);\n this.compiledMap.set(compilationKey, orderedNodes);\n }\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);\n const tensorsMap: NamedTensorsMap = {...this.weightMap};\n\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\n const tensorsToKeep = this.getFrozenTensorIds(tensorsMap);\n const intermediateTensorConsumerCount: {[key: number]: number} = {};\n for (let i = 0; i < orderedNodes.length; i++) {\n const node = orderedNodes[i];\n if (!tensorsMap[node.name]) {\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 this.checkTensorForDisposal(\n node.name, node, tensorsMap, context, tensorsToKeep,\n outputNodeNames, intermediateTensorConsumerCount);\n }\n }\n // dispose the context for the root executor\n if (this.parent == null) {\n context.dispose(tensorsToKeep);\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 private checkTensorForDisposal(\n nodeName: string, node: Node, tensorMap: NamedTensorsMap,\n context: ExecutionContext, tensorsToKeep: Set<number>,\n outputNames: 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 (node.category === 'control' || outputNames.indexOf(nodeName) !== -1) {\n return;\n }\n\n tensorMap[nodeName].forEach(tensor => {\n if (tensor != null) {\n intermediateTensorConsumerCount[tensor.id] =\n (intermediateTensorConsumerCount[tensor.id] || 0) +\n node.children.length;\n }\n });\n node.inputs.forEach(input => {\n // Skip any control flow nodes, since its dependency is tricky to track\n // correctly.\n if (input.category !== 'control') {\n const tensors =\n getTensorsForCurrentContenxt(input.name, tensorMap, context);\n if (tensors != null) {\n tensors.forEach(tensor => {\n if (tensor && !tensor.kept && !tensorsToKeep.has(tensor.id)) {\n const count = intermediateTensorConsumerCount[tensor.id];\n if (count === 1) {\n tensor.dispose();\n delete intermediateTensorConsumerCount[tensor.id];\n } else if (count != null) {\n // only intermediate nodes has count set, inputs and weights are\n // not.\n intermediateTensorConsumerCount[tensor.id]--;\n }\n }\n });\n }\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 /**\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 the\n * 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 Optinal 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 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 const context = new ExecutionContext(\n this.weightMap, tensorArrayMap, tensorListMap,\n this.functionExecutorMap);\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 tensorMap = await this.executeWithControlFlow(\n inputs, context, outputs, isFunctionExecution);\n const results = outputs.map(name => getTensor(name, tensorMap, 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 Object.keys(tensorMap).forEach(key => {\n const tensorArray = tensorMap[key];\n tensorArray.forEach(tensor => {\n if (tensor && !tensor.kept && !tensor.isDisposed &&\n !keepIds.has(tensor.id)) {\n tensor.dispose();\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 * 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 the\n * 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 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 outputNodeNames, 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>, outputNames: 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 as Promise<Tensor[]>).then(t => {\n tensorMap[nodeName] = t;\n context.currentContext = currentContext;\n this.checkTensorForDisposal(\n nodeName, item.node, tensorMap, context, tensorsToKeep,\n outputNames, intermediateTensorConsumerCount);\n this.processChildNodes(\n item.node, stack, context, tensorMap, added, usedNodes);\n return t;\n }));\n } else {\n tensorMap[nodeName] = tensors as Tensor[];\n this.checkTensorForDisposal(\n nodeName, item.node, tensorMap, context, tensorsToKeep,\n outputNames, 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 if (this._signature != null && this._signature.inputs != null &&\n this._signature.inputs[inputName] != null) {\n const tensor = this._signature.inputs[inputName];\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 if (this._signature != null && this._signature.outputs != null &&\n this._signature.outputs[name] != null) {\n const tensor = this._signature.outputs[name];\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\nimport {InferenceModel, io, ModelPredictConfig, NamedTensorMap, Tensor} 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\nexport const TFHUB_SEARCH_PARAM = '?tfjs-format=file';\nexport const DEFAULT_MODEL_NAME = 'model.json';\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 implements InferenceModel {\n private executor: GraphExecutor;\n private version = 'n/a';\n private handler: io.IOHandler;\n private artifacts: io.ModelArtifacts;\n private initializer: GraphExecutor;\n private resourceManager: ResourceManager;\n private signature: tensorflow.ISignatureDef;\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 /**\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: string|io.IOHandler,\n private loadOptions: io.LoadOptions = {}) {\n if (loadOptions == null) {\n this.loadOptions = {};\n }\n this.resourceManager = new ResourceManager();\n }\n\n private findIOHandler() {\n const path = this.modelUrl;\n if ((path as io.IOHandler).load != null) {\n // Path is an IO Handler.\n this.handler = path as io.IOHandler;\n } else if (this.loadOptions.requestInit != null) {\n this.handler = io.browserHTTPRequest(path as string, this.loadOptions);\n } else {\n const handlers = 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(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];\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 async load(): Promise<boolean> {\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 const artifacts = await this.handler.load();\n\n return this.loadSync(artifacts);\n }\n\n /**\n * Synchronously construct the in memory weight map and\n * compile the inference graph. Also initialize hashtable if any.\n *\n * @doc {heading: 'Models', subheading: 'Classes', ignoreCI: true}\n */\n loadSync(artifacts: io.ModelArtifacts) {\n this.artifacts = artifacts;\n const graph = this.artifacts.modelTopology as tensorflow.IGraphDef;\n\n let signature;\n if (this.artifacts.userDefinedMetadata != null &&\n this.artifacts.userDefinedMetadata.signature != null) {\n signature = // tslint:disable-next-line:no-any\n (this.artifacts.userDefinedMetadata as any).signature as\n tensorflow.ISignatureDef;\n } else {\n signature = this.artifacts.signature;\n }\n this.signature = signature;\n\n this.version = `${graph.versions.producer}.${graph.versions.minConsumer}`;\n const weightMap =\n io.decodeWeights(this.artifacts.weightData, this.artifacts.weightSpecs);\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.initializer.executeAsync({}, []);\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 = 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 /**\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 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 and\n * output node names. Currently the batch size option is ignored for graph\n * model.\n *\n * @returns Inference result tensors. The output would be single `tf.Tensor`\n * if model has single output node, otherwise Tensor[] or NamedTensorMap[]\n * will be returned for model with multiple outputs.\n *\n * @doc {heading: 'Models', subheading: 'Classes'}\n */\n predict(inputs: Tensor|Tensor[]|NamedTensorMap, config?: ModelPredictConfig):\n Tensor|Tensor[]|NamedTensorMap {\n return this.execute(inputs, this.outputNodes);\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 return inputs;\n }\n inputs = Array.isArray(inputs) ? inputs : [inputs];\n if (inputs.length !== this.inputNodes.length) {\n throw new Error(\n 'Input tensor count mismatch,' +\n `the graph model has ${this.inputNodes.length} placeholders, ` +\n `while there are ${inputs.length} input tensors.`);\n }\n return this.inputNodes.reduce((map, inputName, i) => {\n map[inputName] = (inputs as Tensor[])[i];\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 /**\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 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 * 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 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 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 }\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 with\n * 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 credentials\n * and custom headers.\n *\n * @doc {heading: 'Models', subheading: 'Loading'}\n */\nexport async function loadGraphModel(\n modelUrl: string|io.IOHandler,\n options: io.LoadOptions = {}): 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) {\n if ((modelUrl as io.IOHandler).load == null) {\n if (!(modelUrl as string).endsWith('/')) {\n modelUrl = (modelUrl as string) + '/';\n }\n modelUrl = `${modelUrl}${DEFAULT_MODEL_NAME}${TFHUB_SEARCH_PARAM}`;\n }\n }\n const model = new GraphModel(modelUrl, options);\n await model.load();\n return model;\n}\n", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.8.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 */\nexport {GraphModel, loadGraphModel} from './executor/graph_model';\nexport {deregisterOp, registerOp} from './operations/custom_op/register';\nexport {GraphNode, OpExecutor} from './operations/types';\nexport {version as version_converter} from './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\nexport {array, Dataset, zip} from './dataset';\nexport {CSVDataset} from './datasets/csv_dataset';\nexport {TextLineDataset} from './datasets/text_line_dataset';\nexport {csv, func, generator, microphone, webcam} from './readers';\nexport {FileDataSource} from './sources/file_data_source';\nexport {URLDataSource} from './sources/url_data_source';\nexport {ColumnConfig, MicrophoneConfig, WebcamConfig} from './types';\nexport {version as version_data} from './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 */\n\nimport * as tf from '@tensorflow/tfjs-core';\nimport {TensorContainer, TensorLike} from '@tensorflow/tfjs-core';\nimport * as seedrandom from 'seedrandom';\n\nimport {iteratorFromConcatenated, iteratorFromFunction, iteratorFromItems, iteratorFromZipped, LazyIterator, ZipMismatchMode} from './iterators/lazy_iterator';\nimport {Container} from './types';\nimport {canTensorify, deepMapAndAwaitAll, DeepMapResult, isIterable} from './util/deep_map';\n\n/**\n * A nested structure of Datasets, used as the input to zip().\n */\nexport type DatasetContainer = Container<Dataset<TensorContainer>>;\n\n// TODO(soergel): consider vectorized operations within the pipeline.\n\n/**\n * Represents a potentially large list of independent data elements (typically\n * 'samples' or 'examples').\n *\n * A 'data example' may be a primitive, an array, a map from string keys to\n * values, or any nested structure of these.\n *\n * A `Dataset` represents an ordered collection of elements, together with a\n * chain of transformations to be performed on those elements. Each\n * transformation is a method of `Dataset` that returns another `Dataset`, so\n * these may be chained, e.g.\n * `const processedDataset = rawDataset.filter(...).map(...).batch(...)`.\n *\n * Data loading and transformation is done in a lazy, streaming fashion. The\n * dataset may be iterated over multiple times; each iteration starts the data\n * loading anew and recapitulates the transformations.\n *\n * A `Dataset` is typically processed as a stream of unbatched examples --i.e.,\n * its transformations are applied one example at a time. Batching produces a\n * new `Dataset` where each element is a batch. Batching should usually come\n * last in a pipeline, because data transformations are easier to express on a\n * per-example basis than on a per-batch basis.\n *\n * The following code examples are calling `await dataset.forEachAsync(...)` to\n * iterate once over the entire dataset in order to print out the data.\n *\n * @doc {heading: 'Data', subheading: 'Classes', namespace: 'data'}\n */\nexport abstract class Dataset<T extends tf.TensorContainer> {\n /*\n * Provide a new stream of elements. Note this will also start new streams\n * from any underlying `Dataset`s.\n *\n * CAUTION: Any Tensors contained within the elements returned from\n * this stream *must* be manually disposed to avoid a GPU memory leak.\n * The tf.tidy() approach cannot be used in an asynchronous context.\n */\n abstract async iterator(): Promise<LazyIterator<T>>;\n\n readonly size: number = null;\n\n // TODO(soergel): Make Datasets report whether repeated iterator() calls\n // produce the same result (e.g., reading from a file) or different results\n // (e.g., from the webcam). Currently we don't make this distinction but it\n // could be important for the user to know.\n // abstract isDeterministic(): boolean;\n\n /**\n * Groups elements into batches.\n *\n * It is assumed that each of the incoming dataset elements has the same\n * structure-- i.e. the same set of keys at each location in an object\n * hierarchy. For each key, the resulting `Dataset` provides a batched\n * element collecting all of the incoming values for that key.\n *\n * * Incoming primitives are grouped into a 1-D Tensor.\n * * Incoming Tensors are grouped into a new Tensor where the 0'th axis is\n * the batch dimension.\n * * Incoming arrays are converted to Tensor and then batched.\n * * A nested array is interpreted as an n-D Tensor, so the batched result\n * has n+1 dimensions.\n * * An array that cannot be converted to Tensor produces an error.\n *\n * If an array should not be batched as a unit, it should first be converted\n * to an object with integer keys.\n *\n * Here are a few examples:\n *\n * Batch a dataset of numbers:\n * ```js\n * const a = tf.data.array([1, 2, 3, 4, 5, 6, 7, 8]).batch(4);\n * await a.forEachAsync(e => e.print());\n * ```\n *\n * Batch a dataset of arrays:\n * ```js\n * const b = tf.data.array([[1], [2], [3], [4], [5], [6], [7], [8]]).batch(4);\n * await b.forEachAsync(e => e.print());\n * ```\n *\n * Batch a dataset of objects:\n * ```js\n * const c = tf.data.array([{a: 1, b: 11}, {a: 2, b: 12}, {a: 3, b: 13},\n * {a: 4, b: 14}, {a: 5, b: 15}, {a: 6, b: 16}, {a: 7, b: 17},\n * {a: 8, b: 18}]).batch(4);\n * await c.forEachAsync(e => {\n * console.log('{');\n * for(var key in e) {\n * console.log(key+':');\n * e[key].print();\n * }\n * console.log('}');\n * })\n * ```\n *\n * @param batchSize The number of elements desired per batch.\n * @param smallLastBatch Whether to emit the final batch when it has fewer\n * than batchSize elements. Default true.\n * @returns A `Dataset`, from which a stream of batches can be obtained.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n batch(batchSize: number, smallLastBatch = true): Dataset<tf.TensorContainer> {\n const base = this;\n tf.util.assert(\n batchSize > 0, () => `batchSize needs to be positive, but it is\n ${batchSize}`);\n let size;\n if (this.size === Infinity || this.size == null) {\n // If the size of this dataset is infinity or null, the new size keeps the\n // same.\n size = this.size;\n } else if (smallLastBatch) {\n // If the size of this dataset is known and include small last batch, the\n // new size is full batch count plus last batch.\n size = Math.ceil(this.size / batchSize);\n } else {\n // If the size of this dataset is known and not include small last batch,\n // the new size is full batch count.\n size = Math.floor(this.size / batchSize);\n }\n return datasetFromIteratorFn(async () => {\n return (await base.iterator())\n .columnMajorBatch(batchSize, smallLastBatch, deepBatchConcat);\n }, size);\n }\n\n /**\n * Concatenates this `Dataset` with another.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3]);\n * const b = tf.data.array([4, 5, 6]);\n * const c = a.concatenate(b);\n * await c.forEachAsync(e => console.log(e));\n * ```\n *\n * @param dataset A `Dataset` to be concatenated onto this one.\n * @returns A `Dataset`.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n concatenate(dataset: Dataset<T>): Dataset<T> {\n const base = this;\n let size;\n if (this.size === Infinity || dataset.size === Infinity) {\n // If the size of any of these two dataset is infinity, new size is\n // infinity.\n size = Infinity;\n } else if (this.size != null && dataset.size != null) {\n // If the size of both datasets are known and not infinity, new size is\n // sum the size of these two datasets.\n size = this.size + dataset.size;\n } else {\n // If neither of these two datasets has infinite size and any of these two\n // datasets' size is null, the new size is null.\n size = null;\n }\n return datasetFromIteratorFn(\n async () =>\n (await base.iterator()).concatenate(await dataset.iterator()),\n size);\n }\n\n /**\n * Filters this dataset according to `predicate`.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n * .filter(x => x%2 === 0);\n * await a.forEachAsync(e => console.log(e));\n * ```\n *\n * @param predicate A function mapping a dataset element to a boolean or a\n * `Promise` for one.\n *\n * @returns A `Dataset` of elements for which the predicate was true.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n filter(predicate: (value: T) => boolean): Dataset<T> {\n const base = this;\n let size;\n if (this.size === Infinity) {\n // If the size of this dataset is infinity, new size is infinity\n size = Infinity;\n } else {\n // If this dataset has limited elements, new size is null because it might\n // exhausted randomly.\n size = null;\n }\n return datasetFromIteratorFn(async () => {\n return (await base.iterator()).filter(x => tf.tidy(() => predicate(x)));\n }, size);\n }\n\n /**\n * Apply a function to every element of the dataset.\n *\n * After the function is applied to a dataset element, any Tensors contained\n * within that element are disposed.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3]);\n * await a.forEachAsync(e => console.log(e));\n * ```\n *\n * @param f A function to apply to each dataset element.\n * @returns A `Promise` that resolves after all elements have been processed.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n async forEachAsync(f: (input: T) => void): Promise<void> {\n return (await this.iterator()).forEachAsync(f);\n }\n\n /**\n * Maps this dataset through a 1-to-1 transform.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3]).map(x => x*x);\n * await a.forEachAsync(e => console.log(e));\n * ```\n *\n * @param transform A function mapping a dataset element to a transformed\n * dataset element.\n *\n * @returns A `Dataset` of transformed elements.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n map<O extends tf.TensorContainer>(transform: (value: T) => O): Dataset<O> {\n const base = this;\n return datasetFromIteratorFn(async () => {\n return (await base.iterator()).map(x => tf.tidy(() => transform(x)));\n }, this.size);\n }\n\n /**\n * Maps this dataset through an async 1-to-1 transform.\n *\n * ```js\n * const a =\n * tf.data.array([1, 2, 3]).mapAsync(x => new Promise(function(resolve){\n * setTimeout(() => {\n * resolve(x * x);\n * }, Math.random()*1000 + 500);\n * }));\n * console.log(await a.toArray());\n * ```\n *\n * @param transform A function mapping a dataset element to a `Promise` for a\n * transformed dataset element. This transform is responsible for disposing\n * any intermediate `Tensor`s, i.e. by wrapping its computation in\n * `tf.tidy()`; that cannot be automated here (as it is in the synchronous\n * `map()` case).\n *\n * @returns A `Dataset` of transformed elements.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n mapAsync<O extends tf.TensorContainer>(transform: (value: T) => Promise<O>):\n Dataset<O> {\n const base = this;\n return datasetFromIteratorFn(async () => {\n return (await base.iterator()).mapAsync(transform);\n }, this.size);\n }\n\n /**\n * Creates a `Dataset` that prefetches elements from this dataset.\n *\n * @param bufferSize: An integer specifying the number of elements to be\n * prefetched.\n * @returns A `Dataset`.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n prefetch(bufferSize: number): Dataset<T> {\n if (bufferSize == null) {\n throw new RangeError(\n '`Dataset.prefetch()` requires bufferSize to be specified.');\n }\n\n const base = this;\n return datasetFromIteratorFn(\n async () => (await base.iterator()).prefetch(bufferSize), this.size);\n }\n\n /**\n * Repeats this dataset `count` times.\n *\n * NOTE: If this dataset is a function of global state (e.g. a random number\n * generator), then different repetitions may produce different elements.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3]).repeat(3);\n * await a.forEachAsync(e => console.log(e));\n * ```\n *\n * @param count: (Optional) An integer, representing the number of times\n * the dataset should be repeated. The default behavior (if `count` is\n * `undefined` or negative) is for the dataset be repeated indefinitely.\n * @returns A `Dataset`.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n repeat(count?: number): Dataset<T> {\n const base = this;\n let size;\n if (this.size != null && count > 0) {\n // If this dataset has size and count is positive, new size is current\n // size multiply count. This also covers the case that current size is\n // infinity.\n size = this.size * count;\n } else if (count === 0) {\n // If count is 0, new size is 0.\n size = 0;\n } else if (this.size != null && (count === undefined || count < 0)) {\n // If this dataset has size and count is undefined or negative, the\n // dataset will be repeated indefinitely and new size is infinity.\n size = Infinity;\n } else {\n // If the size of this dataset is null, the new dataset's size is null.\n size = null;\n }\n return datasetFromIteratorFn(async () => {\n const iteratorIterator = iteratorFromFunction(\n async () => ({value: await base.iterator(), done: false}));\n return iteratorFromConcatenated(iteratorIterator.take(count));\n }, size);\n }\n\n /**\n * Creates a `Dataset` that skips `count` initial elements from this dataset.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3, 4, 5, 6]).skip(3);\n * await a.forEachAsync(e => console.log(e));\n * ```\n *\n * @param count: The number of elements of this dataset that should be skipped\n * to form the new dataset. If `count` is greater than the size of this\n * dataset, the new dataset will contain no elements. If `count`\n * is `undefined` or negative, skips the entire dataset.\n *\n * @returns A `Dataset`.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n skip(count: number): Dataset<T> {\n const base = this;\n let size;\n if (this.size != null && count >= 0 && this.size >= count) {\n // If the size of this dataset is greater than count, the new dataset's\n // size is current size minus skipped size.This also covers the case that\n // current size is infinity.\n size = this.size - count;\n } else if (\n this.size != null &&\n (this.size < count || count === undefined || count < 0)) {\n // If the size of this dataset is smaller than count, or count is\n // undefined or negative, skips the entire dataset and the new size is 0.\n size = 0;\n } else {\n // If the size of this dataset is null, the new dataset's size is null.\n size = null;\n }\n return datasetFromIteratorFn(\n async () => (await base.iterator()).skip(count), size);\n }\n\n // TODO(soergel): deep sharded shuffle, where supported\n\n static readonly MAX_BUFFER_SIZE = 10000;\n\n /**\n * Pseudorandomly shuffles the elements of this dataset. This is done in a\n * streaming manner, by sampling from a given number of prefetched elements.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3, 4, 5, 6]).shuffle(3);\n * await a.forEachAsync(e => console.log(e));\n * ```\n *\n * @param bufferSize: An integer specifying the number of elements from this\n * dataset from which the new dataset will sample.\n * @param seed: (Optional) An integer specifying the random seed that will\n * be used to create the distribution.\n * @param reshuffleEachIteration: (Optional) A boolean, which if true\n * indicates that the dataset should be pseudorandomly reshuffled each time\n * it is iterated over. If false, elements will be returned in the same\n * shuffled order on each iteration. (Defaults to `true`.)\n * @returns A `Dataset`.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n shuffle(bufferSize: number, seed?: string, reshuffleEachIteration = true):\n Dataset<T> {\n if (bufferSize == null || bufferSize < 0) {\n if (this.size == null) {\n throw new RangeError(\n '`Dataset.shuffle()` requires bufferSize to be specified.');\n } else {\n throw new RangeError(\n '`Dataset.shuffle()` requires bufferSize to be specified. ' +\n 'If your data fits in main memory (for regular JS objects), ' +\n 'and/or GPU memory (for `tf.Tensor`s), consider setting ' +\n `bufferSize to the dataset size (${this.size} elements)`);\n }\n }\n const base = this;\n const random = seedrandom.alea(seed || tf.util.now().toString());\n return datasetFromIteratorFn(async () => {\n let seed2 = random.int32();\n if (reshuffleEachIteration) {\n seed2 += random.int32();\n }\n return (await base.iterator()).shuffle(bufferSize, seed2.toString());\n }, this.size);\n }\n\n /**\n * Creates a `Dataset` with at most `count` initial elements from this\n * dataset.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3, 4, 5, 6]).take(3);\n * await a.forEachAsync(e => console.log(e));\n * ```\n *\n * @param count: The number of elements of this dataset that should be taken\n * to form the new dataset. If `count` is `undefined` or negative, or if\n * `count` is greater than the size of this dataset, the new dataset will\n * contain all elements of this dataset.\n * @returns A `Dataset`.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n take(count: number): Dataset<T> {\n const base = this;\n let size;\n if (this.size != null && this.size > count) {\n // If the size of this dataset is greater than count, the new dataset's\n // size is count.\n size = count;\n } else if (this.size != null && this.size <= count) {\n // If the size of this dataset is equal or smaller than count, the new\n // dataset's size is the size of this dataset.\n size = this.size;\n } else {\n // If the size of this dataset is null, the new dataset's size is null.\n size = null;\n }\n return datasetFromIteratorFn(\n async () => (await base.iterator()).take(count), size);\n }\n\n /**\n * Collect all elements of this dataset into an array.\n *\n * Obviously this will succeed only for small datasets that fit in memory.\n * Useful for testing and generally should be avoided if possible.\n *\n * ```js\n * const a = tf.data.array([1, 2, 3, 4, 5, 6]);\n * console.log(await a.toArray());\n * ```\n *\n * @returns A Promise for an array of elements, which will resolve\n * when a new stream has been obtained and fully consumed.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n async toArray() {\n if (this.size === Infinity) {\n throw new Error('Can not convert infinite data stream to array.');\n }\n return (await this.iterator()).toArray();\n }\n\n /**\n * Collect all elements of this dataset into an array with prefetching 100\n * elements. This is useful for testing, because the prefetch changes the\n * order in which the Promises are resolved along the processing pipeline.\n * This may help expose bugs where results are dependent on the order of\n * Promise resolution rather than on the logical order of the stream (i.e.,\n * due to hidden mutable state).\n *\n * @returns A Promise for an array of elements, which will resolve\n * when a new stream has been obtained and fully consumed.\n */\n async toArrayForTest() {\n if (this.size === Infinity) {\n throw new Error('Can not convert infinite data stream to array.');\n }\n return (await this.iterator()).toArrayForTest();\n }\n}\n\n/**\n * Create a `Dataset` defined by a provided iterator() function.\n *\n * ```js\n * let i = -1;\n * const func = () =>\n * ++i < 5 ? {value: i, done: false} : {value: null, done: true};\n * const iter = tf.data.iteratorFromFunction(func);\n * const ds = tf.data.datasetFromIteratorFn(iter);\n * await ds.forEachAsync(e => console.log(e));\n * ```\n */\nexport function datasetFromIteratorFn<T extends tf.TensorContainer>(\n iteratorFn: () => Promise<LazyIterator<T>>,\n size: number = null): Dataset<T> {\n return new class extends Dataset<T> {\n size = size;\n\n /*\n * Provide a new stream of elements. Note this will also start new streams\n * from any underlying `Dataset`s.\n */\n async iterator(): Promise<LazyIterator<T>> {\n return iteratorFn();\n }\n }\n ();\n}\n\n/**\n * Create a `Dataset` from an array of elements.\n *\n * Create a Dataset from an array of objects:\n * ```js\n * const a = tf.data.array([{'item': 1}, {'item': 2}, {'item': 3}]);\n * await a.forEachAsync(e => console.log(e));\n * ```\n *\n * Create a Dataset from an array of numbers:\n * ```js\n * const a = tf.data.array([4, 5, 6]);\n * await a.forEachAsync(e => console.log(e));\n * ```\n * @param items An array of elements that will be parsed as items in a dataset.\n *\n * @doc {heading: 'Data', subheading: 'Creation', namespace: 'data'}\n */\nexport function array<T extends tf.TensorContainer>(items: T[]): Dataset<T> {\n return datasetFromIteratorFn(\n async () => iteratorFromItems(items), items.length);\n}\n\n/**\n * Create a `Dataset` by zipping together an array, dict, or nested\n * structure of `Dataset`s (and perhaps additional constants).\n * The underlying datasets must provide elements in a consistent order such that\n * they correspond.\n *\n * The number of elements in the resulting dataset is the same as the size of\n * the smallest dataset in datasets.\n *\n * The nested structure of the `datasets` argument determines the\n * structure of elements in the resulting iterator.\n *\n * Note this means that, given an array of two datasets that produce dict\n * elements, the result is a dataset that produces elements that are arrays\n * of two dicts:\n *\n * Zip an array of datasets:\n * ```js\n * console.log('Zip two datasets of objects:');\n * const ds1 = tf.data.array([{a: 1}, {a: 2}, {a: 3}]);\n * const ds2 = tf.data.array([{b: 4}, {b: 5}, {b: 6}]);\n * const ds3 = tf.data.zip([ds1, ds2]);\n * await ds3.forEachAsync(e => console.log(JSON.stringify(e)));\n *\n * // If the goal is to merge the dicts in order to produce elements like\n * // {a: ..., b: ...}, this requires a second step such as:\n * console.log('Merge the objects:');\n * const ds4 = ds3.map(x => {return {a: x[0].a, b: x[1].b}});\n * await ds4.forEachAsync(e => console.log(e));\n * ```\n *\n * Zip a dict of datasets:\n * ```js\n * const a = tf.data.array([{a: 1}, {a: 2}, {a: 3}]);\n * const b = tf.data.array([{b: 4}, {b: 5}, {b: 6}]);\n * const c = tf.data.zip({c: a, d: b});\n * await c.forEachAsync(e => console.log(JSON.stringify(e)));\n * ```\n *\n * @doc {heading: 'Data', subheading: 'Operations', namespace: 'data'}\n */\nexport function zip<O extends tf.TensorContainer>(datasets: DatasetContainer):\n Dataset<O> {\n // manually type-check the argument for JS users\n if (!isIterable(datasets)) {\n throw new Error('The argument to zip() must be an object or array.');\n }\n let size;\n if (Array.isArray(datasets)) {\n for (let i = 0; i < datasets.length; i++) {\n size = size == null ? (datasets[i] as Dataset<O>).size :\n Math.min(size, (datasets[i] as Dataset<O>).size);\n }\n } else if (datasets instanceof Object) {\n for (const ds in datasets) {\n size = size == null ? (datasets[ds] as Dataset<O>).size :\n Math.min(size, (datasets[ds] as Dataset<O>).size);\n }\n }\n return datasetFromIteratorFn<O>(async () => {\n const streams = await deepMapAndAwaitAll(datasets, d => {\n if (d instanceof Dataset) {\n return {value: d.iterator(), recurse: false};\n } else if (isIterable(d)) {\n return {value: null, recurse: true};\n } else {\n throw new Error(\n 'Leaves of the structure passed to zip() must be Datasets, ' +\n 'not primitives.');\n }\n });\n return iteratorFromZipped<O>(streams, ZipMismatchMode.SHORTEST);\n }, size);\n}\n\n/**\n * A zip function for use with deepZip, passed via the columnMajorBatch call.\n *\n * Accepts an array of identically-structured nested elements and either batches\n * them (if they are primitives, numeric arrays, or Tensors) or requests\n * recursion (if not).\n */\n// tslint:disable-next-line:no-any\nfunction deepBatchConcat(rows: any[]): DeepMapResult {\n if (rows === null) {\n return null;\n }\n\n // use the first item to decide whether to recurse or batch here.\n const exampleRow = rows[0];\n\n if (canTensorify(exampleRow)) {\n // rows is an array of primitives, Tensors, or arrays. Batch them.\n const value = batchConcat(rows);\n return {value, recurse: false};\n }\n\n // the example row is an object, so recurse into it.\n return {value: null, recurse: true};\n}\n\n/**\n * Assembles a list of same-shaped numbers, number arrays, or Tensors\n * into a single new Tensor where axis 0 is the batch dimension.\n */\nfunction batchConcat<T extends(TensorLike | tf.Tensor)>(arrays: T[]):\n tf.Tensor {\n if (arrays.length === 0) {\n // We can't return an empty Tensor because we don't know the element shape.\n throw new Error('Can\\'t make a batch of zero elements.');\n }\n\n if (arrays[0] instanceof tf.Tensor) {\n // Input is an array of Tensors\n return tf.stack(arrays as tf.Tensor[]);\n } else {\n // Input is a possibly-nested array of numbers.\n return tf.tensor(arrays as TensorLike);\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\nimport * as tf from '@tensorflow/tfjs-core';\nimport * as seedrandom from 'seedrandom';\n\nimport {Container} from '../types';\nimport {deepClone} from '../util/deep_clone';\nimport {deepMapAndAwaitAll, DeepMapAsyncResult, DeepMapResult, deepZip, zipToList} from '../util/deep_map';\nimport {GrowingRingBuffer} from '../util/growing_ring_buffer';\nimport {RingBuffer} from '../util/ring_buffer';\n\n/**\n * A nested structure of LazyIterators, used as the input to zip().\n */\nexport type IteratorContainer = Container<LazyIterator<tf.TensorContainer>>;\n\n// Here we implement a simple asynchronous iterator.\n// This lets us avoid using either third-party stream libraries or\n// recent TypeScript language support requiring polyfills.\n\n/**\n * Create a `LazyIterator` from an array of items.\n */\nexport function iteratorFromItems<T>(items: T[]): LazyIterator<T> {\n return new ArrayIterator(items);\n}\n\n/**\n * Create a `LazyIterator` of incrementing integers.\n */\nexport function iteratorFromIncrementing(start: number): LazyIterator<number> {\n let i = start;\n return iteratorFromFunction(() => ({value: i++, done: false}));\n}\n\n/**\n * Create a `LazyIterator` from a function.\n *\n * ```js\n * let i = -1;\n * const func = () =>\n * ++i < 5 ? {value: i, done: false} : {value: null, done: true};\n * const iter = tf.data.iteratorFromFunction(func);\n * await iter.forEachAsync(e => console.log(e));\n * ```\n *\n * @param func A function that produces data on each call.\n */\nexport function iteratorFromFunction<T>(\n func: () =>\n IteratorResult<T>| Promise<IteratorResult<T>>): LazyIterator<T> {\n return new FunctionCallIterator(func);\n}\n\n/**\n * Create a `LazyIterator` by concatenating underlying streams, which are\n * themselves provided as a stream.\n *\n * This can also be thought of as a \"stream flatten\" operation.\n *\n * @param baseIterators A stream of streams to be concatenated.\n * @param baseErrorHandler An optional function that can intercept `Error`s\n * raised during a `next()` call on the base stream. This function can decide\n * whether the error should be propagated, whether the error should be\n * ignored, or whether the base stream should be terminated.\n */\nexport function iteratorFromConcatenated<T>(\n baseIterators: LazyIterator<LazyIterator<T>>,\n baseErrorHandler?: (e: Error) => boolean): LazyIterator<T> {\n return new ChainedIterator(baseIterators, baseErrorHandler);\n}\n\n/**\n * Create a `LazyIterator` by concatenating streams produced by calling a\n * stream-generating function a given number of times.\n *\n * Since a `LazyIterator` is read-once, it cannot be repeated, but this\n * function can be used to achieve a similar effect:\n *\n * LazyIterator.ofConcatenatedFunction(() => new MyIterator(), 6);\n *\n * @param iteratorFunc: A function that produces a new stream on each call.\n * @param count: The number of times to call the function.\n * @param baseErrorHandler An optional function that can intercept `Error`s\n * raised during a `next()` call on the base stream. This function can decide\n * whether the error should be propagated, whether the error should be\n * ignored, or whether the base stream should be terminated.\n */\nexport function iteratorFromConcatenatedFunction<T>(\n iteratorFunc: () => IteratorResult<LazyIterator<T>>, count: number,\n baseErrorHandler?: (e: Error) => boolean): LazyIterator<T> {\n return iteratorFromConcatenated(\n iteratorFromFunction(iteratorFunc).take(count), baseErrorHandler);\n}\n\n/**\n * Create a `LazyIterator` by zipping together an array, dict, or nested\n * structure of `LazyIterator`s (and perhaps additional constants).\n *\n * The underlying streams must provide elements in a consistent order such\n * that they correspond.\n *\n * Typically, the underlying streams should have the same number of\n * elements. If they do not, the behavior is determined by the\n * `mismatchMode` argument.\n *\n * The nested structure of the `iterators` argument determines the\n * structure of elements in the resulting iterator.\n *\n * @param iterators: An array or object containing LazyIterators at the\n * leaves.\n * @param mismatchMode: Determines what to do when one underlying iterator\n * is exhausted before the others. `ZipMismatchMode.FAIL` (the default)\n * causes an error to be thrown in this case. `ZipMismatchMode.SHORTEST`\n * causes the zipped iterator to terminate with the furst underlying\n * streams, so elements remaining on the longer streams are ignored.\n * `ZipMismatchMode.LONGEST` causes the zipped stream to continue, filling\n * in nulls for the exhausted streams, until all streams are exhausted.\n */\nexport function iteratorFromZipped<O extends tf.TensorContainer>(\n iterators: IteratorContainer,\n mismatchMode: ZipMismatchMode = ZipMismatchMode.FAIL): LazyIterator<O> {\n return new ZipIterator<O>(iterators, mismatchMode);\n}\n\n/**\n * An asynchronous iterator, providing lazy access to a potentially\n * unbounded stream of elements.\n *\n * Iterator can be obtained from a dataset:\n * `const iter = await dataset.iterator();`\n */\nexport abstract class LazyIterator<T> {\n // This class implements AsyncIterator<T>, but we have not yet set the\n // TypeScript --downlevelIteration flag to enable that.\n\n abstract summary(): string;\n\n /**\n * Returns a `Promise` for the next element in the stream.\n *\n * When an item can be provided successfully, the return value is\n * `{value:T, done:false}`.\n *\n * Calling next() on a closed stream returns `{value:null, done:true}`.\n */\n abstract async next(): Promise<IteratorResult<T>>;\n\n /**\n * Collect all remaining elements of a bounded stream into an array.\n * Obviously this will succeed only for small streams that fit in memory.\n * Useful for testing.\n *\n * @returns A Promise for an array of stream elements, which will resolve\n * when the stream is exhausted.\n */\n async toArray(): Promise<T[]> {\n const result: T[] = [];\n let x = await this.next();\n while (!x.done) {\n result.push(x.value);\n x = await this.next();\n }\n return result;\n }\n\n /**\n * Collect all elements of this dataset into an array with prefetching 100\n * elements. This is useful for testing, because the prefetch changes the\n * order in which the Promises are resolved along the processing pipeline.\n * This may help expose bugs where results are dependent on the order of\n * Promise resolution rather than on the logical order of the stream (i.e.,\n * due to hidden mutable state).\n *\n * @returns A Promise for an array of stream elements, which will resolve\n * when the stream is exhausted.\n */\n async toArrayForTest(): Promise<T[]> {\n const stream = this.prefetch(100);\n const result: T[] = [];\n let x = await stream.next();\n while (!x.done) {\n result.push(x.value);\n x = await stream.next();\n }\n return result;\n }\n\n /**\n * Draw items from the stream until it is exhausted.\n *\n * This can be useful when the stream has side effects but no output. In\n * that case, calling this function guarantees that the stream will be\n * fully processed.\n */\n async resolveFully(): Promise<void> {\n let x = await this.next();\n while (!x.done) {\n x = await this.next();\n }\n }\n\n /**\n * Draw items from the stream until it is exhausted, or a predicate fails.\n *\n * This can be useful when the stream has side effects but no output. In\n * that case, calling this function guarantees that the stream will be\n * fully processed.\n */\n async resolveWhile(predicate: (r: T) => boolean): Promise<void> {\n let x = await this.next();\n let shouldContinue = predicate(x.value);\n while ((!x.done) && shouldContinue) {\n x = await this.next();\n shouldContinue = predicate(x.value);\n }\n }\n\n /**\n * Handles errors thrown on this stream using a provided handler function.\n *\n * @param handler A function that handles any `Error` thrown during a `next()`\n * call and returns true if the stream should continue (dropping the failed\n * call) or false if the stream should quietly terminate. If the handler\n * itself throws (or rethrows) an `Error`, that will be propagated.\n *\n * @returns A `LazyIterator` of elements passed through from upstream,\n * possibly filtering or terminating on upstream `next()` calls that\n * throw an `Error`.\n */\n handleErrors(handler: (error: Error) => boolean): LazyIterator<T> {\n return new ErrorHandlingLazyIterator(this, handler);\n }\n\n // TODO(soergel): Implement reduce() etc.\n\n /**\n * Filters this stream according to `predicate`.\n *\n * @param predicate A function mapping a stream element to a boolean or a\n * `Promise` for one.\n *\n * @returns A `LazyIterator` of elements for which the predicate was true.\n */\n filter(predicate: (value: T) => boolean): LazyIterator<T> {\n return new FilterIterator(this, predicate);\n }\n\n /**\n * Maps this stream through a 1-to-1 transform.\n *\n * @param transform A function mapping a stream element to a transformed\n * element.\n *\n * @returns A `LazyIterator` of transformed elements.\n */\n map<O>(transform: (value: T) => O): LazyIterator<O> {\n return new MapIterator(this, transform);\n }\n\n /**\n * Maps this stream through an async 1-to-1 transform.\n *\n * @param transform A function mapping a stream element to a `Promise` for a\n * transformed stream element.\n *\n * @returns A `LazyIterator` of transformed elements.\n */\n mapAsync<O>(transform: (value: T) => Promise<O>): LazyIterator<O> {\n return new AsyncMapIterator(this, transform);\n }\n\n /**\n * Maps this stream through a 1-to-1 transform, forcing serial execution.\n *\n * @param transform A function mapping a stream element to a transformed\n * element.\n *\n * @returns A `LazyIterator` of transformed elements.\n */\n serialMapAsync<O>(transform: (value: T) => Promise<O>): LazyIterator<O> {\n return new AsyncMapIterator(this, transform).serial();\n }\n\n /**\n * Maps this stream through a 1-to-many transform.\n *\n * @param transform A function mapping a stream element to an array of\n * transformed elements.\n *\n * @returns A `DataStream` of transformed elements.\n */\n flatmap<O>(transform: (value: T) => O[]): LazyIterator<O> {\n return new FlatmapIterator(this, transform);\n }\n\n /**\n * Apply a function to every element of the stream.\n *\n * @param f A function to apply to each stream element.\n */\n async forEachAsync(f: (value: T) => void): Promise<void> {\n return this.map(f).resolveFully();\n }\n\n /**\n * Apply a function to every element of the stream, forcing serial execution.\n *\n * @param f A function to apply to each stream element. Should return 'true'\n * to indicate that the stream should continue, or 'false' to cause it to\n * terminate.\n */\n async serialForEach(f: (value: T) => Promise<boolean>): Promise<void> {\n return this.serialMapAsync(f).resolveWhile(x => (x === true));\n }\n\n /**\n * Groups elements into batches, represented as arrays of elements.\n *\n * We can think of the elements of this iterator as 'rows' (even if they are\n * nested structures). By the same token, consecutive values for a given\n * key within the elements form a 'column'. This matches the usual sense of\n * 'row' and 'column' when processing tabular data (e.g., parsing a CSV).\n *\n * Thus, \"Row-major\" means that the resulting batch is simply a collection of\n * rows: `[row1, row2, row3, ...]`. This is contrast to the column-major\n * form, which is needed for vectorized computation.\n *\n * @param batchSize The number of elements desired per batch.\n * @param smallLastBatch Whether to emit the final batch when it has fewer\n * than batchSize elements. Default true.\n * @returns A `LazyIterator` of batches of elements, represented as arrays\n * of the original element type.\n */\n rowMajorBatch(batchSize: number, smallLastBatch = true): LazyIterator<T[]> {\n return new RowMajorBatchIterator(this, batchSize, smallLastBatch);\n }\n\n /**\n * Groups elements into batches, represented in column-major form.\n *\n * We can think of the elements of this iterator as 'rows' (even if they are\n * nested structures). By the same token, consecutive values for a given\n * key within the elements form a 'column'. This matches the usual sense of\n * 'row' and 'column' when processing tabular data (e.g., parsing a CSV).\n *\n * Thus, \"column-major\" means that the resulting batch is a (potentially\n * nested) structure representing the columns. Each column entry, then,\n * contains a collection of the values found in that column for a range of\n * input elements. This representation allows for vectorized computation, in\n * contrast to the row-major form.\n *\n * The inputs should all have the same nested structure (i.e., of arrays and\n * dicts). The result is a single object with the same nested structure,\n * where the leaves are arrays collecting the values of the inputs at that\n * location (or, optionally, the result of a custom function applied to those\n * arrays).\n *\n * @param batchSize The number of elements desired per batch.\n * @param smallLastBatch Whether to emit the final batch when it has fewer\n * than batchSize elements. Default true.\n * @param zipFn: (optional) A function that expects an array of elements at a\n * single node of the object tree, and returns a `DeepMapResult`. The\n * `DeepMapResult` either provides a result value for that node (i.e.,\n * representing the subtree), or indicates that the node should be processed\n * recursively. The default zipFn recurses as far as possible and places\n * arrays at the leaves.\n * @returns A `LazyIterator` of batches of elements, represented as an object\n * with collections at the leaves.\n */\n columnMajorBatch(\n batchSize: number, smallLastBatch = true,\n // tslint:disable-next-line:no-any\n zipFn: (xs: any[]) => DeepMapResult = zipToList):\n LazyIterator<tf.TensorContainer> {\n // First collect the desired number of input elements as a row-major batch.\n const rowBatches = this.rowMajorBatch(batchSize, smallLastBatch);\n // Now 'rotate' or 'pivot' the data, collecting all values from each column\n // in the batch (i.e., for each key within the elements) into an array.\n return rowBatches.map(x => deepZip(x, zipFn));\n }\n\n /**\n * Concatenate this `LazyIterator` with another.\n *\n * @param iterator A `LazyIterator` to be concatenated onto this one.\n * @param baseErrorHandler An optional function that can intercept `Error`s\n * raised during a `next()` call on the base stream. This function can\n * decide whether the error should be propagated, whether the error should\n * be ignored, or whether the base stream should be terminated.\n * @returns A `LazyIterator`.\n */\n concatenate(\n iterator: LazyIterator<T>,\n baseErrorHandler?: (e: Error) => boolean): LazyIterator<T> {\n return new ChainedIterator(\n iteratorFromItems([this, iterator]), baseErrorHandler);\n }\n\n /**\n * Limits this stream to return at most `count` items.\n *\n * @param count The maximum number of items to provide from the stream. If\n * a negative or undefined value is given, the entire stream is returned\n * unaltered.\n */\n take(count: number): LazyIterator<T> {\n if (count < 0 || count == null) {\n return this;\n }\n return new TakeIterator(this, count);\n }\n\n /**\n * Skips the first `count` items in this stream.\n *\n * @param count The number of items to skip. If a negative or undefined\n * value is given, the entire stream is returned unaltered.\n */\n skip(count: number): LazyIterator<T> {\n if (count < 0 || count == null) {\n return this;\n }\n return new SkipIterator(this, count);\n }\n\n /**\n * Prefetch the first `bufferSize` items in this stream.\n *\n * Note this prefetches Promises, but makes no guarantees about when those\n * Promises resolve.\n *\n * @param bufferSize: An integer specifying the number of elements to be\n * prefetched.\n */\n prefetch(bufferSize: number): LazyIterator<T> {\n return new PrefetchIterator(this, bufferSize);\n }\n\n // TODO(soergel): deep sharded shuffle, where supported\n\n /**\n * Randomly shuffles the elements of this stream.\n *\n * @param bufferSize: An integer specifying the number of elements from\n * this stream from which the new stream will sample.\n * @param seed: (Optional.) An integer specifying the random seed that\n * will be used to create the distribution.\n */\n shuffle(windowSize: number, seed?: string): LazyIterator<T> {\n return new ShuffleIterator(this, windowSize, seed);\n }\n\n /**\n * Force an iterator to execute serially: each next() call will await the\n * prior one, so that they cannot execute concurrently.\n */\n serial(): LazyIterator<T> {\n return new SerialIterator(this);\n }\n}\n\n// ============================================================================\n// The following private classes serve to implement the chainable methods\n// on LazyIterator. Unfortunately they can't be placed in separate files,\n// due to resulting trouble with circular imports.\n// ============================================================================\n\n// Iterators that just extend LazyIterator directly\n// ============================================================================\n\nclass ArrayIterator<T> extends LazyIterator<T> {\n private trav = 0;\n constructor(protected items: T[]) {\n super();\n }\n\n summary() {\n return `Array of ${this.items.length} items`;\n }\n\n async next(): Promise<IteratorResult<T>> {\n if (this.trav >= this.items.length) {\n return {value: null, done: true};\n }\n const item = this.items[this.trav];\n this.trav++;\n return {value: deepClone(item), done: false};\n }\n}\n\nclass FunctionCallIterator<T> extends LazyIterator<T> {\n constructor(\n protected nextFn: () => IteratorResult<T>| Promise<IteratorResult<T>>) {\n super();\n }\n\n summary() {\n return `Function call`;\n }\n\n async next(): Promise<IteratorResult<T>> {\n try {\n return this.nextFn();\n } catch (e) {\n // Modify the error message but leave the stack trace intact\n e.message =\n `Error thrown while iterating through a dataset: ${e.message}`;\n throw e;\n }\n }\n}\n\nclass SerialIterator<T> extends LazyIterator<T> {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise<IteratorResult<T>>;\n\n constructor(protected upstream: LazyIterator<T>) {\n super();\n this.lastRead = Promise.resolve({value: null, done: false});\n }\n\n summary() {\n return `${this.upstream.summary()} -> Serial`;\n }\n\n async next(): Promise<IteratorResult<T>> {\n // This sets this.lastRead to a new Promise right away, as opposed to\n // saying `await this.lastRead; this.lastRead = this.serialNext();` which\n // would not work because this.nextRead would be updated only after the\n // promise resolves.\n this.lastRead = this.lastRead.then(() => this.serialNext());\n return this.lastRead;\n }\n\n private async serialNext(): Promise<IteratorResult<T>> {\n return this.upstream.next();\n }\n}\n\nclass SkipIterator<T> extends LazyIterator<T> {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise<IteratorResult<T>>;\n\n // Local state that should not be clobbered by out-of-order execution.\n count = 0;\n\n constructor(protected upstream: LazyIterator<T>, protected maxCount: number) {\n super();\n this.lastRead = Promise.resolve({value: null, done: false});\n }\n\n summary() {\n return `${this.upstream.summary()} -> Skip`;\n }\n\n async next(): Promise<IteratorResult<T>> {\n // This sets this.lastRead to a new Promise right away, as opposed to\n // saying `await this.lastRead; this.lastRead = this.serialNext();` which\n // would not work because this.nextRead would be updated only after the\n // promise resolves.\n this.lastRead = this.lastRead.then(() => this.serialNext());\n return this.lastRead;\n }\n\n private async serialNext(): Promise<IteratorResult<T>> {\n // TODO(soergel): consider tradeoffs of reading in parallel, eg.\n // collecting next() promises in an Array and then waiting for\n // Promise.all() of those. Benefit: pseudo-parallel execution. Drawback:\n // maybe delayed GC.\n while (this.count++ < this.maxCount) {\n const skipped = await this.upstream.next();\n // short-circuit if upstream is already empty\n if (skipped.done) {\n return skipped;\n }\n tf.dispose(skipped.value as {});\n }\n return this.upstream.next();\n }\n}\n\nclass TakeIterator<T> extends LazyIterator<T> {\n count = 0;\n constructor(protected upstream: LazyIterator<T>, protected maxCount: number) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> Take`;\n }\n\n async next(): Promise<IteratorResult<T>> {\n if (this.count++ >= this.maxCount) {\n return {value: null, done: true};\n }\n return this.upstream.next();\n }\n}\n\n// Note this batch just groups items into row-wise element arrays.\n// Rotating these to a column-wise representation happens only at the dataset\n// level.\nclass RowMajorBatchIterator<T> extends LazyIterator<T[]> {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise<IteratorResult<T[]>>;\n\n constructor(\n protected upstream: LazyIterator<T>, protected batchSize: number,\n protected enableSmallLastBatch = true) {\n super();\n this.lastRead = Promise.resolve({value: null, done: false});\n }\n\n summary() {\n return `${this.upstream.summary()} -> RowMajorBatch`;\n }\n\n async next(): Promise<IteratorResult<T[]>> {\n // This sets this.lastRead to a new Promise right away, as opposed to\n // saying `await this.lastRead; this.lastRead = this.serialNext();` which\n // would not work because this.nextRead would be updated only after the\n // promise resolves.\n this.lastRead = this.lastRead.then(() => this.serialNext());\n return this.lastRead;\n }\n\n private async serialNext(): Promise<IteratorResult<T[]>> {\n const batch: T[] = [];\n while (batch.length < this.batchSize) {\n const item = await this.upstream.next();\n if (item.done) {\n if (this.enableSmallLastBatch && batch.length > 0) {\n return {value: batch, done: false};\n }\n return {value: null, done: true};\n }\n batch.push(item.value);\n }\n return {value: batch, done: false};\n }\n}\n\nclass FilterIterator<T> extends LazyIterator<T> {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise<IteratorResult<T>>;\n\n constructor(\n protected upstream: LazyIterator<T>,\n protected predicate: (value: T) => boolean) {\n super();\n this.lastRead = Promise.resolve({value: null, done: false});\n }\n\n summary() {\n return `${this.upstream.summary()} -> Filter`;\n }\n\n async next(): Promise<IteratorResult<T>> {\n // This sets this.lastRead to a new Promise right away, as opposed to\n // saying `await this.lastRead; this.lastRead = this.serialNext();` which\n // would not work because this.nextRead would be updated only after the\n // promise resolves.\n this.lastRead = this.lastRead.then(() => this.serialNext());\n return this.lastRead;\n }\n\n private async serialNext(): Promise<IteratorResult<T>> {\n while (true) {\n const item = await this.upstream.next();\n if (item.done || this.predicate(item.value)) {\n return item;\n }\n tf.dispose(item.value as {});\n }\n }\n}\n\nclass MapIterator<I, O> extends LazyIterator<O> {\n constructor(\n protected upstream: LazyIterator<I>,\n protected transform: (value: I) => O) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> Map`;\n }\n\n async next(): Promise<IteratorResult<O>> {\n const item = await this.upstream.next();\n if (item.done) {\n return {value: null, done: true};\n }\n const inputTensors = tf.tensor_util.getTensorsInContainer(item.value as {});\n // Careful: the transform may mutate the item in place.\n // That's why we have to remember the input Tensors above, and then\n // below dispose only those that were not passed through to the output.\n // Note too that the transform function is responsible for tidying\n // any intermediate Tensors. Here we are concerned only about the\n // inputs.\n const mapped = this.transform(item.value);\n const outputTensors = tf.tensor_util.getTensorsInContainer(mapped as {});\n\n // TODO(soergel) faster intersection\n // TODO(soergel) move to tf.disposeExcept(in, out)?\n for (const t of inputTensors) {\n if (!tf.tensor_util.isTensorInList(t, outputTensors)) {\n t.dispose();\n }\n }\n return {value: mapped, done: false};\n }\n}\n\nclass ErrorHandlingLazyIterator<T> extends LazyIterator<T> {\n count = 0;\n constructor(\n protected upstream: LazyIterator<T>,\n protected handler: (error: Error) => boolean) {\n super();\n this.lastRead = Promise.resolve({value: null, done: false});\n }\n\n summary() {\n return `${this.upstream.summary()} -> handleErrors`;\n }\n\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise<IteratorResult<T>>;\n\n async next(): Promise<IteratorResult<T>> {\n // This sets this.lastRead to a new Promise right away, as opposed to\n // saying `await this.lastRead; this.lastRead = this.serialNext();` which\n // would not work because this.nextRead would be updated only after the\n // promise resolves.\n this.lastRead = this.lastRead.then(() => this.serialNext());\n return this.lastRead;\n }\n\n async serialNext(): Promise<IteratorResult<T>> {\n while (true) {\n try {\n return await this.upstream.next();\n } catch (e) {\n if (!this.handler(e)) {\n return {value: null, done: true};\n }\n // If the handler returns true, loop and fetch the next upstream item.\n\n // If the upstream iterator throws an endless stream of errors, and if\n // the handler says to ignore them, then we loop forever here. That is\n // the correct behavior-- it's up to the handler to decide when to stop.\n }\n }\n }\n}\n\nclass AsyncMapIterator<I, O> extends LazyIterator<O> {\n constructor(\n protected upstream: LazyIterator<I>,\n protected transform: (value: I) => Promise<O>) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> AsyncMap`;\n }\n\n async next(): Promise<IteratorResult<O>> {\n const item = await this.upstream.next();\n if (item.done) {\n return {value: null, done: true};\n }\n const inputTensors = tf.tensor_util.getTensorsInContainer(item.value as {});\n // Careful: the transform may mutate the item in place.\n // That's why we have to remember the input Tensors above, and then\n // below dispose only those that were not passed through to the output.\n // Note too that the transform function is responsible for tidying\n // any intermediate Tensors. Here we are concerned only about the\n // inputs.\n const mapped = await this.transform(item.value);\n const outputTensors = tf.tensor_util.getTensorsInContainer(mapped as {});\n\n // TODO(soergel) faster intersection\n // TODO(soergel) move to tf.disposeExcept(in, out)?\n for (const t of inputTensors) {\n if (!tf.tensor_util.isTensorInList(t, outputTensors)) {\n t.dispose();\n }\n }\n return {value: mapped, done: false};\n }\n}\n\n// Iterators that maintain a queue of pending items\n// ============================================================================\n\n/**\n * A base class for transforming streams that operate by maintaining an\n * output queue of elements that are ready to return via next(). This is\n * commonly required when the transformation is 1-to-many: A call to next()\n * may trigger a call to the underlying stream, which will produce many\n * mapped elements of this stream-- of which we need to return only one, so\n * we have to queue the rest.\n */\nexport abstract class OneToManyIterator<T> extends LazyIterator<T> {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise<IteratorResult<T>>;\n\n // Local state that should not be clobbered by out-of-order execution.\n protected outputQueue: RingBuffer<T>;\n\n constructor() {\n super();\n this.outputQueue = new GrowingRingBuffer<T>();\n this.lastRead = Promise.resolve({value: null, done: false});\n }\n\n async next(): Promise<IteratorResult<T>> {\n // This sets this.lastRead to a new Promise right away, as opposed to\n // saying `await this.lastRead; this.lastRead = this.serialNext();` which\n // would not work because this.nextRead would be updated only after the\n // promise resolves.\n this.lastRead = this.lastRead.then(() => this.serialNext());\n return this.lastRead;\n }\n\n /**\n * Read one or more chunks from upstream and process them, possibly\n * reading or writing a carryover, and adding processed items to the\n * output queue. Note it's possible that no items are added to the queue\n * on a given pump() call, even if the upstream stream is not closed\n * (e.g., because items are filtered).\n *\n * @return `true` if any action was taken, i.e. fetching items from the\n * upstream source OR adding items to the output queue. `false` if the\n * upstream source is exhausted AND nothing was added to the queue\n * (i.e., any remaining carryover).\n */\n protected abstract async pump(): Promise<boolean>;\n\n async serialNext(): Promise<IteratorResult<T>> {\n // Fetch so that the queue contains at least one item if possible.\n // If the upstream source is exhausted, AND there are no items left in\n // the output queue, then this stream is also exhausted.\n while (this.outputQueue.length() === 0) {\n // TODO(soergel): consider parallel reads.\n if (!await this.pump()) {\n return {value: null, done: true};\n }\n }\n return {value: this.outputQueue.shift(), done: false};\n }\n}\nclass FlatmapIterator<I, O> extends OneToManyIterator<O> {\n constructor(\n protected upstream: LazyIterator<I>,\n protected transform: (value: I) => O[]) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> Flatmap`;\n }\n\n async pump(): Promise<boolean> {\n const item = await this.upstream.next();\n if (item.done) {\n return false;\n }\n const inputTensors = tf.tensor_util.getTensorsInContainer(item.value as {});\n // Careful: the transform may mutate the item in place.\n // that's why we have to remember the input Tensors above, and then\n // below dispose only those that were not passed through to the output.\n // Note too that the transform function is responsible for tidying any\n // intermediate Tensors. Here we are concerned only about the inputs.\n const mappedArray = this.transform(item.value);\n const outputTensors =\n tf.tensor_util.getTensorsInContainer(mappedArray as {});\n this.outputQueue.pushAll(mappedArray);\n\n // TODO(soergel) faster intersection, and deduplicate outputTensors\n // TODO(soergel) move to tf.disposeExcept(in, out)?\n for (const t of inputTensors) {\n if (!tf.tensor_util.isTensorInList(t, outputTensors)) {\n t.dispose();\n }\n }\n\n return true;\n }\n}\n\n/**\n * Provides a `LazyIterator` that concatenates a stream of underlying\n * streams.\n *\n * Doing this in a concurrency-safe way requires some trickery. In\n * particular, we want this stream to return the elements from the\n * underlying streams in the correct order according to when next() was\n * called, even if the resulting Promises resolve in a different order.\n */\nexport class ChainedIterator<T> extends LazyIterator<T> {\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise<IteratorResult<T>> = null;\n\n // Local state that should not be clobbered by out-of-order execution.\n private iterator: LazyIterator<T> = null;\n private moreIterators: LazyIterator<LazyIterator<T>>;\n\n constructor(\n iterators: LazyIterator<LazyIterator<T>>,\n private readonly baseErrorHandler?: (e: Error) => boolean) {\n super();\n this.moreIterators = iterators;\n }\n\n summary() {\n const upstreamSummaries = 'TODO: fill in upstream of chained summaries';\n return `${upstreamSummaries} -> Chained`;\n }\n\n async next(): Promise<IteratorResult<T>> {\n this.lastRead = this.readFromChain(this.lastRead);\n return this.lastRead;\n }\n\n private async readFromChain(lastRead: Promise<IteratorResult<T>>):\n Promise<IteratorResult<T>> {\n // Must await on the previous read since the previous read may have advanced\n // the stream of streams, from which we need to read.\n // This is unfortunate since we can't parallelize reads. Which means\n // prefetching of chained streams is a no-op.\n // One solution is to prefetch immediately upstream of this.\n await lastRead;\n if (this.iterator == null) {\n const iteratorResult = await this.moreIterators.next();\n if (iteratorResult.done) {\n // No more streams to stream from.\n return {value: null, done: true};\n }\n this.iterator = iteratorResult.value;\n if (this.baseErrorHandler != null) {\n this.iterator = this.iterator.handleErrors(this.baseErrorHandler);\n }\n }\n const itemResult = await this.iterator.next();\n if (itemResult.done) {\n this.iterator = null;\n return this.readFromChain(lastRead);\n }\n return itemResult;\n }\n}\n\nexport enum ZipMismatchMode {\n FAIL, // require zipped streams to have the same length\n SHORTEST, // terminate zip when the first stream is exhausted\n LONGEST // use nulls for exhausted streams; use up the longest stream.\n}\n\n/**\n * Provides a `LazyIterator` that zips together an array, dict, or nested\n * structure of `LazyIterator`s (and perhaps additional constants).\n *\n * The underlying streams must provide elements in a consistent order such\n * that they correspond.\n *\n * Typically, the underlying streams should have the same number of\n * elements. If they do not, the behavior is determined by the\n * `mismatchMode` argument.\n *\n * The nested structure of the `iterators` argument determines the\n * structure of elements in the resulting iterator.\n *\n * Doing this in a concurrency-safe way requires some trickery. In\n * particular, we want this stream to return the elements from the\n * underlying streams in the correct order according to when next() was\n * called, even if the resulting Promises resolve in a different order.\n *\n * @param iterators: An array or object containing LazyIterators at the\n * leaves.\n * @param mismatchMode: Determines what to do when one underlying iterator\n * is exhausted before the others. `ZipMismatchMode.FAIL` (the default)\n * causes an error to be thrown in this case. `ZipMismatchMode.SHORTEST`\n * causes the zipped iterator to terminate with the furst underlying\n * streams, so elements remaining on the longer streams are ignored.\n * `ZipMismatchMode.LONGEST` causes the zipped stream to continue, filling\n * in nulls for the exhausted streams, until all streams are exhausted.\n */\nclass ZipIterator<O extends tf.TensorContainer> extends LazyIterator<O> {\n private count = 0;\n private currentPromise: Promise<IteratorResult<O>> = null;\n\n constructor(\n protected readonly iterators: IteratorContainer,\n protected readonly mismatchMode: ZipMismatchMode = ZipMismatchMode.FAIL) {\n super();\n }\n\n summary() {\n const upstreamSummaries = 'TODO: fill in upstream of zip summaries';\n return `{${upstreamSummaries}} -> Zip`;\n }\n\n private async nextState(afterState: Promise<IteratorResult<O>>):\n Promise<IteratorResult<O>> {\n // This chaining ensures that the underlying next() are not even called\n // before the previous ones have resolved.\n await afterState;\n\n // Collect underlying iterator \"done\" signals as a side effect in\n // getNext()\n let numIterators = 0;\n let iteratorsDone = 0;\n\n function getNext(container: IteratorContainer): DeepMapAsyncResult {\n if (container instanceof LazyIterator) {\n const result = container.next();\n return {\n value: result.then(x => {\n numIterators++;\n if (x.done) {\n iteratorsDone++;\n }\n return x.value;\n }),\n recurse: false\n };\n } else {\n return {value: null, recurse: true};\n }\n }\n\n const mapped: O = await deepMapAndAwaitAll(this.iterators, getNext);\n\n if (numIterators === iteratorsDone) {\n // The streams have all ended.\n return {value: null, done: true};\n }\n if (iteratorsDone > 0) {\n switch (this.mismatchMode) {\n case ZipMismatchMode.FAIL:\n throw new Error(\n 'Zipped streams should have the same length. ' +\n `Mismatched at element ${this.count}.`);\n case ZipMismatchMode.SHORTEST:\n return {value: null, done: true};\n case ZipMismatchMode.LONGEST:\n default:\n // Continue. The exhausted streams already produced value: null.\n }\n }\n\n this.count++;\n return {value: mapped, done: false};\n }\n\n async next(): Promise<IteratorResult<O>> {\n this.currentPromise = this.nextState(this.currentPromise);\n return this.currentPromise;\n }\n}\n\n// Iterators that maintain a ring buffer of pending promises\n// ============================================================================\n\n/**\n * A stream that prefetches a given number of items from an upstream source,\n * returning them in FIFO order.\n *\n * Note this prefetches Promises, but makes no guarantees about when those\n * Promises resolve.\n */\nexport class PrefetchIterator<T> extends LazyIterator<T> {\n protected buffer: RingBuffer<Promise<IteratorResult<T>>>;\n\n constructor(\n protected upstream: LazyIterator<T>, protected bufferSize: number) {\n super();\n this.buffer = new RingBuffer<Promise<IteratorResult<T>>>(bufferSize);\n }\n\n summary() {\n return `${this.upstream.summary()} -> Prefetch`;\n }\n\n /**\n * Refill the prefetch buffer. Returns only after the buffer is full, or\n * the upstream source is exhausted.\n */\n protected refill() {\n while (!this.buffer.isFull()) {\n const v = this.upstream.next();\n this.buffer.push(v);\n }\n }\n\n next(): Promise<IteratorResult<T>> {\n this.refill();\n // This shift will never throw an error because the buffer is always\n // full after a refill. If the stream is exhausted, the buffer will be\n // full of Promises that will resolve to the end-of-stream signal.\n return this.buffer.shift();\n }\n}\n\n/**\n * A stream that performs a sliding-window random shuffle on an upstream\n * source. This is like a `PrefetchIterator` except that the items are\n * returned in randomized order. Mixing naturally improves as the buffer\n * size increases.\n */\nexport class ShuffleIterator<T> extends PrefetchIterator<T> {\n private readonly random: seedrandom.prng;\n\n // Strict Promise execution order:\n // a next() call may not even begin until the previous one completes.\n private lastRead: Promise<IteratorResult<T>>;\n\n // Local state that should not be clobbered by out-of-order execution.\n private upstreamExhausted = false;\n\n constructor(\n protected upstream: LazyIterator<T>, protected windowSize: number,\n seed?: string) {\n super(upstream, windowSize);\n this.random = seedrandom.alea(seed || tf.util.now().toString());\n this.lastRead = Promise.resolve({value: null, done: false});\n }\n\n async next(): Promise<IteratorResult<T>> {\n // This sets this.lastRead to a new Promise right away, as opposed to\n // saying `await this.lastRead; this.lastRead = this.serialNext();` which\n // would not work because this.nextRead would be updated only after the\n // promise resolves.\n this.lastRead = this.lastRead.then(() => this.serialNext());\n return this.lastRead;\n }\n\n private randomInt(max: number) {\n return Math.floor(this.random() * max);\n }\n\n protected chooseIndex(): number {\n return this.randomInt(this.buffer.length());\n }\n\n async serialNext(): Promise<IteratorResult<T>> {\n // TODO(soergel): consider performance\n if (!this.upstreamExhausted) {\n this.refill();\n }\n while (!this.buffer.isEmpty()) {\n const chosenIndex = this.chooseIndex();\n const result = await this.buffer.shuffleExcise(chosenIndex);\n if (result.done) {\n this.upstreamExhausted = true;\n } else {\n this.refill();\n return result;\n }\n }\n return {value: null, done: true};\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\nimport * as tf from '@tensorflow/tfjs-core';\n\n// tslint:disable:no-any\n\n/**\n * A return value for a mapping function that can be applied via deepMap.\n *\n * If recurse is true, the value should be empty, and iteration will continue\n * into the object or array.\n */\nexport type DeepMapResult = {\n value: any,\n recurse: boolean\n};\n\n/**\n * Apply a mapping function to a nested structure in a recursive manner.\n *\n * The result of the mapping is an object with the same nested structure (i.e.,\n * of arrays and dicts) as the input, except that some subtrees are replaced,\n * according to the results of the mapping function.\n *\n * Mappings are memoized. Thus, if the nested structure contains the same\n * object in multiple positions, the output will contain the same mapped object\n * in those positions. Cycles are not supported, however.\n *\n * @param input: The object to which to apply the mapping function.\n * @param mapFn: A function that expects a single node of the object tree, and\n * returns a `DeepMapResult`. The `DeepMapResult` either provides a\n * replacement value for that node (i.e., replacing the subtree), or indicates\n * that the node should be processed recursively.\n */\nexport function deepMap(input: any, mapFn: (x: any) => DeepMapResult): any|\n any[] {\n return deepMapInternal(input, mapFn);\n}\n\n/**\n * @param seen: A Map of known object mappings (i.e., memoized results of\n * `mapFn()`)\n * @param containedIn: An set containing objects on the reference path currently\n * being processed (used to detect cycles).\n */\nfunction deepMapInternal(\n input: any, mapFn: (x: any) => DeepMapResult,\n seen: Map<any, any> = new Map(), containedIn: Set<{}> = new Set()): any|\n any[] {\n if (input == null) {\n return null;\n }\n if (containedIn.has(input)) {\n throw new Error('Circular references are not supported.');\n }\n if (seen.has(input)) {\n return seen.get(input);\n }\n const result = mapFn(input);\n\n if (result.recurse && result.value !== null) {\n throw new Error(\n 'A deep map function may not return both a value and recurse=true.');\n }\n\n if (!result.recurse) {\n seen.set(input, result.value);\n return result.value;\n } else if (isIterable(input)) {\n // tslint:disable-next-line:no-any\n const mappedIterable: any|any[] = Array.isArray(input) ? [] : {};\n containedIn.add(input);\n for (const k in input) {\n const child = input[k];\n const childResult = deepMapInternal(child, mapFn, seen, containedIn);\n mappedIterable[k] = childResult;\n }\n containedIn.delete(input);\n return mappedIterable;\n } else {\n throw new Error(`Can't recurse into non-iterable type: ${input}`);\n }\n}\n\n// TODO(soergel, kangyizhang) Reconsider naming of deepZip() to avoid confusion\n// with zip()\n\n/**\n * Zip nested structures together in a recursive manner.\n *\n * This has the effect of transposing or pivoting data, e.g. converting it from\n * a row-major representation to a column-major representation.\n *\n * For example, `deepZip([{a: 1, b: 2}, {a: 3, b: 4}])` returns\n * `{a: [1, 3], b: [2, 4]}`.\n *\n * The inputs should all have the same nested structure (i.e., of arrays and\n * dicts). The result is a single object with the same nested structure, where\n * the leaves are arrays collecting the values of the inputs at that location\n * (or, optionally, the result of a custom function applied to those arrays).\n *\n * @param inputs: An array of the objects to zip together.\n * @param zipFn: (optional) A function that expects an array of elements at a\n * single node of the object tree, and returns a `DeepMapResult`. The\n * `DeepMapResult` either provides a result value for that node (i.e.,\n * representing the subtree), or indicates that the node should be processed\n * recursively. The default zipFn recurses as far as possible and places\n * arrays at the leaves.\n */\nexport function deepZip(\n inputs: any[], zipFn: (xs: any[]) => DeepMapResult = zipToList): any|any[] {\n return deepZipInternal(inputs, zipFn);\n}\n\n/**\n * @param containedIn: An set containing objects on the reference path currently\n * being processed (used to detect cycles).\n */\nfunction deepZipInternal(\n inputs: any[], zipFn: (xs: any[]) => DeepMapResult,\n containedIn: Set<{}> = new Set()): any|any[] {\n // The recursion follows the structure of input 0; it's assumed that all the\n // other inputs have the same structure.\n const input = inputs[0];\n if (containedIn.has(input)) {\n throw new Error('Circular references are not supported.');\n }\n const result = zipFn(inputs);\n\n if (result.recurse && result.value !== null) {\n throw new Error(\n 'A deep zip function may not return both a value and recurse=true.');\n }\n\n if (!result.recurse) {\n return result.value;\n } else if (isIterable(input)) {\n // tslint:disable-next-line:no-any\n const mappedIterable: any|any[] = Array.isArray(input) ? [] : {};\n containedIn.add(input);\n for (const k in input) {\n const children = inputs.map(x => x[k]);\n const childResult = deepZipInternal(children, zipFn, containedIn);\n mappedIterable[k] = childResult;\n }\n containedIn.delete(input);\n return mappedIterable;\n } else {\n throw new Error(`Can't recurse into non-iterable type: ${input}`);\n }\n}\n\n// tslint:disable-next-line:no-any\nexport function zipToList(x: any[]): DeepMapResult {\n if (x === null) {\n return null;\n }\n // TODO(soergel): validate array type?\n\n if (isIterable(x[0])) {\n return {value: null, recurse: true};\n } else {\n return {value: x, recurse: false};\n }\n}\n\n/**\n * A return value for an async map function for use with deepMapAndAwaitAll.\n *\n * If recurse is true, the value should be empty, and iteration will continue\n * into the object or array.\n */\nexport type DeepMapAsyncResult = {\n value: Promise<any>,\n recurse: boolean\n};\n\n/**\n * Apply an async mapping function to a nested structure in a recursive manner.\n *\n * This first creates a nested structure of Promises, and then awaits all of\n * those, resulting in a single Promise for a resolved nested structure.\n *\n * The result of the mapping is an object with the same nested structure (i.e.,\n * of arrays and dicts) as the input, except that some subtrees are replaced,\n * according to the results of the mapping function.\n *\n * Mappings are memoized. Thus, if the nested structure contains the same\n * object in multiple positions, the output will contain the same mapped object\n * in those positions. Cycles are not supported, however.\n *\n * @param input: The object to which to apply the mapping function.\n * @param mapFn: A function that expects a single node of the object tree, and\n * returns a `DeepMapAsyncResult`. The `DeepMapAsyncResult` either provides\n * a `Promise` for a replacement value for that node (i.e., replacing the\n * subtree), or indicates that the node should be processed recursively. Note\n * that the decision whether or not to recurse must be made immediately; only\n * the mapped value may be promised.\n */\nexport async function deepMapAndAwaitAll(\n input: any, mapFn: (x: any) => DeepMapAsyncResult): Promise<any|any[]> {\n const seen: Map<any, Promise<any>> = new Map();\n\n // First do a normal deepMap, collecting Promises in 'seen' as a side effect.\n deepMapInternal(input, mapFn, seen);\n\n // Replace the Promises in 'seen' in place.\n // Note TypeScript provides no async map iteration, and regular map iteration\n // is broken too, so sadly we have to do Array.from() to make it work.\n // (There's no advantage to Promise.all(), and that would be tricky anyway.)\n for (const key of Array.from(seen.keys())) {\n const value = seen.get(key);\n if (tf.util.isPromise(value)) {\n const mappedValue = await value;\n seen.set(key, mappedValue);\n }\n }\n\n // Normal deepMap again, this time filling in the resolved values.\n // It's unfortunate that we have to do two passes.\n // TODO(soergel): test performance and think harder about a fast solution.\n const result = deepMapInternal(input, mapFn, seen);\n return result;\n}\n\n/**\n * Determine whether the argument is iterable.\n *\n * @returns true if the argument is an array or any non-Tensor object.\n */\n// tslint:disable-next-line:no-any\nexport function isIterable(obj: any): boolean {\n return obj != null && (!ArrayBuffer.isView(obj)) &&\n (Array.isArray(obj) ||\n (typeof obj === 'object' && !(obj instanceof tf.Tensor)));\n}\n\n/**\n * Determine whether the argument can be converted to Tensor.\n *\n * Tensors, primitives, arrays, and TypedArrays all qualify; anything else does\n * not.\n *\n * @returns true if the argument can be converted to Tensor.\n */\n// tslint:disable-next-line:no-any\nexport function canTensorify(obj: any): boolean {\n return obj == null || isPrimitive(obj) || Array.isArray(obj) ||\n (typeof obj === 'object' && (obj instanceof tf.Tensor)) ||\n tf.util.isTypedArray(obj);\n}\n\n/**\n * Returns true if the given `value` is a primitive type. Otherwise returns\n * false. This is equivalant to node util.isPrimitive\n */\nfunction isPrimitive(value: any): boolean {\n return (\n value === null ||\n (typeof value !== 'object' && typeof value !== 'function'));\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\nimport * as tf from '@tensorflow/tfjs-core';\nimport {deepMap, DeepMapResult, isIterable} from './deep_map';\n\nexport function deepClone<T>(container: T): T {\n return deepMap(container, cloneIfTensor);\n}\n\n// tslint:disable-next-line: no-any\nfunction cloneIfTensor(item: any): DeepMapResult {\n if (item instanceof tf.Tensor) {\n return ({value: item.clone(), recurse: false});\n } else if (isIterable(item)) {\n return {value: null, recurse: true};\n } else {\n return {value: item, recurse: false};\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/**\n * A ring buffer, providing O(1) FIFO, LIFO, and related operations.\n */\nexport class RingBuffer<T> {\n // Note we store the indices in the range 0 <= index < 2*capacity.\n // This allows us to distinguish the full from the empty case.\n // See https://www.snellman.net/blog/archive/2016-12-13-ring-buffers/\n protected begin = 0; // inclusive\n protected end = 0; // exclusive\n protected doubledCapacity: number;\n\n protected data: T[];\n\n /**\n * Constructs a `RingBuffer`.\n * @param capacity The number of items that the buffer can accomodate.\n */\n constructor(public capacity: number) {\n if (capacity == null) {\n throw new RangeError('Can\\'t create a ring buffer of unknown capacity.');\n }\n if (capacity < 1) {\n throw new RangeError('Can\\'t create ring buffer of capacity < 1.');\n }\n this.data = new Array<T>(capacity);\n this.doubledCapacity = 2 * capacity;\n }\n\n /**\n * Map any index into the range 0 <= index < 2*capacity.\n */\n protected wrap(index: number) {\n // don't trust % on negative numbers\n while (index < 0) {\n index += this.doubledCapacity;\n }\n return index % this.doubledCapacity;\n }\n\n protected get(index: number) {\n if (index < 0) {\n throw new RangeError('Can\\'t get item at a negative index.');\n }\n return this.data[index % this.capacity];\n }\n\n protected set(index: number, value: T) {\n if (index < 0) {\n throw new RangeError('Can\\'t set item at a negative index.');\n }\n this.data[index % this.capacity] = value;\n }\n\n /**\n * Returns the current number of items in the buffer.\n */\n length(): number {\n let length = this.end - this.begin;\n if (length < 0) {\n length = this.doubledCapacity + length;\n }\n return length;\n }\n\n /**\n * Reports whether the buffer is full.\n * @returns true if the number of items in the buffer equals its capacity, and\n * false otherwise.\n */\n isFull() {\n return this.length() === this.capacity;\n }\n\n /**\n * Reports whether the buffer is empty.\n * @returns true if the number of items in the buffer equals zero, and\n * false otherwise.\n */\n isEmpty() {\n return this.length() === 0;\n }\n\n /**\n * Adds an item to the end of the buffer.\n */\n push(value: T) {\n if (this.isFull()) {\n throw new RangeError('Ring buffer is full.');\n }\n this.set(this.end, value);\n this.end = this.wrap(this.end + 1);\n }\n\n /**\n * Adds many items to the end of the buffer, in order.\n */\n pushAll(values: T[]) {\n for (const value of values) {\n this.push(value);\n }\n }\n\n /**\n * Removes and returns the last item in the buffer.\n */\n pop(): T {\n if (this.isEmpty()) {\n throw new RangeError('Ring buffer is empty.');\n }\n this.end = this.wrap(this.end - 1);\n const result = this.get(this.end);\n this.set(this.end, undefined);\n return result;\n }\n\n /**\n * Adds an item to the beginning of the buffer.\n */\n unshift(value: T) {\n if (this.isFull()) {\n throw new RangeError('Ring buffer is full.');\n }\n this.begin = this.wrap(this.begin - 1);\n this.set(this.begin, value);\n }\n\n /**\n * Removes and returns the first item in the buffer.\n */\n shift(): T {\n if (this.isEmpty()) {\n throw new RangeError('Ring buffer is empty.');\n }\n const result = this.get(this.begin);\n this.set(this.begin, undefined);\n this.begin = this.wrap(this.begin + 1);\n return result;\n }\n\n /**\n * Removes and returns a specific item in the buffer, and moves the last item\n * to the vacated slot. This is useful for implementing a shuffling stream.\n * Note that this operation necessarily scrambles the original order.\n *\n * @param relativeIndex: the index of the item to remove, relative to the\n * first item in the buffer (e.g., hiding the ring nature of the underlying\n * storage).\n */\n shuffleExcise(relativeIndex: number): T {\n if (this.isEmpty()) {\n throw new RangeError('Ring buffer is empty.');\n }\n const index = this.wrap(this.begin + relativeIndex);\n const result = this.get(index);\n this.set(index, this.pop());\n return result;\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\nimport {RingBuffer} from './ring_buffer';\n\nexport class GrowingRingBuffer<T> extends RingBuffer<T> {\n private static INITIAL_CAPACITY = 32;\n\n /**\n * Constructs a `GrowingRingBuffer`.\n */\n constructor() {\n super(GrowingRingBuffer.INITIAL_CAPACITY);\n }\n\n isFull() {\n return false;\n }\n\n push(value: T) {\n if (super.isFull()) {\n this.expand();\n }\n super.push(value);\n }\n\n unshift(value: T) {\n if (super.isFull()) {\n this.expand();\n }\n super.unshift(value);\n }\n\n /**\n * Doubles the capacity of the buffer.\n */\n private expand() {\n const newCapacity = this.capacity * 2;\n const newData = new Array<T>(newCapacity);\n const len = this.length();\n\n // Rotate the buffer to start at index 0 again, since we can't just\n // allocate more space at the end.\n for (let i = 0; i < len; i++) {\n newData[i] = this.get(this.wrap(this.begin + i));\n }\n\n this.data = newData;\n this.capacity = newCapacity;\n this.doubledCapacity = 2 * this.capacity;\n this.begin = 0;\n this.end = len;\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\nimport {Dataset} from '../dataset';\nimport {DataSource} from '../datasource';\nimport {LazyIterator} from '../iterators/lazy_iterator';\n\n/**\n * Represents a potentially large collection of text lines.\n *\n * The results are not batched.\n */\nexport class TextLineDataset extends Dataset<string> {\n /**\n * Create a `TextLineDataset`.\n *\n * @param input A `DataSource` providing a chunked, UTF8-encoded byte stream.\n */\n constructor(protected readonly input: DataSource) {\n super();\n }\n\n async iterator(): Promise<LazyIterator<string>> {\n const inputIterator = await this.input.iterator();\n const utf8Iterator = inputIterator.decodeUTF8();\n const lineIterator = utf8Iterator.split('\\n').map(line => {\n // Windows/DOS format text file has extra line breaker at the end of line.\n if (line.endsWith('\\r')) {\n line = line.slice(0, -1);\n }\n return line;\n });\n return lineIterator;\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\nimport {TensorContainer, util} from '@tensorflow/tfjs-core';\nimport {Dataset} from '../dataset';\nimport {DataSource} from '../datasource';\nimport {LazyIterator} from '../iterators/lazy_iterator';\nimport {ColumnConfig, CSVConfig} from '../types';\nimport {TextLineDataset} from './text_line_dataset';\n\nconst CODE_QUOTE = '\"';\nconst STATE_OUT = Symbol('out');\nconst STATE_FIELD = Symbol('field');\nconst STATE_QUOTE = Symbol('quote');\nconst STATE_QUOTE_AFTER_QUOTE = Symbol('quoteafterquote');\nconst STATE_WITHIN_QUOTE_IN_QUOTE = Symbol('quoteinquote');\n\n/**\n * Represents a potentially large collection of delimited text records.\n *\n * The produced `TensorContainer`s each contain one key-value pair for\n * every column of the table. When a field is empty in the incoming data, the\n * resulting value is `undefined`, or throw error if it is required. Values\n * that can be parsed as numbers are emitted as type `number`, other values\n * are parsed as `string`.\n *\n * The results are not batched.\n *\n * @doc {heading: 'Data', subheading: 'Classes', namespace: 'data'}\n */\nexport class CSVDataset extends Dataset<TensorContainer> {\n base: TextLineDataset;\n private hasHeader = true;\n private fullColumnNames: string[] = null;\n private columnNamesValidated = false;\n private columnConfigs: {[key: string]: ColumnConfig} = null;\n private configuredColumnsOnly = false;\n private delimiter = ',';\n private delimWhitespace = false;\n\n /**\n * Returns column names of the csv dataset. If `configuredColumnsOnly` is\n * true, return column names in `columnConfigs`. If `configuredColumnsOnly` is\n * false and `columnNames` is provided, `columnNames`. If\n * `configuredColumnsOnly` is false and `columnNames` is not provided, return\n * all column names parsed from the csv file. For example usage please go to\n * `tf.data.csv`.\n *\n * @doc {heading: 'Data', subheading: 'Classes'}\n */\n async columnNames() {\n if (!this.columnNamesValidated) {\n await this.setColumnNames();\n }\n return this.configuredColumnsOnly ? Object.keys(this.columnConfigs) :\n this.fullColumnNames;\n }\n\n /* 1) If `columnNames` is provided as string[], use this string[] as output\n * keys in corresponding order. The length must match the number of inferred\n * columns if `hasHeader` is true .\n * 2) If `columnNames` is not provided, parse header line as `columnNames` if\n * hasHeader is true. If `hasHeader` is false, throw an error.\n * 3) If `columnConfigs` is provided, all the keys in `columnConfigs` must\n * exist in parsed `columnNames`.\n */\n private async setColumnNames() {\n const columnNamesFromFile = await this.maybeReadHeaderLine();\n if (!this.fullColumnNames && !columnNamesFromFile) {\n // Throw an error if columnNames is not provided and no header line.\n throw new Error(\n 'Column names must be provided if there is no header line.');\n } else if (this.fullColumnNames && columnNamesFromFile) {\n // Check provided columnNames match header line.\n util.assert(\n columnNamesFromFile.length === this.fullColumnNames.length,\n () => 'The length of provided columnNames (' +\n this.fullColumnNames.length.toString() +\n ') does not match the length of the header line read from ' +\n 'file (' + columnNamesFromFile.length.toString() + ').');\n }\n if (!this.fullColumnNames) {\n this.fullColumnNames = columnNamesFromFile;\n }\n // Check if there are duplicate column names.\n const counts: {[key: string]: number} = this.fullColumnNames.reduce(\n (countAcc: {[key: string]: number}, name) => {\n countAcc[name] = (countAcc[name] + 1) || 1;\n return countAcc;\n },\n {});\n const duplicateNames =\n Object.keys(counts).filter((name) => (counts[name] > 1));\n util.assert(\n duplicateNames.length === 0,\n () => 'Duplicate column names found: ' + duplicateNames.toString());\n // Check if keys in columnConfigs match columnNames.\n if (this.columnConfigs) {\n for (const key of Object.keys(this.columnConfigs)) {\n const index = this.fullColumnNames.indexOf(key);\n if (index === -1) {\n throw new Error(\n 'The key \"' + key +\n '\" provided in columnConfigs does not match any of the column ' +\n 'names (' + this.fullColumnNames.toString() + ').');\n }\n }\n }\n this.columnNamesValidated = true;\n }\n\n private async maybeReadHeaderLine() {\n if (this.hasHeader) {\n const iter = await this.base.iterator();\n const firstElement = await iter.next();\n if (firstElement.done) {\n throw new Error('No data was found for CSV parsing.');\n }\n const firstLine: string = firstElement.value;\n const headers = this.parseRow(firstLine, false);\n return headers;\n } else {\n return null;\n }\n }\n\n /**\n * Create a `CSVDataset`.\n *\n * @param input A `DataSource` providing a chunked, UTF8-encoded byte stream.\n * @param csvConfig (Optional) A CSVConfig object that contains configurations\n * of reading and decoding from CSV file(s).\n *\n * hasHeader: (Optional) A boolean value that indicates whether the first\n * row of provided CSV file is a header line with column names, and should\n * not be included in the data. Defaults to `true`.\n *\n * columnNames: (Optional) A list of strings that corresponds to\n * the CSV column names, in order. If provided, it ignores the column\n * names inferred from the header row. If not provided, infers the column\n * names from the first row of the records. If hasHeader is false and\n * columnNames is not provided, this method throws an error.\n *\n * columnConfigs: (Optional) A dictionary whose key is column names, value\n * is an object stating if this column is required, column's data type,\n * default value, and if this column is label. If provided, keys must\n * correspond to names provided in columnNames or inferred from the file\n * header lines. If isLabel is true any column, returns an array of two\n * items: the first item is a dict of features key/value pairs, the second\n * item is a dict of labels key/value pairs. If no feature is marked as\n * label, returns a dict of features only.\n *\n * configuredColumnsOnly (Optional) If true, only columns provided in\n * columnConfigs will be parsed and provided during iteration.\n *\n * delimiter (Optional) The string used to parse each line of the input\n * file. Defaults to `,`.\n */\n constructor(protected readonly input: DataSource, csvConfig?: CSVConfig) {\n super();\n this.base = new TextLineDataset(input);\n if (!csvConfig) {\n csvConfig = {};\n }\n this.hasHeader = csvConfig.hasHeader === false ? false : true;\n this.fullColumnNames = csvConfig.columnNames;\n this.columnConfigs = csvConfig.columnConfigs;\n this.configuredColumnsOnly = csvConfig.configuredColumnsOnly;\n if (csvConfig.delimWhitespace) {\n util.assert(\n csvConfig.delimiter == null,\n () =>\n 'Delimiter should not be provided when delimWhitespace is true.');\n this.delimWhitespace = true;\n this.delimiter = ' ';\n } else {\n this.delimiter = csvConfig.delimiter ? csvConfig.delimiter : ',';\n }\n }\n\n async iterator(): Promise<LazyIterator<TensorContainer>> {\n if (!this.columnNamesValidated) {\n await this.setColumnNames();\n }\n let lines = await this.base.iterator();\n if (this.hasHeader) {\n // We previously read the first line to get the columnNames.\n // Now that we're providing data, skip it.\n lines = lines.skip(1);\n }\n return lines.map(x => this.makeDataElement(x));\n }\n\n makeDataElement(line: string): TensorContainer {\n const values = this.parseRow(line);\n const features: {[key: string]: TensorContainer} = {};\n const labels: {[key: string]: TensorContainer} = {};\n\n for (let i = 0; i < this.fullColumnNames.length; i++) {\n const key = this.fullColumnNames[i];\n const config = this.columnConfigs ? this.columnConfigs[key] : null;\n if (this.configuredColumnsOnly && !config) {\n // This column is not selected.\n continue;\n } else {\n const value = values[i];\n let parsedValue = null;\n if (value === '') {\n // If default value is provided, use it. If default value is not\n // provided, set as undefined.\n if (config && config.default !== undefined) {\n parsedValue = config.default;\n } else if (config && (config.required || config.isLabel)) {\n throw new Error(\n `Required column ${key} is empty in this line: ${line}`);\n } else {\n parsedValue = undefined;\n }\n } else {\n // A value is present, so parse it based on type\n const valueAsNum = Number(value);\n if (isNaN(valueAsNum)) {\n // The value is a string and this column is declared as boolean\n // in config, parse it as boolean.\n if (config && config.dtype === 'bool') {\n parsedValue = this.getBoolean(value);\n } else {\n // Set value as string\n parsedValue = value;\n }\n } else if (!config || !config.dtype) {\n // If this value is a number and no type config is provided, return\n // it as number.\n parsedValue = valueAsNum;\n } else {\n // If this value is a number and data type is provided, parse it\n // according to provided data type.\n switch (config.dtype) {\n case 'float32':\n parsedValue = valueAsNum;\n break;\n case 'int32':\n parsedValue = Math.floor(valueAsNum);\n break;\n case 'bool':\n parsedValue = this.getBoolean(value);\n break;\n default:\n parsedValue = valueAsNum;\n }\n }\n }\n // Check if this column is label.\n (config && config.isLabel) ? labels[key] = parsedValue :\n features[key] = parsedValue;\n }\n }\n // If label exists, return an object of features and labels as {xs:features,\n // ys:labels}, otherwise return features only.\n if (Object.keys(labels).length === 0) {\n return features;\n\n } else {\n return {xs: features, ys: labels};\n }\n }\n\n private getBoolean(value: string): number {\n if (value === '1' || value.toLowerCase() === 'true') {\n return 1;\n } else {\n return 0;\n }\n }\n\n // adapted from https://beta.observablehq.com/@mbostock/streaming-csv\n private parseRow(line: string, validateElementCount = true): string[] {\n const result: string[] = [];\n let readOffset = 0;\n const readLength = line.length;\n let currentState = STATE_OUT;\n // Goes through the line to parse quote.\n for (let i = 0; i < readLength; i++) {\n switch (currentState) {\n // Before enter a new field\n case STATE_OUT:\n switch (line.charAt(i)) {\n // Enter a quoted field\n case CODE_QUOTE:\n readOffset = i + 1;\n currentState = STATE_QUOTE;\n break;\n // Read an empty field\n case this.delimiter:\n readOffset = i + 1;\n // If delimiter is white space and configured to collapse\n // multiple white spaces, ignore this white space.\n if (this.delimiter === ' ' && this.delimWhitespace) {\n break;\n }\n result.push('');\n currentState = STATE_OUT;\n break;\n // Enter an unquoted field\n default:\n currentState = STATE_FIELD;\n readOffset = i;\n break;\n }\n break;\n // In an unquoted field\n case STATE_FIELD:\n switch (line.charAt(i)) {\n // Exit an unquoted field, add it to result\n case this.delimiter:\n result.push(line.substring(readOffset, i));\n currentState = STATE_OUT;\n readOffset = i + 1;\n break;\n default:\n }\n break;\n // In a quoted field\n case STATE_QUOTE:\n switch (line.charAt(i)) {\n // Read a quote after a quote\n case CODE_QUOTE:\n currentState = STATE_QUOTE_AFTER_QUOTE;\n break;\n default:\n }\n break;\n // This state means it's right after a second quote in a field\n case STATE_QUOTE_AFTER_QUOTE:\n switch (line.charAt(i)) {\n // Finished a quoted field\n case this.delimiter:\n result.push(line.substring(readOffset, i - 1));\n currentState = STATE_OUT;\n readOffset = i + 1;\n break;\n // Finished a quoted part in a quoted field\n case CODE_QUOTE:\n currentState = STATE_QUOTE;\n break;\n // In a quoted part in a quoted field\n default:\n currentState = STATE_WITHIN_QUOTE_IN_QUOTE;\n break;\n }\n break;\n case STATE_WITHIN_QUOTE_IN_QUOTE:\n switch (line.charAt(i)) {\n // Exit a quoted part in a quoted field\n case CODE_QUOTE:\n currentState = STATE_QUOTE;\n break;\n default:\n }\n break;\n default:\n }\n }\n // Adds last item based on if it is quoted.\n if (currentState === STATE_QUOTE_AFTER_QUOTE) {\n result.push(line.substring(readOffset, readLength - 1));\n } else {\n result.push(line.substring(readOffset));\n }\n // Check if each row has the same number of elements as column names.\n if (validateElementCount && result.length !== this.fullColumnNames.length) {\n throw new Error(`Invalid row in csv file. Should have ${\n this.fullColumnNames.length} elements in a row, but got ${result}`);\n }\n return result;\n }\n}\n\n// TODO(soergel): add more basic datasets for parity with tf.data\n// tf.data.FixedLengthRecordDataset()\n// tf.data.TFRecordDataset()\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\nimport {env, Tensor, tensor, Tensor2D, Tensor3D, TensorContainer, util} from '@tensorflow/tfjs-core';\nimport {MicrophoneConfig} from '../types';\nimport {LazyIterator} from './lazy_iterator';\n\n/**\n * Provide a stream of tensors from microphone audio stream. The tensors are\n * representing audio data as frequency-domain spectrogram generated with\n * browser's native FFT. Tensors representing time-domain waveform is available\n * based on configuration. Only works in browser environment.\n */\nexport class MicrophoneIterator extends LazyIterator<TensorContainer> {\n private isClosed = false;\n private stream: MediaStream;\n private readonly fftSize: number;\n private readonly columnTruncateLength: number;\n private freqData: Float32Array;\n private timeData: Float32Array;\n private readonly numFrames: number;\n private analyser: AnalyserNode;\n private audioContext: AudioContext;\n private sampleRateHz: number;\n private readonly audioTrackConstraints: MediaTrackConstraints;\n private readonly smoothingTimeConstant: number;\n private readonly includeSpectrogram: boolean;\n private readonly includeWaveform: boolean;\n\n private constructor(protected readonly microphoneConfig: MicrophoneConfig) {\n super();\n this.fftSize = microphoneConfig.fftSize || 1024;\n const fftSizeLog2 = Math.log2(this.fftSize);\n if (this.fftSize < 0 || fftSizeLog2 < 4 || fftSizeLog2 > 14 ||\n !Number.isInteger(fftSizeLog2)) {\n throw new Error(\n `Invalid fftSize: it must be a power of 2 between ` +\n `2 to 4 and 2 to 14, but got ${this.fftSize}`);\n }\n\n this.numFrames = microphoneConfig.numFramesPerSpectrogram || 43;\n this.sampleRateHz = microphoneConfig.sampleRateHz;\n this.columnTruncateLength =\n microphoneConfig.columnTruncateLength || this.fftSize;\n this.audioTrackConstraints = microphoneConfig.audioTrackConstraints;\n this.smoothingTimeConstant = microphoneConfig.smoothingTimeConstant || 0;\n\n this.includeSpectrogram =\n microphoneConfig.includeSpectrogram === false ? false : true;\n this.includeWaveform =\n microphoneConfig.includeWaveform === true ? true : false;\n if (!this.includeSpectrogram && !this.includeWaveform) {\n throw new Error(\n 'Both includeSpectrogram and includeWaveform are false. ' +\n 'At least one type of data should be returned.');\n }\n }\n\n summary() {\n return `microphone`;\n }\n\n // Construct a MicrophoneIterator and start the audio stream.\n static async create(microphoneConfig: MicrophoneConfig = {}) {\n if (env().get('IS_NODE')) {\n throw new Error(\n 'microphone API is only supported in browser environment.');\n }\n\n const microphoneIterator = new MicrophoneIterator(microphoneConfig);\n\n // Call async function start() to initialize the audio stream.\n await microphoneIterator.start();\n\n return microphoneIterator;\n }\n\n // Start the audio stream and FFT.\n async start(): Promise<void> {\n try {\n this.stream = await navigator.mediaDevices.getUserMedia({\n audio: this.audioTrackConstraints == null ? true :\n this.audioTrackConstraints,\n video: false\n });\n } catch (e) {\n throw new Error(\n `Error thrown while initializing video stream: ${e.message}`);\n }\n\n if (!this.stream) {\n throw new Error('Could not obtain audio from microphone.');\n }\n\n const ctxConstructor =\n // tslint:disable-next-line:no-any\n (window as any).AudioContext || (window as any).webkitAudioContext;\n this.audioContext = new ctxConstructor();\n\n if (!this.sampleRateHz) {\n // If sample rate is not provided, use the available sample rate on\n // device.\n this.sampleRateHz = this.audioContext.sampleRate;\n } else if (this.audioContext.sampleRate !== this.sampleRateHz) {\n throw new Error(\n `Mismatch in sampling rate: ` +\n `Expected: ${this.sampleRateHz}; ` +\n `Actual: ${this.audioContext.sampleRate}`);\n }\n\n const streamSource = this.audioContext.createMediaStreamSource(this.stream);\n this.analyser = this.audioContext.createAnalyser();\n this.analyser.fftSize = this.fftSize * 2;\n this.analyser.smoothingTimeConstant = this.smoothingTimeConstant;\n streamSource.connect(this.analyser);\n this.freqData = new Float32Array(this.fftSize);\n this.timeData = new Float32Array(this.fftSize);\n return;\n }\n\n async next(): Promise<IteratorResult<TensorContainer>> {\n if (this.isClosed) {\n return {value: null, done: true};\n }\n\n let spectrogramTensor: Tensor;\n let waveformTensor: Tensor;\n\n const audioDataQueue = await this.getAudioData();\n if (this.includeSpectrogram) {\n const freqData = this.flattenQueue(audioDataQueue.freqDataQueue);\n spectrogramTensor = this.getTensorFromAudioDataArray(\n freqData, [this.numFrames, this.columnTruncateLength, 1]);\n }\n if (this.includeWaveform) {\n const timeData = this.flattenQueue(audioDataQueue.timeDataQueue);\n waveformTensor = this.getTensorFromAudioDataArray(\n timeData, [this.numFrames * this.fftSize, 1]);\n }\n\n return {\n value: {'spectrogram': spectrogramTensor, 'waveform': waveformTensor},\n done: false\n };\n }\n\n // Capture one result from the audio stream, and extract the value from\n // iterator.next() result.\n async capture(): Promise<{spectrogram: Tensor3D, waveform: Tensor2D}> {\n return (await this.next()).value as\n {spectrogram: Tensor3D, waveform: Tensor2D};\n }\n\n private async getAudioData():\n Promise<{freqDataQueue: Float32Array[], timeDataQueue: Float32Array[]}> {\n const freqDataQueue: Float32Array[] = [];\n const timeDataQueue: Float32Array[] = [];\n let currentFrames = 0;\n return new Promise(resolve => {\n const intervalID = setInterval(() => {\n if (this.includeSpectrogram) {\n this.analyser.getFloatFrequencyData(this.freqData);\n // If the audio stream is initializing, return empty queue.\n if (this.freqData[0] === -Infinity) {\n resolve({freqDataQueue, timeDataQueue});\n }\n freqDataQueue.push(this.freqData.slice(0, this.columnTruncateLength));\n }\n if (this.includeWaveform) {\n this.analyser.getFloatTimeDomainData(this.timeData);\n timeDataQueue.push(this.timeData.slice());\n }\n\n // Clean interval and return when all frames have been collected\n if (++currentFrames === this.numFrames) {\n clearInterval(intervalID);\n resolve({freqDataQueue, timeDataQueue});\n }\n }, this.fftSize / this.sampleRateHz * 1e3);\n });\n }\n\n // Stop the audio stream and pause the iterator.\n stop(): void {\n if (!this.isClosed) {\n this.isClosed = true;\n this.analyser.disconnect();\n this.audioContext.close();\n if (this.stream != null && this.stream.getTracks().length > 0) {\n this.stream.getTracks()[0].stop();\n }\n }\n }\n\n // Override toArray() function to prevent collecting.\n toArray(): Promise<Tensor[]> {\n throw new Error('Can not convert infinite audio stream to array.');\n }\n\n // Return audio sampling rate in Hz\n getSampleRate(): number {\n return this.sampleRateHz;\n }\n\n private flattenQueue(queue: Float32Array[]): Float32Array {\n const frameSize = queue[0].length;\n const freqData = new Float32Array(queue.length * frameSize);\n queue.forEach((data, i) => freqData.set(data, i * frameSize));\n return freqData;\n }\n\n private getTensorFromAudioDataArray(freqData: Float32Array, shape: number[]):\n Tensor {\n const vals = new Float32Array(util.sizeFromShape(shape));\n // If the data is less than the output shape, the rest is padded with zeros.\n vals.set(freqData, vals.length - freqData.length);\n return tensor(vals, shape);\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\nimport {browser, cast, env, expandDims, image, reshape, tensor1d, Tensor1D, tensor2d, Tensor2D, Tensor3D, Tensor4D, tidy, util} from '@tensorflow/tfjs-core';\nimport {WebcamConfig} from '../types';\nimport {LazyIterator} from './lazy_iterator';\n\n/**\n * Provide a stream of image tensors from webcam video stream. Only works in\n * browser environment.\n */\nexport class WebcamIterator extends LazyIterator<Tensor3D> {\n private isClosed = true;\n private stream: MediaStream;\n private resize = false;\n private cropSize: [number, number];\n private cropBox: Tensor2D;\n private cropBoxInd: Tensor1D;\n\n private constructor(\n protected readonly webcamVideoElement: HTMLVideoElement,\n protected readonly webcamConfig: WebcamConfig) {\n super();\n if (this.needToResize()) {\n this.resize = true;\n this.cropSize =\n [this.webcamConfig.resizeHeight, this.webcamConfig.resizeWidth];\n this.cropBoxInd = tensor1d([0], 'int32');\n if (this.webcamConfig.centerCrop) {\n // Calculate the box based on resizing shape.\n const widthCroppingRatio =\n this.webcamConfig.resizeWidth * 1.0 / this.webcamVideoElement.width;\n const heightCroppingRatio = this.webcamConfig.resizeHeight * 1.0 /\n this.webcamVideoElement.height;\n const widthCropStart = (1 - widthCroppingRatio) / 2;\n const heightCropStart = (1 - heightCroppingRatio) / 2;\n const widthCropEnd = widthCropStart + widthCroppingRatio;\n const heightCropEnd = heightCroppingRatio + heightCropStart;\n this.cropBox = tensor2d(\n [heightCropStart, widthCropStart, heightCropEnd, widthCropEnd],\n [1, 4]);\n } else {\n this.cropBox = tensor2d([0, 0, 1, 1], [1, 4]);\n }\n }\n }\n\n summary() {\n return `webcam`;\n }\n\n // Construct a WebcamIterator and start it's video stream.\n static async create(\n webcamVideoElement?: HTMLVideoElement, webcamConfig: WebcamConfig = {}) {\n if (env().get('IS_NODE')) {\n throw new Error(\n 'tf.data.webcam is only supported in browser environment.');\n }\n\n if (!webcamVideoElement) {\n // If webcam video element is not provided, create a hidden video element\n // with provided width and height.\n webcamVideoElement = document.createElement('video');\n if (!webcamConfig.resizeWidth || !webcamConfig.resizeHeight) {\n throw new Error(\n 'Please provide webcam video element, or resizeWidth and ' +\n 'resizeHeight to create a hidden video element.');\n }\n webcamVideoElement.width = webcamConfig.resizeWidth;\n webcamVideoElement.height = webcamConfig.resizeHeight;\n }\n const webcamIterator = new WebcamIterator(webcamVideoElement, webcamConfig);\n\n // Call async function to initialize the video stream.\n await webcamIterator.start();\n\n return webcamIterator;\n }\n\n // Async function to start video stream.\n async start(): Promise<void> {\n if (this.webcamConfig.facingMode) {\n util.assert(\n (this.webcamConfig.facingMode === 'user') ||\n (this.webcamConfig.facingMode === 'environment'),\n () =>\n `Invalid webcam facing mode: ${this.webcamConfig.facingMode}. ` +\n `Please provide 'user' or 'environment'`);\n }\n\n try {\n this.stream = await navigator.mediaDevices.getUserMedia({\n video: {\n deviceId: this.webcamConfig.deviceId,\n facingMode: this.webcamConfig.facingMode ?\n this.webcamConfig.facingMode :\n 'user',\n width: this.webcamVideoElement.width,\n height: this.webcamVideoElement.height\n }\n });\n } catch (e) {\n // Modify the error message but leave the stack trace intact\n e.message = `Error thrown while initializing video stream: ${e.message}`;\n throw e;\n }\n\n if (!this.stream) {\n throw new Error('Could not obtain video from webcam.');\n }\n\n // Older browsers may not have srcObject\n try {\n this.webcamVideoElement.srcObject = this.stream;\n } catch (error) {\n console.log(error);\n this.webcamVideoElement.src = window.URL.createObjectURL(this.stream);\n }\n // Start the webcam video stream\n this.webcamVideoElement.play();\n\n this.isClosed = false;\n\n return new Promise<void>(resolve => {\n // Add event listener to make sure the webcam has been fully initialized.\n this.webcamVideoElement.onloadedmetadata = () => {\n resolve();\n };\n });\n }\n\n async next(): Promise<IteratorResult<Tensor3D>> {\n if (this.isClosed) {\n return {value: null, done: true};\n }\n\n let img;\n try {\n img = browser.fromPixels(this.webcamVideoElement);\n } catch (e) {\n throw new Error(\n `Error thrown converting video to pixels: ${JSON.stringify(e)}`);\n }\n if (this.resize) {\n try {\n return {value: this.cropAndResizeFrame(img), done: false};\n } catch (e) {\n throw new Error(`Error thrown cropping the video: ${e.message}`);\n } finally {\n img.dispose();\n }\n } else {\n return {value: img, done: false};\n }\n }\n\n private needToResize() {\n // If resizeWidth and resizeHeight are provided, and different from the\n // width and height of original HTMLVideoElement, then resizing and cropping\n // is required.\n if (this.webcamConfig.resizeWidth && this.webcamConfig.resizeHeight &&\n (this.webcamVideoElement.width !== this.webcamConfig.resizeWidth ||\n this.webcamVideoElement.height !== this.webcamConfig.resizeHeight)) {\n return true;\n }\n return false;\n }\n\n // Cropping and resizing each frame based on config\n cropAndResizeFrame(img: Tensor3D): Tensor3D {\n return tidy(() => {\n const expandedImage: Tensor4D = expandDims(cast(img, 'float32'), (0));\n let resizedImage;\n resizedImage = image.cropAndResize(\n expandedImage, this.cropBox, this.cropBoxInd, this.cropSize,\n 'bilinear');\n // Extract image from batch cropping.\n const shape = resizedImage.shape;\n return reshape(resizedImage, shape.slice(1) as [number, number, number]);\n });\n }\n\n // Capture one frame from the video stream, and extract the value from\n // iterator.next() result.\n async capture(): Promise<Tensor3D> {\n return (await this.next()).value;\n }\n\n // Stop the video stream and pause webcam iterator.\n stop(): void {\n const tracks = this.stream.getTracks();\n\n tracks.forEach(track => track.stop());\n\n try {\n this.webcamVideoElement.srcObject = null;\n } catch (error) {\n console.log(error);\n this.webcamVideoElement.src = null;\n }\n this.isClosed = true;\n }\n\n // Override toArray() function to prevent collecting.\n toArray(): Promise<Tensor3D[]> {\n throw new Error('Can not convert infinite video stream to array.');\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\nimport {ByteChunkIterator} from './iterators/byte_chunk_iterator';\n\n/**\n * Represents a data source readable as a stream of binary data chunks.\n *\n * Because `Dataset`s can be read repeatedly (via `Dataset.iterator()`), this\n * provides a means to repeatedly create streams from the underlying data\n * sources.\n */\nexport abstract class DataSource {\n /**\n * Obtain a new stream of binary data chunks.\n *\n * Starts the new stream from the beginning of the data source, even if other\n * streams have been obtained previously.\n */\n abstract async iterator(): Promise<ByteChunkIterator>;\n\n // TODO(soergel): consider chainable Dataset construction here\n}\n\n// TODO(soergel): consider convenience factory functions here\n// in combination with chainable source->dataset above, e.g.:\n// tf.data.url(...).asCsvDataset().shuffle().batch()\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\nimport {LazyIterator, OneToManyIterator} from './lazy_iterator';\n\nexport abstract class StringIterator extends LazyIterator<string> {\n /**\n * Splits a string stream on a given separator.\n *\n * It is assumed that the incoming chunk boundaries have no semantic meaning,\n * so conceptually the incoming stream is treated simply as the concatenation\n * of its elements.\n *\n * The outgoing stream provides chunks corresponding to the results of the\n * standard string split() operation (even if such a chunk spanned incoming\n * chunks). The separators are not included.\n *\n * A typical usage is to split a text file (represented as a stream with\n * arbitrary chunk boundaries) into lines.\n *\n * @param upstream A readable stream of strings that can be treated as\n * concatenated.\n * @param separator A character to split on.\n */\n split(separator: string): StringIterator {\n return new SplitIterator(this, separator);\n }\n}\n\n// ============================================================================\n// The following private classes serve to implement the chainable methods\n// on StringIterator. Unfortunately they can't be placed in separate files, due\n// to resulting trouble with circular imports.\n// ============================================================================\n\n// We wanted multiple inheritance, e.g.\n// class SplitIterator extends QueueIterator<string>, StringIterator\n// but the TypeScript mixin approach is a bit hacky, so we take this adapter\n// approach instead.\n\nclass SplitIterator extends StringIterator {\n private impl: SplitIteratorImpl;\n\n constructor(protected upstream: LazyIterator<string>, separator: string) {\n super();\n this.impl = new SplitIteratorImpl(upstream, separator);\n }\n\n summary() {\n return this.impl.summary();\n }\n\n async next() {\n return this.impl.next();\n }\n}\n\nclass SplitIteratorImpl extends OneToManyIterator<string> {\n // A partial string at the end of an upstream chunk\n carryover = '';\n\n constructor(\n protected upstream: LazyIterator<string>, protected separator: string) {\n super();\n }\n\n summary() {\n return `${this.upstream.summary()} -> Split('${this.separator}')`;\n }\n\n async pump(): Promise<boolean> {\n const chunkResult = await this.upstream.next();\n if (chunkResult.done) {\n if (this.carryover === '') {\n return false;\n }\n\n // Pretend that the pump succeeded in order to emit the small last batch.\n // The next pump() call will actually fail.\n this.outputQueue.push(this.carryover);\n this.carryover = '';\n return true;\n }\n const lines = chunkResult.value.split(this.separator);\n // Note the behavior: \" ab \".split(' ') === ['', 'ab', '']\n // Thus the carryover may be '' if the separator falls on a chunk\n // boundary; this produces the correct result.\n\n lines[0] = this.carryover + lines[0];\n for (const line of lines.slice(0, -1)) {\n this.outputQueue.push(line);\n }\n this.carryover = lines[lines.length - 1];\n\n return true;\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\nimport {env} from '@tensorflow/tfjs-core';\nimport {LazyIterator, OneToManyIterator} from './lazy_iterator';\nimport {StringIterator} from './string_iterator';\n\nexport abstract class ByteChunkIterator extends LazyIterator<Uint8Array> {\n /**\n * Decode a stream of UTF8-encoded byte arrays to a stream of strings.\n *\n * The byte arrays producetd from the ByteChunkIterator on which this is\n * called will be interpreted as concatenated. No assumptions are made about\n * the boundaries of the incoming chunks, so a multi-byte UTF8 encoding of a\n * character may span the boundary between chunks. This naturally happens,\n * for instance, when reading fixed-size byte arrays from a file.\n */\n decodeUTF8(): StringIterator {\n return new Utf8Iterator(this);\n }\n}\n\n// ============================================================================\n// The following private classes serve to implement the chainable methods\n// on ByteChunkIterator. Unfortunately they can't be placed in separate files,\n// due to resulting trouble with circular imports.\n// ============================================================================\n\n// We wanted multiple inheritance, e.g.\n// class Utf8Iterator extends QueueIterator<string>, StringIterator\n// but the TypeScript mixin approach is a bit hacky, so we take this adapter\n// approach instead.\n\nclass Utf8Iterator extends StringIterator {\n private impl: Utf8IteratorImpl;\n\n constructor(protected upstream: LazyIterator<Uint8Array>) {\n super();\n this.impl = new Utf8IteratorImpl(upstream);\n }\n\n summary() {\n return this.impl.summary();\n }\n\n async next() {\n return this.impl.next();\n }\n}\n\n/**\n * Decode a stream of UTF8-encoded byte arrays to a stream of strings.\n *\n * This is tricky because the incoming byte array boundaries may disrupt a\n * multi-byte UTF8 character. Thus any incomplete character data at the end of\n * a chunk must be carried over and prepended to the next chunk before\n * decoding. Luckily with native decoder, TextDecoder in browser and\n * string_decoder in node, byte array boundaries are handled automatically.\n *\n * In the context of an input pipeline for machine learning, UTF8 decoding is\n * needed to parse text files containing training examples or prediction\n * requests (e.g., formatted as CSV or JSON). We cannot use the built-in\n * decoding provided by FileReader.readAsText() because here we are in a\n * streaming context, which FileReader does not support.\n *\n * @param upstream A `LazyIterator` of `Uint8Arrays` containing UTF8-encoded\n * text, which should be interpreted as concatenated. No assumptions are\n * made about the boundaries of the incoming chunks, so a multi-byte UTF8\n * encoding of a character may span the boundary between chunks. This\n * naturally happens, for instance, when reading fixed-size byte arrays from a\n * file.\n */\nclass Utf8IteratorImpl extends OneToManyIterator<string> {\n // `decoder` as `any` here to dynamically assign value based on the\n // environment.\n // tslint:disable-next-line:no-any\n decoder: any;\n\n constructor(protected readonly upstream: LazyIterator<Uint8Array>) {\n super();\n if (env().get('IS_BROWSER')) {\n this.decoder = new TextDecoder('utf-8');\n } else {\n // tslint:disable-next-line:no-require-imports\n const {StringDecoder} = require('string_decoder');\n this.decoder = new StringDecoder('utf8');\n }\n }\n summary() {\n return `${this.upstream.summary()} -> Utf8`;\n }\n\n async pump(): Promise<boolean> {\n const chunkResult = await this.upstream.next();\n let chunk;\n if (chunkResult.done) {\n return false;\n } else {\n chunk = chunkResult.value;\n }\n\n let text: string;\n if (env().get('IS_BROWSER')) {\n text = this.decoder.decode(chunk, {stream: true});\n } else {\n text = this.decoder.write(Buffer.from(chunk.buffer));\n }\n this.outputQueue.push(text);\n return true;\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// inspired by https://github.com/maxogden/filereader-stream\nimport {env, util} from '@tensorflow/tfjs-core';\nimport {FileElement} from '../types';\nimport {ByteChunkIterator} from './byte_chunk_iterator';\n\nexport interface FileChunkIteratorOptions {\n /** The byte offset at which to begin reading the File or Blob. Default 0. */\n offset?: number;\n /** The number of bytes to read at a time. Default 1MB. */\n chunkSize?: number;\n}\n\n/**\n * Provide a stream of chunks from a File, Blob, or Uint8Array.\n * @param file The source File, Blob or Uint8Array.\n * @param options Optional settings controlling file reading.\n * @returns a lazy Iterator of Uint8Arrays containing sequential chunks of the\n * input File, Blob or Uint8Array.\n */\nexport class FileChunkIterator extends ByteChunkIterator {\n offset: number;\n chunkSize: number;\n\n constructor(\n protected file: FileElement,\n protected options: FileChunkIteratorOptions = {}) {\n super();\n util.assert(\n (file instanceof Uint8Array) ||\n (env().get('IS_BROWSER') ?\n (file instanceof File || file instanceof Blob) :\n false),\n () => 'FileChunkIterator only supports File, Blob and Uint8Array ' +\n 'right now.');\n this.offset = options.offset || 0;\n // default 1MB chunk has tolerable perf on large files\n this.chunkSize = options.chunkSize || 1024 * 1024;\n }\n\n summary() {\n return `FileChunks ${this.file}`;\n }\n\n async next(): Promise<IteratorResult<Uint8Array>> {\n if (this.offset >= ((this.file instanceof Uint8Array) ?\n this.file.byteLength :\n this.file.size)) {\n return {value: null, done: true};\n }\n const chunk = new Promise<Uint8Array>((resolve, reject) => {\n const end = this.offset + this.chunkSize;\n if (this.file instanceof Uint8Array) {\n // Note if end > this.uint8Array.byteLength, we just get a small last\n // chunk.\n resolve(new Uint8Array(this.file.slice(this.offset, end)));\n } else {\n // This branch assumes that this.file type is File or Blob, which\n // means it is in the browser environment.\n\n // TODO(soergel): is this a performance issue?\n const fileReader = new FileReader();\n fileReader.onload = (event) => {\n let data: string|ArrayBuffer|Uint8Array = fileReader.result;\n // Not sure we can trust the return type of\n // FileReader.readAsArrayBuffer See e.g.\n // https://github.com/node-file-api/FileReader/issues/2\n if (data instanceof ArrayBuffer) {\n data = new Uint8Array(data);\n }\n if (!(data instanceof Uint8Array)) {\n return reject(new TypeError('FileReader returned unknown type.'));\n }\n resolve(data);\n };\n fileReader.onabort = (event) => {\n return reject(new Error('Aborted'));\n };\n fileReader.onerror = (event) => {\n return reject(new Error(event.type));\n };\n // TODO(soergel): better handle onabort, onerror\n // Note if end > this.file.size, we just get a small last chunk.\n const slice = this.file.slice(this.offset, end);\n // We can't use readAsText here (even if we know the file is text)\n // because the slice boundary may fall within a multi-byte character.\n fileReader.readAsArrayBuffer(slice);\n }\n this.offset = end;\n });\n return {value: (await chunk), done: false};\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\nimport {util} from '@tensorflow/tfjs-core';\nimport {FileChunkIterator, FileChunkIteratorOptions} from './file_chunk_iterator';\n\n/**\n * Provide a stream of chunks from a URL.\n *\n * Note this class first downloads the entire file into memory before providing\n * the first element from the stream. This is because the Fetch API does not\n * yet reliably provide a reader stream for the response body.\n */\nexport async function urlChunkIterator(\n url: RequestInfo, options: FileChunkIteratorOptions = {}) {\n let urlString;\n let requestInit;\n if ((typeof url) === 'string') {\n urlString = url as string;\n } else {\n urlString = (url as Request).url;\n requestInit = getRequestInitFromRequest(url as Request);\n }\n const response = await util.fetch(urlString, requestInit);\n if (response.ok) {\n const uint8Array = new Uint8Array(await response.arrayBuffer());\n return new FileChunkIterator(uint8Array, options);\n } else {\n throw new Error(response.statusText);\n }\n}\n\n// Generate RequestInit from Request to match tf.util.fetch signature.\nconst getRequestInitFromRequest = (request: Request) => {\n const init = {\n method: request.method,\n headers: request.headers,\n body: request.body,\n mode: request.mode,\n credentials: request.credentials,\n cache: request.cache,\n redirect: request.redirect,\n referrer: request.referrer,\n integrity: request.integrity,\n };\n return init;\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// Skip tslint any type check cause this method is aiming to check type of\n// input.\n// tslint:disable-next-line:no-any\nexport function isLocalPath(source: any): boolean {\n return (typeof source === 'string') && source.substr(0, 7) === 'file://';\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\nimport {env} from '@tensorflow/tfjs-core';\nimport {DataSource} from '../datasource';\nimport {ByteChunkIterator} from '../iterators/byte_chunk_iterator';\nimport {FileChunkIterator, FileChunkIteratorOptions} from '../iterators/file_chunk_iterator';\nimport {FileElement} from '../types';\nimport {isLocalPath} from '../util/source_util';\n\n/**\n * Represents a file, blob, or Uint8Array readable as a stream of binary data\n * chunks.\n */\nexport class FileDataSource extends DataSource {\n /**\n * Create a `FileDataSource`.\n *\n * @param input Local file path, or `File`/`Blob`/`Uint8Array` object to\n * read. Local file only works in node environment.\n * @param options Options passed to the underlying `FileChunkIterator`s,\n * such as {chunksize: 1024}.\n */\n constructor(\n protected input: FileElement|string,\n protected readonly options: FileChunkIteratorOptions = {}) {\n super();\n }\n\n async iterator(): Promise<ByteChunkIterator> {\n if (isLocalPath(this.input) && env().get('IS_NODE')) {\n // tslint:disable-next-line:no-require-imports\n const fs = require('fs');\n this.input = fs.readFileSync((this.input as string).substr(7));\n }\n // TODO(kangyizhang): Add LocalFileChunkIterator to split local streaming\n // with file in browser.\n return new FileChunkIterator(this.input as FileElement, this.options);\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\nimport {DataSource} from '../datasource';\nimport {ByteChunkIterator} from '../iterators/byte_chunk_iterator';\nimport {FileChunkIteratorOptions} from '../iterators/file_chunk_iterator';\nimport {urlChunkIterator} from '../iterators/url_chunk_iterator';\nimport {isLocalPath} from '../util/source_util';\nimport {FileDataSource} from './file_data_source';\n\n/*\n * Represents a URL readable as a stream of binary data chunks.\n */\nexport class URLDataSource extends DataSource {\n /**\n * Create a `URLDataSource`.\n *\n * @param url A source URL string, or a `Request` object.\n * @param options Options passed to the underlying `FileChunkIterator`s,\n * such as {chunksize: 1024}.\n */\n constructor(\n protected readonly url: RequestInfo,\n protected readonly fileOptions: FileChunkIteratorOptions = {}) {\n super();\n }\n\n // TODO(soergel): provide appropriate caching options. Currently this\n // will download the URL anew for each call to iterator(). Since we have\n // to treat the downloaded file as a blob/buffer anyway, we may as well retain\n // it-- but that raises GC issues. Also we may want a persistent disk cache.\n async iterator(): Promise<ByteChunkIterator> {\n if (isLocalPath(this.url)) {\n return (new FileDataSource(this.url as string, this.fileOptions))\n .iterator();\n } else {\n return urlChunkIterator(this.url, this.fileOptions);\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\nimport {TensorContainer} from '@tensorflow/tfjs-core';\nimport {Dataset, datasetFromIteratorFn} from './dataset';\nimport {CSVDataset} from './datasets/csv_dataset';\nimport {iteratorFromFunction} from './iterators/lazy_iterator';\nimport {MicrophoneIterator} from './iterators/microphone_iterator';\nimport {WebcamIterator} from './iterators/webcam_iterator';\nimport {URLDataSource} from './sources/url_data_source';\nimport {CSVConfig, MicrophoneConfig, WebcamConfig} from './types';\n\n/**\n * Create a `CSVDataset` by reading and decoding CSV file(s) from provided URL\n * or local path if it's in Node environment.\n *\n * Note: If isLabel in columnConfigs is `true` for at least one column, the\n * element in returned `CSVDataset` will be an object of\n * `{xs:features, ys:labels}`: xs is a dict of features key/value pairs, ys\n * is a dict of labels key/value pairs. If no column is marked as label,\n * returns a dict of features only.\n *\n * ```js\n * const csvUrl =\n * 'https://storage.googleapis.com/tfjs-examples/multivariate-linear-regression/data/boston-housing-train.csv';\n *\n * async function run() {\n * // We want to predict the column \"medv\", which represents a median value of\n * // a home (in $1000s), so we mark it as a label.\n * const csvDataset = tf.data.csv(\n * csvUrl, {\n * columnConfigs: {\n * medv: {\n * isLabel: true\n * }\n * }\n * });\n *\n * // Number of features is the number of column names minus one for the label\n * // column.\n * const numOfFeatures = (await csvDataset.columnNames()).length - 1;\n *\n * // Prepare the Dataset for training.\n * const flattenedDataset =\n * csvDataset\n * .map(({xs, ys}) =>\n * {\n * // Convert xs(features) and ys(labels) from object form (keyed by\n * // column name) to array form.\n * return {xs:Object.values(xs), ys:Object.values(ys)};\n * })\n * .batch(10);\n *\n * // Define the model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense({\n * inputShape: [numOfFeatures],\n * units: 1\n * }));\n * model.compile({\n * optimizer: tf.train.sgd(0.000001),\n * loss: 'meanSquaredError'\n * });\n *\n * // Fit the model using the prepared Dataset\n * return model.fitDataset(flattenedDataset, {\n * epochs: 10,\n * callbacks: {\n * onEpochEnd: async (epoch, logs) => {\n * console.log(epoch + ':' + logs.loss);\n * }\n * }\n * });\n * }\n *\n * await run();\n * ```\n *\n * @param source URL or local path to get CSV file. If it's a local path, it\n * must have prefix `file://` and it only works in node environment.\n * @param csvConfig (Optional) A CSVConfig object that contains configurations\n * of reading and decoding from CSV file(s).\n *\n * @doc {\n * heading: 'Data',\n * subheading: 'Creation',\n * namespace: 'data',\n * configParamIndices: [1]\n * }\n */\nexport function csv(\n source: RequestInfo, csvConfig: CSVConfig = {}): CSVDataset {\n return new CSVDataset(new URLDataSource(source), csvConfig);\n}\n\n/**\n * Create a `Dataset` that produces each element by calling a provided function.\n *\n * Note that repeated iterations over this `Dataset` may produce different\n * results, because the function will be called anew for each element of each\n * iteration.\n *\n * Also, beware that the sequence of calls to this function may be out of order\n * in time with respect to the logical order of the Dataset. This is due to the\n * asynchronous lazy nature of stream processing, and depends on downstream\n * transformations (e.g. .shuffle()). If the provided function is pure, this is\n * no problem, but if it is a closure over a mutable state (e.g., a traversal\n * pointer), then the order of the produced elements may be scrambled.\n *\n * ```js\n * let i = -1;\n * const func = () =>\n * ++i < 5 ? {value: i, done: false} : {value: null, done: true};\n * const ds = tf.data.func(func);\n * await ds.forEachAsync(e => console.log(e));\n * ```\n *\n * @param f A function that produces one data element on each call.\n */\nexport function func<T extends TensorContainer>(\n f: () => IteratorResult<T>| Promise<IteratorResult<T>>): Dataset<T> {\n const iter = iteratorFromFunction(f);\n return datasetFromIteratorFn(async () => iter);\n}\n\n/**\n * Create a `Dataset` that produces each element from provided JavaScript\n * generator, which is a function*\n * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generator_functions),\n * or a function that returns an\n * iterator\n * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generator_functions).\n *\n * The returned iterator should have `.next()` function that returns element in\n * format of `{value: TensorContainer, done:boolean}`.\n *\n * Example of creating a dataset from an iterator factory:\n * ```js\n * function makeIterator() {\n * const numElements = 10;\n * let index = 0;\n *\n * const iterator = {\n * next: () => {\n * let result;\n * if (index < numElements) {\n * result = {value: index, done: false};\n * index++;\n * return result;\n * }\n * return {value: index, done: true};\n * }\n * };\n * return iterator;\n * }\n * const ds = tf.data.generator(makeIterator);\n * await ds.forEachAsync(e => console.log(e));\n * ```\n *\n * Example of creating a dataset from a generator:\n * ```js\n * function* dataGenerator() {\n * const numElements = 10;\n * let index = 0;\n * while (index < numElements) {\n * const x = index;\n * index++;\n * yield x;\n * }\n * }\n *\n * const ds = tf.data.generator(dataGenerator);\n * await ds.forEachAsync(e => console.log(e));\n * ```\n *\n * @param generator A Javascript generator function that returns a JavaScript\n * iterator.\n *\n * @doc {\n * heading: 'Data',\n * subheading: 'Creation',\n * namespace: 'data',\n * configParamIndices: [1]\n * }\n */\nexport function generator<T extends TensorContainer>(\n generator: () => Iterator<T>| Promise<Iterator<T>>): Dataset<T> {\n return datasetFromIteratorFn(async () => {\n const gen = await generator();\n return iteratorFromFunction(() => gen.next());\n });\n}\n\n/**\n * Create an iterator that generate `Tensor`s from webcam video stream. This API\n * only works in Browser environment when the device has webcam.\n *\n * Note: this code snippet only works when the device has a webcam. It will\n * request permission to open the webcam when running.\n * ```js\n * const videoElement = document.createElement('video');\n * videoElement.width = 100;\n * videoElement.height = 100;\n * const cam = await tf.data.webcam(videoElement);\n * const img = await cam.capture();\n * img.print();\n * cam.stop();\n * ```\n *\n * @param webcamVideoElement A `HTMLVideoElement` used to play video from\n * webcam. If this element is not provided, a hidden `HTMLVideoElement` will\n * be created. In that case, `resizeWidth` and `resizeHeight` must be\n * provided to set the generated tensor shape.\n * @param webcamConfig A `WebcamConfig` object that contains configurations of\n * reading and manipulating data from webcam video stream.\n *\n * @doc {\n * heading: 'Data',\n * subheading: 'Creation',\n * namespace: 'data',\n * ignoreCI: true\n * }\n */\nexport async function webcam(\n webcamVideoElement?: HTMLVideoElement,\n webcamConfig?: WebcamConfig): Promise<WebcamIterator> {\n return WebcamIterator.create(webcamVideoElement, webcamConfig);\n}\n\n/**\n * Create an iterator that generate frequency-domain spectrogram `Tensor`s from\n * microphone audio stream with browser's native FFT. This API only works in\n * browser environment when the device has microphone.\n *\n * Note: this code snippet only works when the device has a microphone. It will\n * request permission to open the microphone when running.\n * ```js\n * const mic = await tf.data.microphone({\n * fftSize: 1024,\n * columnTruncateLength: 232,\n * numFramesPerSpectrogram: 43,\n * sampleRateHz:44100,\n * includeSpectrogram: true,\n * includeWaveform: true\n * });\n * const audioData = await mic.capture();\n * const spectrogramTensor = audioData.spectrogram;\n * spectrogramTensor.print();\n * const waveformTensor = audioData.waveform;\n * waveformTensor.print();\n * mic.stop();\n * ```\n *\n * @param microphoneConfig A `MicrophoneConfig` object that contains\n * configurations of reading audio data from microphone.\n *\n * @doc {\n * heading: 'Data',\n * subheading: 'Creation',\n * namespace: 'data',\n * ignoreCI: true\n * }\n */\nexport async function microphone(microphoneConfig?: MicrophoneConfig):\n Promise<MicrophoneIterator> {\n return MicrophoneIterator.create(microphoneConfig);\n}\n", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.8.0';\nexport {version};\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 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, DataValues, 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 write(values: backend_util.BackendValues, shape: number[], dtype: DataType):\n DataId {\n if (this.firstUse) {\n this.firstUse = false;\n if (env().get('IS_NODE')) {\n backend_util.warn(\n '\\n============================\\n' +\n 'Hi there \uD83D\uDC4B. Looks like you are running TensorFlow.js in ' +\n 'Node.js. To speed things up dramatically, install our node ' +\n 'backend, which binds to TensorFlow C++, by running ' +\n 'npm i @tensorflow/tfjs-node, ' +\n 'or npm i @tensorflow/tfjs-node-gpu if you have CUDA. ' +\n 'Then call require(\\'@tensorflow/tfjs-node\\'); (-gpu ' +\n 'suffix for CUDA) at the start of your program. ' +\n '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 {} 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 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 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 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 numDataIds(): number {\n return this.data.numDataIds();\n }\n\n async read(dataId: DataId): Promise<backend_util.BackendValues> {\n return this.readSync(dataId);\n }\n 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\n return this.data.get(dataId).values;\n }\n\n bufferSync<R extends Rank>(t: TensorInfo): TensorBuffer<R> {\n const data = this.readSync(t.dataId);\n let decodedData = data as DataValues;\n if (t.dtype === 'string') {\n try {\n // Decode the bytes into string.\n decodedData = (data as Uint8Array[]).map(d => util.decodeString(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, decodedData) as\n TensorBuffer<R>;\n }\n\n makeOutput<T extends Tensor>(\n values: backend_util.BackendValues, shape: number[], dtype: DataType): T {\n const dataId = this.write(values, shape, dtype);\n return engine().makeTensorFromDataId(dataId, shape, dtype, 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 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 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 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 dispose() {}\n\n floatPrecision(): 16|32 {\n return 32;\n }\n\n /** Returns the smallest representable number. */\n epsilon(): number {\n return super.epsilon();\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\n// Shared functionality among backends.\nexport {simpleAbsImpl} from './kernels/Abs';\nexport {addImpl} from './kernels/Add';\nexport {bincountImpl, bincountReduceImpl} from './kernels/Bincount_impl';\nexport {ceilImpl} from './kernels/Ceil';\nexport {concatImpl} from './kernels/Concat_impl';\nexport {equalImpl} from './kernels/Equal';\nexport {expImpl} from './kernels/Exp';\nexport {expm1Impl} from './kernels/Expm1';\nexport {floorImpl} from './kernels/Floor';\nexport {gatherNdImpl} from './kernels/GatherNd_Impl';\nexport {gatherV2Impl} from './kernels/GatherV2_impl';\nexport {greaterImpl} from './kernels/Greater';\nexport {greaterEqualImpl} from './kernels/GreaterEqual';\nexport {lessImpl} from './kernels/Less';\nexport {lessEqualImpl} from './kernels/LessEqual';\nexport {linSpaceImpl} from './kernels/LinSpace_impl';\nexport {logImpl} from './kernels/Log';\nexport {maxImpl} from './kernels/Max_impl';\nexport {maximumImpl} from './kernels/Maximum';\nexport {minimumImpl} from './kernels/Minimum';\nexport {multiplyImpl} from './kernels/Multiply';\nexport {negImpl} from './kernels/Neg';\nexport {notEqualImpl} from './kernels/NotEqual';\nexport {prodImpl} from './kernels/Prod';\nexport {rangeImpl} from './kernels/Range_impl';\nexport {rsqrtImpl} from './kernels/Rsqrt';\nexport {sliceImpl} from './kernels/Slice';\nexport {sparseFillEmptyRowsImpl} from './kernels/SparseFillEmptyRows_impl';\nexport {sparseReshapeImpl} from './kernels/SparseReshape_impl';\nexport {sparseSegmentReductionImpl} from './kernels/SparseSegmentReduction_impl';\nexport {squaredDifferenceImpl} from './kernels/SquaredDifference';\nexport {stridedSliceImpl} from './kernels/StridedSlice_impl';\nexport {stringNGramsImpl} from './kernels/StringNGrams_impl';\nexport {stringSplitImpl} from './kernels/StringSplit_impl';\nexport {stringToHashBucketFastImpl} from './kernels/StringToHashBucketFast_impl';\nexport {subImpl} from './kernels/Sub';\nexport {tileImpl} from './kernels/Tile_impl';\nexport {topKImpl} from './kernels/TopK_impl';\nexport {transposeImpl} from './kernels/Transpose_impl';\nexport {uniqueImpl} from './kernels/Unique_impl';\nexport {ComplexBinaryKernelImpl, SimpleBinaryKernelImpl} from './utils/binary_types';\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Abs, AbsInputs, KernelConfig, KernelFunc, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function simpleAbsImpl(vals: TypedArray): Float32Array {\n const resultValues = new Float32Array(vals.length);\n for (let i = 0; i < vals.length; ++i) {\n resultValues[i] = Math.abs(vals[i]);\n }\n return resultValues;\n}\n\nexport const abs = (args: {inputs: AbsInputs, backend: MathBackendCPU}) => {\n const {x} = args.inputs;\n const cpuBackend = args.backend;\n\n assertNotComplex(x, 'abs');\n\n let resultValues = new Float32Array(util.sizeFromShape(x.shape));\n const values = cpuBackend.data.get(x.dataId).values as TypedArray;\n resultValues = simpleAbsImpl(values);\n\n return cpuBackend.makeOutput(resultValues, x.shape, 'float32');\n};\n\nexport const absConfig: KernelConfig = {\n kernelName: Abs,\n backendName: 'cpu',\n kernelFunc: abs as {} 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, 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 {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 {} 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 {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 {} 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 {} 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 */\nimport {Cast, CastAttrs, CastInputs, 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 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 if (dtype === 'int32') {\n const values = backend.data.get(x.dataId).values as TypedArray;\n const resultValues = Int32Array.from(values);\n return backend.makeTensorInfo(x.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 xVals = backend.data.get(x.dataId).values as TypedArray;\n const zero = util.toTypedArray([0], x.dtype);\n\n const [resultData, resultShape] = createSimpleBinaryKernelImpl(\n (a, b) => (a !== b) ? 1 : 0)(x.shape, [], xVals, zero, 'bool');\n\n return backend.makeTensorInfo(resultShape, 'bool', resultData);\n }\n\n throw new Error(`Error in Cast: failed to cast ${x.dtype} to ${dtype}`);\n}\n\nexport const castConfig: KernelConfig = {\n kernelName: Cast,\n backendName: 'cpu',\n kernelFunc: cast as {} 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, 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 */\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 {buffer, DataType, Rank, TensorBuffer, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function bincountImpl(\n xVals: TypedArray, weightsVals: TypedArray, weightsDtype: DataType,\n weightsShape: number[], size: number): TypedArray {\n const weightsSize = util.sizeFromShape(weightsShape);\n const outVals = util.makeZerosTypedArray(size, weightsDtype) as TypedArray;\n\n for (let i = 0; i < xVals.length; i++) {\n const value = xVals[i];\n if (value < 0) {\n throw new Error('Input x must be non-negative!');\n }\n\n if (value >= size) {\n continue;\n }\n\n if (weightsSize > 0) {\n outVals[value] += weightsVals[i];\n } else {\n outVals[value] += 1;\n }\n }\n\n return outVals;\n}\n\nexport function bincountReduceImpl<R extends Rank>(\n xBuf: TensorBuffer<R>, weightsBuf: TensorBuffer<R>, size: number,\n binaryOutput = false): TensorBuffer<R> {\n const numRows = xBuf.shape[0];\n const numCols = xBuf.shape[1];\n\n const outBuf = buffer([numRows, size], weightsBuf.dtype);\n\n for (let i = 0; i < numRows; i++) {\n for (let j = 0; j < numCols; j++) {\n const value = xBuf.get(i, j);\n if (value < 0) {\n throw new Error('Input x must be non-negative!');\n }\n\n if (value >= size) {\n continue;\n }\n\n if (binaryOutput) {\n outBuf.set(1, i, value);\n } else {\n if (weightsBuf.size > 0) {\n outBuf.set(outBuf.get(i, value) + weightsBuf.get(i, j), i, value);\n } else {\n outBuf.set(outBuf.get(i, value) + 1, i, value);\n }\n }\n }\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 {NumericDataType, 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(op: SimpleUnaryOperation):\n SimpleUnaryImpl {\n return (values, dtype, attrs) => {\n const newValues =\n util.getTypedArrayFromDType(dtype as NumericDataType, 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 {DataType, KernelFunc, TypedArray, UnaryInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\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(\n name: string, op: SimpleUnaryOperation, dtype?: DataType): KernelFunc {\n return ({inputs, attrs, backend}) => {\n const {x} = inputs as UnaryInputs;\n assertNotComplex(x, name);\n if (x.dtype === 'string' || dtype === 'string') {\n throw new Error('unaryKernelFunc does not support string input/output');\n }\n\n const cpuBackend = backend as MathBackendCPU;\n const values = cpuBackend.data.get(x.dataId).values as TypedArray;\n const xSize = util.sizeFromShape(x.shape);\n const $dtype = dtype || x.dtype;\n const newValues = util.getArrayFromDType($dtype, xSize);\n for (let i = 0; i < xSize; ++i) {\n newValues[i] = op(values[i], attrs);\n }\n return cpuBackend.makeTensorInfo(x.shape, $dtype, newValues);\n };\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(\n name: string, unaryImpl: SimpleUnaryImpl, dtype?: DataType): KernelFunc {\n return ({inputs, attrs, backend}) => {\n const {x} = inputs as UnaryInputs;\n assertNotComplex(x, name);\n if (x.dtype === 'string' || dtype === 'string') {\n throw new Error('unaryKernelFunc does not support string input/output');\n }\n\n const cpuBackend = backend as MathBackendCPU;\n const values = cpuBackend.data.get(x.dataId).values as TypedArray;\n const $dtype = dtype || x.dtype;\n const newValues = unaryImpl(values, $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 {Ceil, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const ceilImpl = createSimpleUnaryImpl((xi) => Math.ceil(xi));\nexport const ceil = unaryKernelFuncFromImpl(Ceil, ceilImpl);\n\nexport const ceilConfig: KernelConfig = {\n kernelName: Ceil,\n backendName: 'cpu',\n kernelFunc: ceil,\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 {Equal, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const equalImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a === b) ? 1 : 0);\nexport const equal =\n binaryKernelFunc(Equal, equalImpl, null /* complexImpl */, 'bool');\n\nexport const equalConfig: KernelConfig = {\n kernelName: Equal,\n backendName: 'cpu',\n kernelFunc: equal\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);\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 {Expm1, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const expm1Impl = createSimpleUnaryImpl((xi) => Math.expm1(xi));\nexport const expm1 = unaryKernelFuncFromImpl(Expm1, expm1Impl);\n\nexport const expm1Config: KernelConfig = {\n kernelName: Expm1,\n backendName: 'cpu',\n kernelFunc: expm1,\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 {Floor, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const floorImpl = createSimpleUnaryImpl((xi) => Math.floor(xi));\nexport const floor = unaryKernelFuncFromImpl(Floor, floorImpl);\n\nexport const floorConfig: KernelConfig = {\n kernelName: Floor,\n backendName: 'cpu',\n kernelFunc: floor,\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 {buffer, DataType, Rank, TensorBuffer, TypedArray} from '@tensorflow/tfjs-core';\n\nexport function gatherNdImpl<R extends Rank>(\n indicesData: TypedArray, paramsBuf: TensorBuffer<R>, dtype: DataType,\n numSlices: number, sliceRank: number, sliceSize: number, strides: number[],\n paramsShape: number[], paramsSize: number): TensorBuffer<R> {\n const outBuf = buffer([numSlices, sliceSize], dtype);\n\n for (let i = 0; i < numSlices; i++) {\n const index = [];\n let flattenIndex = 0;\n for (let j = 0; j < sliceRank; j++) {\n const dim = indicesData[i * sliceRank + j];\n flattenIndex += dim * strides[j];\n index.push(dim);\n }\n if (flattenIndex < 0 || flattenIndex >= paramsSize / sliceSize) {\n throw new Error(\n `Invalid indices: ${index} does not index into ${paramsShape}`);\n }\n\n for (let k = 0; k < sliceSize; k++) {\n outBuf.values[i * sliceSize + k] =\n paramsBuf.get(...paramsBuf.indexToLoc(flattenIndex * sliceSize + k));\n }\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 {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 outBuf.values[i] = xBuf.values[originalIndex];\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 {Greater, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const greaterImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a > b) ? 1 : 0);\nexport const greater =\n binaryKernelFunc(Greater, greaterImpl, null /* complexImpl */, 'bool');\n\nexport const greaterConfig: KernelConfig = {\n kernelName: Greater,\n backendName: 'cpu',\n kernelFunc: greater\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 {GreaterEqual, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const greaterEqualImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a >= b) ? 1 : 0);\nexport const greaterEqual = binaryKernelFunc(\n GreaterEqual, greaterEqualImpl, null /* complexImpl */, 'bool');\n\nexport const greaterEqualConfig: KernelConfig = {\n kernelName: GreaterEqual,\n backendName: 'cpu',\n kernelFunc: greaterEqual\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, Less} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const lessImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a < b) ? 1 : 0);\nexport const less =\n binaryKernelFunc(Less, lessImpl, null /* complexImpl */, 'bool');\n\nexport const lessConfig: KernelConfig = {\n kernelName: Less,\n backendName: 'cpu',\n kernelFunc: less\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, LessEqual} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const lessEqualImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => (a <= b) ? 1 : 0);\nexport const lessEqual =\n binaryKernelFunc(LessEqual, lessEqualImpl, null /* complexImpl */, 'bool');\n\nexport const lessEqualConfig: KernelConfig = {\n kernelName: LessEqual,\n backendName: 'cpu',\n kernelFunc: lessEqual\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, util} from '@tensorflow/tfjs-core';\n\nexport function linSpaceImpl(\n start: number, stop: number, num: number): TypedArray {\n const step = (stop - start) / (num - 1);\n\n const values = util.makeZerosTypedArray(num, 'float32');\n values[0] = start;\n for (let i = 1; i < values.length; i++) {\n values[i] = values[i - 1] + step;\n }\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, Log} from '@tensorflow/tfjs-core';\n\nimport {createSimpleUnaryImpl} from '../utils/unary_impl';\nimport {unaryKernelFuncFromImpl} from '../utils/unary_utils';\n\nexport const logImpl = createSimpleUnaryImpl((xi) => Math.log(xi));\nexport const log = unaryKernelFuncFromImpl(Log, logImpl);\n\nexport const logConfig: KernelConfig = {\n kernelName: Log,\n backendName: 'cpu',\n kernelFunc: log,\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 {DataType, KernelConfig, KernelFunc, Neg, TensorInfo, TypedArray, UnaryInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {multiplyImpl} from './Multiply';\n\nexport function negImpl(xVals: TypedArray, xShape: number[], xDtype: DataType):\n [TypedArray, number[]] {\n const minusOne =\n util.createScalarValue(-1 as {} as 'float32', xDtype) as TypedArray;\n return multiplyImpl([], xShape, minusOne, xVals, xDtype);\n}\n\nexport function neg(args: {inputs: UnaryInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n assertNotComplex(x, 'neg');\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const [res, newShape] = negImpl(xVals, x.shape, x.dtype);\n\n return backend.makeTensorInfo(newShape, x.dtype, res);\n}\n\nexport const negConfig: KernelConfig = {\n kernelName: Neg,\n backendName: 'cpu',\n kernelFunc: neg as {} 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, NotEqual} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const notEqualImpl =\n createSimpleBinaryKernelImpl(((a, b) => (a !== b) ? 1 : 0));\nexport const notEqual =\n binaryKernelFunc(NotEqual, notEqualImpl, null /* complexOp */, 'bool');\n\nexport const notEqualConfig: KernelConfig = {\n kernelName: NotEqual,\n backendName: 'cpu',\n kernelFunc: notEqual\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 {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 {} 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, 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 {} 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 {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 {} as KernelFunc\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 {DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function sparseFillEmptyRowsImpl(\n indices: TypedArray, indicesShape: number[], indicesDType: DataType,\n values: TypedArray, valuesDType: DataType, denseShape: TypedArray,\n defaultValue: number):\n [TypedArray, number[], TypedArray, boolean[], number[]] {\n const indicesCount = indicesShape[0];\n const denseRows = denseShape[0];\n\n const emptyRowIndicator: boolean[] = new Array(denseRows);\n const reverseIndexMap: number[] = new Array(indicesCount);\n\n const rank = indicesShape[1];\n\n if (denseRows === 0) {\n if (indicesCount !== 0) {\n throw new Error(`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${indicesCount}`);\n }\n const outputIndices = util.getArrayFromDType(indicesDType, 0) as TypedArray;\n const outputValues = util.getArrayFromDType(valuesDType, 0) as TypedArray;\n return [\n outputIndices, [0, rank], outputValues, emptyRowIndicator, reverseIndexMap\n ];\n }\n\n let rowsAreOrdered = true;\n let lastIndicesRow = 0;\n const csrOffset: number[] = new Array(denseRows).fill(0);\n\n for (let i = 0; i < indicesCount; ++i) {\n // indices is a 2d tensor with shape of [N, rank]\n const row = indices[i * rank];\n if (row < 0) {\n throw new Error(`indices(${i}, 0) is invalid: ${row} < 0`);\n }\n if (row >= denseRows) {\n throw new Error(`indices(${i}, 0) is invalid: ${row} >= ${denseRows}`);\n }\n ++csrOffset[row];\n rowsAreOrdered = rowsAreOrdered && (row >= lastIndicesRow);\n lastIndicesRow = row;\n }\n\n let allRowsFull = true;\n for (let row = 0; row < denseRows; ++row) {\n // csrOffset here describes the number of elements in this dense row\n const rowEmpty = (csrOffset[row] === 0);\n emptyRowIndicator[row] = rowEmpty;\n allRowsFull = allRowsFull && !rowEmpty;\n // In filled version, each row has at least one element.\n csrOffset[row] = Math.max(csrOffset[row], 1);\n // Update csrOffset to represent the number of elements up to and\n // including denseRows + 1:\n // csrOffset[0] == #{elements of row 0}\n // csrOffset[1] == #{elements of row 1} + #{elements of row 0}\n // ..\n // csrOffset[i] == starting index for elements in row i + 1.\n if (row > 0) {\n csrOffset[row] += csrOffset[row - 1];\n }\n }\n\n if (allRowsFull && rowsAreOrdered) {\n const outputIndices: TypedArray = indices;\n const outputValues: TypedArray = values;\n for (let i = 0; i < indicesCount; ++i) {\n reverseIndexMap[i] = i;\n }\n return [\n outputIndices, [indicesCount, rank], outputValues, emptyRowIndicator,\n reverseIndexMap\n ];\n } else {\n const fullIndicesCount = csrOffset[denseRows - 1];\n const outputIndices =\n util.getArrayFromDType(indicesDType, fullIndicesCount * rank) as\n TypedArray;\n const outputValues =\n util.getArrayFromDType(valuesDType, fullIndicesCount) as TypedArray;\n const filledCount: number[] = new Array(denseRows).fill(0);\n\n // Fill in values for rows that are not missing\n for (let i = 0; i < indicesCount; ++i) {\n // indices is a 2d tensor with shape of [N, rank]\n const row = indices[i * rank];\n const offset = filledCount[row];\n const outputI = ((row === 0) ? 0 : csrOffset[row - 1]) + offset;\n filledCount[row]++; // Increment the filled count for this row.\n for (let j = 0; j < rank; ++j) {\n // indices and outputIndices are 2d tensors with shape of [N, rank]\n outputIndices[outputI * rank + j] = indices[i * rank + j];\n }\n outputValues[outputI] = values[i];\n // We'll need this reverse index map to backprop correctly.\n reverseIndexMap[i] = outputI;\n }\n\n // Fill in values for rows that are missing\n for (let row = 0; row < denseRows; ++row) {\n const rowCount = filledCount[row];\n if (rowCount === 0) { // We haven't filled this row\n const startingIndex = (row === 0) ? 0 : csrOffset[row - 1];\n // Remaining index values were set to zero already.\n // Just need to set the row index in the right location.\n // outputIndices is a 2d tensor with shape of [N, rank]\n outputIndices[startingIndex * rank + 0] = row;\n for (let col = 1; col < rank; ++col) {\n outputIndices[startingIndex * rank + col] = 0;\n }\n outputValues[startingIndex] = defaultValue;\n }\n }\n return [\n outputIndices, [fullIndicesCount, rank], outputValues, emptyRowIndicator,\n reverseIndexMap\n ];\n }\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 {DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function sparseReshapeImpl(\n inputIndices: TypedArray, inputIndicesShape: number[], inputDType: DataType,\n inputShape: number[],\n targetShape: number[]): [TypedArray, number[], number[]] {\n const denseSize = util.sizeFromShape(inputShape);\n const nnz = inputIndicesShape[0];\n const outputRank = targetShape.length;\n\n // Compute the output shape. Determine product of specified dimensions, and\n // find the index of the unspecified one.\n const outputShape: number[] = [];\n let product = 1;\n let unknownIndex = -1;\n for (let d = 0; d < outputRank; ++d) {\n const size = targetShape[d];\n if (size === -1) {\n if (unknownIndex !== -1) {\n throw new Error(`only one output dimension may be -1, not both ${\n unknownIndex} and ${d}`);\n }\n unknownIndex = d;\n outputShape.push(1);\n } else {\n if (size < 0) {\n throw new Error(`size ${d} must be non-negative, not ${size}`);\n }\n product *= size;\n outputShape.push(size);\n }\n }\n if (unknownIndex !== -1) {\n if (product <= 0) {\n throw new Error(\n 'reshape cannot infer the missing ' +\n 'input size for an empty tensor unless all ' +\n 'specified input sizes are non-zero');\n }\n const missing = Math.trunc(denseSize / product);\n if (product * missing !== denseSize) {\n throw new Error(`Input to reshape is a SparseTensor with ${denseSize}\n dense values, but the requested shape requires a multiple of ${\n product}. inputShape=${inputShape} outputShape= ${outputShape}`);\n }\n\n outputShape[unknownIndex] = missing;\n }\n const outputSize = util.sizeFromShape(outputShape);\n if (outputSize !== denseSize) {\n throw new Error(`Input to reshape is a tensor with ${\n denseSize} dense values, but the requested shape has ${\n outputSize}. inputShape=${inputShape} outputShape=${outputShape}`);\n }\n\n const inputRank = inputShape.length;\n const inputStrides: number[] = [];\n if (inputRank > 0) {\n inputStrides[inputRank - 1] = 1;\n for (let d = inputRank - 2; d >= 0; --d) {\n inputStrides[d] = inputStrides[d + 1] * inputShape[d + 1];\n }\n }\n\n const outputStrides: number[] = [];\n if (outputRank > 0) {\n outputStrides[outputRank - 1] = 1;\n for (let d = outputRank - 2; d >= 0; --d) {\n outputStrides[d] = outputStrides[d + 1] * outputShape[d + 1];\n }\n }\n\n const newIndices =\n util.getArrayFromDType(inputDType, nnz * outputRank) as TypedArray;\n for (let i = 0; i < nnz; ++i) {\n let id = 0;\n for (let j = 0; j < inputRank; ++j) {\n // inputIndices is a 2d tensor with shape of [nnz, inputRank]\n id += inputIndices[i * inputRank + j] * inputStrides[j];\n }\n for (let j = 0; j < outputRank; ++j) {\n // newIndices is a 2d tensor with shape of [nnz, outputRank]\n newIndices[i * outputRank + j] = Math.trunc(id / outputStrides[j]);\n id %= outputStrides[j];\n }\n }\n return [newIndices, [nnz, outputRank], 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\nimport {DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function sparseSegmentReductionImpl(\n input: TypedArray, inputShape: number[], inputDType: DataType,\n indices: TypedArray, segmentIds: TypedArray, isMean = false,\n defaultValue = 0): [TypedArray, number[]] {\n const numIndices = indices.length;\n if (numIndices !== segmentIds.length) {\n throw new Error(`segmentIds and indices should have same size.`);\n }\n\n // Flatten the array to two dimensions\n const inputFlat: number[] = [inputShape[0], input.length / inputShape[0]];\n const numCol = inputFlat[1];\n // Note that the current implementation assumes that segmentIds values are\n // sorted.\n const lastSegmentIdPlusOne =\n numIndices > 0 ? segmentIds[numIndices - 1] + 1 : 0;\n const outputRows = lastSegmentIdPlusOne;\n\n if (outputRows < 0) {\n throw new Error(`segment ids must be >= 0`);\n }\n\n const outputShape = inputShape.slice();\n outputShape[0] = outputRows;\n\n const outputLength =\n outputShape.reduce((product, value) => product * value, 1);\n // Output array is initialized with the value 0 by default.\n const output = util.getArrayFromDType(inputDType, outputLength) as TypedArray;\n\n // Note that we do not initialize the output buffer with a default value, so\n // we need to explicitly set missing indices to the default value.\n if (numIndices === 0) {\n if (outputRows > 0) {\n output.fill(defaultValue);\n }\n return [output, outputShape];\n }\n\n if (outputRows <= 0) {\n throw new Error(`segment ids must be >= 0`);\n }\n\n let start = 0, end = 1;\n // Index from which the output is not initialized.\n let uninitializedIndex = 0;\n let outIndex = segmentIds[start];\n\n while (true) {\n // We initialize nextIndex to 0 to avoid may be uninitialized warning\n let nextIndex = 0;\n if (end < numIndices) {\n nextIndex = segmentIds[end];\n if (outIndex === nextIndex) {\n ++end;\n continue;\n }\n // We have a new segment here. Verify that the segment ids are growing.\n if (outIndex >= nextIndex) {\n throw new Error(`segment ids are not increasing`);\n }\n }\n\n if (outIndex < 0 || outIndex >= outputRows) {\n throw new Error(`Segment id ${outIndex} out of range [0, ${\n outputRows}), possibly because segmentIds input is not sorted.`);\n }\n\n // If there is a gap between two indices, we need to set that gap to the\n // default value.\n if (outIndex > uninitializedIndex) {\n output.fill(defaultValue, uninitializedIndex * numCol, outIndex * numCol);\n }\n\n for (let i = start; i < end; ++i) {\n const index = indices[i];\n if (index < 0 || index >= inputFlat[0]) {\n throw new Error(`Bad: indices[${i}] == ${indices[i]} out of range [0, ${\n inputFlat[0]})`);\n }\n for (let j = 0; j < numCol; j++) {\n output[outIndex * numCol + j] += input[index * numCol + j];\n }\n }\n\n if (isMean) {\n for (let j = 0; j < numCol; j++) {\n output[outIndex * numCol + j] /= end - start;\n }\n }\n\n start = end;\n ++end;\n uninitializedIndex = outIndex + 1;\n outIndex = nextIndex;\n if (end > numIndices) {\n break;\n }\n }\n\n // Fill the gap at the end with the default value.\n if (uninitializedIndex < outputRows) {\n output.fill(defaultValue, uninitializedIndex * numCol, outputRows * numCol);\n }\n\n return [output, outputShape];\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 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 {util} from '@tensorflow/tfjs-core';\n\n/**\n * The StringNGramsOp class creates ngrams from ragged string data.\n * The constructor contains all attributes related to the operation such as\n * padding widths and strings, and the compute function can be used to\n * compute the ngrams for different ragged tensor inputs.\n */\nclass StringNGramsOp {\n private separator: Uint8Array;\n private nGramWidths: number[];\n private padWidth: number;\n private leftPad: Uint8Array;\n private rightPad: Uint8Array;\n private preserveShort: boolean;\n\n constructor(\n separator: string, nGramWidths: number[], leftPad: string,\n rightPad: string, padWidth: number, preserveShortSequences: boolean) {\n this.separator = util.encodeString(separator);\n this.nGramWidths = nGramWidths;\n this.leftPad = util.encodeString(leftPad);\n this.rightPad = util.encodeString(rightPad);\n this.padWidth = padWidth;\n this.preserveShort = preserveShortSequences;\n }\n\n private getPadWidth(nGramWidth: number) {\n // Ngrams can be padded with either a fixed pad width or a dynamic pad\n // width depending on the 'padWidth' arg, but in no case should the padding\n // ever be wider than 'nGramWidth' - 1.\n return Math.min(\n this.padWidth < 0 ? nGramWidth - 1 : this.padWidth, nGramWidth - 1);\n }\n\n private getNumNGrams(length: number, nGramWidth: number) {\n const padWidth = this.getPadWidth(nGramWidth);\n return Math.max(0, ((length + 2 * padWidth) - nGramWidth) + 1);\n }\n\n private createNGrams(\n data: Uint8Array[], splitIndex: number, output: Uint8Array[],\n outputStartIndex: number, numNGrams: number, nGramWidth: number) {\n for (let nGramIndex = 0; nGramIndex < numNGrams; ++nGramIndex) {\n const padWidth = this.getPadWidth(nGramWidth);\n const leftPadding = Math.max(0, padWidth - nGramIndex);\n const rightPadding =\n Math.max(0, padWidth - (numNGrams - (nGramIndex + 1)));\n const numTokens = nGramWidth - (leftPadding + rightPadding);\n const dataStartIndex =\n splitIndex + (leftPadding > 0 ? 0 : nGramIndex - padWidth);\n\n // Calculate the total expected size of the nGram so we can reserve the\n // correct amount of space in the string.\n let nGramSize = 0;\n // Size of the left padding.\n nGramSize += leftPadding * this.leftPad.length;\n // Size of the tokens.\n for (let n = 0; n < numTokens; ++n) {\n nGramSize += data[dataStartIndex + n].length;\n }\n // Size of the right padding.\n nGramSize += rightPadding * this.rightPad.length;\n // Size of the separators.\n const numSeparators = leftPadding + rightPadding + numTokens - 1;\n nGramSize += numSeparators * this.separator.length;\n\n // Build the nGram.\n output[outputStartIndex + nGramIndex] = new Uint8Array(nGramSize);\n const nGram = output[outputStartIndex + nGramIndex];\n\n let nextNGramIndex = 0;\n const appendToNGram = (str: Uint8Array) =>\n str.forEach((value) => nGram[nextNGramIndex++] = value);\n\n for (let n = 0; n < leftPadding; ++n) {\n appendToNGram(this.leftPad);\n appendToNGram(this.separator);\n }\n // Only output first numTokens - 1 pairs of data and separator\n for (let n = 0; n < numTokens - 1; ++n) {\n appendToNGram(data[dataStartIndex + n]);\n appendToNGram(this.separator);\n }\n // Handle case when there are no tokens or no right padding as these\n // can result in consecutive separators.\n if (numTokens > 0) {\n // If we have tokens, then output last and then pair each separator\n // with the right padding that follows, to ensure nGram ends either with\n // the token or with the right pad.\n appendToNGram(data[dataStartIndex + numTokens - 1]);\n for (let n = 0; n < rightPadding; ++n) {\n appendToNGram(this.separator);\n appendToNGram(this.rightPad);\n }\n } else {\n // If we don't have tokens, then the last item inserted into the nGram\n // has been the separator from the left padding loop above. Hence,\n // output right pad and separator and make sure to finish with a\n // padding, not a separator.\n for (let n = 0; n < rightPadding - 1; ++n) {\n appendToNGram(this.rightPad);\n appendToNGram(this.separator);\n }\n appendToNGram(this.rightPad);\n }\n }\n }\n\n // Data and splits together form the definition of the ragged tensor,\n // where data is 1 dimensional and contains the values of the tensor\n // and splits denotes the indices at which each row starts.\n public compute(data: Uint8Array[], splits: Int32Array):\n [Uint8Array[], Int32Array] {\n // Validate that the splits are valid indices into data, only if there are\n // splits specified.\n const inputDataSize = data.length;\n const splitsSize = splits.length;\n if (splitsSize > 0) {\n let prevSplit = splits[0];\n if (prevSplit !== 0) {\n throw new Error(`First split value must be 0, got ${prevSplit}`);\n }\n for (let i = 1; i < splitsSize; ++i) {\n let validSplits = splits[i] >= prevSplit;\n validSplits = validSplits && (splits[i] <= inputDataSize);\n if (!validSplits) {\n throw new Error(`Invalid split value ${splits[i]}, must be in [${\n prevSplit}, ${inputDataSize}]`);\n }\n prevSplit = splits[i];\n }\n if (prevSplit !== inputDataSize) {\n throw new Error(`Last split value must be data size. Expected ${\n inputDataSize}, got ${prevSplit}`);\n }\n }\n\n const numBatchItems = splitsSize - 1;\n const nGramsSplits = util.getArrayFromDType('int32', splitsSize);\n // If there is no data or size, return an empty ragged tensor.\n if (inputDataSize === 0 || splitsSize === 0) {\n const empty: Uint8Array[] = new Array(inputDataSize);\n for (let i = 0; i <= numBatchItems; ++i) {\n nGramsSplits[i] = 0;\n }\n return [empty, nGramsSplits];\n }\n\n nGramsSplits[0] = 0;\n for (let i = 1; i <= numBatchItems; ++i) {\n const length = splits[i] - splits[i - 1];\n let numNGrams = 0;\n this.nGramWidths.forEach((nGramWidth) => {\n numNGrams += this.getNumNGrams(length, nGramWidth);\n });\n if (this.preserveShort && length > 0 && numNGrams === 0) {\n numNGrams = 1;\n }\n nGramsSplits[i] = nGramsSplits[i - 1] + numNGrams;\n }\n\n const nGrams: Uint8Array[] = new Array(nGramsSplits[numBatchItems]);\n\n for (let i = 0; i < numBatchItems; ++i) {\n const splitIndex = splits[i];\n let outputStartIdx = nGramsSplits[i];\n this.nGramWidths.forEach((nGramWidth) => {\n const length = splits[i + 1] - splits[i];\n const numNGrams = this.getNumNGrams(length, nGramWidth);\n this.createNGrams(\n data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);\n outputStartIdx += numNGrams;\n });\n // If we're preserving short sequences, check to see if no sequence was\n // generated by comparing the current output start idx to the original\n // one (nGramSplitsdata). If no ngrams were generated, then they will\n // be equal (since we increment outputStartIdx by numNGrams every\n // time we create a set of ngrams.)\n if (this.preserveShort && outputStartIdx === nGramsSplits[i]) {\n const dataLength = splits[i + 1] - splits[i];\n // One legitimate reason to not have any ngrams when this.preserveShort\n // is true is if the sequence itself is empty. In that case, move on.\n if (dataLength === 0) {\n continue;\n }\n // We don't have to worry about dynamic padding sizes here: if padding\n // was dynamic, every sequence would have had sufficient padding to\n // generate at least one nGram.\n const nGramWidth = dataLength + 2 * this.padWidth;\n const numNGrams = 1;\n this.createNGrams(\n data, splitIndex, nGrams, outputStartIdx, numNGrams, nGramWidth);\n }\n }\n return [nGrams, nGramsSplits];\n }\n}\n\nexport function stringNGramsImpl(\n data: Uint8Array[], dataSplits: Int32Array, separator: string,\n nGramWidths: number[], leftPad: string, rightPad: string, padWidth: number,\n preserveShortSequences: boolean): [Uint8Array[], Int32Array] {\n return new StringNGramsOp(\n separator, nGramWidths, leftPad, rightPad, padWidth,\n preserveShortSequences)\n .compute(data, dataSplits);\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 {TypedArray, util} from '@tensorflow/tfjs-core';\n\nfunction split(\n str: Uint8Array, delimiters: Uint8Array, skipEmpty: boolean): Uint8Array[] {\n if (!str.length) {\n return [];\n }\n // When the delimiter is empty, the input is split into individual characters.\n if (delimiters.length === 0) {\n const result: Uint8Array[] = new Array(str.length);\n for (let i = 0; i < str.length; ++i) {\n result[i] = str.subarray(i, i + 1);\n }\n return result;\n }\n // When there is one delimiter, the input is split only at that delimiter.\n if (delimiters.length === 1) {\n const delimiter = delimiters[0];\n const result: Uint8Array[] = [];\n let f = str.indexOf(delimiter);\n while (f !== -1) {\n const token = str.subarray(0, f);\n if (!skipEmpty || token.length !== 0) {\n result.push(token);\n }\n str = str.subarray(f + 1);\n f = str.indexOf(delimiter);\n }\n if (!skipEmpty || str.length !== 0) {\n result.push(str);\n }\n return result;\n }\n // When there are multiple delimiters, the input is split at every instance\n // one of the delimiters appears.\n const result: Uint8Array[] = [];\n let tokenStart = 0;\n for (let i = 0; i < str.length + 1; i++) {\n if ((i === str.length) || (delimiters.indexOf(str[i]) !== -1)) {\n const token = str.subarray(tokenStart, i);\n if (!skipEmpty || token.length !== 0) {\n result.push(token);\n }\n tokenStart = i + 1;\n }\n }\n return result;\n}\n\nexport function stringSplitImpl(\n input: Uint8Array[], delimiter: Uint8Array,\n skipEmpty: boolean): [TypedArray, Uint8Array[], [number, number]] {\n const batchSize = input.length;\n\n // Empty delimiter means split the input character by character.\n const tokens: Uint8Array[] = [];\n\n let outputSize = 0;\n let maxNumEntries = 0;\n const numIndices: number[] = new Array(batchSize);\n for (let i = 0; i < batchSize; ++i) {\n const parts = split(input[i], delimiter, skipEmpty);\n const nEntries = parts.length;\n numIndices[i] = nEntries;\n outputSize += nEntries;\n maxNumEntries = Math.max(maxNumEntries, nEntries);\n tokens.push(...parts);\n }\n\n const indices = util.getArrayFromDType('int32', outputSize * 2) as TypedArray;\n const values: Uint8Array[] = new Array(outputSize);\n const shape: [number, number] = [batchSize, maxNumEntries];\n\n let c = 0;\n for (let i = 0; i < batchSize; ++i) {\n for (let j = 0; j < numIndices[i]; ++j) {\n // indices is a 2d tensor with shape of [outputSize, 2]\n indices[c * 2] = i;\n indices[c * 2 + 1] = j;\n values[c] = tokens[c];\n ++c;\n }\n }\n\n return [indices, values, shape];\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 {TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function stringToHashBucketFastImpl(\n input: Uint8Array[], numBuckets: number): TypedArray {\n const output = util.getArrayFromDType('int32', input.length) as TypedArray;\n\n for (let i = 0; i < input.length; ++i) {\n output[i] =\n util.fingerPrint64(input[i]).modulo(numBuckets).getLowBitsUnsigned();\n }\n\n return output;\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\n/** An implementation of the TopK kernel shared between webgl and cpu. */\n\nimport {buffer, NumericDataType, Rank, ShapeMap, Tensor, TensorBuffer, TypedArray, util} from '@tensorflow/tfjs-core';\n\ntype Pair = {\n value: number,\n index: number\n};\n\nconst comparePair = (a: Pair, b: Pair) => {\n const valueDiff = b.value - a.value;\n return valueDiff === 0 ? a.index - b.index : valueDiff;\n};\n\n/**\n * Partitions array where all elements smaller than the (k+1) smallest element\n * are found to the left of it, and all larger to the right of it.\n * Based on the Floyd-Rivest Algorithm, ref:\n * https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm\n * @param array: Array to partition\n * @param left: Left index for the interval\n * @param right: Right index for the interval\n * @param k: Desired index value, where array[k] is the (k+1)th smallest element\n * when left = 0\n */\nfunction select(array: Pair[], k: number, left = 0, right = array.length - 1) {\n while (right > left) {\n // Use select recursively to sample a smaller set of size s\n // the arbitrary constants 600 and 0.5 are used in the original\n // version to minimize execution time.\n if (right - left > 600) {\n const n = right - left + 1;\n const i = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * Math.sign(i - n / 2);\n const newLeft = Math.max(left, Math.floor(k - i * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - i) * s / n + sd));\n select(array, k, newLeft, newRight);\n }\n // partition the elements between left and right around t\n const t = array[k];\n let i = left;\n let j = right;\n\n util.swap(array, left, k);\n\n if (comparePair(array[right], t) > 0) {\n util.swap(array, left, right);\n }\n while (i < j) {\n util.swap(array, i, j);\n i++;\n j--;\n while (comparePair(array[i], t) < 0) {\n i = i + 1;\n }\n while (comparePair(array[j], t) > 0) {\n j = j - 1;\n }\n }\n if (comparePair(array[left], t) === 0) {\n util.swap(array, left, j);\n } else {\n j = j + 1;\n util.swap(array, j, right);\n }\n // Adjust left and right towards the boundaries of the subset\n // containing the (k - left + 1)th smallest element.\n if (j <= k) {\n left = j + 1;\n }\n if (k <= j) {\n right = j - 1;\n }\n }\n}\n\nexport function topKImpl<T extends Tensor, R extends Rank>(\n x: TypedArray, xShape: number[], xDtype: NumericDataType, k: number,\n sorted: boolean):\n [TensorBuffer<R, NumericDataType>, TensorBuffer<R, 'int32'>] {\n // Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.\n const lastDim = xShape[xShape.length - 1];\n const [batch, size] = [x.length / lastDim, lastDim];\n const allTopKVals = util.getTypedArrayFromDType(xDtype, batch * k);\n const allTopKIndices = util.getTypedArrayFromDType('int32', batch * k);\n\n for (let b = 0; b < batch; b++) {\n const offset = b * size;\n const vals = x.subarray(offset, offset + size);\n\n let valAndInd: Pair[] = new Array(vals.length);\n vals.forEach(\n (value: number, index: number) => valAndInd[index] = {value, index});\n\n if (k < valAndInd.length) {\n select(valAndInd, k);\n valAndInd = valAndInd.slice(0, k);\n }\n\n if (sorted) {\n valAndInd.sort(comparePair);\n }\n \n const outOffset = b * k;\n const topKVals = allTopKVals.subarray(outOffset, outOffset + k);\n const topKIndices = allTopKIndices.subarray(outOffset, outOffset + k);\n for (let i = 0; i < k; i++) {\n topKVals[i] = valAndInd[i].value;\n topKIndices[i] = valAndInd[i].index;\n }\n }\n // Reshape back to the original input shape, except that the last\n // dimension is k.\n const outputShape = xShape.slice();\n outputShape[outputShape.length - 1] = k;\n\n return [\n buffer(outputShape as ShapeMap[R], xDtype, allTopKVals),\n buffer(outputShape as ShapeMap[R], 'int32', allTopKIndices)\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 {BackendValues, DataType, TensorBuffer, TypedArray, util} from '@tensorflow/tfjs-core';\n\nexport function uniqueImpl(\n values: BackendValues, axis: number, shape: number[], dtype: DataType): {\n outputValues: BackendValues,\n outputShape: number[],\n indices: BackendValues\n} {\n // Normalize and validate axis.\n const $axis = util.parseAxisParam(axis, shape)[0];\n\n // Calculate the new shape that is suitable for extracting data along the\n // given axis.\n //\n // The rank is 3.\n // The size of the 1st dimension is the size of all the axes < the given axis.\n // The size of the 2nd dimension is the same as the size of the given axis.\n // The size of the 3rd dimension is the size of all the axes > the given axis.\n //\n // For example, for a 4D tensor with shape=[2, 3, 5, 4] and axis=2, the\n // newShape would be: [2*3, 5, 4].\n //\n // Note that this is not the final output shape. This will be the shape for an\n // intermediate TensorBuffer (see inputBuffer below) to allow us to extract\n // values along the given axis. To demonstrate how it works, consider the\n // following example:\n //\n // Input: a 3D tensor, with shape [1, 2, 3]\n // [\n // [\n // [1,2,3],\n // [4,5,6]\n // ]\n // ]\n // Axis: 2 (the last axis).\n // Along axis 2, we expect to extract 3 tensors: [1,4], [2,5], [3,6].\n //\n // For this example, newShape would be: [2, 3, 1], where 2 is calculated from\n // 1*2. The re-shaped data would look like:\n //\n // [\n // [\n // [1], [2], [3]\n // ],\n // [\n // [4], [5], [6]\n // ]\n // ]\n //\n // Then, we can construct a 3-level nested loop by the following dimension\n // order to extract the values along the axis (dimension1):\n // i: dimension1 // 0,1,2 (newShape[1])\n // m: dimension0 // 0,1 (newShape[0])\n // n: dimension2 // 0 (newShape[2])\n //\n // m, i, n\n // ---------\n // Iteration 0: data at [0, 0, 0] => \"1\"\n // Iteration 1: data at [1, 0, 0] => \"4\"\n // We got [1,4].\n // Iteration 2: data at [0, 1, 0] => \"2\"\n // Iteration 3: data at [1, 1, 0] => \"5\"\n // We got [2,5].\n // Iteration 4: data at [0, 2, 0] => \"3\"\n // Iteration 5: data at [1, 2, 0] => \"6\"\n // We got [3,6].\n const newShape = [1, shape[0], 1];\n for (let i = 0; i < $axis; i++) {\n newShape[0] *= shape[i];\n }\n newShape[1] = shape[$axis];\n for (let i = $axis + 1; i < shape.length; i++) {\n newShape[2] *= shape[i];\n }\n\n // A map from unique elements (their string representations) to their values\n // in \"indices\" (below).\n const uniqueElements: {[key: string]: number} = {};\n // The indices of each unique element in the original tensor along the given\n // axis. It is 1D and has the same size as the given axis.\n const indices = new Int32Array(shape[$axis]);\n // Create a buffer so we can easily extract value at a given location.\n const inputBuffer = new TensorBuffer(newShape, dtype, values as TypedArray);\n // The indices along the given axis that have unique elements. This is a\n // de-duped version of \"indices\" above.\n const uniqueIndices: number[] = [];\n const is1DTensor = newShape[0] === 1 && newShape[2] === 1;\n for (let i = 0; i < shape[$axis]; i++) {\n // Extract values along the axis.\n let element: string;\n if (is1DTensor) {\n // Fast path for 1D tensor input.\n element = values[i].toString();\n } else {\n const axisValues = [];\n for (let m = 0; m < newShape[0]; m++) {\n for (let n = 0; n < newShape[2]; n++) {\n axisValues.push(inputBuffer.get(m, i, n));\n }\n }\n element = axisValues.join(',');\n }\n\n // Dedup and update various indices.\n if (uniqueElements[element] !== undefined) {\n indices[i] = uniqueElements[element];\n } else {\n const uniqueIndex = Object.keys(uniqueElements).length;\n uniqueElements[element] = uniqueIndex;\n indices[i] = uniqueIndex;\n uniqueIndices.push(i);\n }\n }\n\n // Now we know where each of the unique elements are located along the axis\n // (uniqueIndices). Extract them from input buffer and store them in the\n // output buffer.\n const outputTmpShape = newShape.slice();\n outputTmpShape[1] = Object.keys(uniqueElements).length;\n const outputBuffer = new TensorBuffer(outputTmpShape, dtype);\n uniqueIndices.forEach((uniqueElementIndex, i) => {\n for (let m = 0; m < newShape[0]; m++) {\n for (let n = 0; n < newShape[2]; n++) {\n outputBuffer.set(inputBuffer.get(m, uniqueElementIndex, n), m, i, n);\n }\n }\n });\n\n // The output shape can be calculated from the input shape with the size of\n // the given axis replaced by the number of unique elements along that axis.\n const outputShape = shape.slice();\n outputShape[$axis] = outputTmpShape[1];\n\n return {\n outputValues: outputBuffer.values as BackendValues,\n outputShape,\n indices,\n };\n}\n", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.8.0';\nexport {version};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Elu, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const elu =\n unaryKernelFunc(Elu, (xi) => xi >= 0 ? xi : (Math.exp(xi) - 1));\n\nexport const eluConfig: KernelConfig = {\n kernelName: Elu,\n backendName: 'cpu',\n kernelFunc: elu,\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, LeakyRelu, LeakyReluAttrs, LeakyReluInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function leakyRelu(args: {\n inputs: LeakyReluInputs,\n backend: MathBackendCPU,\n attrs: LeakyReluAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {alpha} = attrs;\n\n assertNotComplex([x], 'leakyRelu');\n\n const xSize = util.sizeFromShape(x.shape);\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const outVals = util.getTypedArrayFromDType('float32', xSize);\n\n for (let i = 0; i < xVals.length; i++) {\n outVals[i] = xVals[i] < 0 ? alpha * xVals[i] : xVals[i];\n }\n\n return backend.makeTensorInfo(x.shape, 'float32', outVals);\n}\n\nexport const leakyReluConfig: KernelConfig = {\n kernelName: LeakyRelu,\n backendName: 'cpu',\n kernelFunc: leakyRelu as {} 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, Prelu, PreluInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\n\nconst preluImpl = createSimpleBinaryKernelImpl(\n (xValue: number, aValue: number) => xValue < 0 ? aValue * xValue : xValue);\n\nexport function prelu(args: {inputs: PreluInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x, alpha} = inputs;\n\n assertNotComplex([x, alpha], 'prelu');\n\n const aVals = backend.data.get(x.dataId).values as TypedArray;\n const bVals = backend.data.get(alpha.dataId).values as TypedArray;\n\n const [resultData, resultShape] =\n preluImpl(x.shape, alpha.shape, aVals, bVals, x.dtype);\n\n return backend.makeTensorInfo(resultShape, x.dtype, resultData);\n}\n\nexport const preluConfig: KernelConfig = {\n kernelName: Prelu,\n backendName: 'cpu',\n kernelFunc: prelu,\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, Relu} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const relu = unaryKernelFunc(Relu, (xi) => Math.max(0, xi));\n\nexport const reluConfig: KernelConfig = {\n kernelName: Relu,\n backendName: 'cpu',\n kernelFunc: relu,\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, Relu6} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const relu6 =\n unaryKernelFunc(Relu6, (xi) => Math.min(Math.max(0, xi), 6));\n\nexport const relu6Config: KernelConfig = {\n kernelName: Relu6,\n backendName: 'cpu',\n kernelFunc: relu6,\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, Sigmoid} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sigmoid =\n unaryKernelFunc(Sigmoid, (xi) => 1 / (1 + Math.exp(-xi)));\n\nexport const sigmoidConfig: KernelConfig = {\n kernelName: Sigmoid,\n backendName: 'cpu',\n kernelFunc: sigmoid,\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 {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs, backend_util, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {elu} from '../kernels/Elu';\nimport {identity} from '../kernels/Identity';\nimport {leakyRelu} from '../kernels/LeakyRelu';\nimport {prelu} from '../kernels/Prelu';\nimport {relu} from '../kernels/Relu';\nimport {relu6} from '../kernels/Relu6';\nimport {sigmoid} from '../kernels/Sigmoid';\n\nexport function applyActivation(\n backend: MathBackendCPU, x: TensorInfo, activation: backend_util.Activation,\n preluActivationWeights?: TensorInfo, leakyreluAlpha?: number): TensorInfo {\n if (activation === 'linear') {\n return identity({inputs: {x}, backend});\n } else if (activation === 'relu') {\n return relu({inputs: {x}, backend}) as TensorInfo;\n } else if (activation === 'elu') {\n return elu({inputs: {x}, backend}) as TensorInfo;\n } else if (activation === 'relu6') {\n return relu6({inputs: {x}, backend}) as TensorInfo;\n } else if (activation === 'prelu') {\n return prelu({inputs: {x, alpha: preluActivationWeights}, backend});\n } else if (activation === 'leakyrelu') {\n return leakyRelu({inputs: {x}, backend, attrs: {alpha: leakyreluAlpha}});\n } else if (activation === 'sigmoid') {\n return sigmoid({inputs: {x}, backend}) as TensorInfo;\n }\n throw new Error(\n `Activation ${activation} has not been implemented for the CPU backend.`);\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 {} 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, 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 batchDimsCompatible =\n batchDimA === batchDimB || batchDimA === 1 || batchDimB === 1;\n\n util.assert(\n aRank >= 2 && bRank >= 2 && batchDimsCompatible,\n () => `Error in matMul: the input batch dimensions must either be the ` +\n `same or at least one input batch dimension must be 1. Got input ` +\n `batch dimensions of (${outerDimsA}) and (${outerDimsB}).`);\n\n const outShapeOuterDims =\n batchDimA > batchDimB ? 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 for (let i0 = 0; i0 < leftDim; i0 += blockSize) {\n for (let j0 = 0; j0 < rightDim; j0 += blockSize) {\n for (let k0 = 0; k0 < sharedDim; k0 += blockSize) {\n // for when blockSize doesn't evenly divide the input\n const iBlock = Math.min(i0 + blockSize, leftDim);\n const jBlock = Math.min(j0 + blockSize, rightDim);\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 batchOffsetA = Math.min(bi, batchDimA - 1) * aBatch;\n const batchOffsetB = Math.min(bi, batchDimB - 1) * bBatch;\n const aVal =\n a3dValues[batchOffsetA + i * aOuterStep + k * aInnerStep];\n const bVal =\n b3dValues[k * bInnerStep + j * bOuterStep + batchOffsetB];\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 {} 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 {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {applyActivation} from '../utils/fused_utils';\n\nimport {add} from './Add';\nimport {batchMatMul} from './BatchMatMul';\n\nexport function _fusedMatMul(args: {\n inputs: _FusedMatMulInputs,\n attrs: _FusedMatMulAttrs,\n backend: MathBackendCPU\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b, bias, preluActivationWeights} = inputs;\n const {transposeA, transposeB, activation, leakyreluAlpha} = attrs;\n\n let current;\n let addRes;\n let activationRes;\n\n const intermediates: TensorInfo[] = [];\n\n const matMulRes =\n batchMatMul({inputs: {a, b}, attrs: {transposeA, transposeB}, backend});\n current = matMulRes;\n\n if (bias) {\n addRes = add({inputs: {a: current, b: bias}, backend}) as TensorInfo;\n intermediates.push(current);\n current = addRes;\n }\n if (activation) {\n activationRes = applyActivation(\n backend, current, activation, preluActivationWeights, leakyreluAlpha);\n intermediates.push(current);\n current = activationRes;\n }\n\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n\n return current;\n}\n\nexport const _fusedMatMulConfig: KernelConfig = {\n kernelName: _FusedMatMul,\n backendName: 'cpu',\n kernelFunc: _fusedMatMul as {} 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 {Acos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const acos = unaryKernelFunc(Acos, (xi) => Math.acos(xi));\n\nexport const acosConfig: KernelConfig = {\n kernelName: Acos,\n backendName: 'cpu',\n kernelFunc: acos,\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 {Acosh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const acosh = unaryKernelFunc(Acosh, (xi) => Math.acosh(xi));\n\nexport const acoshConfig: KernelConfig = {\n kernelName: Acosh,\n backendName: 'cpu',\n kernelFunc: acosh,\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 {AddN, AddNInputs, buffer, KernelConfig, KernelFunc, Tensor, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function addN(args: {inputs: AddNInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const tensors = inputs as Tensor[];\n\n assertNotComplex(inputs, 'addN');\n\n const vals =\n tensors.map(t => backend.data.get(t.dataId).values as TypedArray);\n const outBuf = buffer(tensors[0].shape, tensors[0].dtype as 'float32');\n const outVals = outBuf.values;\n for (let i = 0; i < tensors.length; i++) {\n const currVals = vals[i];\n for (let j = 0; j < outVals.length; j++) {\n outVals[j] += currVals[j];\n }\n }\n\n return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n}\n\nexport const addNConfig: KernelConfig = {\n kernelName: AddN,\n backendName: 'cpu',\n kernelFunc: addN as {} 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 {All, AllAttrs, AllInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function all(\n args: {inputs: AllInputs, backend: MathBackendCPU, attrs: AllAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n assertNotComplex(x, 'all');\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('all', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n const vals = util.makeZerosTypedArray(util.sizeFromShape(outShape), $x.dtype);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let all = aVals[offset];\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n all = all && value;\n }\n vals[i] = all;\n }\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo($x);\n }\n\n const result = backend.makeTensorInfo(outShape, $x.dtype, vals);\n\n if (keepDims) {\n const expandedShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n const reshapedResult =\n reshape({inputs: {x: result}, backend, attrs: {shape: expandedShape}});\n\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n }\n\n return result;\n}\n\nexport const allConfig: KernelConfig = {\n kernelName: All,\n backendName: 'cpu',\n kernelFunc: all as {} 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 {Any, AnyAttrs, AnyInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function any(\n args: {inputs: AnyInputs, backend: MathBackendCPU, attrs: AnyAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n assertNotComplex(x, 'any');\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('any', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n const vals = util.makeZerosTypedArray(util.sizeFromShape(outShape), $x.dtype);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let anyVal = aVals[offset];\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n anyVal = anyVal || value;\n }\n vals[i] = anyVal;\n }\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo($x);\n }\n\n const result = backend.makeTensorInfo(outShape, $x.dtype, vals);\n\n if (keepDims) {\n const expandedShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n const reshapedResult =\n reshape({inputs: {x: result}, backend, attrs: {shape: expandedShape}});\n\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n }\n\n return result;\n}\n\nexport const anyConfig: KernelConfig = {\n kernelName: Any,\n backendName: 'cpu',\n kernelFunc: any as {} 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 {ArgMax, ArgMaxAttrs, ArgMaxInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {transpose} from './Transpose';\n\nexport function argMax(\n args: {inputs: ArgMaxInputs, backend: MathBackendCPU, attrs: ArgMaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n assertNotComplex(x, 'argMax');\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n axes = [axes[0]];\n backend_util.assertAxesAreInnerMostDims('argMax', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n\n const outSize = util.sizeFromShape(outShape);\n const vals = util.makeZerosTypedArray(outSize, 'int32');\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let max = aVals[offset];\n let maxIndex = 0;\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n if (value > max) {\n max = value;\n maxIndex = j;\n }\n }\n vals[i] = maxIndex;\n }\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n\n return backend.makeTensorInfo(outShape, 'int32', vals);\n}\n\nexport const argMaxConfig: KernelConfig = {\n kernelName: ArgMax,\n backendName: 'cpu',\n kernelFunc: argMax as {} 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 {ArgMin, ArgMinAttrs, ArgMinInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {transpose} from './Transpose';\n\nexport function argMin(\n args: {inputs: ArgMinInputs, backend: MathBackendCPU, attrs: ArgMinAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n assertNotComplex(x, 'argMin');\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n axes = [axes[0]];\n backend_util.assertAxesAreInnerMostDims('argMin', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n\n const outSize = util.sizeFromShape(outShape);\n const vals = util.makeZerosTypedArray(outSize, 'int32');\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let min = aVals[offset];\n let minIndex = 0;\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n if (value < min) {\n min = value;\n minIndex = j;\n }\n }\n vals[i] = minIndex;\n }\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n\n return backend.makeTensorInfo(outShape, 'int32', vals);\n}\n\nexport const argMinConfig: KernelConfig = {\n kernelName: ArgMin,\n backendName: 'cpu',\n kernelFunc: argMin as {} 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 {Asin, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const asin = unaryKernelFunc(Asin, (xi) => Math.asin(xi));\n\nexport const asinConfig: KernelConfig = {\n kernelName: Asin,\n backendName: 'cpu',\n kernelFunc: asin,\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 {Asinh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const asinh = unaryKernelFunc(Asinh, (xi) => Math.asinh(xi));\n\nexport const asinhConfig: KernelConfig = {\n kernelName: Asinh,\n backendName: 'cpu',\n kernelFunc: asinh,\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 {Atan, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const atan = unaryKernelFunc(Atan, (xi) => Math.atan(xi));\n\nexport const atanConfig: KernelConfig = {\n kernelName: Atan,\n backendName: 'cpu',\n kernelFunc: atan,\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 {Atan2, KernelConfig} from '@tensorflow/tfjs-core';\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const atan2Impl = createSimpleBinaryKernelImpl(\n (aValue, bValue) => Math.atan2(aValue as number, bValue as number));\n\nexport const atan2 = binaryKernelFunc(Atan2, atan2Impl);\n\nexport const atan2Config: KernelConfig = {\n kernelName: Atan2,\n backendName: 'cpu',\n kernelFunc: atan2,\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 {Atanh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const atanh = unaryKernelFunc(Atanh, (xi) => Math.atanh(xi));\n\nexport const atanhConfig: KernelConfig = {\n kernelName: Atanh,\n backendName: 'cpu',\n kernelFunc: atanh,\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, buffer, DataType, Rank, TensorBuffer, TypedArray} from '@tensorflow/tfjs-core';\n\nexport function pool(\n xValues: TypedArray, xShape: number[], dtype: DataType, strides: number[],\n convInfo: backend_util.Conv2DInfo,\n poolType: 'max'|'avg'): TensorBuffer<Rank, DataType> {\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n\n const initialValue =\n (poolType === 'max' ? Number.NEGATIVE_INFINITY :\n Number.POSITIVE_INFINITY);\n\n const output = buffer(convInfo.outShape, dtype);\n const outputVals = output.values;\n\n const outputBatchStrides =\n convInfo.outShape[1] * convInfo.outShape[2] * convInfo.outShape[3];\n const outputRowStrides = convInfo.outShape[2] * convInfo.outShape[3];\n const outputColStrides = convInfo.outShape[3];\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const outputBatchOffset = b * outputBatchStrides;\n const inputBatchOffset = b * strides[0];\n for (let d = 0; d < convInfo.inChannels; ++d) {\n for (let yR = 0; yR < convInfo.outHeight; ++yR) {\n const xRCorner = yR * strideHeight - padTop;\n const xRMin = Math.max(0, xRCorner);\n const xRMax =\n Math.min(convInfo.inHeight, effectiveFilterHeight + xRCorner);\n const outputRowOffset = outputBatchOffset + yR * outputRowStrides;\n for (let yC = 0; yC < convInfo.outWidth; ++yC) {\n const xCCorner = yC * strideWidth - padLeft;\n const xCMin = Math.max(0, xCCorner);\n const xCMax =\n Math.min(convInfo.inWidth, effectiveFilterWidth + xCCorner);\n let minMaxValue = initialValue;\n let avgValue = 0;\n let count = 0;\n for (let xR = xRMin; xR < xRMax; xR += dilationHeight) {\n const xROffset = inputBatchOffset + xR * strides[1];\n for (let xC = xCMin; xC < xCMax; xC += dilationWidth) {\n const xCOffset = xROffset + xC * strides[2];\n const pixel = xValues[xCOffset + d];\n if ((poolType === 'max' && pixel > minMaxValue)) {\n minMaxValue = pixel;\n } else if (poolType === 'avg') {\n avgValue += pixel;\n count++;\n }\n }\n if (isNaN(minMaxValue)) {\n break;\n }\n }\n const outputOffset = outputRowOffset + yC * outputColStrides + d;\n outputVals[outputOffset] =\n poolType === 'avg' ? avgValue / count : minMaxValue;\n }\n }\n }\n }\n return output;\n}\n\nexport function maxPoolPositions(\n xValues: TypedArray, xShape: number[], dtype: DataType,\n convInfo: backend_util.Conv2DInfo, flattenPositions = false,\n includeBatchInIndex = false): TensorBuffer<Rank, 'int32'> {\n const maxPositions = buffer(convInfo.outShape, 'int32');\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n\n const xBuf = buffer(xShape, dtype, xValues);\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let d = 0; d < convInfo.inChannels; ++d) {\n for (let yR = 0; yR < convInfo.outHeight; ++yR) {\n const xRCorner = yR * strideHeight - padTop;\n let xRMin = xRCorner;\n while (xRMin < 0) {\n xRMin += dilationHeight;\n }\n // const xRMin = Math.max(0, xRCorner);\n const xRMax =\n Math.min(convInfo.inHeight, effectiveFilterHeight + xRCorner);\n for (let yC = 0; yC < convInfo.outWidth; ++yC) {\n const xCCorner = yC * strideWidth - padLeft;\n let xCMin = xCCorner;\n while (xCMin < 0) {\n xCMin += dilationWidth;\n }\n const xCMax =\n Math.min(convInfo.inWidth, effectiveFilterWidth + xCCorner);\n let maxValue = Number.NEGATIVE_INFINITY;\n let maxPosition = -1;\n\n for (let xR = xRMin; xR < xRMax; xR += dilationHeight) {\n const wR = xR - xRCorner;\n for (let xC = xCMin; xC < xCMax; xC += dilationWidth) {\n const wC = xC - xCCorner;\n const pixel = xBuf.get(b, xR, xC, d);\n if (pixel > maxValue) {\n maxValue = pixel as number;\n if (flattenPositions) {\n maxPosition = includeBatchInIndex ?\n ((b * convInfo.inHeight + xR) * convInfo.inWidth + xC) *\n convInfo.inChannels +\n d :\n (xR * convInfo.inWidth + xC) * convInfo.inChannels + d;\n } else {\n maxPosition = wR * effectiveFilterWidth + wC;\n }\n }\n }\n }\n maxPositions.set(maxPosition, b, yR, yC, d);\n }\n }\n }\n }\n return maxPositions;\n}\n\nexport function pool3d(\n xValues: TypedArray, xShape: number[], dtype: DataType, strides: number[],\n convInfo: backend_util.Conv3DInfo,\n poolType: 'max'|'avg'): TensorBuffer<Rank, DataType> {\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n\n const initialValue =\n (poolType === 'max' ? Number.NEGATIVE_INFINITY :\n Number.POSITIVE_INFINITY);\n\n const output = buffer(convInfo.outShape, dtype);\n const outputVals = output.values;\n\n const outputBatchStrides = convInfo.outShape[1] * convInfo.outShape[2] *\n convInfo.outShape[3] * convInfo.outShape[4];\n const outputDepthStrides =\n convInfo.outShape[2] * convInfo.outShape[3] * convInfo.outShape[4];\n const outputRowStrides = convInfo.outShape[3] * convInfo.outShape[4];\n const outputColStrides = convInfo.outShape[4];\n\n for (let batch = 0; batch < convInfo.batchSize; ++batch) {\n const outputBatchOffset = batch * outputBatchStrides;\n const inputBatchOffset = batch * strides[0];\n for (let channel = 0; channel < convInfo.inChannels; ++channel) {\n for (let yDepth = 0; yDepth < convInfo.outDepth; ++yDepth) {\n const xDepthCorner = yDepth * strideDepth - padFront;\n let xDepthMin = xDepthCorner;\n while (xDepthMin < 0) {\n xDepthMin += dilationDepth;\n }\n const xDepthMax =\n Math.min(convInfo.inDepth, effectiveFilterDepth + xDepthCorner);\n const outputDepthOffset =\n outputBatchOffset + yDepth * outputDepthStrides;\n for (let yRow = 0; yRow < convInfo.outHeight; ++yRow) {\n const xRowCorner = yRow * strideHeight - padTop;\n let xRowMin = xRowCorner;\n while (xRowMin < 0) {\n xRowMin += dilationHeight;\n }\n const xRowMax =\n Math.min(convInfo.inHeight, effectiveFilterHeight + xRowCorner);\n const outputRowOffset = outputDepthOffset + yRow * outputRowStrides;\n for (let yCol = 0; yCol < convInfo.outWidth; ++yCol) {\n const xColCorner = yCol * strideWidth - padLeft;\n let xColMin = xColCorner;\n while (xColMin < 0) {\n xColMin += dilationWidth;\n }\n const xColMax =\n Math.min(convInfo.inWidth, effectiveFilterWidth + xColCorner);\n // Shader code begins\n const outputColOffset = outputRowOffset + yCol * outputColStrides;\n let minMaxValue = initialValue;\n let avgValue = 0;\n let count = 0;\n for (let xDepth = xDepthMin; xDepth < xDepthMax;\n xDepth += dilationDepth) {\n const xDepthOffset = inputBatchOffset + xDepth * strides[1];\n for (let xRow = xRowMin; xRow < xRowMax; xRow += dilationHeight) {\n const xRowOffset = xDepthOffset + xRow * strides[2];\n for (let xCol = xColMin; xCol < xColMax;\n xCol += dilationWidth) {\n const xColOffset = xRowOffset + xCol * strides[3];\n const pixel = xValues[xColOffset + channel];\n if ((poolType === 'max' && pixel > minMaxValue)) {\n minMaxValue = pixel;\n } else if (poolType === 'avg') {\n avgValue += pixel;\n count++;\n }\n if (isNaN(minMaxValue)) {\n break;\n }\n }\n if (isNaN(minMaxValue)) {\n break;\n }\n }\n if (isNaN(minMaxValue)) {\n break;\n }\n }\n const outputOffset = outputColOffset + channel;\n outputVals[outputOffset] =\n poolType === 'avg' ? avgValue / count : minMaxValue;\n }\n }\n }\n }\n }\n\n return output;\n}\n\nexport function maxPool3dPositions(\n xBuf: TensorBuffer<Rank, DataType>,\n convInfo: backend_util.Conv3DInfo): TensorBuffer<Rank, DataType> {\n const maxPositions = buffer(convInfo.outShape, 'int32');\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n\n for (let batch = 0; batch < convInfo.batchSize; ++batch) {\n for (let channel = 0; channel < convInfo.inChannels; ++channel) {\n for (let yDepth = 0; yDepth < convInfo.outDepth; ++yDepth) {\n const xDepthCorner = yDepth * strideDepth - padFront;\n let xDepthMin = xDepthCorner;\n while (xDepthMin < 0) {\n xDepthMin += dilationDepth;\n }\n const xDepthMax =\n Math.min(convInfo.inDepth, effectiveFilterDepth + xDepthCorner);\n for (let yRow = 0; yRow < convInfo.outHeight; ++yRow) {\n const xRowCorner = yRow * strideHeight - padTop;\n let xRowMin = xRowCorner;\n while (xRowMin < 0) {\n xRowMin += dilationHeight;\n }\n const xRowMax =\n Math.min(convInfo.inHeight, effectiveFilterHeight + xRowCorner);\n for (let yCol = 0; yCol < convInfo.outWidth; ++yCol) {\n const xColCorner = yCol * strideWidth - padLeft;\n let xColMin = xColCorner;\n while (xColMin < 0) {\n xColMin += dilationWidth;\n }\n const xColMax =\n Math.min(convInfo.inWidth, effectiveFilterWidth + xColCorner);\n\n // Shader code begins\n let maxValue = Number.NEGATIVE_INFINITY;\n let maxPosition = -1;\n\n for (let xDepth = xDepthMin; xDepth < xDepthMax;\n xDepth += dilationDepth) {\n const wDepth = xDepth - xDepthCorner;\n for (let xRow = xRowMin; xRow < xRowMax; xRow += dilationHeight) {\n const wRow = xRow - xRowCorner;\n for (let xCol = xColMin; xCol < xColMax;\n xCol += dilationWidth) {\n const wCol = xCol - xColCorner;\n const pixel = xBuf.get(batch, xDepth, xRow, xCol, channel);\n if (pixel >= maxValue) {\n maxValue = pixel as number;\n maxPosition =\n wDepth * effectiveFilterHeight * effectiveFilterWidth +\n wRow * effectiveFilterHeight + wCol;\n }\n }\n }\n }\n\n maxPositions.set(maxPosition, batch, yDepth, yRow, yCol, channel);\n }\n }\n }\n }\n }\n\n return maxPositions;\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 {AvgPool, AvgPoolAttrs, AvgPoolInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {pool} from '../utils/pool_utils';\nimport {identity} from './Identity';\n\nexport function avgPool(\n args:\n {inputs: AvgPoolInputs, backend: MathBackendCPU, attrs: AvgPoolAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n assertNotComplex(x, 'avgPool');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations = 1;\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in avgPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n let res: TensorInfo;\n\n if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&\n util.arraysEqual(convInfo.inShape, convInfo.outShape)) {\n res = identity({inputs: {x}, backend});\n } else {\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const strides = util.computeStrides(x.shape);\n const buffer = pool(xValues, x.shape, x.dtype, strides, convInfo, 'avg');\n res = backend.makeTensorInfo(\n convInfo.outShape, x.dtype, buffer.values as TypedArray);\n }\n return res;\n}\n\nexport const avgPoolConfig: KernelConfig = {\n kernelName: AvgPool,\n backendName: 'cpu',\n kernelFunc: avgPool as {} 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 {AvgPool3D, AvgPool3DAttrs, AvgPool3DInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {pool3d} from '../utils/pool_utils';\n\nexport function avgPool3D(args: {\n inputs: AvgPool3DInputs,\n backend: MathBackendCPU,\n attrs: AvgPool3DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {filterSize, strides, pad, dimRoundingMode, dataFormat} = attrs;\n\n assertNotComplex(x, 'avgPool3d');\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad, dimRoundingMode, dataFormat);\n\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const outBuf = pool3d(\n xValues, x.shape, x.dtype, util.computeStrides(x.shape), convInfo, 'avg');\n\n return backend.makeTensorInfo(outBuf.shape, 'float32', outBuf.values);\n}\n\nexport const avgPool3DConfig: KernelConfig = {\n kernelName: AvgPool3D,\n backendName: 'cpu',\n kernelFunc: avgPool3D as {} 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 {AvgPool3DGrad, AvgPool3DGradAttrs, AvgPool3DGradInputs, backend_util, buffer, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function avgPool3DGrad(args: {\n inputs: AvgPool3DGradInputs,\n backend: MathBackendCPU,\n attrs: AvgPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n\n assertNotComplex([dy, input], 'avgPool3DGrad');\n\n const convInfo = backend_util.computePool3DInfo(\n input.shape as [number, number, number, number, number], filterSize,\n strides, 1 /* dilations */, pad, dimRoundingMode);\n\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const dx = buffer(input.shape, 'float32');\n\n const avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);\n\n const dyBuf = backend.bufferSync(dy);\n\n for (let batch = 0; batch < convInfo.batchSize; ++batch) {\n for (let channel = 0; channel < convInfo.inChannels; ++channel) {\n for (let dxDepth = 0; dxDepth < convInfo.inDepth; ++dxDepth) {\n for (let dxRow = 0; dxRow < convInfo.inHeight; ++dxRow) {\n for (let dxCol = 0; dxCol < convInfo.inWidth; ++dxCol) {\n // Shader code begins.\n const dyDepthCorner = dxDepth - padFront;\n const dyRowCorner = dxRow - padTop;\n const dyColCorner = dxCol - padLeft;\n let dotProd = 0;\n for (let wDepth = 0; wDepth < effectiveFilterDepth;\n wDepth += dilationDepth) {\n const dyDepth = (dyDepthCorner + wDepth) / strideDepth;\n if (dyDepth < 0 || dyDepth >= convInfo.outDepth ||\n Math.floor(dyDepth) !== dyDepth) {\n continue;\n }\n for (let wRow = 0; wRow < effectiveFilterHeight;\n wRow += dilationHeight) {\n const dyRow = (dyRowCorner + wRow) / strideHeight;\n if (dyRow < 0 || dyRow >= convInfo.outHeight ||\n Math.floor(dyRow) !== dyRow) {\n continue;\n }\n for (let wCol = 0; wCol < effectiveFilterWidth;\n wCol += dilationWidth) {\n const dyCol = (dyColCorner + wCol) / strideWidth;\n if (dyCol < 0 || dyCol >= convInfo.outWidth ||\n Math.floor(dyCol) !== dyCol) {\n continue;\n }\n\n const pixel =\n dyBuf.get(batch, dyDepth, dyRow, dyCol, channel);\n dotProd += pixel;\n }\n }\n }\n dx.set(\n dotProd * avgMultiplier, batch, dxDepth, dxRow, dxCol, channel);\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const avgPool3DGradConfig: KernelConfig = {\n kernelName: AvgPool3DGrad,\n backendName: 'cpu',\n kernelFunc: avgPool3DGrad as {} 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 */\nimport {AvgPoolGrad, AvgPoolGradAttrs, AvgPoolGradInputs, backend_util, buffer, KernelConfig, KernelFunc, Rank, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function avgPoolGrad(args: {\n inputs: AvgPoolGradInputs,\n backend: MathBackendCPU,\n attrs: AvgPoolGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n assertNotComplex([dy, input], 'avgPoolGrad');\n const {filterSize, strides, pad} = attrs;\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad);\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const dx =\n buffer<Rank.R4>(x.shape as [number, number, number, number], 'float32');\n\n const avgMultiplier = 1 / (filterHeight * filterWidth);\n\n const dyData = backend.data.get(dy.dataId).values as Float32Array;\n const dyBuf = buffer<Rank.R4>(\n dy.shape as [number, number, number, number], 'float32', dyData);\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let d = 0; d < convInfo.inChannels; ++d) {\n for (let dxR = 0; dxR < convInfo.inHeight; ++dxR) {\n for (let dxC = 0; dxC < convInfo.inWidth; ++dxC) {\n // Shader code begins.\n const dyRCorner = dxR - padTop;\n const dyCCorner = dxC - padLeft;\n let dotProd = 0;\n for (let wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {\n const dyR = (dyRCorner + wR) / strideHeight;\n if (dyR < 0 || dyR >= convInfo.outHeight ||\n Math.floor(dyR) !== dyR) {\n continue;\n }\n for (let wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {\n const dyC = (dyCCorner + wC) / strideWidth;\n if (dyC < 0 || dyC >= convInfo.outWidth ||\n Math.floor(dyC) !== dyC) {\n continue;\n }\n\n const pixel = dyBuf.get(b, dyR, dyC, d);\n dotProd += pixel;\n }\n }\n dx.set(dotProd * avgMultiplier, b, dxR, dxC, d);\n }\n }\n }\n }\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const avgPoolGradConfig: KernelConfig = {\n kernelName: AvgPoolGrad,\n backendName: 'cpu',\n kernelFunc: avgPoolGrad as {} 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 {FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function batchNorm(args: {\n inputs: FusedBatchNormInputs,\n backend: MathBackendCPU,\n attrs: FusedBatchNormAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, scale, offset, mean, variance} = inputs;\n\n util.assert(\n mean.shape.length === variance.shape.length,\n () => 'Batch normalization gradient requires mean and variance to have ' +\n 'equal ranks.');\n util.assert(\n offset == null || mean.shape.length === offset.shape.length,\n () => 'Batch normalization gradient requires mean and offset to have ' +\n 'equal ranks.');\n util.assert(\n scale == null || mean.shape.length === scale.shape.length,\n () => 'Batch normalization gradient requires mean and scale to have ' +\n 'equal ranks.');\n\n assertNotComplex([x, mean, variance, scale, offset], 'batchNorm');\n\n let {varianceEpsilon} = attrs;\n if (varianceEpsilon == null) {\n varianceEpsilon = 0.001;\n }\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const mVals = backend.data.get(mean.dataId).values as TypedArray;\n const varVals = backend.data.get(variance.dataId).values as TypedArray;\n const sVals = scale ? backend.data.get(scale.dataId).values as TypedArray :\n new Float32Array([1]);\n const offVals = offset ?\n backend.data.get(offset.dataId).values as TypedArray :\n new Float32Array([0]);\n const outVals = new Float32Array(xVals.length);\n\n const offValsLength = offVals.length;\n const sValsLength = sVals.length;\n const varValsLength = varVals.length;\n const mValsLength = mVals.length;\n\n let offi = 0;\n let mi = 0;\n let si = 0;\n let vi = 0;\n for (let i = 0; i < xVals.length; ++i) {\n outVals[i] = offVals[offi++] +\n (xVals[i] - mVals[mi++]) * sVals[si++] /\n Math.sqrt(varVals[vi++] + varianceEpsilon);\n if (offi >= offValsLength) {\n offi = 0;\n }\n if (mi >= mValsLength) {\n mi = 0;\n }\n if (si >= sValsLength) {\n si = 0;\n }\n if (vi >= varValsLength) {\n vi = 0;\n }\n }\n return backend.makeTensorInfo(x.shape, x.dtype, outVals);\n}\n\nexport const batchNormConfig: KernelConfig = {\n kernelName: FusedBatchNorm,\n backendName: 'cpu',\n kernelFunc: batchNorm as {} 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, BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\nimport {transpose} from './Transpose';\n\nexport function batchToSpaceND(args: {\n inputs: BatchToSpaceNDInputs,\n backend: MathBackendCPU,\n attrs: BatchToSpaceNDAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, crops} = attrs;\n\n assertNotComplex([x], 'batchToSpaceND');\n\n const prod = blockShape.reduce((a, b) => a * b);\n\n const reshaped = backend_util.getReshaped(x.shape, blockShape, prod);\n const permuted = backend_util.getPermuted(reshaped.length, blockShape.length);\n const reshapedPermuted =\n backend_util.getReshapedPermuted(x.shape, blockShape, prod);\n const sliceBeginCoords =\n backend_util.getSliceBeginCoords(crops, blockShape.length);\n const sliceSize =\n backend_util.getSliceSize(reshapedPermuted, crops, blockShape.length);\n\n const xReshaped = reshape({inputs: {x}, backend, attrs: {shape: reshaped}});\n const xTransposed =\n transpose({inputs: {x: xReshaped}, backend, attrs: {perm: permuted}});\n const xTransposedReshaped = reshape(\n {inputs: {x: xTransposed}, backend, attrs: {shape: reshapedPermuted}});\n const result = slice({\n inputs: {x: xTransposedReshaped},\n backend,\n attrs: {begin: sliceBeginCoords, size: sliceSize}\n });\n\n backend.disposeIntermediateTensorInfo(xReshaped);\n backend.disposeIntermediateTensorInfo(xTransposed);\n backend.disposeIntermediateTensorInfo(xTransposedReshaped);\n\n return result;\n}\n\nexport const batchToSpaceNDConfig: KernelConfig = {\n kernelName: BatchToSpaceND,\n backendName: 'cpu',\n kernelFunc: batchToSpaceND as {} 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 {Bincount, BincountAttrs, BincountInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {bincountImpl} from './Bincount_impl';\n\nexport function bincount(args: {\n inputs: BincountInputs,\n backend: MathBackendCPU,\n attrs: BincountAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, weights} = inputs;\n const {size} = attrs;\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const weightsVals = backend.data.get(weights.dataId).values as TypedArray;\n\n const outVals =\n bincountImpl(xVals, weightsVals, weights.dtype, weights.shape, size);\n\n return backend.makeTensorInfo([size], weights.dtype, outVals);\n}\n\nexport const bincountConfig: KernelConfig = {\n kernelName: Bincount,\n backendName: 'cpu',\n kernelFunc: bincount as {} 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 {ClipByValue, ClipByValueAttrs, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const clip = unaryKernelFunc(ClipByValue, (xi, attrs) => {\n const clipAttrs = attrs as {} as ClipByValueAttrs;\n if (xi > clipAttrs.clipValueMax) {\n return clipAttrs.clipValueMax;\n }\n return xi < clipAttrs.clipValueMin ? clipAttrs.clipValueMin : xi;\n});\n\nexport const clipConfig: KernelConfig = {\n kernelName: ClipByValue,\n backendName: 'cpu',\n kernelFunc: clip,\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 {ComplexAbs, ComplexAbsInputs, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const complexAbs =\n (args: {inputs: ComplexAbsInputs, backend: MathBackendCPU}) => {\n const {x} = args.inputs;\n const cpuBackend = args.backend;\n const resultValues = new Float32Array(util.sizeFromShape(x.shape));\n const complexVals = cpuBackend.data.get(x.dataId);\n const real = complexVals.complexTensorInfos.real;\n const imag = complexVals.complexTensorInfos.imag;\n const realVals = cpuBackend.data.get(real.dataId).values as Float32Array;\n const imagVals = cpuBackend.data.get(imag.dataId).values as Float32Array;\n for (let i = 0; i < realVals.length; i++) {\n const real = realVals[i];\n const imag = imagVals[i];\n resultValues[i] = Math.hypot(real, imag);\n }\n\n return cpuBackend.makeOutput(resultValues, x.shape, 'float32');\n };\n\nexport const complexAbsConfig: KernelConfig = {\n kernelName: ComplexAbs,\n backendName: 'cpu',\n kernelFunc: complexAbs as {} 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 {} 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 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 const shapes = $inputs.map(t => t.shape);\n backend_util.assertParamsConsistent(shapes, $axis);\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 {} 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, Conv2D, Conv2DAttrs, Conv2DInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv2D(\n args: {inputs: Conv2DInputs, backend: MathBackendCPU, attrs: Conv2DAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dataFormat, dilations, dimRoundingMode} = attrs;\n\n assertNotComplex([x, filter], 'conv2d');\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, dilations, pad,\n dimRoundingMode, false /* depthwise */, $dataFormat);\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const padLeft = convInfo.padInfo.left;\n const padTop = convInfo.padInfo.top;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n const y = new TensorBuffer(convInfo.outShape, x.dtype as 'float32');\n\n const xStrides = util.computeStrides(x.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n const xBatchStride = xStrides[0];\n const xRowStride = isChannelsLast ? xStrides[1] : xStrides[2];\n const xColStride = isChannelsLast ? xStrides[2] : 1;\n const xChannelStride = isChannelsLast ? 1 : xStrides[1];\n const yBatchStride = y.strides[0];\n const yRowStride = isChannelsLast ? y.strides[1] : y.strides[2];\n const yColStride = isChannelsLast ? y.strides[2] : 1;\n const yChannelStride = isChannelsLast ? 1 : y.strides[1];\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const wVals = backend.data.get(filter.dataId).values as TypedArray;\n const yVals = y.values;\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const xOffset1 = b * xBatchStride;\n const yOffset1 = b * yBatchStride;\n for (let yR = 0; yR < convInfo.outHeight; ++yR) {\n const yOffset2 = yOffset1 + yR * yRowStride;\n const xRCorner = yR * convInfo.strideHeight - padTop;\n for (let wR = 0; wR < filterHeight; ++wR) {\n const xR = xRCorner + wR * dilationHeight;\n if (xR < 0 || xR >= convInfo.inHeight) {\n continue;\n }\n const wOffset1 = wR * filterStrides[0];\n const xOffset2 = xOffset1 + xR * xRowStride;\n for (let yC = 0; yC < convInfo.outWidth; ++yC) {\n const yOffset3 = yOffset2 + yC * yColStride;\n const xCCorner = yC * convInfo.strideWidth - padLeft;\n for (let wC = 0; wC < filterWidth; ++wC) {\n const xC = xCCorner + wC * dilationWidth;\n if (xC < 0 || xC >= convInfo.inWidth) {\n continue;\n }\n const wOffset2 = wOffset1 + wC * filterStrides[1];\n const xOffset3 = xOffset2 + xC * xColStride;\n let wOffset3 = wOffset2;\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n const xVal = xVals[xOffset3 + d1 * xChannelStride];\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n yVals[yOffset3 + d2 * yChannelStride] +=\n xVal * wVals[wOffset3 + d2];\n }\n wOffset3 += convInfo.outChannels;\n }\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(y.shape, y.dtype, yVals);\n}\n\nexport const conv2DConfig: KernelConfig = {\n kernelName: Conv2D,\n backendName: 'cpu',\n kernelFunc: conv2D as {} 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, Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv2DBackpropFilter(args: {\n inputs: Conv2DBackpropFilterInputs,\n backend: MathBackendCPU,\n attrs: Conv2DBackpropFilterAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, dataFormat, dimRoundingMode, filterShape} = attrs;\n\n assertNotComplex([x, dy], 'conv2dBackpropFilter');\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad, dimRoundingMode, false /* depthwise */,\n $dataFormat);\n\n const {strideHeight, strideWidth, filterHeight, filterWidth} = convInfo;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n const dW = new TensorBuffer(convInfo.filterShape, 'float32');\n\n const leftPad = convInfo.padInfo.left;\n const topPad = convInfo.padInfo.top;\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const dyVals = backend.data.get(dy.dataId).values as TypedArray;\n\n const xBuf = new TensorBuffer(x.shape, x.dtype, xVals);\n const dyBuf = new TensorBuffer(dy.shape, dy.dtype, dyVals);\n\n for (let wR = 0; wR < filterHeight; ++wR) {\n const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));\n const yRMax = Math.min(\n convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);\n\n for (let wC = 0; wC < filterWidth; ++wC) {\n const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));\n const yCMax = Math.min(\n convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);\n\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n let dotProd = 0;\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let yR = yRMin; yR < yRMax; ++yR) {\n const xR = wR + yR * strideHeight - topPad;\n for (let yC = yCMin; yC < yCMax; ++yC) {\n const xC = wC + yC * strideWidth - leftPad;\n if (isChannelsLast) {\n dotProd += (xBuf.get(b, xR, xC, d1) as number) *\n (dyBuf.get(b, yR, yC, d2) as number);\n } else {\n dotProd += (xBuf.get(b, d1, xR, xC) as number) *\n (dyBuf.get(b, d2, yR, yC) as number);\n }\n }\n }\n }\n dW.set(dotProd, wR, wC, d1, d2);\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dW.shape, dW.dtype, dW.values);\n}\n\nexport const conv2DBackpropFilterConfig: KernelConfig = {\n kernelName: Conv2DBackpropFilter,\n backendName: 'cpu',\n kernelFunc: conv2DBackpropFilter as {} 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, Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv2DBackpropInput(args: {\n inputs: Conv2DBackpropInputInputs,\n backend: MathBackendCPU,\n attrs: Conv2DBackpropInputAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {inputShape, strides, pad, dataFormat, dimRoundingMode} = attrs;\n\n assertNotComplex([dy, filter], 'conv2dBackpropInput');\n\n const filterStrides = util.computeStrides(filter.shape);\n const dyStrides = util.computeStrides(dy.shape);\n\n let $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n 1 /* dilations */, pad, dimRoundingMode, false, $dataFormat);\n\n const dx = new TensorBuffer(convInfo.inShape, 'float32');\n const dxValues = dx.values;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const fltValues = backend.data.get(filter.dataId).values as TypedArray;\n const [fltS0, fltS1, fltS2] = filterStrides;\n const {\n batchSize,\n filterHeight,\n filterWidth,\n inChannels,\n inHeight,\n inWidth,\n outChannels,\n outHeight,\n outWidth,\n strideHeight,\n strideWidth\n } = convInfo;\n $dataFormat = convInfo.dataFormat;\n const topPad = filterHeight - 1 - convInfo.padInfo.top;\n const leftPad = filterWidth - 1 - convInfo.padInfo.left;\n\n const isChannelsLast = $dataFormat === 'channelsLast';\n const xBatchStride = dx.strides[0];\n const xRowStride = isChannelsLast ? dx.strides[1] : dx.strides[2];\n const xColStride = isChannelsLast ? dx.strides[2] : 1;\n const xChannelStride = isChannelsLast ? 1 : dx.strides[1];\n const yBatchStride = dyStrides[0];\n const yRowStride = isChannelsLast ? dyStrides[1] : dyStrides[2];\n const yColStride = isChannelsLast ? dyStrides[2] : 1;\n const yChannelStride = isChannelsLast ? 1 : dyStrides[1];\n\n for (let b = 0; b < batchSize; ++b) {\n for (let d1 = 0; d1 < inChannels; ++d1) {\n for (let xR = 0; xR < inHeight; ++xR) {\n const xRCorner = xR - topPad;\n const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));\n const yRMax =\n Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);\n\n for (let xC = 0; xC < inWidth; ++xC) {\n const xCCorner = xC - leftPad;\n const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));\n const yCMax =\n Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);\n\n let dotProd = 0;\n for (let yR = xRMin; yR < yRMax; ++yR) {\n const wR = yR * strideHeight - xRCorner;\n\n for (let yC = xCMin; yC < yCMax; ++yC) {\n const wC = yC * strideWidth - xCCorner;\n const dyOffset =\n yBatchStride * b + yRowStride * yR + yColStride * yC;\n const fltOffset = fltS0 * (filterHeight - 1 - wR) +\n fltS1 * (filterWidth - 1 - wC) + fltS2 * d1;\n\n for (let d2 = 0; d2 < outChannels; ++d2) {\n const pixel = dyValues[dyOffset + yChannelStride * d2];\n const weight = fltValues[fltOffset + d2];\n dotProd += pixel * weight;\n }\n }\n }\n const dxOffset = xBatchStride * b + xRowStride * xR +\n xColStride * xC + xChannelStride * d1;\n dxValues[dxOffset] = dotProd;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const conv2DBackpropInputConfig: KernelConfig = {\n kernelName: Conv2DBackpropInput,\n backendName: 'cpu',\n kernelFunc: conv2DBackpropInput as {} 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, Conv3D, Conv3DAttrs, Conv3DInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv3D(\n args: {inputs: Conv3DInputs, backend: MathBackendCPU, attrs: Conv3DAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations} = attrs;\n\n assertNotComplex([x, filter], 'conv3d');\n\n const convInfo = backend_util.computeConv3DInfo(\n x.shape as [number, number, number, number, number],\n filter.shape as [number, number, number, number, number], strides,\n dilations, pad);\n\n const {\n filterDepth,\n filterHeight,\n filterWidth,\n dilationDepth,\n dilationHeight,\n dilationWidth,\n padInfo\n } = convInfo;\n const padFront = padInfo.front;\n const padLeft = padInfo.left;\n const padTop = padInfo.top;\n const y = new TensorBuffer(convInfo.outShape, x.dtype as 'float32');\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const wVals = backend.data.get(filter.dataId).values as TypedArray;\n const yVals = y.values;\n\n const xStrides = util.computeStrides(x.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const xOffset1 = b * xStrides[0];\n const yOffset1 = b * y.strides[0];\n for (let yF = 0; yF < convInfo.outDepth; ++yF) {\n const yOffset2 = yOffset1 + yF * y.strides[1];\n const xFCorner = yF * convInfo.strideDepth - padFront;\n for (let wF = 0; wF < filterDepth; ++wF) {\n const xF = xFCorner + wF * dilationDepth;\n if (xF < 0 || xF >= convInfo.inDepth) {\n continue;\n }\n const wOffset1 = wF * filterStrides[0];\n const xOffset2 = xOffset1 + xF * xStrides[1];\n\n for (let yR = 0; yR < convInfo.outHeight; ++yR) {\n const yOffset3 = yOffset2 + yR * y.strides[2];\n const xRCorner = yR * convInfo.strideHeight - padTop;\n for (let wR = 0; wR < filterHeight; ++wR) {\n const xR = xRCorner + wR * dilationHeight;\n if (xR < 0 || xR >= convInfo.inHeight) {\n continue;\n }\n const wOffset2 = wOffset1 + wR * filterStrides[1];\n const xOffset3 = xOffset2 + xR * xStrides[2];\n for (let yC = 0; yC < convInfo.outWidth; ++yC) {\n const yOffset4 = yOffset3 + yC * convInfo.outChannels;\n const xCCorner = yC * convInfo.strideWidth - padLeft;\n for (let wC = 0; wC < filterWidth; ++wC) {\n const xC = xCCorner + wC * dilationWidth;\n if (xC < 0 || xC >= convInfo.inWidth) {\n continue;\n }\n const wOffset3 = wOffset2 + wC * filterStrides[2];\n const xOffset4 = xOffset3 + xC * convInfo.inChannels;\n let wOffset4 = wOffset3;\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n const xVal = xVals[xOffset4 + d1];\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n yVals[yOffset4 + d2] += xVal * wVals[wOffset4 + d2];\n }\n wOffset4 += convInfo.outChannels;\n }\n }\n }\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(y.shape, y.dtype, y.values);\n}\n\nexport const conv3DConfig: KernelConfig = {\n kernelName: Conv3D,\n backendName: 'cpu',\n kernelFunc: conv3D as {} 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, Conv3DBackpropFilterV2, Conv3DBackpropFilterV2Attrs, Conv3DBackpropFilterV2Inputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv3DBackpropFilterV2(args: {\n inputs: Conv3DBackpropFilterV2Inputs,\n backend: MathBackendCPU,\n attrs: Conv3DBackpropFilterV2Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, filterShape} = attrs;\n\n assertNotComplex([x, dy], 'conv3dBackpropFilterV2');\n\n const xStrides = util.computeStrides(x.shape);\n const dyStrides = util.computeStrides(dy.shape);\n\n const convInfo = backend_util.computeConv3DInfo(\n x.shape as [number, number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad);\n\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const dw = new TensorBuffer(convInfo.filterShape, 'float32');\n const dwValues = dw.values;\n const [dwS0, dwS1, dwS2, dwS3] = dw.strides;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const [dyS0, dyS1, dyS2, dyS3] = dyStrides;\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const [xS0, xS1, xS2, xS3] = xStrides;\n\n const frontPad = convInfo.padInfo.front;\n const leftPad = convInfo.padInfo.left;\n const topPad = convInfo.padInfo.top;\n\n for (let wF = 0; wF < filterDepth; ++wF) {\n const yFMin = Math.max(0, Math.ceil((frontPad - wF) / strideDepth));\n const yFMax = Math.min(\n convInfo.outDepth, (convInfo.inDepth + frontPad - wF) / strideDepth);\n const wOffset1 = wF * dwS0;\n\n for (let wR = 0; wR < filterHeight; ++wR) {\n const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));\n const yRMax = Math.min(\n convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);\n const wOffset2 = wR * dwS1 + wOffset1;\n\n for (let wC = 0; wC < filterWidth; ++wC) {\n const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));\n const yCMax = Math.min(\n convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);\n const wOffset3 = wC * dwS2 + wOffset2;\n\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n const wOffset4 = d1 * dwS3 + wOffset3;\n\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n let dotProd = 0;\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const xOffset1 = b * xS0;\n const yOffset1 = b * dyS0;\n\n for (let yF = yFMin; yF < yFMax; ++yF) {\n const xF = wF + yF * strideDepth - frontPad;\n const xOffset2 = xF * xS1 + xOffset1;\n const yOffset2 = yF * dyS1 + yOffset1;\n\n for (let yR = yRMin; yR < yRMax; ++yR) {\n const xR = wR + yR * strideHeight - topPad;\n const xOffset3 = xR * xS2 + xOffset2;\n const yOffset3 = yR * dyS2 + yOffset2;\n\n for (let yC = yCMin; yC < yCMax; ++yC) {\n const xC = wC + yC * strideWidth - leftPad;\n const xOffset4 = xC * xS3 + xOffset3;\n const yOffset4 = yC * dyS3 + yOffset3;\n\n dotProd += xValues[xOffset4 + d1] * dyValues[yOffset4 + d2];\n }\n }\n }\n }\n dwValues[wOffset4 + d2] = dotProd;\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dw.shape, dw.dtype, dw.values);\n}\n\nexport const conv3DBackpropFilterV2Config: KernelConfig = {\n kernelName: Conv3DBackpropFilterV2,\n backendName: 'cpu',\n kernelFunc: conv3DBackpropFilterV2 as {} 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, Conv3DBackpropInputV2, Conv3DBackpropInputV2Attrs, Conv3DBackpropInputV2Inputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function conv3DBackpropInputV2(args: {\n inputs: Conv3DBackpropInputV2Inputs,\n backend: MathBackendCPU,\n attrs: Conv3DBackpropInputV2Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {pad, strides, inputShape} = attrs;\n\n assertNotComplex([dy], 'conv3dBackpropInputV2');\n\n const dyStrides = util.computeStrides(dy.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n const convInfo = backend_util.computeConv3DInfo(\n inputShape, filter.shape as [number, number, number, number, number],\n strides, 1 /* dilations */, pad);\n\n const dx = new TensorBuffer(convInfo.inShape, 'float32');\n const dxValues = dx.values;\n const [dxS0, dxS1, dxS2, dxS3] = dx.strides;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const [dyS0, dyS1, dyS2, dyS3] = dyStrides;\n const fltValues = backend.data.get(filter.dataId).values as TypedArray;\n const [fltS0, fltS1, fltS2, fltS3] = filterStrides;\n const {\n batchSize,\n filterDepth,\n filterHeight,\n filterWidth,\n inChannels,\n inDepth,\n inHeight,\n inWidth,\n outChannels,\n outDepth,\n outHeight,\n outWidth,\n strideDepth,\n strideHeight,\n strideWidth\n } = convInfo;\n const frontPad = filterDepth - 1 - convInfo.padInfo.front;\n const topPad = filterHeight - 1 - convInfo.padInfo.top;\n const leftPad = filterWidth - 1 - convInfo.padInfo.left;\n\n for (let b = 0; b < batchSize; ++b) {\n for (let d1 = 0; d1 < inChannels; ++d1) {\n // Frames of depth\n for (let xF = 0; xF < inDepth; ++xF) {\n const xFCorner = xF - frontPad;\n const xFMin = Math.max(0, Math.ceil(xFCorner / strideDepth));\n const yFMax =\n Math.min(outDepth, (filterDepth + xFCorner) / strideDepth);\n\n // Rows as per standard 2d matrix notation\n for (let xR = 0; xR < inHeight; ++xR) {\n const xRCorner = xR - topPad;\n const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));\n const yRMax =\n Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);\n // Columns as per standard 2d matrix notation\n for (let xC = 0; xC < inWidth; ++xC) {\n const xCCorner = xC - leftPad;\n const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));\n const yCMax =\n Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);\n\n let dotProd = 0;\n for (let yF = xFMin; yF < yFMax; ++yF) {\n const wF = yF * strideDepth - xFCorner;\n\n for (let yR = xRMin; yR < yRMax; ++yR) {\n const wR = yR * strideHeight - xRCorner;\n\n for (let yC = xCMin; yC < yCMax; ++yC) {\n const wC = yC * strideWidth - xCCorner;\n const dyOffset = dyS0 * b + dyS1 * yF + dyS2 * yR + dyS3 * yC;\n const fltOffset = fltS0 * (filterDepth - 1 - wF) +\n fltS1 * (filterHeight - 1 - wR) +\n fltS2 * (filterWidth - 1 - wC) + fltS3 * d1;\n\n for (let d2 = 0; d2 < outChannels; ++d2) {\n const pixel = dyValues[dyOffset + d2];\n const weight = fltValues[fltOffset + d2];\n dotProd += pixel * weight;\n }\n }\n }\n }\n dxValues[dxS0 * b + dxS1 * xF + dxS2 * xR + dxS3 * xC + d1] =\n dotProd;\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const conv3DBackpropInputV2Config: KernelConfig = {\n kernelName: Conv3DBackpropInputV2,\n backendName: 'cpu',\n kernelFunc: conv3DBackpropInputV2 as {} 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 {Cos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const cos = unaryKernelFunc(Cos, (xi) => Math.cos(xi));\n\nexport const cosConfig: KernelConfig = {\n kernelName: Cos,\n backendName: 'cpu',\n kernelFunc: cos,\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 {Cosh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const cosh = unaryKernelFunc(Cosh, (xi) => Math.cosh(xi));\n\nexport const coshConfig: KernelConfig = {\n kernelName: Cosh,\n backendName: 'cpu',\n kernelFunc: cosh,\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, CropAndResize, CropAndResizeAttrs, CropAndResizeInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function cropAndResize(args: {\n inputs: CropAndResizeInputs,\n backend: MathBackendCPU,\n attrs: CropAndResizeAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {image, boxes, boxInd} = inputs;\n const {cropSize, method, extrapolationValue} = attrs;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n const numBoxes = boxes.shape[0];\n\n const [cropHeight, cropWidth] = cropSize;\n const output =\n buffer([numBoxes, cropHeight, cropWidth, numChannels], 'float32');\n\n const boxVals = backend.data.get(boxes.dataId).values as TypedArray;\n const boxIndVals = backend.data.get(boxInd.dataId).values as TypedArray;\n const imageVals = backend.data.get(image.dataId).values as TypedArray;\n\n const inStride =\n util.computeStrides(image.shape); // to calculate flat indexes into image\n const outStride = util.computeStrides(\n output.shape); // to calculate flat indexes into output\n\n // Reference implementation\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/crop_and_resize_op.cc\n for (let b = 0; b < numBoxes; b++) {\n const startInd = b * 4;\n const y1 = boxVals[startInd];\n const x1 = boxVals[startInd + 1];\n const y2 = boxVals[startInd + 2];\n const x2 = boxVals[startInd + 3];\n\n const bInd: number = boxIndVals[b];\n if (bInd >= batch) {\n continue;\n }\n\n const heightScale =\n (cropHeight > 1) ? (y2 - y1) * (imageHeight - 1) / (cropHeight - 1) : 0;\n const widthScale =\n (cropWidth > 1) ? (x2 - x1) * (imageWidth - 1) / (cropWidth - 1) : 0;\n\n for (let y = 0; y < cropHeight; y++) {\n const yInd: number = (cropHeight > 1) ?\n y1 * (imageHeight - 1) + y * (heightScale) :\n 0.5 * (y1 + y2) * (imageHeight - 1);\n\n if (yInd < 0 || yInd > imageHeight - 1) {\n for (let x = 0; x < cropWidth; x++) {\n for (let c = 0; c < numChannels; c++) {\n const ind =\n c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[ind] = extrapolationValue;\n }\n }\n continue;\n }\n\n if (method === 'bilinear') {\n const topInd = Math.floor(yInd);\n const bottomInd = Math.ceil(yInd);\n const yLerp = yInd - topInd;\n\n for (let x = 0; x < cropWidth; x++) {\n const xInd = (cropWidth > 1) ?\n x1 * (imageWidth - 1) + x * widthScale :\n 0.5 * (x1 + x2) * (imageWidth - 1);\n\n if (xInd < 0 || xInd > imageWidth - 1) {\n for (let c = 0; c < numChannels; c++) {\n const ind =\n c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[ind] = extrapolationValue;\n }\n continue;\n }\n\n const leftInd = Math.floor(xInd);\n const rightInd = Math.ceil(xInd);\n const xLerp = xInd - leftInd;\n\n for (let c = 0; c < numChannels; c++) {\n let ind = c + leftInd * inStride[2] + topInd * inStride[1] +\n bInd * inStride[0];\n const topLeft = imageVals[ind];\n\n ind = c + rightInd * inStride[2] + topInd * inStride[1] +\n bInd * inStride[0];\n const topRight = imageVals[ind];\n\n ind = c + leftInd * inStride[2] + bottomInd * inStride[1] +\n bInd * inStride[0];\n const bottomLeft = imageVals[ind];\n\n ind = c + rightInd * inStride[2] + bottomInd * inStride[1] +\n bInd * inStride[0];\n const bottomRight = imageVals[ind];\n\n const top = topLeft + (topRight - topLeft) * xLerp;\n const bottom = bottomLeft + (bottomRight - bottomLeft) * xLerp;\n\n ind = c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[ind] = top + ((bottom - top) * yLerp);\n }\n }\n } else { // method == \"nearest\"\n for (let x = 0; x < cropWidth; ++x) {\n const xInd = (cropWidth > 1) ?\n x1 * (imageWidth - 1) + x * widthScale :\n 0.5 * (x1 + x2) * (imageWidth - 1);\n\n if (xInd < 0 || xInd > imageWidth - 1) {\n for (let c = 0; c < numChannels; c++) {\n const ind =\n c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[ind] = extrapolationValue;\n }\n continue;\n }\n\n const closestX = Math.round(xInd);\n const closestY = Math.round(yInd);\n for (let c = 0; c < numChannels; c++) {\n const inInd = c + closestX * inStride[2] + closestY * inStride[1] +\n bInd * inStride[0];\n const outInd =\n c + x * outStride[2] + y * outStride[1] + b * outStride[0];\n output.values[outInd] = imageVals[inInd];\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(output.shape, output.dtype, output.values);\n}\n\nexport const cropAndResizeConfig: KernelConfig = {\n kernelName: CropAndResize,\n backendName: 'cpu',\n kernelFunc: cropAndResize as {} 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, Cumsum, CumsumAttrs, CumsumInputs, KernelConfig, KernelFunc, 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 cumsum(\n args: {inputs: CumsumInputs, backend: MathBackendCPU, attrs: CumsumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, exclusive, reverse} = attrs;\n\n assertNotComplex(x, 'cumsum');\n\n const permutation = backend_util.getAxesPermutation([axis], x.shape.length);\n let $x = x;\n if (permutation != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n }\n const permutedAxis = backend_util.getInnerMostAxes(1, x.shape.length)[0];\n\n if (permutedAxis !== $x.shape.length - 1) {\n throw new Error(\n `backend.cumsum in CPU expects an inner-most ` +\n `axis=${$x.shape.length - 1} but got axis=${permutedAxis}`);\n }\n\n const resultDtype = upcastType($x.dtype, 'int32');\n const vals = util.makeZerosTypedArray(\n util.sizeFromShape($x.shape), resultDtype) as TypedArray;\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n const finalDim = $x.shape[$x.shape.length - 1];\n const indexAdjuster = reverse ?\n (i: number, j: number) => i + finalDim - j - 1 :\n (i: number, j: number) => i + j;\n for (let i = 0; i < aVals.length; i += finalDim) {\n for (let j = 0; j < finalDim; j++) {\n const idx = indexAdjuster(i, j);\n if (j === 0) {\n vals[idx] = exclusive ? 0 : aVals[idx];\n } else {\n const prevIdx = indexAdjuster(i, j - 1);\n vals[idx] = exclusive ? aVals[prevIdx] + vals[prevIdx] :\n aVals[idx] + vals[prevIdx];\n }\n }\n }\n\n const result = backend.makeTensorInfo($x.shape, resultDtype, vals);\n\n if (permutation != null) {\n const reversePermutation = backend_util.getUndoAxesPermutation(permutation);\n const reverseTransposedResult = transpose(\n {inputs: {x: result}, backend, attrs: {perm: reversePermutation}});\n\n backend.disposeIntermediateTensorInfo(result);\n backend.disposeIntermediateTensorInfo($x);\n\n return reverseTransposedResult;\n }\n\n return result;\n}\n\nexport const cumsumConfig: KernelConfig = {\n kernelName: Cumsum,\n backendName: 'cpu',\n kernelFunc: cumsum as {} 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 {DenseBincount, DenseBincountAttrs, DenseBincountInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {bincountImpl, bincountReduceImpl} from './Bincount_impl';\n\nexport function denseBincount(args: {\n inputs: DenseBincountInputs,\n backend: MathBackendCPU,\n attrs: DenseBincountAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, weights} = inputs;\n const {size, binaryOutput} = attrs;\n\n if (x.shape.length === 1) {\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const weightsVals = backend.data.get(weights.dataId).values as TypedArray;\n\n const outVals =\n bincountImpl(xVals, weightsVals, weights.dtype, weights.shape, size);\n\n return backend.makeTensorInfo([size], weights.dtype, outVals);\n } else if (x.shape.length === 2) {\n const xBuf = backend.bufferSync(x);\n const weightsBuf = backend.bufferSync(weights);\n\n const outBuf = bincountReduceImpl(xBuf, weightsBuf, size, binaryOutput);\n\n return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);\n }\n\n throw new Error(\n `Error in denseBincount: input must be at most rank 2, but got rank` +\n `${x.shape.length}.`);\n}\n\nexport const denseBincountConfig: KernelConfig = {\n kernelName: DenseBincount,\n backendName: 'cpu',\n kernelFunc: denseBincount as {} 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 {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function depthToSpace(args: {\n inputs: DepthToSpaceInputs,\n backend: MathBackendCPU,\n attrs: DepthToSpaceAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockSize, dataFormat} = attrs;\n\n util.assert(\n dataFormat === 'NHWC',\n () => `Only NHWC dataFormat supported on CPU for depthToSpace. Got ${\n dataFormat}`);\n util.assert(\n blockSize > 1,\n () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);\n\n const batchSize = x.shape[0];\n const inputHeight = x.shape[1];\n const inputWidth = x.shape[2];\n const inputDepth = x.shape[3];\n\n const outputHeight = inputHeight * blockSize;\n const outputWidth = inputWidth * blockSize;\n const outputDepth = inputDepth / (blockSize * blockSize);\n\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const result =\n new Float32Array(batchSize * outputHeight * outputWidth * outputDepth);\n\n let outputIdx = 0;\n for (let b = 0; b < batchSize; ++b) {\n for (let h = 0; h < outputHeight; ++h) {\n const inH = Math.floor(h / blockSize);\n const offsetH = (h % blockSize);\n for (let w = 0; w < outputWidth; ++w) {\n const inW = Math.floor(w / blockSize);\n const offsetW = (w % blockSize);\n const offsetD = (offsetH * blockSize + offsetW) * outputDepth;\n for (let d = 0; d < outputDepth; ++d) {\n const inD = d + offsetD;\n const inputIdx =\n inD + inputDepth * (inW + inputWidth * (inH + inputHeight * b));\n result[outputIdx++] = xValues[inputIdx];\n }\n }\n }\n }\n\n return backend.makeTensorInfo(\n [batchSize, outputHeight, outputWidth, outputDepth], x.dtype, result);\n}\n\nexport const depthToSpaceConfig: KernelConfig = {\n kernelName: DepthToSpace,\n backendName: 'cpu',\n kernelFunc: depthToSpace as {} 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, DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function depthwiseConv2dNative(args: {\n inputs: DepthwiseConv2dNativeInputs,\n backend: MathBackendCPU,\n attrs: DepthwiseConv2dNativeAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations, dimRoundingMode} = attrs;\n\n assertNotComplex([x, filter], 'depthwiseConv2DNative');\n\n const xStrides = util.computeStrides(x.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n let $dilations = dilations;\n if ($dilations == null) {\n $dilations = [1, 1];\n }\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, $dilations),\n () => 'Error in depthwiseConv2d: Either strides or dilations must be ' +\n `1. Got strides ${strides} and dilations '${$dilations}'`);\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, $dilations,\n pad, dimRoundingMode, true /* depthwise */);\n\n const {filterHeight, filterWidth, dilationHeight, dilationWidth, padInfo} =\n convInfo;\n const padLeft = padInfo.left;\n const padTop = padInfo.top;\n const chMul = convInfo.outChannels / convInfo.inChannels;\n const y = new TensorBuffer(convInfo.outShape, x.dtype as 'float32');\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const wVals = backend.data.get(filter.dataId).values as TypedArray;\n const yVals = y.values;\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n const xOffset1 = b * xStrides[0];\n const yOffset1 = b * y.strides[0];\n for (let yR = 0; yR < convInfo.outHeight; ++yR) {\n const yOffset2 = yOffset1 + yR * y.strides[1];\n const xRCorner = yR * convInfo.strideHeight - padTop;\n for (let wR = 0; wR < filterHeight; ++wR) {\n const xR = xRCorner + wR * dilationHeight;\n if (xR < 0 || xR >= convInfo.inHeight) {\n continue;\n }\n const wOffset1 = wR * filterStrides[0];\n const xOffset2 = xOffset1 + xR * xStrides[1];\n for (let yC = 0; yC < convInfo.outWidth; ++yC) {\n const yOffset3 = yOffset2 + yC * y.strides[2];\n const xCCorner = yC * convInfo.strideWidth - padLeft;\n for (let wC = 0; wC < filterWidth; ++wC) {\n const xC = xCCorner + wC * dilationWidth;\n if (xC < 0 || xC >= convInfo.inWidth) {\n continue;\n }\n const wOffset2 = wOffset1 + wC * filterStrides[1];\n const xOffset3 = xOffset2 + xC * convInfo.inChannels;\n let yOffset4 = yOffset3;\n let wOffset3 = wOffset2;\n for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {\n const xVal = xVals[xOffset3 + d1];\n for (let q = 0; q < chMul; ++q) {\n yVals[yOffset4 + q] += xVal * wVals[wOffset3 + q];\n }\n yOffset4 += chMul;\n wOffset3 += chMul;\n }\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(y.shape, y.dtype, y.values);\n}\n\nexport const depthwiseConv2dNativeConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNative,\n backendName: 'cpu',\n kernelFunc: depthwiseConv2dNative as {} 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, DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function depthwiseConv2dNativeBackpropFilter(args: {\n inputs: DepthwiseConv2dNativeBackpropFilterInputs,\n backend: MathBackendCPU,\n attrs: DepthwiseConv2dNativeBackpropFilterAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, dilations, pad, dimRoundingMode, filterShape} = attrs;\n\n assertNotComplex([x, dy], 'depthwiseConv2dNativeBackpropFilter');\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const {strideHeight, strideWidth, filterHeight, filterWidth} = convInfo;\n\n const dW = new TensorBuffer(convInfo.filterShape, 'float32');\n\n const leftPad = convInfo.padInfo.left;\n const topPad = convInfo.padInfo.top;\n const chMul = convInfo.outChannels / convInfo.inChannels;\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const xBuf = new TensorBuffer(x.shape, x.dtype, xVals);\n const dyVals = backend.data.get(dy.dataId).values as TypedArray;\n const dyBuf = new TensorBuffer(dy.shape, dy.dtype, dyVals);\n for (let wR = 0; wR < filterHeight; ++wR) {\n const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));\n const yRMax = Math.min(\n convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);\n\n for (let wC = 0; wC < filterWidth; ++wC) {\n const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));\n const yCMax = Math.min(\n convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);\n\n for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {\n const d1 = Math.trunc(d2 / chMul);\n const dm = d2 % chMul;\n\n let dotProd = 0;\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let yR = yRMin; yR < yRMax; ++yR) {\n const xR = wR + yR * strideHeight - topPad;\n for (let yC = yCMin; yC < yCMax; ++yC) {\n const xC = wC + yC * strideWidth - leftPad;\n dotProd += (xBuf.get(b, xR, xC, d1) as number) *\n (dyBuf.get(b, yR, yC, d2) as number);\n }\n }\n }\n dW.set(dotProd, wR, wC, d1, dm);\n }\n }\n }\n\n return backend.makeTensorInfo(dW.shape, dW.dtype, dW.values);\n}\n\nexport const depthwiseConv2dNativeBackpropFilterConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropFilter,\n backendName: 'cpu',\n kernelFunc: depthwiseConv2dNativeBackpropFilter as {} 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, DepthwiseConv2dNativeBackpropInput, DepthwiseConv2dNativeBackpropInputAttrs, DepthwiseConv2dNativeBackpropInputInputs, KernelConfig, KernelFunc, TensorBuffer, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function depthwiseConv2dNativeBackpropInput(args: {\n inputs: DepthwiseConv2dNativeBackpropInputInputs,\n backend: MathBackendCPU,\n attrs: DepthwiseConv2dNativeBackpropInputAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {strides, dilations, pad, dimRoundingMode, inputShape} = attrs;\n\n assertNotComplex([dy, filter], 'depthwiseConv2DNativeBackpropInput');\n\n const dyStrides = util.computeStrides(dy.shape);\n const filterStrides = util.computeStrides(filter.shape);\n\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const dx = new TensorBuffer(convInfo.inShape, 'float32');\n const dxValues = dx.values;\n const [dxS0, dxS1, dxS2] = dx.strides;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const [dyS0, dyS1, dyS2] = dyStrides;\n const fltValues = backend.data.get(filter.dataId).values as TypedArray;\n const [fltS0, fltS1, fltS2] = filterStrides;\n const {\n batchSize,\n filterHeight,\n filterWidth,\n inChannels,\n inHeight,\n inWidth,\n outChannels,\n outHeight,\n outWidth,\n strideHeight,\n strideWidth\n } = convInfo;\n const topPad = filterHeight - 1 - convInfo.padInfo.top;\n const leftPad = filterWidth - 1 - convInfo.padInfo.left;\n const chMul = outChannels / inChannels;\n\n for (let b = 0; b < batchSize; ++b) {\n for (let d1 = 0; d1 < inChannels; ++d1) {\n for (let xR = 0; xR < inHeight; ++xR) {\n const xRCorner = xR - topPad;\n const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));\n const yRMax =\n Math.min(outHeight, (filterHeight + xRCorner) / strideHeight);\n\n for (let xC = 0; xC < inWidth; ++xC) {\n const xCCorner = xC - leftPad;\n const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));\n const yCMax =\n Math.min(outWidth, (filterWidth + xCCorner) / strideWidth);\n\n let dotProd = 0;\n for (let yR = xRMin; yR < yRMax; ++yR) {\n const wR = yR * strideHeight - xRCorner;\n\n for (let yC = xCMin; yC < yCMax; ++yC) {\n const wC = yC * strideWidth - xCCorner;\n const dyOffset = dyS0 * b + dyS1 * yR + dyS2 * yC;\n const fltOffset = fltS0 * (filterHeight - 1 - wR) +\n fltS1 * (filterWidth - 1 - wC) + fltS2 * d1;\n\n for (let dm = 0; dm < chMul; ++dm) {\n const d2 = d1 * chMul + dm;\n const pixel = dyValues[dyOffset + d2];\n const weight = fltValues[fltOffset + dm];\n dotProd += pixel * weight;\n }\n }\n }\n dxValues[dxS0 * b + dxS1 * xR + dxS2 * xC + d1] = dotProd;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const depthwiseConv2dNativeBackpropInputConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropInput,\n backendName: 'cpu',\n kernelFunc: depthwiseConv2dNativeBackpropInput as {} 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 {buffer, Diag, DiagInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function diag(args: {inputs: DiagInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n const xSize = util.sizeFromShape(x.shape);\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const outBuf = buffer([xSize, xSize], x.dtype);\n const vals = outBuf.values;\n for (let i = 0; i < xVals.length; i++) {\n vals[i * xSize + i] = xVals[i];\n }\n\n const outShape = [...x.shape, ...x.shape];\n\n return backend.makeTensorInfo(outShape, outBuf.dtype, outBuf.values);\n}\n\nexport const diagConfig: KernelConfig = {\n kernelName: Diag,\n backendName: 'cpu',\n kernelFunc: diag as {} 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, Dilation2D, Dilation2DAttrs, Dilation2DInputs, KernelConfig, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const dilation2dConfig: KernelConfig = {\n kernelName: Dilation2D,\n backendName: 'cpu',\n kernelFunc: ({inputs, backend, attrs}) => {\n const {x, filter} = inputs as Dilation2DInputs;\n const {strides, pad, dilations} = attrs as {} as Dilation2DAttrs;\n const cpuBackend = backend as MathBackendCPU;\n\n const xVals = cpuBackend.data.get(x.dataId).values as TypedArray;\n const xRank = x.shape.length;\n\n const filterVals = cpuBackend.data.get(filter.dataId).values as TypedArray;\n const filterRank = filter.shape.length;\n\n const {\n batchSize,\n inHeight,\n inWidth,\n inChannels,\n outHeight,\n outWidth,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n dilationHeight,\n dilationWidth,\n outShape\n } =\n backend_util.computeDilation2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number], strides, pad,\n 'NHWC' /* dataFormat */, dilations);\n\n const outSize = util.sizeFromShape(outShape);\n const outRank = outShape.length;\n const outputVals = util.getArrayFromDType(x.dtype, outSize);\n\n // Upsampling the input by fill in `dilation size - 1` values between each\n // input value.\n // This implementation follows the TF c++ implementation:\n // https://github.com/tensorflow/tensorflow/blob/d9a3a849edc198e90172bc58eb293de457f9d986/tensorflow/core/kernels/dilation_ops.cc\n for (let b = 0; b < batchSize; ++b) {\n for (let hOut = 0; hOut < outHeight; ++hOut) {\n const hBeg = hOut * strideHeight - padInfo.top;\n for (let wOut = 0; wOut < outWidth; ++wOut) {\n const wBeg = wOut * strideWidth - padInfo.left;\n for (let d = 0; d < inChannels; ++d) {\n let curVal = Number.MIN_SAFE_INTEGER;\n for (let h = 0; h < filterHeight; ++h) {\n const hIn = hBeg + h * dilationHeight;\n if (hIn >= 0 && hIn < inHeight) {\n for (let w = 0; w < filterWidth; ++w) {\n const wIn = wBeg + w * dilationWidth;\n if (wIn >= 0 && wIn < inWidth) {\n const xIndex = util.locToIndex(\n [b, hIn, wIn, d], xRank, util.computeStrides(x.shape));\n const filterIndex = util.locToIndex(\n [h, w, d], filterRank,\n util.computeStrides(filter.shape));\n const val = xVals[xIndex] + filterVals[filterIndex];\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n const outputIndex = util.locToIndex(\n [b, hOut, wOut, d], outRank, util.computeStrides(outShape));\n outputVals[outputIndex] = curVal;\n }\n }\n }\n }\n\n const dataId = cpuBackend.write(\n util.toTypedArray(outputVals, x.dtype), outShape, x.dtype);\n\n return {dataId, shape: outShape, dtype: x.dtype};\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, Dilation2DAttrs, Dilation2DBackpropFilter, Tensor3D, Tensor4D, TypedArray, util} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const dilation2dBackpropFilterConfig: KernelConfig = {\n kernelName: Dilation2DBackpropFilter,\n backendName: 'cpu',\n kernelFunc: ({inputs, backend, attrs}) => {\n const {x, filter, dy} =\n inputs as {x: Tensor4D, filter: Tensor3D, dy: Tensor4D};\n const {strides, pad, dilations} = attrs as {} as Dilation2DAttrs;\n const cpuBackend = backend as MathBackendCPU;\n\n const $x =\n util.toNestedArray(\n x.shape, cpuBackend.data.get(x.dataId).values as TypedArray) as\n number[][][][];\n\n const $filter = util.toNestedArray(\n filter.shape,\n cpuBackend.data.get(filter.dataId).values as\n TypedArray) as number[][][];\n\n const {\n batchSize,\n inHeight,\n inWidth,\n inChannels,\n outHeight,\n outWidth,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n dilationHeight,\n dilationWidth,\n outShape\n } =\n backend_util.computeDilation2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number], strides, pad,\n 'NHWC' /* dataFormat */, dilations);\n\n util.assert(\n dy.rank === outShape.length,\n () => `Error in ${Dilation2DBackpropFilter}, dy ` +\n `must have the same rank as output ${outShape.length}, but got ` +\n `${dy.rank}`);\n\n const $dy =\n util.toNestedArray(\n outShape, cpuBackend.data.get(dy.dataId).values as TypedArray) as\n number[][][][];\n\n // The computed filter gradients has the same dimensions as the filter:\n // [filterHeight, filterWidth, depth]\n const gradients = util.makeZerosNestedTypedArray(\n filter.shape, filter.dtype) as number[][][];\n\n // In the case of multiple argmax branches, we only back-propagate along the\n // last branch, i.e., the one with largest value of `h * filter_cols + w`,\n // similarly to the max-pooling backward routines.\n // This implementation follows the TF c++ implementation:\n // https://github.com/tensorflow/tensorflow/blob/d9a3a849edc198e90172bc58eb293de457f9d986/tensorflow/core/kernels/dilation_ops.cc\n for (let b = 0; b < batchSize; ++b) {\n for (let hOut = 0; hOut < outHeight; ++hOut) {\n const hBeg = hOut * strideHeight - padInfo.top;\n for (let wOut = 0; wOut < outWidth; ++wOut) {\n const wBeg = wOut * strideWidth - padInfo.left;\n for (let d = 0; d < inChannels; ++d) {\n let curVal = Number.MIN_SAFE_INTEGER;\n let hMax = 0;\n let wMax = 0;\n for (let h = 0; h < filterHeight; ++h) {\n const hIn = hBeg + h * dilationHeight;\n if (hIn >= 0 && hIn < inHeight) {\n for (let w = 0; w < filterWidth; ++w) {\n const wIn = wBeg + w * dilationWidth;\n if (wIn >= 0 && wIn < inWidth) {\n const val = $x[b][hIn][wIn][d] + $filter[h][w][d];\n if (val > curVal) {\n curVal = val;\n hMax = h;\n wMax = w;\n }\n }\n }\n }\n }\n gradients[hMax][wMax][d] += $dy[b][hOut][wOut][d];\n }\n }\n }\n }\n\n const dataId = cpuBackend.write(\n util.toTypedArray(gradients, x.dtype), filter.shape, filter.dtype);\n\n return {dataId, shape: filter.shape, dtype: filter.dtype};\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, Dilation2DAttrs, Dilation2DBackpropInput, Tensor3D, Tensor4D, TypedArray, util} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const dilation2dBackpropInputConfig: KernelConfig = {\n kernelName: Dilation2DBackpropInput,\n backendName: 'cpu',\n kernelFunc: ({inputs, backend, attrs}) => {\n const {x, filter, dy} =\n inputs as {x: Tensor4D, filter: Tensor3D, dy: Tensor4D};\n const {strides, pad, dilations} = attrs as {} as Dilation2DAttrs;\n const cpuBackend = backend as MathBackendCPU;\n\n const $x =\n util.toNestedArray(\n x.shape, cpuBackend.data.get(x.dataId).values as TypedArray) as\n number[][][][];\n\n const $filter = util.toNestedArray(\n filter.shape,\n cpuBackend.data.get(filter.dataId).values as\n TypedArray) as number[][][];\n\n const {\n batchSize,\n inHeight,\n inWidth,\n inChannels,\n outHeight,\n outWidth,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n dilationHeight,\n dilationWidth,\n outShape\n } =\n backend_util.computeDilation2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number], strides, pad,\n 'NHWC' /* dataFormat */, dilations);\n\n util.assert(\n dy.rank === outShape.length,\n () => `Error in ${Dilation2DBackpropInput}, dy ` +\n `must have the same rank as output ${outShape.length}, but got ` +\n `${dy.rank}`);\n\n const $dy =\n util.toNestedArray(\n outShape, cpuBackend.data.get(dy.dataId).values as TypedArray) as\n number[][][][];\n\n // The computed gradients has the same dimensions as the input:\n // [batch, inputHeight, inputCols, inChannel]\n const gradients =\n util.makeZerosNestedTypedArray(x.shape, x.dtype) as number[][][][];\n\n // In the case of multiple argmax branches, we only back-propagate along the\n // last branch, i.e., the one with largest value of `h * filter_cols + w`,\n // similarly to the max-pooling backward routines.\n // This implementation follows the TF c++ implementation:\n // https://github.com/tensorflow/tensorflow/blob/d9a3a849edc198e90172bc58eb293de457f9d986/tensorflow/core/kernels/dilation_ops.cc\n for (let b = 0; b < batchSize; ++b) {\n for (let hOut = 0; hOut < outHeight; ++hOut) {\n const hBeg = hOut * strideHeight - padInfo.top;\n for (let wOut = 0; wOut < outWidth; ++wOut) {\n const wBeg = wOut * strideWidth - padInfo.left;\n for (let d = 0; d < inChannels; ++d) {\n let curVal = Number.MIN_SAFE_INTEGER;\n let hInMax = (hBeg < 0) ? 0 : hBeg;\n let wInMax = (wBeg < 0) ? 0 : wBeg;\n for (let h = 0; h < filterHeight; ++h) {\n const hIn = hBeg + h * dilationHeight;\n if (hIn >= 0 && hIn < inHeight) {\n for (let w = 0; w < filterWidth; ++w) {\n const wIn = wBeg + w * dilationWidth;\n if (wIn >= 0 && wIn < inWidth) {\n const val = $x[b][hIn][wIn][d] + $filter[h][w][d];\n if (val > curVal) {\n curVal = val;\n hInMax = hIn;\n wInMax = wIn;\n }\n }\n }\n }\n }\n gradients[b][hInMax][wInMax][d] += $dy[b][hOut][wOut][d];\n }\n }\n }\n }\n\n const dataId = cpuBackend.write(\n util.toTypedArray(gradients, x.dtype), x.shape, x.dtype);\n\n return {dataId, shape: x.shape, dtype: x.dtype};\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, 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 {} as KernelFunc\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 {backend_util, Einsum, EinsumAttrs, EinsumInputs, KernelConfig, KernelFunc, Tensor, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {multiply} from './Multiply';\nimport {reshape} from './Reshape';\nimport {sum} from './Sum';\nimport {transpose} from './Transpose';\n\nexport function einsum(\n args: {inputs: EinsumInputs, backend: MathBackendCPU, attrs: EinsumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {equation} = attrs;\n const tensors = inputs as Tensor[];\n\n const {allDims, summedDims, idDims} =\n backend_util.decodeEinsumEquation(equation, tensors.length);\n backend_util.checkEinsumDimSizes(allDims.length, idDims, tensors);\n const {path, steps} = backend_util.getEinsumComputePath(summedDims, idDims);\n\n const nSteps = steps.length;\n let out: TensorInfo|null = null;\n let numDimsRemaining = allDims.length;\n const tensorsToDispose: TensorInfo[] = [];\n for (let i = 0; i < nSteps; ++i) {\n for (const idTerm of steps[i]) {\n const {permutationIndices: perm, expandDims: dimsToExpand} =\n backend_util.getEinsumPermutation(numDimsRemaining, idDims[idTerm]);\n let x: TensorInfo;\n if (backend_util.isIdentityPermutation(perm)) {\n x = tensors[idTerm];\n } else {\n x = transpose({inputs: {x: tensors[idTerm]}, backend, attrs: {perm}});\n tensorsToDispose.push(x);\n }\n const targetShape: number[] = x.shape.slice();\n for (let k = 0; k < dimsToExpand.length; ++k) {\n targetShape.splice(dimsToExpand[k], 0, 1);\n }\n\n if (!util.arraysEqual(x.shape, targetShape)) {\n x = reshape({inputs: {x}, backend, attrs: {shape: targetShape}});\n tensorsToDispose.push(x);\n }\n if (out === null) {\n out = x;\n } else {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n out = multiply({inputs: {a: x, b: out}, backend}) as TensorInfo;\n tensorsToDispose.push(out);\n }\n }\n if (i < nSteps - 1) {\n if (path[i] >= 0) {\n out = sum({\n inputs: {x: out},\n backend,\n attrs: {\n axis: path[i] - (allDims.length - numDimsRemaining),\n keepDims: false\n }\n });\n tensorsToDispose.push(out);\n }\n numDimsRemaining--;\n }\n }\n\n // Clean up intermediate tensors.\n for (const tensorInfo of tensorsToDispose) {\n if (tensorInfo === out) {\n continue;\n }\n backend.disposeIntermediateTensorInfo(tensorInfo);\n }\n\n return out;\n}\n\nexport const einsumConfig: KernelConfig = {\n kernelName: Einsum,\n backendName: 'cpu',\n kernelFunc: einsum as {} 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 {EluGrad, EluGradInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function eluGrad(args: {inputs: EluGradInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {dy, y} = inputs;\n\n assertNotComplex([dy, y], 'eluGrad');\n\n const resultValues = new Float32Array(util.sizeFromShape(y.shape));\n const values = backend.data.get(y.dataId).values as TypedArray;\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n for (let i = 0; i < values.length; ++i) {\n const v = values[i];\n if (v >= 1) {\n resultValues[i] = dyValues[i];\n } else {\n resultValues[i] = dyValues[i] * (v + 1);\n }\n }\n\n return backend.makeTensorInfo(y.shape, 'float32', resultValues);\n}\n\nexport const eluGradConfig: KernelConfig = {\n kernelName: EluGrad,\n backendName: 'cpu',\n kernelFunc: eluGrad as {} 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 {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 {} 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, Tensor, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {add} from '../kernels/Add';\nimport {complex} from '../kernels/Complex';\nimport {concat} from '../kernels/Concat';\nimport {identity} from '../kernels/Identity';\nimport {imag} from '../kernels/Imag';\nimport {multiply} from '../kernels/Multiply';\nimport {real} from '../kernels/Real';\nimport {realDivConfig} from '../kernels/RealDiv';\nimport {slice} from '../kernels/Slice';\nimport {sub} from '../kernels/Sub';\n\n/**\n * Calculate FFT of inner most elements of batch tensor.\n */\nexport function fftBatch(\n input: TensorInfo, inverse: boolean,\n cpuBackend: MathBackendCPU): TensorInfo {\n const inputShape = input.shape;\n const batch = inputShape[0];\n const innerDim = inputShape[1];\n\n const inputVals = cpuBackend.data.get(input.dataId);\n\n const real2D = inputVals.complexTensorInfos.real;\n const imag2D = inputVals.complexTensorInfos.imag;\n\n // Collects real and imaginary values separately.\n const resultShape = [batch, innerDim];\n const resultSize = util.sizeFromShape(resultShape);\n const resultReal = util.getTypedArrayFromDType('float32', resultSize);\n const resultImag = util.getTypedArrayFromDType('float32', resultSize);\n\n for (let b = 0; b < batch; b++) {\n // TODO: Support slice ops for complex type.\n const r = slice({\n inputs: {x: real2D},\n backend: cpuBackend,\n attrs: {begin: [b, 0], size: [1, innerDim]}\n });\n const i = slice({\n inputs: {x: imag2D},\n backend: cpuBackend,\n attrs: {begin: [b, 0], size: [1, innerDim]}\n });\n\n const input = complex({inputs: {real: r, imag: i}, backend: cpuBackend});\n\n // Run FFT by batch element.\n const {real, imag} = fftImpl(input, inverse, cpuBackend);\n const res = backend_util.mergeRealAndImagArrays(real, imag);\n\n for (let d = 0; d < innerDim; d++) {\n const c = backend_util.getComplexWithIndex(res, d);\n resultReal[b * innerDim + d] = c.real;\n resultImag[b * innerDim + d] = c.imag;\n }\n\n cpuBackend.disposeIntermediateTensorInfo(r);\n cpuBackend.disposeIntermediateTensorInfo(i);\n cpuBackend.disposeIntermediateTensorInfo(input);\n }\n\n const $realInfo: TensorInfo =\n cpuBackend.makeTensorInfo(resultShape, 'float32', resultReal);\n const $imagInfo: TensorInfo =\n cpuBackend.makeTensorInfo(resultShape, 'float32', resultImag);\n\n const result = complex(\n {inputs: {real: $realInfo, imag: $imagInfo}, backend: cpuBackend});\n\n cpuBackend.disposeIntermediateTensorInfo($realInfo);\n cpuBackend.disposeIntermediateTensorInfo($imagInfo);\n\n return result;\n}\n\nexport function fftImpl(\n input: TensorInfo, inverse: boolean,\n cpuBackend: MathBackendCPU): {real: Float32Array, imag: Float32Array} {\n const inputSize = util.sizeFromShape(input.shape);\n\n const inputVals = cpuBackend.data.get(input.dataId);\n\n const realVals =\n cpuBackend.data.get(inputVals.complexTensorInfos.real.dataId).values as\n Float32Array;\n\n const imagVals =\n cpuBackend.data.get(inputVals.complexTensorInfos.imag.dataId).values as\n Float32Array;\n\n if (isExponentOf2(inputSize)) {\n const result =\n fftRadix2(realVals, imagVals, inputSize, inverse, cpuBackend);\n\n const resultShape = [input.shape[0], input.shape[1]];\n\n if (inverse) {\n const realInfo: TensorInfo =\n cpuBackend.makeTensorInfo(resultShape, 'float32', result.real);\n const imagInfo: TensorInfo =\n cpuBackend.makeTensorInfo(resultShape, 'float32', result.imag);\n\n const sizeInfo: TensorInfo = cpuBackend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(inputSize as {} as 'float32', 'float32'));\n const sizeInfoCopy =\n identity({inputs: {x: sizeInfo}, backend: cpuBackend});\n\n const divRealInfo =\n realDivConfig.kernelFunc(\n {inputs: {a: realInfo, b: sizeInfo}, backend: cpuBackend}) as\n TensorInfo;\n const divImagInfo =\n realDivConfig.kernelFunc(\n {inputs: {a: imagInfo, b: sizeInfoCopy}, backend: cpuBackend}) as\n TensorInfo;\n\n const divRealVals =\n cpuBackend.data.get(divRealInfo.dataId).values as Float32Array;\n const divImagVals =\n cpuBackend.data.get(divImagInfo.dataId).values as Float32Array;\n\n cpuBackend.disposeIntermediateTensorInfo(realInfo);\n cpuBackend.disposeIntermediateTensorInfo(imagInfo);\n cpuBackend.disposeIntermediateTensorInfo(sizeInfo);\n cpuBackend.disposeIntermediateTensorInfo(sizeInfoCopy);\n cpuBackend.disposeIntermediateTensorInfo(divRealInfo);\n cpuBackend.disposeIntermediateTensorInfo(divImagInfo);\n\n return {real: divRealVals, imag: divImagVals};\n }\n\n return result;\n } else {\n const data = backend_util.mergeRealAndImagArrays(realVals, imagVals);\n\n const rawOutput =\n fourierTransformByMatmul(data, inputSize, inverse) as Float32Array;\n\n return backend_util.splitRealAndImagArrays(rawOutput);\n }\n}\n\nfunction isExponentOf2(size: number): boolean {\n return (size & size - 1) === 0;\n}\n\n// FFT using Cooley-Tukey algorithm on radix 2 dimensional input.\nfunction fftRadix2(\n realVals: Float32Array, imagVals: Float32Array, size: number,\n inverse: boolean,\n cpuBackend: MathBackendCPU): {real: Float32Array, imag: Float32Array} {\n if (size === 1) {\n return {real: realVals, imag: imagVals};\n }\n\n const data = backend_util.mergeRealAndImagArrays(realVals, imagVals);\n\n const half = size / 2;\n\n const evenComplex = backend_util.complexWithEvenIndex(data);\n\n const evenRealVals = evenComplex.real;\n const evenImagVals = evenComplex.imag;\n\n const evenShape = [evenRealVals.length];\n\n const evenRealInfo =\n cpuBackend.makeTensorInfo(evenShape, 'float32', evenRealVals);\n const evenImagInfo =\n cpuBackend.makeTensorInfo(evenShape, 'float32', evenImagVals);\n\n const evenTensorInfo = complex(\n {inputs: {real: evenRealInfo, imag: evenImagInfo}, backend: cpuBackend});\n\n const oddComplex = backend_util.complexWithOddIndex(data);\n\n const oddRealVals = oddComplex.real;\n const oddImagVals = oddComplex.imag;\n\n const oddShape = [oddRealVals.length];\n\n const oddRealInfo =\n cpuBackend.makeTensorInfo(oddShape, 'float32', oddRealVals);\n const oddImagInfo =\n cpuBackend.makeTensorInfo(oddShape, 'float32', oddImagVals);\n\n const oddTensorInfo = complex(\n {inputs: {real: oddRealInfo, imag: oddImagInfo}, backend: cpuBackend});\n\n // Recursive call for half part of original input.\n const $evenComplex =\n fftRadix2(evenRealVals, evenImagVals, half, inverse, cpuBackend);\n\n const $evenRealVals = $evenComplex.real;\n const $evenImagVals = $evenComplex.imag;\n\n const $evenShape = [$evenRealVals.length];\n\n const $evenRealInfo =\n cpuBackend.makeTensorInfo($evenShape, 'float32', $evenRealVals);\n const $evenImagInfo =\n cpuBackend.makeTensorInfo($evenShape, 'float32', $evenImagVals);\n\n const $evenTensorInfo = complex({\n inputs: {real: $evenRealInfo, imag: $evenImagInfo},\n backend: cpuBackend\n });\n\n const $oddComplex =\n fftRadix2(oddRealVals, oddImagVals, half, inverse, cpuBackend);\n\n const $oddRealVals = $oddComplex.real;\n const $oddImagVals = $oddComplex.imag;\n\n const $oddShape = [$oddRealVals.length];\n\n const $oddRealInfo =\n cpuBackend.makeTensorInfo($oddShape, 'float32', $oddRealVals);\n const $oddImagInfo =\n cpuBackend.makeTensorInfo($oddShape, 'float32', $oddImagVals);\n\n const $oddTensorInfo = complex(\n {inputs: {real: $oddRealInfo, imag: $oddImagInfo}, backend: cpuBackend});\n\n const e = backend_util.exponents(size, inverse);\n const eShape = [e.real.length];\n\n const eRealInfo = cpuBackend.makeTensorInfo(eShape, 'float32', e.real);\n const eImagInfo = cpuBackend.makeTensorInfo(eShape, 'float32', e.imag);\n\n const complexInfo = complex(\n {inputs: {real: eRealInfo, imag: eImagInfo}, backend: cpuBackend});\n\n const exponentInfo =\n multiply(\n {inputs: {a: complexInfo, b: $oddTensorInfo}, backend: cpuBackend}) as\n TensorInfo;\n\n const addPart = add({\n inputs: {a: $evenTensorInfo, b: exponentInfo},\n backend: cpuBackend\n }) as TensorInfo;\n const subPart = sub({\n inputs: {a: $evenTensorInfo, b: exponentInfo},\n backend: cpuBackend\n }) as TensorInfo;\n\n const addPartReal = real({inputs: {input: addPart}, backend: cpuBackend});\n const subPartReal = real({inputs: {input: subPart}, backend: cpuBackend});\n\n const addPartImag = imag({inputs: {input: addPart}, backend: cpuBackend});\n const subPartImag = imag({inputs: {input: subPart}, backend: cpuBackend});\n\n const $real = concat({\n inputs: [addPartReal as Tensor, subPartReal as Tensor],\n backend: cpuBackend,\n attrs: {axis: 0}\n });\n const $imag = concat({\n inputs: [addPartImag as Tensor, subPartImag as Tensor],\n backend: cpuBackend,\n attrs: {axis: 0}\n });\n\n const $realVals = cpuBackend.data.get($real.dataId).values as Float32Array;\n const $imagVals = cpuBackend.data.get($imag.dataId).values as Float32Array;\n\n cpuBackend.disposeIntermediateTensorInfo(evenRealInfo);\n cpuBackend.disposeIntermediateTensorInfo(evenImagInfo);\n cpuBackend.disposeIntermediateTensorInfo(evenTensorInfo);\n cpuBackend.disposeIntermediateTensorInfo(oddRealInfo);\n cpuBackend.disposeIntermediateTensorInfo(oddImagInfo);\n cpuBackend.disposeIntermediateTensorInfo(oddTensorInfo);\n cpuBackend.disposeIntermediateTensorInfo($evenRealInfo);\n cpuBackend.disposeIntermediateTensorInfo($evenImagInfo);\n cpuBackend.disposeIntermediateTensorInfo($evenTensorInfo);\n cpuBackend.disposeIntermediateTensorInfo($oddRealInfo);\n cpuBackend.disposeIntermediateTensorInfo($oddImagInfo);\n cpuBackend.disposeIntermediateTensorInfo($oddTensorInfo);\n cpuBackend.disposeIntermediateTensorInfo(eRealInfo);\n cpuBackend.disposeIntermediateTensorInfo(eImagInfo);\n cpuBackend.disposeIntermediateTensorInfo(complexInfo);\n cpuBackend.disposeIntermediateTensorInfo(exponentInfo);\n cpuBackend.disposeIntermediateTensorInfo(addPart);\n cpuBackend.disposeIntermediateTensorInfo(subPart);\n cpuBackend.disposeIntermediateTensorInfo(addPartReal);\n cpuBackend.disposeIntermediateTensorInfo(addPartImag);\n cpuBackend.disposeIntermediateTensorInfo(subPartReal);\n cpuBackend.disposeIntermediateTensorInfo(subPartImag);\n cpuBackend.disposeIntermediateTensorInfo($real);\n cpuBackend.disposeIntermediateTensorInfo($imag);\n\n return {real: $realVals, imag: $imagVals};\n}\n\n// Calculate fourier transform by multplying sinusoid matrix.\nfunction fourierTransformByMatmul(\n data: TypedArray, size: number, inverse: boolean): TypedArray {\n const ret = new Float32Array(size * 2);\n // TODO: Use matmul instead once it supports complex64 type.\n for (let r = 0; r < size; r++) {\n let real = 0.0;\n let imag = 0.0;\n for (let c = 0; c < size; c++) {\n const e = backend_util.exponent(r * c, size, inverse);\n const term = backend_util.getComplexWithIndex(data as Float32Array, c);\n real += term.real * e.real - term.imag * e.imag;\n imag += term.real * e.imag + term.imag * e.real;\n }\n if (inverse) {\n real /= size;\n imag /= size;\n }\n backend_util.assignToTypedArray(ret, real, imag, r);\n }\n return ret;\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 {FFT, FFTInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {fftBatch} from '../utils/fft_utils';\nimport {reshape} from './Reshape';\n\nexport function fft(args: {inputs: FFTInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n const inputSize = util.sizeFromShape(input.shape);\n\n // Collapse all outer dimensions to a single batch dimension.\n const innerDimensionSize = input.shape[input.shape.length - 1];\n const batch = inputSize / innerDimensionSize;\n\n const input2D = reshape({\n inputs: {x: input},\n backend,\n attrs: {shape: [batch, innerDimensionSize]}\n });\n\n const result = fftBatch(input2D, false, backend);\n\n const resultReshaped =\n reshape({inputs: {x: result}, backend, attrs: {shape: input.shape}});\n\n backend.disposeIntermediateTensorInfo(input2D);\n backend.disposeIntermediateTensorInfo(result);\n\n return resultReshaped;\n}\n\nexport const fftConfig: KernelConfig = {\n kernelName: FFT,\n backendName: 'cpu',\n kernelFunc: fft as {} 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, DataValues, Fill, FillAttrs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function fill(args: {backend: MathBackendCPU, attrs: FillAttrs}):\n TensorInfo {\n const {backend, attrs} = args;\n const {shape, value, dtype} = attrs;\n\n const $dtype = dtype || util.inferDtype(value);\n const values = util.getArrayFromDType($dtype, util.sizeFromShape(shape));\n fillValues(values, value, $dtype);\n\n return backend.makeTensorInfo(shape, $dtype, values);\n}\n\nexport const fillConfig: KernelConfig = {\n kernelName: Fill,\n backendName: 'cpu',\n kernelFunc: fill as {} as KernelFunc\n};\n\nfunction fillValues(\n values: DataValues, value: string|number, dtype: DataType): void {\n if (dtype === 'string') {\n (values as string[]).fill(value as string);\n } else {\n (values as TypedArray).fill(value as number);\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 {KernelConfig, NumericDataType, TypedArray} from '@tensorflow/tfjs-core';\nimport {FlipLeftRight, FlipLeftRightInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const flipLeftRightConfig: KernelConfig = {\n kernelName: FlipLeftRight,\n backendName: 'cpu',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {image} = inputs as FlipLeftRightInputs;\n const cpuBackend = backend as MathBackendCPU;\n\n const output = util.getTypedArrayFromDType(\n image.dtype as NumericDataType, util.sizeFromShape(image.shape));\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n\n const imageVals = cpuBackend.data.get(image.dataId).values as TypedArray;\n\n for (let batchIdx = 0; batchIdx < batch; batchIdx++) {\n const batchOffset = batchIdx * imageWidth * imageHeight * numChannels;\n\n for (let row = 0; row < imageHeight; row++) {\n const rowOffset = row * (imageWidth * numChannels);\n\n for (let col = 0; col < imageWidth; col++) {\n const colOffset = col * numChannels;\n\n for (let channel = 0; channel < numChannels; channel++) {\n const coordX = Math.round(imageWidth - col - 1);\n const outIdx = batchOffset + rowOffset + colOffset + channel;\n\n let outputValue = imageVals[outIdx];\n // If the coordinate position falls within the image boundaries...\n if (coordX >= 0 && coordX < imageWidth) {\n // set the output to the image value at the coordinate position.\n const rotatedColOffset = coordX * numChannels;\n const imageIdx =\n batchOffset + rowOffset + rotatedColOffset + channel;\n outputValue = imageVals[imageIdx];\n }\n output[outIdx] = outputValue;\n }\n }\n }\n }\n\n const dataId = cpuBackend.write(output, image.shape, image.dtype);\n return {dataId, shape: image.shape, dtype: image.dtype};\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 {FloorDiv, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const floorDivImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => Math.floor(a / b));\nexport const floorDiv =\n binaryKernelFunc(FloorDiv, floorDivImpl, null /* complexImpl */, 'int32');\n\nexport const floorDivConfig: KernelConfig = {\n kernelName: FloorDiv,\n backendName: 'cpu',\n kernelFunc: floorDiv\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 {FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {applyActivation} from '../utils/fused_utils';\nimport {add} from './Add';\nimport {conv2D} from './Conv2D';\n\nexport function fusedConv2D(args: {\n inputs: FusedConv2DInputs,\n backend: MathBackendCPU,\n attrs: FusedConv2DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n } = attrs;\n\n let result = conv2D({\n inputs: {x, filter},\n backend,\n attrs: {strides, pad, dataFormat, dilations, dimRoundingMode}\n });\n\n if (bias) {\n const resultOld = result;\n result = add({inputs: {a: result, b: bias}, backend}) as TensorInfo;\n backend.disposeIntermediateTensorInfo(resultOld);\n }\n\n if (activation) {\n const resultOld = result;\n result = applyActivation(\n backend, result, activation, preluActivationWeights, leakyreluAlpha);\n backend.disposeIntermediateTensorInfo(resultOld);\n }\n\n return result;\n}\n\nexport const fusedConv2DConfig: KernelConfig = {\n kernelName: FusedConv2D,\n backendName: 'cpu',\n kernelFunc: fusedConv2D as {} 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 {FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {applyActivation} from '../utils/fused_utils';\nimport {add} from './Add';\nimport {depthwiseConv2dNative} from './DepthwiseConv2dNative';\n\nexport function fusedDepthwiseConv2D(args: {\n inputs: FusedDepthwiseConv2DInputs,\n backend: MathBackendCPU,\n attrs: FusedDepthwiseConv2DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n } = attrs;\n\n let result = depthwiseConv2dNative({\n inputs: {x, filter},\n backend,\n attrs: {strides, pad, dataFormat, dilations, dimRoundingMode}\n });\n\n if (bias) {\n const oldResult = result;\n result = add({inputs: {a: result, b: bias}, backend}) as TensorInfo;\n backend.disposeIntermediateTensorInfo(oldResult);\n }\n if (activation) {\n const oldResult = result;\n result = applyActivation(\n backend, result, activation, preluActivationWeights, leakyreluAlpha);\n backend.disposeIntermediateTensorInfo(oldResult);\n }\n\n return result;\n}\n\nexport const fusedDepthwiseConv2DConfig: KernelConfig = {\n kernelName: FusedDepthwiseConv2D,\n backendName: 'cpu',\n kernelFunc: fusedDepthwiseConv2D as {} 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, GatherNd, GatherNdInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {gatherNdImpl} from './GatherNd_Impl';\n\nexport function gatherNd(\n args: {inputs: GatherNdInputs, backend: MathBackendCPU}): TensorInfo {\n const {inputs, backend} = args;\n const {params, indices} = inputs;\n\n const paramsSize = util.sizeFromShape(params.shape);\n\n const indicesShape = indices.shape;\n const sliceRank = indicesShape[indicesShape.length - 1];\n\n const [resultShape, numSlices, sliceSize, strides] =\n backend_util.prepareAndValidate(params, indices);\n if (numSlices === 0) {\n return backend.makeTensorInfo(resultShape, params.dtype, []);\n }\n\n const indicesData = backend.data.get(indices.dataId).values as TypedArray;\n const paramsBuf = backend.bufferSync(params);\n const outBuf = gatherNdImpl(\n indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize,\n strides, params.shape, paramsSize);\n\n return backend.makeTensorInfo(resultShape, params.dtype, outBuf.values);\n}\n\nexport const gatherNdConfig: KernelConfig = {\n kernelName: GatherNd,\n backendName: 'cpu',\n kernelFunc: gatherNd as {} 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, GatherV2, GatherV2Attrs, GatherV2Inputs, KernelConfig, KernelFunc, TensorInfo, 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 let $batchDims = batchDims;\n\n if (batchDims == null) {\n $batchDims = 0;\n }\n\n const indicesSize = util.sizeFromShape(indices.shape);\n\n const parsedAxis = util.parseAxisParam(axis, x.shape)[0];\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 {} 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 {IFFT, IFFTInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {fftBatch} from '../utils/fft_utils';\nimport {reshape} from './Reshape';\n\nexport function ifft(args: {inputs: IFFTInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n const inputSize = util.sizeFromShape(input.shape);\n\n // Collapse all outer dimensions to a single batch dimension.\n const innerDimensionSize = input.shape[input.shape.length - 1];\n const batch = inputSize / innerDimensionSize;\n\n const input2D = reshape({\n inputs: {x: input},\n backend,\n attrs: {shape: [batch, innerDimensionSize]}\n });\n\n const result = fftBatch(input2D, true, backend);\n\n const resultReshaped =\n reshape({inputs: {x: result}, backend, attrs: {shape: input.shape}});\n\n backend.disposeIntermediateTensorInfo(input2D);\n backend.disposeIntermediateTensorInfo(result);\n\n return resultReshaped;\n}\n\nexport const ifftConfig: KernelConfig = {\n kernelName: IFFT,\n backendName: 'cpu',\n kernelFunc: ifft as {} 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 {IsFinite, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const isFinite =\n unaryKernelFunc(IsFinite, (xi) => Number.isFinite(xi) ? 1 : 0, 'bool');\n\nexport const isFiniteConfig: KernelConfig = {\n kernelName: IsFinite,\n backendName: 'cpu',\n kernelFunc: isFinite,\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 {IsInf, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const isInf =\n unaryKernelFunc(IsInf, (xi) => Math.abs(xi) === Infinity ? 1 : 0, 'bool');\n\nexport const isInfConfig: KernelConfig = {\n kernelName: IsInf,\n backendName: 'cpu',\n kernelFunc: isInf,\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 {IsNan, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const isNaN =\n unaryKernelFunc(IsNan, (xi) => Number.isNaN(xi) ? 1 : 0, 'bool');\n\nexport const isNaNConfig: KernelConfig = {\n kernelName: IsNan,\n backendName: 'cpu',\n kernelFunc: isNaN,\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, LinSpace, LinSpaceAttrs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {linSpaceImpl} from './LinSpace_impl';\n\nexport function linSpace(args: {backend: MathBackendCPU, attrs: LinSpaceAttrs}):\n TensorInfo {\n const {backend, attrs} = args;\n const {start, stop, num} = attrs;\n\n const outVals = linSpaceImpl(start, stop, num);\n\n return backend.makeTensorInfo([outVals.length], 'float32', outVals);\n}\n\nexport const linSpaceConfig: KernelConfig = {\n kernelName: LinSpace,\n backendName: 'cpu',\n kernelFunc: linSpace as {} 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, Log1p} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const log1p = unaryKernelFunc(Log1p, (xi) => Math.log1p(xi));\n\nexport const log1pConfig: KernelConfig = {\n kernelName: Log1p,\n backendName: 'cpu',\n kernelFunc: log1p,\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, LogicalAnd} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const logicalAndImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => a && b);\nexport const logicalAnd = binaryKernelFunc(\n LogicalAnd, logicalAndImpl, null /* complexImpl */, 'bool');\n\nexport const logicalAndConfig: KernelConfig = {\n kernelName: LogicalAnd,\n backendName: 'cpu',\n kernelFunc: logicalAnd\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, LogicalNot} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const logicalNot =\n unaryKernelFunc(LogicalNot, (xi) => xi ? 0 : 1, 'bool');\n\nexport const logicalNotConfig: KernelConfig = {\n kernelName: LogicalNot,\n backendName: 'cpu',\n kernelFunc: logicalNot,\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, LogicalOr} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const logicalOrImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => a || b);\nexport const logicalOr =\n binaryKernelFunc(LogicalOr, logicalOrImpl, null /* complexImpl */, 'bool');\n\nexport const logicalOrConfig: KernelConfig = {\n kernelName: LogicalOr,\n backendName: 'cpu',\n kernelFunc: logicalOr\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, LRN, LRNAttrs, LRNInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function lRN(\n args: {inputs: LRNInputs, backend: MathBackendCPU, attrs: LRNAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n assertNotComplex(x, 'LRN');\n\n const channels = x.shape[3];\n const maxD = channels - 1;\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const size = util.sizeFromShape(x.shape);\n const result = new Float32Array(size);\n\n function sumAcrossChannels(offset: number) {\n const currentChannel = offset % channels;\n let beginSumOffset =\n offset - currentChannel + Math.max(0, currentChannel - depthRadius);\n const endSumOffset =\n offset - currentChannel + Math.min(currentChannel + depthRadius, maxD);\n\n let sum = 0.0;\n for (; beginSumOffset <= endSumOffset; beginSumOffset++) {\n const z = xValues[beginSumOffset];\n sum += z * z;\n }\n return sum;\n }\n\n for (let offset = 0; offset < size; offset++) {\n const sum = sumAcrossChannels(offset);\n const val = xValues[offset] * Math.pow(bias + alpha * sum, -beta);\n result[offset] = val;\n }\n\n return backend.makeTensorInfo(x.shape, x.dtype, result);\n}\n\nexport const lRNConfig: KernelConfig = {\n kernelName: LRN,\n backendName: 'cpu',\n kernelFunc: lRN as {} 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, LRNGrad, LRNGradAttrs, LRNGradInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function lRNGrad(\n args:\n {inputs: LRNGradInputs, backend: MathBackendCPU, attrs: LRNGradAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, y, dy} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n assertNotComplex(dy, 'LRNGrad');\n\n const dySize = util.sizeFromShape(dy.shape);\n\n const channels = dy.shape[3];\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const yValues = backend.data.get(y.dataId).values as TypedArray;\n const result = new Float32Array(dySize);\n const size = dySize;\n\n for (let offset = 0; offset < size; offset++) {\n const currentChannel = offset % channels;\n const depthBegin =\n (offset - currentChannel) + Math.max(0, currentChannel - depthRadius);\n const depthEnd = (offset - currentChannel) +\n Math.min(channels, currentChannel + depthRadius + 1);\n\n let norm = 0;\n for (let k = depthBegin; k < depthEnd; k++) {\n norm += Math.pow(xValues[k], 2);\n }\n norm = alpha * norm + bias;\n\n for (let k = depthBegin; k < depthEnd; k++) {\n let dyi = -2 * alpha * beta * xValues[k] * yValues[offset] / norm;\n if (offset === k) {\n dyi += Math.pow(norm, -beta);\n }\n dyi *= dyValues[offset];\n result[k] += dyi;\n }\n }\n\n return backend.makeTensorInfo(dy.shape, x.dtype, result);\n}\n\nexport const lRNGradConfig: KernelConfig = {\n kernelName: LRNGrad,\n backendName: 'cpu',\n kernelFunc: lRNGrad as {} 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 {} 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 */\nimport {backend_util, KernelConfig, KernelFunc, MaxPool, MaxPoolAttrs, MaxPoolInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {pool} from '../utils/pool_utils';\nimport {identity} from './Identity';\n\nexport function maxPool(\n args:\n {inputs: MaxPoolInputs, backend: MathBackendCPU, attrs: MaxPoolAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n assertNotComplex(x, 'maxPool');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations = 1;\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n let res: TensorInfo;\n\n if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&\n util.arraysEqual(convInfo.inShape, convInfo.outShape)) {\n res = identity({inputs: {x}, backend});\n } else {\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const strides = util.computeStrides(x.shape);\n const buffer = pool(xValues, x.shape, x.dtype, strides, convInfo, 'max');\n res = backend.makeTensorInfo(\n convInfo.outShape, x.dtype, buffer.values as TypedArray);\n }\n return res;\n}\n\nexport const maxPoolConfig: KernelConfig = {\n kernelName: MaxPool,\n backendName: 'cpu',\n kernelFunc: maxPool as {} 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, MaxPool3D, MaxPool3DAttrs, MaxPool3DInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {pool3d} from '../utils/pool_utils';\n\nexport function maxPool3D(args: {\n inputs: MaxPool3DInputs,\n backend: MathBackendCPU,\n attrs: MaxPool3DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {filterSize, strides, pad, dimRoundingMode, dataFormat} = attrs;\n\n assertNotComplex(x, 'maxPool3d');\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad, dimRoundingMode, dataFormat);\n\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const outBuf = pool3d(\n xValues, x.shape, x.dtype, util.computeStrides(x.shape), convInfo, 'max');\n\n return backend.makeTensorInfo(outBuf.shape, 'float32', outBuf.values);\n}\n\nexport const maxPool3DConfig: KernelConfig = {\n kernelName: MaxPool3D,\n backendName: 'cpu',\n kernelFunc: maxPool3D as {} 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, buffer, KernelConfig, KernelFunc, MaxPool3DGrad, MaxPool3DGradAttrs, MaxPool3DGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {maxPool3dPositions} from '../utils/pool_utils';\n\nexport function maxPool3DGrad(args: {\n inputs: MaxPool3DGradInputs,\n backend: MathBackendCPU,\n attrs: MaxPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n\n assertNotComplex([dy, input], 'maxPool3DGrad');\n\n const convInfo = backend_util.computePool3DInfo(\n input.shape as [number, number, number, number, number], filterSize,\n strides, 1 /* dilations */, pad, dimRoundingMode);\n\n const inputBuf = backend.bufferSync(input);\n const maxPosBuf = maxPool3dPositions(inputBuf, convInfo);\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const dx = buffer(input.shape, 'float32');\n\n const dyBuf = backend.bufferSync(dy);\n\n for (let batch = 0; batch < convInfo.batchSize; ++batch) {\n for (let channel = 0; channel < convInfo.inChannels; ++channel) {\n for (let dxDepth = 0; dxDepth < convInfo.inDepth; ++dxDepth) {\n for (let dxRow = 0; dxRow < convInfo.inHeight; ++dxRow) {\n for (let dxCol = 0; dxCol < convInfo.inWidth; ++dxCol) {\n // Shader code begins\n const dyDepthCorner = dxDepth - padFront;\n const dyRowCorner = dxRow - padTop;\n const dyColCorner = dxCol - padLeft;\n let dotProd = 0;\n for (let wDepth = 0; wDepth < effectiveFilterDepth;\n wDepth += dilationDepth) {\n const dyDepth = (dyDepthCorner + wDepth) / strideDepth;\n if (dyDepth < 0 || dyDepth >= convInfo.outDepth ||\n Math.floor(dyDepth) !== dyDepth) {\n continue;\n }\n for (let wRow = 0; wRow < effectiveFilterHeight;\n wRow += dilationHeight) {\n const dyRow = (dyRowCorner + wRow) / strideHeight;\n if (dyRow < 0 || dyRow >= convInfo.outHeight ||\n Math.floor(dyRow) !== dyRow) {\n continue;\n }\n for (let wCol = 0; wCol < effectiveFilterWidth;\n wCol += dilationWidth) {\n const dyCol = (dyColCorner + wCol) / strideWidth;\n if (dyCol < 0 || dyCol >= convInfo.outWidth ||\n Math.floor(dyCol) !== dyCol) {\n continue;\n }\n\n const maxPos = effectiveFilterDepth * effectiveFilterHeight *\n effectiveFilterWidth -\n 1 -\n (maxPosBuf.get(batch, dyDepth, dyRow, dyCol, channel) as\n number);\n const curPos =\n wDepth * effectiveFilterHeight * effectiveFilterWidth +\n wRow * effectiveFilterWidth + wCol;\n\n const mask = maxPos === curPos ? 1 : 0;\n if (mask === 0) {\n continue;\n }\n\n const pixel =\n dyBuf.get(batch, dyDepth, dyRow, dyCol, channel);\n dotProd += pixel * mask;\n }\n }\n }\n dx.set(dotProd, batch, dxDepth, dxRow, dxCol, channel);\n }\n }\n }\n }\n }\n\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const maxPool3DGradConfig: KernelConfig = {\n kernelName: MaxPool3DGrad,\n backendName: 'cpu',\n kernelFunc: maxPool3DGrad as {} 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 */\nimport {backend_util, buffer, KernelConfig, KernelFunc, MaxPoolGrad, MaxPoolGradAttrs, MaxPoolGradInputs, Rank, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {maxPoolPositions} from '../utils/pool_utils';\n\nexport function maxPoolGrad(args: {\n inputs: MaxPoolGradInputs,\n backend: MathBackendCPU,\n attrs: MaxPoolGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input, output} = inputs;\n const x = input;\n assertNotComplex([input, output], 'maxPoolGrad');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad, dimRoundingMode);\n const xValues = backend.data.get(x.dataId).values as TypedArray;\n const maxPosBuf = buffer(\n convInfo.outShape, x.dtype,\n maxPoolPositions(xValues, x.shape, x.dtype, convInfo).values);\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const dx =\n buffer<Rank.R4>(x.shape as [number, number, number, number], 'float32');\n\n const dyData = backend.data.get(dy.dataId).values as Float32Array;\n const dyBuf = buffer<Rank.R4>(\n dy.shape as [number, number, number, number], 'float32', dyData);\n\n for (let b = 0; b < convInfo.batchSize; ++b) {\n for (let d = 0; d < convInfo.inChannels; ++d) {\n for (let dxR = 0; dxR < convInfo.inHeight; ++dxR) {\n for (let dxC = 0; dxC < convInfo.inWidth; ++dxC) {\n // Shader code begins.\n const dyRCorner = dxR - padTop;\n const dyCCorner = dxC - padLeft;\n let dotProd = 0;\n for (let wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {\n const dyR = (dyRCorner + wR) / strideHeight;\n if (dyR < 0 || dyR >= convInfo.outHeight ||\n Math.floor(dyR) !== dyR) {\n continue;\n }\n for (let wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {\n const dyC = (dyCCorner + wC) / strideWidth;\n if (dyC < 0 || dyC >= convInfo.outWidth ||\n Math.floor(dyC) !== dyC) {\n continue;\n }\n const maxPos = effectiveFilterHeight * effectiveFilterWidth - 1 -\n (maxPosBuf.get(b, dyR, dyC, d) as number);\n const curPos = wR * effectiveFilterWidth + wC;\n\n const mask = maxPos === curPos ? 1 : 0;\n if (mask === 0) {\n continue;\n }\n\n const pixel = dyBuf.get(b, dyR, dyC, d);\n dotProd += pixel * mask;\n }\n }\n dx.set(dotProd, b, dxR, dxC, d);\n }\n }\n }\n }\n return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);\n}\n\nexport const maxPoolGradConfig: KernelConfig = {\n kernelName: MaxPoolGrad,\n backendName: 'cpu',\n kernelFunc: maxPoolGrad as {} 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 */\nimport {backend_util, DataType, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {maxPoolPositions, pool} from '../utils/pool_utils';\nexport function maxPoolWithArgmaxImpl(\n xValues: TypedArray, xShape: number[], dtype: DataType,\n includeBatchInIndex: boolean, convInfo: backend_util.Conv2DInfo) {\n const strides = util.computeStrides(xShape);\n const maxPools = pool(xValues, xShape, dtype, strides, convInfo, 'max');\n const maxPositions = maxPoolPositions(\n xValues, xShape, dtype, convInfo, true, includeBatchInIndex);\n\n return [maxPools.values, maxPositions.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 {MaxPoolWithArgmax, MaxPoolWithArgmaxAttrs, MaxPoolWithArgmaxInputs} from '@tensorflow/tfjs-core';\nimport {backend_util, KernelConfig, TypedArray} from '@tensorflow/tfjs-core';\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {maxPoolWithArgmaxImpl} from './MaxPoolWithArgmax_impl';\n\nexport const maxPoolWithArgmaxConfig: KernelConfig = {\n kernelName: MaxPoolWithArgmax,\n backendName: 'cpu',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {x} = inputs as MaxPoolWithArgmaxInputs;\n const {filterSize, strides, pad, includeBatchInIndex} =\n attrs as {} as MaxPoolWithArgmaxAttrs;\n const cpuBackend = backend as MathBackendCPU;\n assertNotComplex(x, 'MaxPoolWithArgmax');\n\n const values = cpuBackend.data.get(x.dataId).values as TypedArray;\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n [1, 1], pad);\n const [pooled, indexes] = maxPoolWithArgmaxImpl(\n values, x.shape, x.dtype, includeBatchInIndex, convInfo);\n\n const pooledDataId =\n cpuBackend.write(pooled as Float32Array, convInfo.outShape, x.dtype);\n const indexesDataId =\n cpuBackend.write(indexes as Int32Array, convInfo.outShape, x.dtype);\n return [\n {dataId: pooledDataId, shape: convInfo.outShape, dtype: x.dtype},\n {dataId: indexesDataId, shape: convInfo.outShape, dtype: 'int32'}\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 {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 {} 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, Min, MinAttrs, MinInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function min(\n args: {inputs: MinInputs, backend: MathBackendCPU, attrs: MinAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n assertNotComplex(x, 'min');\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('min', axes, $x.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes($x.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n const vals = util.makeZerosTypedArray(util.sizeFromShape(outShape), $x.dtype);\n\n const aVals = backend.data.get($x.dataId).values as TypedArray;\n for (let i = 0; i < vals.length; ++i) {\n const offset = i * reduceSize;\n let min = aVals[offset];\n for (let j = 0; j < reduceSize; ++j) {\n const value = aVals[offset + j];\n if (Number.isNaN(value) ||\n value < min) { // comparison with NaN always return false\n min = value;\n }\n }\n vals[i] = min;\n }\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo($x);\n }\n\n const result = backend.makeTensorInfo(outShape, $x.dtype, vals);\n\n if (keepDims) {\n const expandedShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n const reshapedResult =\n reshape({inputs: {x: result}, backend, attrs: {shape: expandedShape}});\n\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n }\n\n return result;\n}\n\nexport const minConfig: KernelConfig = {\n kernelName: Min,\n backendName: 'cpu',\n kernelFunc: min as {} 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, MirrorPad, MirrorPadAttrs, MirrorPadInputs, NumericDataType, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function mirrorPad(args: {\n inputs: MirrorPadInputs,\n backend: MathBackendCPU,\n attrs: MirrorPadAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {paddings, mode} = attrs;\n\n assertNotComplex(x, 'mirrorPad');\n\n const outShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + x.shape[i] + p[1] /* afterPad */);\n\n const start = paddings.map(p => p[0]);\n const end = paddings.map((p, i) => p[0] + x.shape[i]);\n const offset = mode === 'reflect' ? 0 : 1;\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const xRank = x.shape.length;\n const xStrides = util.computeStrides(x.shape);\n\n const resultSize = util.sizeFromShape(outShape);\n const resultRank = outShape.length;\n const resultStrides = util.computeStrides(outShape);\n const resVals =\n util.getTypedArrayFromDType(x.dtype as NumericDataType, resultSize);\n\n for (let i = 0; i < resultSize; i++) {\n let coords = util.indexToLoc(i, resultRank, resultStrides);\n for (let i = 0; i < resultRank; i++) {\n if (coords[i] < start[i]) {\n coords[i] = start[i] * 2 - coords[i] - offset;\n } else if (coords[i] >= end[i]) {\n coords[i] = (end[i] - 1) * 2 - coords[i] + offset;\n }\n }\n coords = coords.map((c, i) => c - start[i]);\n\n const inIndex = util.locToIndex(coords, xRank, xStrides);\n\n resVals[i] = xVals[inIndex];\n }\n\n const outId = backend.write(resVals, outShape, x.dtype);\n\n return {dataId: outId, shape: outShape, dtype: x.dtype};\n}\n\nexport const mirrorPadConfig: KernelConfig = {\n kernelName: MirrorPad,\n backendName: 'cpu',\n kernelFunc: mirrorPad as {} 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, Mod} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const modImpl =\n createSimpleBinaryKernelImpl(((aValue: number, bValue: number) => {\n const rem = aValue % bValue;\n if ((aValue < 0 && bValue < 0) || (aValue >= 0 && bValue >= 0)) {\n return rem;\n } else {\n return (rem + bValue) % bValue;\n }\n }));\n\nexport const mod = binaryKernelFunc(Mod, modImpl);\n\nexport const modConfig: KernelConfig = {\n kernelName: Mod,\n backendName: 'cpu',\n kernelFunc: mod\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, Multinomial, MultinomialAttrs, MultinomialInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\nimport * as seedrandom from 'seedrandom';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {softmax} from './Softmax';\n\nexport function multinomial(args: {\n inputs: MultinomialInputs,\n backend: MathBackendCPU,\n attrs: MultinomialAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {logits} = inputs;\n const {numSamples, seed, normalized} = attrs;\n\n assertNotComplex(logits, 'multinomial');\n\n const probabilities = normalized ?\n logits :\n softmax({inputs: {logits}, backend, attrs: {dim: -1}});\n\n const batchSize = probabilities.shape[0];\n const numEvents = probabilities.shape[1];\n const probVals = backend.data.get(probabilities.dataId).values as TypedArray;\n const resShape = [batchSize, numSamples];\n const resVals =\n util.makeZerosTypedArray(util.sizeFromShape(resShape), 'int32');\n\n for (let b = 0; b < batchSize; ++b) {\n const offset = b * numEvents;\n // The cdf won't include the last event. It will be implicit if no other\n // event happened.\n const cdf = new Float32Array(numEvents - 1);\n cdf[0] = probVals[offset];\n for (let event = 1; event < cdf.length; ++event) {\n cdf[event] = cdf[event - 1] + probVals[offset + event];\n }\n\n const random = seedrandom.alea(seed.toString());\n const outOffset = b * numSamples;\n for (let sampleId = 0; sampleId < numSamples; ++sampleId) {\n const r = random();\n\n // Assume last event happened by default.\n resVals[outOffset + sampleId] = cdf.length;\n\n for (let event = 0; event < cdf.length; event++) {\n if (r < cdf[event]) {\n resVals[outOffset + sampleId] = event;\n break;\n }\n }\n }\n }\n\n if (!normalized) {\n backend.disposeIntermediateTensorInfo(probabilities);\n }\n\n return backend.makeTensorInfo(resShape, 'int32', resVals);\n}\n\nexport const multinomialConfig: KernelConfig = {\n kernelName: Multinomial,\n backendName: 'cpu',\n kernelFunc: multinomial as {} 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 {} 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 {kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV3, NonMaxSuppressionV3Attrs, NonMaxSuppressionV3Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV3Impl = kernel_impls.nonMaxSuppressionV3Impl;\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function nonMaxSuppressionV3(args: {\n inputs: NonMaxSuppressionV3Inputs,\n backend: MathBackendCPU,\n attrs: NonMaxSuppressionV3Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold} = attrs;\n\n assertNotComplex(boxes, 'NonMaxSuppression');\n\n const boxesVals = backend.data.get(boxes.dataId).values as TypedArray;\n const scoresVals = backend.data.get(scores.dataId).values as TypedArray;\n\n const {selectedIndices} = nonMaxSuppressionV3Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);\n\n return backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices));\n}\n\nexport const nonMaxSuppressionV3Config: KernelConfig = {\n kernelName: NonMaxSuppressionV3,\n backendName: 'cpu',\n kernelFunc: nonMaxSuppressionV3 as {} 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 {kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV4Impl = kernel_impls.nonMaxSuppressionV4Impl;\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function nonMaxSuppressionV4(args: {\n inputs: NonMaxSuppressionV4Inputs,\n backend: MathBackendCPU,\n attrs: NonMaxSuppressionV4Attrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize} =\n attrs;\n\n assertNotComplex(boxes, 'NonMaxSuppressionPadded');\n\n const boxesVals = backend.data.get(boxes.dataId).values as TypedArray;\n const scoresVals = backend.data.get(scores.dataId).values as TypedArray;\n\n const {selectedIndices, validOutputs} = nonMaxSuppressionV4Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold,\n padToMaxOutputSize);\n\n return [\n backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices)),\n backend.makeTensorInfo([], 'int32', new Int32Array([validOutputs]))\n ];\n}\nexport const nonMaxSuppressionV4Config: KernelConfig = {\n kernelName: NonMaxSuppressionV4,\n backendName: 'cpu',\n kernelFunc: nonMaxSuppressionV4 as {} 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 {kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV5Impl = kernel_impls.nonMaxSuppressionV5Impl;\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function nonMaxSuppressionV5(args: {\n inputs: NonMaxSuppressionV5Inputs,\n backend: MathBackendCPU,\n attrs: NonMaxSuppressionV5Attrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma} = attrs;\n\n assertNotComplex(boxes, 'NonMaxSuppressionWithScore');\n\n const boxesVals = backend.data.get(boxes.dataId).values as TypedArray;\n const scoresVals = backend.data.get(scores.dataId).values as TypedArray;\n\n const maxOutputSizeVal = maxOutputSize;\n const iouThresholdVal = iouThreshold;\n const scoreThresholdVal = scoreThreshold;\n const softNmsSigmaVal = softNmsSigma;\n\n const {selectedIndices, selectedScores} = nonMaxSuppressionV5Impl(\n boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal,\n scoreThresholdVal, softNmsSigmaVal);\n\n return [\n backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices)),\n backend.makeTensorInfo(\n [selectedScores.length], 'float32', new Float32Array(selectedScores))\n ];\n}\n\nexport const nonMaxSuppressionV5Config: KernelConfig = {\n kernelName: NonMaxSuppressionV5,\n backendName: 'cpu',\n kernelFunc: nonMaxSuppressionV5 as {} 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, OneHot, OneHotAttrs, OneHotInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function oneHot(\n args: {inputs: OneHotInputs, backend: MathBackendCPU, attrs: OneHotAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {indices} = inputs;\n const {depth, onValue, offValue} = attrs;\n\n assertNotComplex(indices, 'oneHot');\n\n const indicesSize = util.sizeFromShape(indices.shape);\n\n const res = new Float32Array(indicesSize * depth);\n res.fill(offValue);\n const indicesVal = backend.data.get(indices.dataId).values as TypedArray;\n\n for (let event = 0; event < indicesSize; ++event) {\n if (indicesVal[event] >= 0 && indicesVal[event] < depth) {\n res[event * depth + indicesVal[event]] = onValue;\n }\n }\n\n return backend.makeTensorInfo([...indices.shape, depth], 'int32', res);\n}\n\nexport const oneHotConfig: KernelConfig = {\n kernelName: OneHot,\n backendName: 'cpu',\n kernelFunc: oneHot as {} 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, ZerosLike, ZerosLikeInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {complex} from './Complex';\nimport {fill} from './Fill';\nimport {imag} from './Imag';\nimport {real} from './Real';\n\nexport function zerosLike(\n args: {inputs: ZerosLikeInputs, backend: MathBackendCPU}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (x.dtype === 'string') {\n throw new Error('zerosLike is not supported for string tensors');\n } else if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const r = zerosLike({inputs: {x: realPart}, backend});\n const imagPart = imag({inputs: {input: x}, backend});\n const i = zerosLike({inputs: {x: imagPart}, backend});\n\n const result = complex({inputs: {real: r, imag: i}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(r);\n backend.disposeIntermediateTensorInfo(imagPart);\n backend.disposeIntermediateTensorInfo(i);\n\n return result;\n } else {\n return fill({backend, attrs: {shape: x.shape, value: 0, dtype: x.dtype}});\n }\n}\n\nexport const zerosLikeConfig: KernelConfig = {\n kernelName: ZerosLike,\n backendName: 'cpu',\n kernelFunc: zerosLike as {} 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, OnesLike, OnesLikeInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {complex} from './Complex';\nimport {fill} from './Fill';\nimport {imag} from './Imag';\nimport {real} from './Real';\nimport {zerosLike} from './ZerosLike';\n\nexport function onesLike(\n args: {inputs: OnesLikeInputs, backend: MathBackendCPU}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (x.dtype === 'string') {\n throw new Error('onesLike is not supported for string tensors');\n } else if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const r = onesLike({inputs: {x: realPart}, backend});\n const imagPart = imag({inputs: {input: x}, backend});\n const i = zerosLike({inputs: {x: imagPart}, backend});\n\n const result = complex({inputs: {real: r, imag: i}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(r);\n backend.disposeIntermediateTensorInfo(imagPart);\n backend.disposeIntermediateTensorInfo(i);\n\n return result;\n } else {\n return fill({backend, attrs: {shape: x.shape, value: 1, dtype: x.dtype}});\n }\n}\n\nexport const onesLikeConfig: KernelConfig = {\n kernelName: OnesLike,\n backendName: 'cpu',\n kernelFunc: onesLike as {} 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 {} 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, NumericDataType, PadV2, PadV2Attrs, PadV2Inputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function padV2(\n args: {inputs: PadV2Inputs, backend: MathBackendCPU, attrs: PadV2Attrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {paddings, constantValue} = attrs;\n\n assertNotComplex(x, 'pad');\n\n const outShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + x.shape[i] + p[1] /* afterPad */);\n\n const start = paddings.map(p => p[0]);\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const xSize = util.sizeFromShape(x.shape);\n const xRank = x.shape.length;\n const xStrides = util.computeStrides(x.shape);\n\n const resultSize = util.sizeFromShape(outShape);\n const resultRank = outShape.length;\n const resultStrides = util.computeStrides(outShape);\n const resVals =\n util.getTypedArrayFromDType(x.dtype as NumericDataType, resultSize);\n\n if (constantValue !== 0) {\n resVals.fill(constantValue);\n }\n\n for (let i = 0; i < xSize; i++) {\n const coords = util.indexToLoc(i, xRank, xStrides);\n const outCoords = coords.map((c, i) => c + start[i]);\n const outIndex = util.locToIndex(outCoords, resultRank, resultStrides);\n\n resVals[outIndex] = xVals[i];\n }\n\n const outId = backend.write(resVals, outShape, x.dtype);\n\n return {dataId: outId, shape: outShape, dtype: x.dtype};\n}\n\nexport const padV2Config: KernelConfig = {\n kernelName: PadV2,\n backendName: 'cpu',\n kernelFunc: padV2 as {} 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, Pow} from '@tensorflow/tfjs-core';\n\nimport {createSimpleBinaryKernelImpl} from '../utils/binary_impl';\nimport {binaryKernelFunc} from '../utils/binary_utils';\n\nexport const powImpl =\n createSimpleBinaryKernelImpl((a: number, b: number) => Math.pow(a, b));\nexport const pow = binaryKernelFunc(Pow, powImpl);\n\nexport const powConfig: KernelConfig = {\n kernelName: Pow,\n backendName: 'cpu',\n kernelFunc: pow\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 {} 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, Reciprocal} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const reciprocal = unaryKernelFunc(Reciprocal, (xi) => 1 / xi);\n\nexport const reciprocalConfig: KernelConfig = {\n kernelName: Reciprocal,\n backendName: 'cpu',\n kernelFunc: reciprocal,\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, ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function resizeBilinear(args: {\n inputs: ResizeBilinearInputs,\n backend: MathBackendCPU,\n attrs: ResizeBilinearAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n assertNotComplex(images, 'resizeBilinear');\n\n const imagesStrides = util.computeStrides(images.shape);\n const [newHeight, newWidth] = size;\n\n const [batch, oldHeight, oldWidth, numChannels] = images.shape;\n const xValues = backend.data.get(images.dataId).values as TypedArray;\n const result = new Float32Array(\n util.sizeFromShape([batch, newHeight, newWidth, numChannels]));\n\n const effectiveInputSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutputSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n let outputIdx = 0;\n const effectiveRowSizeRatio = effectiveInputSize[0] / effectiveOutputSize[0];\n const effectiveColSizeRatio = effectiveInputSize[1] / effectiveOutputSize[1];\n for (let b = 0; b < batch; b++) {\n for (let r = 0; r < newHeight; r++) {\n let sourceFracRow: number;\n if (halfPixelCenters) {\n sourceFracRow = effectiveRowSizeRatio * (r + 0.5) - 0.5;\n } else {\n sourceFracRow = effectiveRowSizeRatio * r;\n }\n\n const sourceRowFloor = Math.max(0, Math.floor(sourceFracRow));\n const rowFrac = sourceFracRow - sourceRowFloor;\n const sourceRowCeil = Math.min(oldHeight - 1, Math.ceil(sourceFracRow));\n const topRowOffset =\n b * imagesStrides[0] + sourceRowFloor * imagesStrides[1];\n const botRowOffset =\n b * imagesStrides[0] + sourceRowCeil * imagesStrides[1];\n for (let c = 0; c < newWidth; c++) {\n let sourceFracCol: number;\n if (halfPixelCenters) {\n sourceFracCol = effectiveColSizeRatio * (c + 0.5) - 0.5;\n } else {\n sourceFracCol = effectiveColSizeRatio * c;\n }\n const sourceColFloor = Math.max(0, Math.floor(sourceFracCol));\n const colFrac = sourceFracCol - sourceColFloor;\n const sourceColCeil = Math.min(oldWidth - 1, Math.ceil(sourceFracCol));\n const topLeftOffest = topRowOffset + sourceColFloor * imagesStrides[2];\n const botLeftOffset = botRowOffset + sourceColFloor * imagesStrides[2];\n const topRightOffset = topRowOffset + sourceColCeil * imagesStrides[2];\n const botRightOffest = botRowOffset + sourceColCeil * imagesStrides[2];\n for (let d = 0; d < numChannels; d++) {\n // Begin shader.\n\n // Compute the fractional index of the source.\n const topLeft = xValues[topLeftOffest + d];\n const bottomLeft = xValues[botLeftOffset + d];\n const topRight = xValues[topRightOffset + d];\n const bottomRight = xValues[botRightOffest + d];\n\n const top = topLeft + (topRight - topLeft) * colFrac;\n const bottom = bottomLeft + (bottomRight - bottomLeft) * colFrac;\n const newValue = top + (bottom - top) * rowFrac;\n\n result[outputIdx++] = newValue;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(\n [batch, newHeight, newWidth, numChannels], 'float32', result);\n}\n\nexport const resizeBilinearConfig: KernelConfig = {\n kernelName: ResizeBilinear,\n backendName: 'cpu',\n kernelFunc: resizeBilinear as {} 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, ResizeBilinearGrad, ResizeBilinearGradAttrs, ResizeBilinearGradInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function resizeBilinearGrad(args: {\n inputs: ResizeBilinearGradInputs,\n backend: MathBackendCPU,\n attrs: ResizeBilinearGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n assertNotComplex([dy, images], 'resizeBilinearGrad');\n\n const imagesStrides = util.computeStrides(images.shape);\n\n const [batch, xHeight, xWidth, depth] = images.shape;\n const [, yHeight, yWidth] = dy.shape;\n\n const output = new Float32Array(batch * xHeight * xWidth * depth);\n\n // In the backwards pass, we want to find the pixels that were generated\n // for each pixel in the input image the forward pass and add the\n // corresponding coefficient from dy to the gradient (with some\n // interpolation).\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n // Reference implementation\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/3039375c86a5bbc9610c7725dcaa95d635f87ba2/tensorflow/core/kernels/resize_bilinear_op.cc#L275\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n let offset = 0;\n for (let b = 0; b < batch; b++) {\n const bOffset = b * imagesStrides[0];\n for (let r = 0; r < yHeight; r++) {\n const dxR = r * heightScale;\n const topDxRIndex = Math.floor(dxR);\n const bottomDxRIndex = Math.min(Math.ceil(dxR), xHeight - 1);\n\n const topDxROffset = bOffset + topDxRIndex * imagesStrides[1];\n const bottomDxROffset = bOffset + bottomDxRIndex * imagesStrides[1];\n\n const dxRLerp = dxR - topDxRIndex;\n const inverseDxRLerp = 1.0 - dxRLerp;\n for (let c = 0; c < yWidth; c++) {\n const dxC = c * widthScale;\n const leftDxCIndex = Math.floor(dxC);\n const rightDxCIndex = Math.min(Math.ceil(dxC), xWidth - 1);\n const dxCLerp = dxC - leftDxCIndex;\n const inverseDxCLerp = 1.0 - dxCLerp;\n\n const topLeftRCOffset = topDxROffset + leftDxCIndex * imagesStrides[2];\n const topRightRCOffset =\n topDxROffset + rightDxCIndex * imagesStrides[2];\n const bottomLeftRCOffset =\n bottomDxROffset + leftDxCIndex * imagesStrides[2];\n const bottomRightRCOffset =\n bottomDxROffset + rightDxCIndex * imagesStrides[2];\n\n const inverseDxRLerpTimesInverseDxCLerp =\n inverseDxRLerp * inverseDxCLerp;\n const inverseDxRLerpTimesDxCLerp = inverseDxRLerp * dxCLerp;\n const dxRLerpTimesInverseDxCLerp = dxRLerp * inverseDxCLerp;\n const dxRLerpTimesDxCLerp = dxRLerp * dxCLerp;\n for (let d = 0; d < depth; d++) {\n const dyVal = dyValues[offset++];\n output[topLeftRCOffset + d] +=\n dyVal * inverseDxRLerpTimesInverseDxCLerp;\n output[topRightRCOffset + d] += dyVal * inverseDxRLerpTimesDxCLerp;\n output[bottomLeftRCOffset + d] += dyVal * dxRLerpTimesInverseDxCLerp;\n output[bottomRightRCOffset + d] += dyVal * dxRLerpTimesDxCLerp;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(\n [batch, xWidth, xHeight, depth], 'float32', output);\n}\n\nexport const resizeBilinearGradConfig: KernelConfig = {\n kernelName: ResizeBilinearGrad,\n backendName: 'cpu',\n kernelFunc: resizeBilinearGrad as {} 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, ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function resizeNearestNeighbor(args: {\n inputs: ResizeNearestNeighborInputs,\n backend: MathBackendCPU,\n attrs: ResizeNearestNeighborAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n assertNotComplex(images, 'resizeNearestNeighbor');\n\n const imagesStrides = util.computeStrides(images.shape);\n const [newHeight, newWidth] = size;\n\n const [batch, oldHeight, oldWidth, numChannels] = images.shape;\n const xValues = backend.data.get(images.dataId).values as TypedArray;\n const output = new Float32Array(batch * newHeight * newWidth * numChannels);\n\n const effectiveInputSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutputSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n const effectiveRowSizeRatio = effectiveInputSize[0] / effectiveOutputSize[0];\n const effectiveColSizeRatio = effectiveInputSize[1] / effectiveOutputSize[1];\n\n let outputOffset = 0;\n for (let b = 0; b < batch; b++) {\n const batchOffset = b * imagesStrides[0];\n for (let r = 0; r < newHeight; r++) {\n const sourceFracRow = halfPixelCenters ?\n effectiveRowSizeRatio * (r + 0.5) :\n effectiveRowSizeRatio * r;\n let sourceNearestRow = Math.min(\n oldHeight - 1,\n alignCorners ? Math.round(sourceFracRow) : Math.floor(sourceFracRow));\n if (halfPixelCenters) {\n sourceNearestRow = Math.max(0, sourceNearestRow);\n }\n const rowOffset = batchOffset + sourceNearestRow * imagesStrides[1];\n for (let c = 0; c < newWidth; c++) {\n const sourceFracCol = halfPixelCenters ?\n effectiveColSizeRatio * (c + 0.5) :\n effectiveColSizeRatio * c;\n let sourceNearestCol = Math.min(\n oldWidth - 1,\n alignCorners ? Math.round(sourceFracCol) :\n Math.floor(sourceFracCol));\n if (halfPixelCenters) {\n sourceNearestCol = Math.max(0, sourceNearestCol);\n }\n const colOffset = rowOffset + sourceNearestCol * imagesStrides[2];\n for (let d = 0; d < numChannels; d++) {\n // Begin shader.\n // Compute the fractional index of the source.\n const newVal = xValues[colOffset + d];\n output[outputOffset++] = newVal;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(\n [batch, newHeight, newWidth, numChannels], images.dtype, output);\n}\n\nexport const resizeNearestNeighborConfig: KernelConfig = {\n kernelName: ResizeNearestNeighbor,\n backendName: 'cpu',\n kernelFunc: resizeNearestNeighbor as {} 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, ResizeNearestNeighborGrad, ResizeNearestNeighborGradAttrs, ResizeNearestNeighborGradInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function resizeNearestNeighborGrad(args: {\n inputs: ResizeNearestNeighborGradInputs,\n backend: MathBackendCPU,\n attrs: ResizeNearestNeighborGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n assertNotComplex([dy, images], 'resizeNearestNeighborGrad');\n\n const imagesStrides = util.computeStrides(images.shape);\n const dyStrides = util.computeStrides(dy.shape);\n const [batch, xHeight, xWidth, depth] = images.shape;\n const [, yHeight, yWidth] = dy.shape;\n\n const output = new Float32Array(batch * xHeight * xWidth * depth);\n const dyValues = backend.data.get(dy.dataId).values as TypedArray;\n\n // In the backwards pass, we want to find the pixels that were generated\n // for each pixel in the input image the forward pass\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n const invHeightScale = 1 / heightScale;\n const invWidthScale = 1 / widthScale;\n\n // This defines the size of the window of values around a particular\n // index in dy that we want to search for contributions to dx.\n const winHeight = (Math.ceil(invHeightScale) * 2) + 2;\n const winWidth = (Math.ceil(invWidthScale) * 2) + 2;\n\n // Loop over the output space.\n for (let b = 0; b < batch; b++) {\n const batchOffset = b * imagesStrides[0];\n for (let r = 0; r < xHeight; r++) {\n const rowOffset = batchOffset + r * imagesStrides[1];\n\n // Compute bounds for where in dy we will look\n const startRLerp = Math.floor(r * invHeightScale);\n const startDyR = Math.floor(startRLerp - (winHeight / 2));\n for (let c = 0; c < xWidth; c++) {\n const colOffset = rowOffset + c * imagesStrides[2];\n\n // Compute bounds for where in dy we will look\n const startCLerp = Math.floor(c * invWidthScale);\n const startDyC = Math.floor(startCLerp - (winWidth / 2));\n\n for (let d = 0; d < depth; d++) {\n let accum = 0;\n // loop over dy\n\n for (let dyRIndex = 0; dyRIndex < winHeight; dyRIndex++) {\n const dyR = dyRIndex + startDyR;\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= yHeight) {\n continue;\n }\n\n const dyROffset = batchOffset + dyR * dyStrides[1];\n const sourceFracRow = dyR * heightScale;\n const sourceNearestRow = Math.min(\n xHeight - 1,\n alignCorners ? Math.round(sourceFracRow) :\n Math.floor(sourceFracRow));\n if (r !== sourceNearestRow) {\n continue;\n }\n for (let dyCIndex = 0; dyCIndex < winWidth; dyCIndex++) {\n const dyC = dyCIndex + startDyC;\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= yWidth) {\n continue;\n }\n\n const dyCOffset = dyROffset + dyC * dyStrides[2];\n const sourceFracCol = dyC * widthScale;\n const sourceNearestCol = Math.min(\n xWidth - 1,\n alignCorners ? Math.round(sourceFracCol) :\n Math.floor(sourceFracCol));\n\n if (c === sourceNearestCol) {\n accum += dyValues[dyCOffset + d];\n }\n }\n }\n output[colOffset + d] = accum;\n }\n }\n }\n }\n\n return backend.makeTensorInfo(images.shape, images.dtype, output);\n}\n\nexport const resizeNearestNeighborGradConfig: KernelConfig = {\n kernelName: ResizeNearestNeighborGrad,\n backendName: 'cpu',\n kernelFunc: resizeNearestNeighborGrad as {} 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, Reverse, ReverseAttrs, ReverseInputs, TensorBuffer, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {identity} from './Identity';\n\nexport function reverse(\n args:\n {inputs: ReverseInputs, backend: MathBackendCPU, attrs: ReverseAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {dims} = attrs;\n\n assertNotComplex(x, 'reverse');\n\n const xRank = x.shape.length;\n\n const $dims = util.parseAxisParam(dims, x.shape);\n if (xRank === 0) {\n return identity({inputs: {x}, backend});\n }\n\n const outBuf = new TensorBuffer(x.shape, x.dtype);\n const xBuf = backend.bufferSync(x);\n\n for (let i = 0; i < outBuf.size; i++) {\n const outLoc = outBuf.indexToLoc(i);\n const inLoc = outLoc.slice();\n $dims.forEach(d => inLoc[d] = x.shape[d] - 1 - inLoc[d]);\n outBuf.set(xBuf.get(...inLoc), ...outLoc);\n }\n\n return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n}\n\nexport const reverseConfig: KernelConfig = {\n kernelName: Reverse,\n backendName: 'cpu',\n kernelFunc: reverse as {} 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, NumericDataType, TypedArray} from '@tensorflow/tfjs-core';\nimport {backend_util, RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport const rotateWithOffsetConfig: KernelConfig = {\n kernelName: RotateWithOffset,\n backendName: 'cpu',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {image} = inputs as RotateWithOffsetInputs;\n const {radians, fillValue, center} = attrs as {} as RotateWithOffsetAttrs;\n const cpuBackend = backend as MathBackendCPU;\n\n const output = util.getTypedArrayFromDType(\n image.dtype as NumericDataType, util.sizeFromShape(image.shape));\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n\n const [centerX, centerY] =\n backend_util.getImageCenter(center, imageHeight, imageWidth);\n const fullOpacityValue = 255;\n\n const sinFactor = Math.sin(radians);\n const cosFactor = Math.cos(radians);\n const imageVals = cpuBackend.data.get(image.dataId).values as TypedArray;\n\n for (let batchIdx = 0; batchIdx < batch; batchIdx++) {\n const batchOffset = batchIdx * imageWidth * imageHeight * numChannels;\n\n for (let row = 0; row < imageHeight; row++) {\n const rowOffset = row * (imageWidth * numChannels);\n\n for (let col = 0; col < imageWidth; col++) {\n const colOffset = col * numChannels;\n\n for (let channel = 0; channel < numChannels; channel++) {\n const coords = [batch, row, col, channel];\n\n const x = coords[2];\n const y = coords[1];\n\n // coordX/coordY are the result of rotating and translating x/y.\n let coordX = (x - centerX) * cosFactor - (y - centerY) * sinFactor;\n let coordY = (x - centerX) * sinFactor + (y - centerY) * cosFactor;\n coordX = Math.round(coordX + centerX);\n coordY = Math.round(coordY + centerY);\n\n let outputValue = fillValue;\n if (typeof fillValue !== 'number') {\n if (channel === 3) {\n outputValue = fullOpacityValue;\n } else {\n outputValue = fillValue[channel];\n }\n }\n\n // If the coordinate position falls within the image boundaries...\n if (coordX >= 0 && coordX < imageWidth && coordY >= 0 &&\n coordY < imageHeight) {\n // set the output to the image value at the coordinate position.\n const rotatedRowOffset = coordY * (imageWidth * numChannels);\n const rotatedColOffset = coordX * numChannels;\n const imageIdx =\n batchOffset + rotatedRowOffset + rotatedColOffset + channel;\n outputValue = imageVals[imageIdx];\n }\n\n const outIdx = batchOffset + rowOffset + colOffset + channel;\n output[outIdx] = outputValue as number;\n }\n }\n }\n }\n\n const dataId = cpuBackend.write(output, image.shape, image.dtype);\n return {dataId, shape: image.shape, dtype: image.dtype};\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 {KernelConfig, Round} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const round = unaryKernelFunc(Round, (xi) => {\n // The algorithm is based on banker's rounding.\n const base = Math.floor(xi);\n if (xi - base < 0.5) {\n return Math.floor(xi);\n } else if (xi - base > 0.5) {\n return Math.ceil(xi);\n } else {\n if (base % 2.0 === 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n});\n\nexport const roundConfig: KernelConfig = {\n kernelName: Round,\n backendName: 'cpu',\n kernelFunc: round,\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 {buffer, Rank, ShapeMap, TensorBuffer, TypedArray} from '@tensorflow/tfjs-core';\n\nexport function scatterImpl<R extends Rank>(\n indices: TensorBuffer<R>, updates: TensorBuffer<R>, shape: number[],\n outputSize: number, sliceSize: number, numUpdates: number,\n sliceRank: number, strides: number[], defaultValue: number,\n sumDupeIndices: boolean): TensorBuffer<R> {\n const flattenShape = [outputSize / sliceSize, sliceSize];\n\n const indicesData = indices.values as TypedArray;\n const updatesData = updates.values as TypedArray;\n\n if (outputSize === 0) {\n return buffer(shape as ShapeMap[R], updates.dtype);\n }\n\n const outBuf = buffer(flattenShape, updates.dtype);\n (outBuf.values as TypedArray).fill(defaultValue);\n\n for (let i = 0; i < numUpdates; i++) {\n const index = [];\n let flattenIndex = 0;\n for (let j = 0; j < sliceRank; j++) {\n const dim = indicesData[i * sliceRank + j];\n index.push(dim);\n flattenIndex += dim * strides[j];\n }\n\n if (flattenIndex < 0 || flattenIndex >= outputSize / sliceSize) {\n throw new Error(`Invalid indices: ${index} does not index into ${shape}`);\n }\n\n for (let k = 0; k < sliceSize; k++) {\n if (sumDupeIndices) {\n outBuf.values[flattenIndex * sliceSize + k] +=\n updatesData[i * sliceSize + k];\n } else {\n outBuf.values[flattenIndex * sliceSize + k] = updates.rank === 0 ?\n updatesData[0] :\n updatesData[i * sliceSize + k];\n }\n }\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 {backend_util, KernelConfig, KernelFunc, ScatterNd, ScatterNdAttrs, ScatterNdInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {scatterImpl} from './Scatter_impl';\n\nexport function scatterNd(args: {\n inputs: ScatterNdInputs,\n backend: MathBackendCPU,\n attrs: ScatterNdAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {indices, updates} = inputs;\n const {shape} = attrs;\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(updates, indices, shape);\n const sumDupeIndices = true;\n\n const indicesBuf = backend.bufferSync(indices);\n const updatesBuf = backend.bufferSync(updates);\n\n const outBuf = scatterImpl(\n indicesBuf, updatesBuf, shape, outputSize, sliceSize, numUpdates,\n sliceRank, strides, 0 /* defaultValue */, sumDupeIndices);\n\n return backend.makeTensorInfo(shape, outBuf.dtype, outBuf.values);\n}\n\nexport const scatterNdConfig: KernelConfig = {\n kernelName: ScatterNd,\n backendName: 'cpu',\n kernelFunc: scatterNd as {} 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, Select, SelectInputs, TensorInfo, TypedArray, upcastType, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nexport function select(args: {inputs: SelectInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {condition, t, e} = inputs;\n\n assertNotComplex([condition, t, e], 'select');\n const conditionRank = condition.shape.length;\n\n const values = backend.data.get(condition.dataId).values as TypedArray;\n const tValues = backend.data.get(t.dataId).values as TypedArray;\n const eValues = backend.data.get(e.dataId).values as TypedArray;\n const resultDtype = upcastType(t.dtype, e.dtype);\n const newValues =\n util.makeZerosTypedArray(util.sizeFromShape(t.shape), resultDtype);\n\n let index = 0;\n const offset =\n conditionRank === 0 || conditionRank > 1 || t.shape.length === 1 ?\n 1 :\n util.sizeFromShape(t.shape.slice(1));\n\n for (let i = 0; i < values.length; i++) {\n for (let j = 0; j < offset; j++) {\n if (values[i] === 1) {\n newValues[index++] = tValues[i];\n } else {\n newValues[index++] = eValues[i];\n }\n }\n }\n\n return backend.makeTensorInfo(t.shape, resultDtype, newValues);\n}\n\nexport const selectConfig: KernelConfig = {\n kernelName: Select,\n backendName: 'cpu',\n kernelFunc: select as {} 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, Selu} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nconst scaleAlpha = backend_util.SELU_SCALEALPHA;\nconst scale = backend_util.SELU_SCALE;\n\nexport const selu = unaryKernelFunc(Selu, (xi) => {\n if (xi >= 0) {\n return scale * xi;\n } else {\n return scaleAlpha * (Math.exp(xi) - 1);\n }\n});\n\nexport const seluConfig: KernelConfig = {\n kernelName: Selu,\n backendName: 'cpu',\n kernelFunc: selu,\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, Sign} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sign = unaryKernelFunc(Sign, (xi) => {\n if (xi < 0) {\n return -1;\n } else if (xi > 0) {\n return 1;\n } else {\n return 0;\n }\n});\n\nexport const signConfig: KernelConfig = {\n kernelName: Sign,\n backendName: 'cpu',\n kernelFunc: sign,\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, Sin} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sin = unaryKernelFunc(Sin, (xi) => Math.sin(xi));\n\nexport const sinConfig: KernelConfig = {\n kernelName: Sin,\n backendName: 'cpu',\n kernelFunc: sin,\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, Sinh} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sinh = unaryKernelFunc(Sinh, (xi) => Math.sinh(xi));\n\nexport const sinhConfig: KernelConfig = {\n kernelName: Sinh,\n backendName: 'cpu',\n kernelFunc: sinh,\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, Softplus} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\n// mirrors the implementation of tf.nn.softplus: https://goo.gl/vkcvwX\n\n// epsilon is the difference between 1.0 and the next representable float.\n// For a single precision 32 bit float this should be 2^-23, see:\n// https://math.byu.edu/~schow/work/IEEEFloatingPoint.htm\nconst epsilon = 1.1920928955078125e-7;\nconst threshold = Math.log(epsilon) + 2.0;\n\nexport const softplus = unaryKernelFunc(Softplus, (xi) => {\n // Value above which exp(x) may overflow, but softplus(x) == x\n // is within machine epsilon.\n const tooLarge = xi > -threshold;\n\n // Value below which exp(x) may underflow, but softplus(x) == exp(x)\n // is within machine epsilon.\n const tooSmall = xi < threshold;\n\n const expX = Math.exp(xi);\n let result;\n\n if (tooSmall) {\n result = expX;\n } else if (tooLarge) {\n result = xi;\n } else {\n result = Math.log(1.0 + expX);\n }\n return result;\n});\n\nexport const softplusConfig: KernelConfig = {\n kernelName: Softplus,\n backendName: 'cpu',\n kernelFunc: softplus,\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, ReshapeAttrs, ReshapeInputs, SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs, TensorInfo, TransposeAttrs, TransposeInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {padV2Config} from './PadV2';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function spaceToBatchND(args: {\n inputs: SpaceToBatchNDInputs,\n backend: MathBackendCPU,\n attrs: SpaceToBatchNDAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, paddings} = attrs;\n\n assertNotComplex([x], 'spaceToBatchND');\n\n const prod = util.sizeFromShape(blockShape);\n\n const completePaddings: Array<[number, number]> = [[0, 0]];\n completePaddings.push(...(paddings as Array<[number, number]>));\n\n for (let i = 1 + blockShape.length; i < x.shape.length; ++i) {\n completePaddings.push([0, 0]);\n }\n\n const paddedX = padV2Config.kernelFunc({\n inputs: {x},\n backend,\n attrs: {paddings: completePaddings, constantValue: 0}\n }) as TensorInfo;\n\n const reshapedPaddedShape =\n backend_util.getReshaped(paddedX.shape, blockShape, prod, false);\n\n const permutedReshapedPaddedPermutation = backend_util.getPermuted(\n reshapedPaddedShape.length, blockShape.length, false);\n\n const flattenShape =\n backend_util.getReshapedPermuted(paddedX.shape, blockShape, prod, false);\n\n const reshapeInputs: ReshapeInputs = {x: paddedX};\n const reshapeAttrs: ReshapeAttrs = {shape: reshapedPaddedShape};\n const paddedXReshaped =\n reshape({inputs: reshapeInputs, backend, attrs: reshapeAttrs});\n\n const transposeInputs: TransposeInputs = {x: paddedXReshaped};\n const transposeAttrs:\n TransposeAttrs = {perm: permutedReshapedPaddedPermutation};\n const paddedXT =\n transpose({inputs: transposeInputs, backend, attrs: transposeAttrs});\n\n const resultReshapeInputs: ReshapeInputs = {x: paddedXT};\n const resultReshapeAttrs: ReshapeAttrs = {shape: flattenShape};\n const result = reshape(\n {inputs: resultReshapeInputs, backend, attrs: resultReshapeAttrs});\n\n backend.disposeIntermediateTensorInfo(paddedX);\n backend.disposeIntermediateTensorInfo(paddedXReshaped);\n backend.disposeIntermediateTensorInfo(paddedXT);\n\n return result;\n}\n\nexport const spaceToBatchNDConfig: KernelConfig = {\n kernelName: SpaceToBatchND,\n backendName: 'cpu',\n kernelFunc: spaceToBatchND as {} as KernelFunc\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 {KernelConfig, KernelFunc, SparseFillEmptyRows, SparseFillEmptyRowsInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {sparseFillEmptyRowsImpl} from './SparseFillEmptyRows_impl';\n\nexport function sparseFillEmptyRows(args: {\n inputs: SparseFillEmptyRowsInputs,\n backend: MathBackendCPU\n}): [TensorInfo, TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {indices, values, denseShape, defaultValue} = inputs;\n if (denseShape.shape.length !== 1) {\n throw new Error(`Dense shape must be a vector, saw:\n ${denseShape.shape}`);\n }\n if (indices.shape.length !== 2) {\n throw new Error(`Indices must be a matrix, saw:\n ${indices.shape}`);\n }\n if (values.shape.length !== 1) {\n throw new Error(`Values must be a vector, saw:\n ${values.shape}`);\n }\n if (defaultValue.shape.length !== 0) {\n throw new Error(`Default value must be a scalar, saw:\n ${defaultValue.shape}`);\n }\n\n const $indices = backend.data.get(indices.dataId).values as TypedArray;\n const $values = backend.data.get(values.dataId).values as TypedArray;\n const $denseShape = backend.data.get(denseShape.dataId).values as TypedArray;\n const $defaultValue =\n backend.data.get(defaultValue.dataId).values[0] as number;\n\n const [outputIndices, outputIndicesShape, outputValues,\n emptyRowIndicator, reverseIndexMap] =\n sparseFillEmptyRowsImpl(\n $indices, indices.shape, indices.dtype, $values, values.dtype,\n $denseShape, $defaultValue);\n return [\n backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),\n backend.makeTensorInfo(\n [outputIndicesShape[0]], values.dtype, outputValues),\n backend.makeTensorInfo(\n [emptyRowIndicator.length], 'bool',\n new Uint8Array(\n emptyRowIndicator.map((value: boolean) => Number(value)))),\n backend.makeTensorInfo(\n [reverseIndexMap.length], indices.dtype,\n new Int32Array(reverseIndexMap)),\n ];\n}\n\nexport const sparseFillEmptyRowsConfig: KernelConfig = {\n kernelName: SparseFillEmptyRows,\n backendName: 'cpu',\n kernelFunc: sparseFillEmptyRows as {} as KernelFunc,\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 {KernelConfig, SparseReshape, SparseReshapeInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {sparseReshapeImpl} from './SparseReshape_impl';\n\nexport function sparseReshape(\n args: {inputs: SparseReshapeInputs, backend: MathBackendCPU}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {inputIndices, inputShape, newShape} = inputs;\n if (inputIndices.shape.length !== 2) {\n throw new Error(`Input indices should be a matrix but received shape\n ${inputIndices.shape}`);\n }\n if (inputShape.shape.length !== 1) {\n throw new Error(`Input shape should be a vector but received shape\n ${inputShape.shape}`);\n }\n\n if (newShape.shape.length !== 1) {\n throw new Error(\n `Target shape should be a vector but received shape ${newShape.shape}`);\n }\n\n const $inputShape =\n Array.from(backend.data.get(inputShape.dataId).values as TypedArray);\n const $inputIndices =\n backend.data.get(inputIndices.dataId).values as TypedArray;\n const targetShape =\n Array.from(backend.data.get(newShape.dataId).values as TypedArray);\n\n const [newIndices, indicesShape, outputShape] = sparseReshapeImpl(\n $inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape,\n targetShape);\n return [\n backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),\n backend.makeTensorInfo(\n [outputShape.length], newShape.dtype, new Int32Array(outputShape)),\n ];\n}\n\nexport const sparseReshapeConfig: KernelConfig = {\n kernelName: SparseReshape,\n backendName: 'cpu',\n kernelFunc: sparseReshape,\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 {KernelConfig, SparseSegmentMean, SparseSegmentMeanInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {sparseSegmentReductionImpl} from './SparseSegmentReduction_impl';\n\nexport function sparseSegmentMean(\n args: {inputs: SparseSegmentMeanInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n\n const $data = backend.data.get(data.dataId).values as TypedArray;\n const $indices = backend.data.get(indices.dataId).values as TypedArray;\n const $segmentIds = backend.data.get(segmentIds.dataId).values as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImpl(\n $data, data.shape, data.dtype, $indices, $segmentIds, true);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentMeanConfig: KernelConfig = {\n kernelName: SparseSegmentMean,\n backendName: 'cpu',\n kernelFunc: sparseSegmentMean,\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 {KernelConfig, SparseSegmentSum, SparseSegmentSumInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {sparseSegmentReductionImpl} from './SparseSegmentReduction_impl';\n\nexport function sparseSegmentSum(\n args: {inputs: SparseSegmentSumInputs, backend: MathBackendCPU}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n\n const $data = backend.data.get(data.dataId).values as TypedArray;\n const $indices = backend.data.get(indices.dataId).values as TypedArray;\n const $segmentIds = backend.data.get(segmentIds.dataId).values as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImpl(\n $data, data.shape, data.dtype, $indices, $segmentIds);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentSumConfig: KernelConfig = {\n kernelName: SparseSegmentSum,\n backendName: 'cpu',\n kernelFunc: sparseSegmentSum,\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, SparseToDense, SparseToDenseAttrs, SparseToDenseInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {scatterImpl} from './Scatter_impl';\n\nexport function sparseToDense(args: {\n inputs: SparseToDenseInputs,\n backend: MathBackendCPU,\n attrs: SparseToDenseAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {sparseIndices, sparseValues, defaultValue} = inputs;\n const {outputShape} = attrs;\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(sparseValues, sparseIndices, outputShape);\n const sumDupeIndices = false;\n\n const indicesBuf = backend.bufferSync(sparseIndices);\n const updatesBuf = backend.bufferSync(sparseValues);\n const $defaultValue =\n backend.data.get(defaultValue.dataId).values[0] as number;\n\n const outBuf = scatterImpl(\n indicesBuf, updatesBuf, outputShape, outputSize, sliceSize, numUpdates,\n sliceRank, strides, $defaultValue, sumDupeIndices);\n\n return backend.makeTensorInfo(outputShape, outBuf.dtype, outBuf.values);\n}\n\nexport const sparseToDenseConfig: KernelConfig = {\n kernelName: SparseToDense,\n backendName: 'cpu',\n kernelFunc: sparseToDense as {} 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, SplitVAttrs, SplitVInputs} from '@tensorflow/tfjs-core';\nimport {KernelConfig, KernelFunc, SplitV, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {slice} from './Slice';\n\nexport function splitV(\n args: {inputs: SplitVInputs, backend: MathBackendCPU, attrs: SplitVAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {numOrSizeSplits, axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, x.shape)[0];\n const splitSizes = backend_util.prepareSplitSize(x, numOrSizeSplits, $axis);\n\n const begin = new Array(x.shape.length).fill(0);\n const size = x.shape.slice();\n return splitSizes.map(s => {\n const sliceSize = [...size];\n sliceSize[$axis] = s;\n const sliceT =\n slice({inputs: {x}, backend, attrs: {begin, size: sliceSize}});\n begin[$axis] += s;\n return sliceT;\n });\n}\n\nexport const splitVConfig: KernelConfig = {\n kernelName: SplitV,\n backendName: 'cpu',\n kernelFunc: splitV as {} 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, Sqrt} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const sqrt = unaryKernelFunc(Sqrt, (xi) => Math.sqrt(xi));\n\nexport const sqrtConfig: KernelConfig = {\n kernelName: Sqrt,\n backendName: 'cpu',\n kernelFunc: sqrt,\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", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, Step, StepAttrs} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const step = unaryKernelFunc(Step, (xi, attrs) => {\n const stepAttrs = attrs as {} as StepAttrs;\n if (isNaN(xi)) {\n return NaN;\n } else {\n return xi > 0 ? 1 : stepAttrs.alpha;\n }\n});\n\nexport const stepConfig: KernelConfig = {\n kernelName: Step,\n backendName: 'cpu',\n kernelFunc: step,\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, slice_util, StridedSlice, StridedSliceAttrs, StridedSliceInputs, TensorInfo} 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 {nonStrided, $begin, $strides, size, newShape, outShape} =\n slice_util.sliceInfo(\n x.shape, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask);\n\n const $x = reshape({inputs: {x}, backend, attrs: {shape: newShape}});\n\n let result;\n if (nonStrided) {\n const sliced =\n slice({inputs: {x: $x}, backend, attrs: {begin: $begin, size}});\n result = reshape({inputs: {x: sliced}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo(sliced);\n } else if (outShape.some(axis => axis === 0)) {\n result = backend.makeTensorInfo(outShape, x.dtype, []);\n } else {\n const xBuf = backend.bufferSync($x);\n const outBuf = stridedSliceImpl(outShape, xBuf, $strides, $begin);\n\n result = backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n }\n\n const resultReshaped =\n reshape({inputs: {x: result}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo($x);\n backend.disposeIntermediateTensorInfo(result);\n\n return resultReshaped;\n}\n\nexport const stridedSliceConfig: KernelConfig = {\n kernelName: StridedSlice,\n backendName: 'cpu',\n kernelFunc: stridedSlice as {} as KernelFunc\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 {KernelConfig, KernelFunc, StringNGrams, StringNGramsAttrs, StringNGramsInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {stringNGramsImpl} from './StringNGrams_impl';\n\nexport function stringNGrams(args: {\n inputs: StringNGramsInputs,\n backend: MathBackendCPU,\n attrs: StringNGramsAttrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {\n separator,\n nGramWidths,\n leftPad,\n rightPad,\n padWidth,\n preserveShortSequences\n } = attrs;\n const {data, dataSplits} = inputs;\n const $data = backend.data.get(data.dataId).values as Uint8Array[];\n const $dataSplits = backend.data.get(dataSplits.dataId).values as Int32Array;\n\n const [nGrams, nGramsSplits] = stringNGramsImpl(\n $data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth,\n preserveShortSequences);\n return [\n backend.makeTensorInfo([nGrams.length], 'string', nGrams),\n backend.makeTensorInfo(dataSplits.shape, 'int32', nGramsSplits),\n ];\n}\n\nexport const stringNGramsConfig: KernelConfig = {\n kernelName: StringNGrams,\n backendName: 'cpu',\n kernelFunc: stringNGrams as {} as KernelFunc,\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 {KernelConfig, KernelFunc, StringSplit, StringSplitAttrs, StringSplitInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {stringSplitImpl} from './StringSplit_impl';\n\nexport function stringSplit(args: {\n inputs: StringSplitInputs,\n backend: MathBackendCPU,\n attrs: StringSplitAttrs\n}): [TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {skipEmpty} = attrs;\n const {input, delimiter} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (input.shape.length !== 1) {\n throw new Error(`Input must be a vector, got shape: ${input.shape}`);\n }\n if (delimiter.shape.length !== 0) {\n throw new Error(\n `Delimiter must be a scalar, got shape: ${delimiter.shape}`);\n }\n\n const $input = backend.data.get(input.dataId).values as Uint8Array[];\n const $delimiter = backend.data.get(delimiter.dataId).values[0] as Uint8Array;\n\n const [indices, values, shape] =\n stringSplitImpl($input, $delimiter, skipEmpty);\n const outputSize = values.length;\n return [\n backend.makeTensorInfo([outputSize, 2], 'int32', indices),\n backend.makeTensorInfo([outputSize], 'string', values),\n backend.makeTensorInfo([2], 'int32', new Int32Array(shape))\n ];\n}\n\nexport const stringSplitConfig: KernelConfig = {\n kernelName: StringSplit,\n backendName: 'cpu',\n kernelFunc: stringSplit as {} as KernelFunc,\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 {KernelConfig, KernelFunc, StringToHashBucketFast, StringToHashBucketFastAttrs, StringToHashBucketFastInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nimport {stringToHashBucketFastImpl} from './StringToHashBucketFast_impl';\n\nexport function stringToHashBucketFast(args: {\n inputs: StringToHashBucketFastInputs,\n backend: MathBackendCPU,\n attrs: StringToHashBucketFastAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {numBuckets} = attrs;\n const {input} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (numBuckets <= 0) {\n throw new Error(`Number of buckets must be at least 1`);\n }\n\n const $input = backend.data.get(input.dataId).values as Uint8Array[];\n\n const output = stringToHashBucketFastImpl($input, numBuckets);\n return backend.makeTensorInfo(input.shape, 'int32', output);\n}\n\nexport const stringToHashBucketFastConfig: KernelConfig = {\n kernelName: StringToHashBucketFast,\n backendName: 'cpu',\n kernelFunc: stringToHashBucketFast as {} 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, Tan} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const tan = unaryKernelFunc(Tan, (xi) => Math.tan(xi));\n\nexport const tanConfig: KernelConfig = {\n kernelName: Tan,\n backendName: 'cpu',\n kernelFunc: tan,\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, Tanh} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../utils/unary_utils';\n\nexport const tanh = unaryKernelFunc(Tanh, (xi) => Math.tanh(xi));\n\nexport const tanhConfig: KernelConfig = {\n kernelName: Tanh,\n backendName: 'cpu',\n kernelFunc: tanh,\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 {} 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, NumericDataType, TensorInfo, TopK, TopKAttrs, TopKInputs, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {topKImpl} from './TopK_impl';\n\nexport function topK(\n args: {inputs: TopKInputs, backend: MathBackendCPU, attrs: TopKAttrs}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {k, sorted} = attrs;\n\n assertNotComplex(x, 'topk');\n\n const xVals = backend.data.get(x.dataId).values as TypedArray;\n const [allTopKVals, allTopKIndices] =\n topKImpl(xVals, x.shape, x.dtype as NumericDataType, k, sorted);\n\n return [\n backend.makeTensorInfo(\n allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),\n backend.makeTensorInfo(\n allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)\n ];\n}\n\nexport const topKConfig: KernelConfig = {\n kernelName: TopK,\n backendName: 'cpu',\n kernelFunc: topK as {} as KernelFunc\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 {KernelConfig, KernelFunc, NumericDataType, TensorInfo, Transform, TransformAttrs, TransformInputs, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\n\nexport function transform(args: {\n inputs: TransformInputs,\n attrs: TransformAttrs,\n backend: MathBackendCPU\n}): TensorInfo {\n const {inputs, attrs, backend} = args;\n const {image, transforms} = inputs;\n const {interpolation, fillMode, fillValue, outputShape} = attrs;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n const [outHeight, outWidth] =\n outputShape != null ? outputShape : [imageHeight, imageWidth];\n const outShape = [batch, outHeight, outWidth, numChannels];\n\n const strides = util.computeStrides(image.shape);\n const batchStride = strides[0];\n const rowStride = strides[1];\n const colStride = strides[2];\n\n const outVals = util.getTypedArrayFromDType(\n image.dtype as NumericDataType, util.sizeFromShape(outShape));\n\n outVals.fill(fillValue);\n\n const imageVals = backend.data.get(image.dataId).values as TypedArray;\n const transformVals =\n backend.data.get(transforms.dataId).values as TypedArray;\n\n // Ref TF implementation:\n // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/image/image_ops.h\n for (let b = 0; b < batch; ++b) {\n const transform = transforms.shape[0] === 1 ?\n transformVals :\n transformVals.subarray(b * 8, b * 8 + 8);\n\n for (let outY = 0; outY < outHeight; ++outY) {\n for (let outX = 0; outX < outWidth; ++outX) {\n for (let channel = 0; channel < numChannels; ++channel) {\n let val;\n\n const projection = transform[6] * outX + transform[7] * outY + 1;\n\n if (projection === 0) {\n // Return the fill value for infinite coordinates,\n // which are outside the input image\n continue;\n }\n\n const inX =\n (transform[0] * outX + transform[1] * outY + transform[2]) /\n projection;\n const inY =\n (transform[3] * outX + transform[4] * outY + transform[5]) /\n projection;\n\n const x = mapCoord(inX, imageWidth, fillMode);\n const y = mapCoord(inY, imageHeight, fillMode);\n\n switch (interpolation) {\n case 'nearest':\n val = nearestInterpolation(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, b, y, x, channel, fillValue);\n break;\n case 'bilinear':\n val = bilinearInterpolation(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, b, y, x, channel, fillValue);\n break;\n default:\n throw new Error(\n `Error in Transform: Expect 'nearest' or ` +\n `'bilinear', but got ${interpolation}`);\n }\n\n const ind =\n b * batchStride + outY * rowStride + outX * colStride + channel;\n\n outVals[ind] = val;\n }\n }\n }\n\n return backend.makeTensorInfo(outShape, image.dtype, outVals);\n }\n\n const dataId = backend.write(outVals, outShape, image.dtype);\n return {dataId, shape: image.shape, dtype: image.dtype};\n}\n\nexport const transformConfig: KernelConfig = {\n kernelName: Transform,\n backendName: 'cpu',\n kernelFunc: transform as {} as KernelFunc\n};\n\nfunction mapCoord(\n outCoord: number, len: number,\n mode: 'constant'|'reflect'|'wrap'|'nearest') {\n switch (mode) {\n case 'reflect':\n return mapCoordReflect(outCoord, len);\n case 'wrap':\n return mapCoordWrap(outCoord, len);\n case 'nearest':\n return mapCoordNearest(outCoord, len);\n case 'constant':\n default:\n return mapCoordConstant(outCoord, len);\n }\n}\n\nfunction mapCoordReflect(outCoord: number, len: number): number {\n // Reflect [abcd] to [dcba|abcd|dcba].\n let inCoord = outCoord;\n if (inCoord < 0) {\n if (len <= 1) {\n inCoord = 0;\n } else {\n const sz2 = 2 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * Math.trunc(-inCoord / sz2) + inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1;\n }\n } else if (inCoord > len - 1) {\n if (len <= 1) {\n inCoord = 0;\n } else {\n const sz2 = 2 * len;\n inCoord -= sz2 * Math.trunc(inCoord / sz2);\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1;\n }\n }\n }\n // clamp is necessary because when outCoord = 3.5 and len = 4,\n // inCoord = 3.5 and will be rounded to 4 in nearest interpolation.\n return util.clamp(0, inCoord, len - 1);\n}\n\nfunction mapCoordWrap(outCoord: number, len: number): number {\n // Wrap [abcd] to [abcd|abcd|abcd].\n let inCoord = outCoord;\n if (inCoord < 0) {\n if (len <= 1) {\n inCoord = 0;\n } else {\n const sz = len - 1;\n inCoord += len * (Math.trunc(-inCoord / sz) + 1);\n }\n } else if (inCoord > len - 1) {\n if (len <= 1) {\n inCoord = 0;\n } else {\n const sz = len - 1;\n inCoord -= len * Math.trunc(inCoord / sz);\n }\n }\n // clamp is necessary because when outCoord = -0.5 and len = 4,\n // inCoord = 3.5 and will be rounded to 4 in nearest interpolation.\n return util.clamp(0, inCoord, len - 1);\n}\n\nfunction mapCoordConstant(outCoord: number, len: number): number {\n return outCoord;\n}\n\nfunction mapCoordNearest(outCoord: number, len: number): number {\n return util.clamp(0, outCoord, len - 1);\n}\n\nfunction readWithFillValue(\n imageVals: TypedArray, imageHeight: number, imageWidth: number,\n batchStride: number, rowStride: number, colStride: number, batch: number,\n y: number, x: number, channel: number, fillValue: number): number {\n const ind = batch * batchStride + y * rowStride + x * colStride + channel;\n if (0 <= y && y < imageHeight && 0 <= x && x < imageWidth) {\n return imageVals[ind];\n } else {\n return fillValue;\n }\n}\n\nfunction nearestInterpolation(\n imageVals: TypedArray, imageHeight: number, imageWidth: number,\n batchStride: number, rowStride: number, colStride: number, batch: number,\n y: number, x: number, channel: number, fillValue: number): number {\n const $y = Math.round(y);\n const $x = Math.round(x);\n\n return readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride, colStride,\n batch, $y, $x, channel, fillValue);\n}\n\nfunction bilinearInterpolation(\n imageVals: TypedArray, imageHeight: number, imageWidth: number,\n batchStride: number, rowStride: number, colStride: number, batch: number,\n y: number, x: number, channel: number, fillValue: number) {\n const yFloor = Math.floor(y);\n const xFloor = Math.floor(x);\n const yCeil = yFloor + 1;\n const xCeil = xFloor + 1;\n // f(x, yFloor) = (xCeil - x) / (xCeil - xFloor) * f(xFloor, yFloor)\n // + (x - xFloor) / (xCeil - xFloor) * f(xCeil, yFloor)\n const valueYFloor =\n (xCeil - x) *\n readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, batch, yFloor, xFloor, channel, fillValue) +\n (x - xFloor) *\n readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, batch, yFloor, xCeil, channel, fillValue);\n // f(x, yCeil) = (xCeil - x) / (xCeil - xFloor) * f(xFloor, yCeil)\n // + (x - xFloor) / (xCeil - xFloor) * f(xCeil, yCeil)\n const valueYCeil =\n (xCeil - x) *\n readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, batch, yCeil, xFloor, channel, fillValue) +\n (x - xFloor) *\n readWithFillValue(\n imageVals, imageHeight, imageWidth, batchStride, rowStride,\n colStride, batch, yCeil, xCeil, channel, fillValue);\n // f(x, y) = (yCeil - y) / (yCeil - yFloor) * f(x, yFloor)\n // + (y - yFloor) / (yCeil - yFloor) * f(x, yCeil)\n return (yCeil - y) * valueYFloor + (y - yFloor) * valueYCeil;\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, Unique, UniqueAttrs, UniqueInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\n\nimport {uniqueImpl} from './Unique_impl';\n\nexport function unique(\n args: {inputs: UniqueInputs, attrs: UniqueAttrs, backend: MathBackendCPU}):\n TensorInfo[] {\n const {inputs, attrs, backend} = args;\n const {axis} = attrs;\n const {x} = inputs;\n assertNotComplex(x, 'unique');\n\n const values = backend.data.get(x.dataId).values;\n const {outputValues, outputShape, indices} =\n uniqueImpl(values, axis, x.shape, x.dtype);\n return [\n backend.makeTensorInfo(outputShape, x.dtype, outputValues),\n backend.makeTensorInfo([indices.length], 'int32', indices),\n ];\n}\n\nexport const uniqueConfig: KernelConfig = {\n kernelName: Unique,\n backendName: 'cpu',\n kernelFunc: unique as {} 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, Unpack, UnpackAttrs, UnpackInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nexport function unpack(\n args: {inputs: UnpackInputs, backend: MathBackendCPU, attrs: UnpackAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {value} = inputs;\n let {axis} = attrs;\n\n if (axis < 0) {\n axis += value.shape.length;\n }\n\n const valueRank = value.shape.length;\n\n const num = value.shape[axis];\n const outShape: number[] = new Array(valueRank - 1);\n let outIndex = 0;\n for (let i = 0; i < valueRank; i++) {\n if (i !== axis) {\n outShape[outIndex++] = value.shape[i];\n }\n }\n\n const begin = new Array(valueRank).fill(0);\n const size = value.shape.slice();\n size[axis] = 1;\n const res = new Array(num);\n for (let i = 0; i < res.length; i++) {\n begin[axis] = i;\n const tempRes = slice({inputs: {x: value}, backend, attrs: {begin, size}});\n res[i] = reshape({inputs: {x: tempRes}, backend, attrs: {shape: outShape}});\n backend.disposeIntermediateTensorInfo(tempRes);\n }\n\n return res;\n}\n\nexport const unpackConfig: KernelConfig = {\n kernelName: Unpack,\n backendName: 'cpu',\n kernelFunc: unpack as {} 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, UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendCPU} from '../backend_cpu';\nimport {assertNotComplex} from '../cpu_util';\nimport {cast} from './Cast';\nimport {equal} from './Equal';\nimport {expandDims} from './ExpandDims';\nimport {multiply} from './Multiply';\nimport {pack} from './Pack';\nimport {sum} from './Sum';\n\nexport function unsortedSegmentSum(args: {\n inputs: UnsortedSegmentSumInputs,\n backend: MathBackendCPU,\n attrs: UnsortedSegmentSumAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, segmentIds} = inputs;\n const {numSegments} = attrs;\n\n assertNotComplex(x, 'unsortedSegmentSum');\n\n const xRank = x.shape.length;\n const segmentIdsRank = segmentIds.shape.length;\n const res = [];\n const intermediates: TensorInfo[] = [];\n\n // Reshape the segment id's so that they can be broadcast with\n // x. The new shape should be [segmentIds.shape, 1, ..., 1]\n const numIters = xRank - segmentIdsRank;\n let $segmentIds = segmentIds;\n\n for (let i = 0; i < numIters; ++i) {\n const expanded = expandDims(\n {inputs: {input: $segmentIds}, backend, attrs: {dim: i + 1}});\n $segmentIds = expanded;\n intermediates.push(expanded);\n }\n\n for (let i = 0; i < numSegments; ++i) {\n const scalarValue = util.createScalarValue(i as {} as 'int32', 'int32');\n const segmentId = backend.makeTensorInfo([], 'int32', scalarValue);\n const mask =\n equal({inputs: {a: segmentId, b: $segmentIds}, backend}) as TensorInfo;\n const maskCasted =\n cast({inputs: {x: mask}, backend, attrs: {dtype: 'float32'}});\n const mul =\n multiply({inputs: {a: maskCasted, b: x}, backend}) as TensorInfo;\n const sumTensorInfo =\n sum({inputs: {x: mul}, backend, attrs: {axis: 0, keepDims: false}});\n res.push(sumTensorInfo);\n intermediates.push(segmentId);\n intermediates.push(mask);\n intermediates.push(maskCasted);\n intermediates.push(mul);\n intermediates.push(sumTensorInfo);\n }\n\n const result = pack({inputs: res, backend, attrs: {axis: 0}});\n\n intermediates.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n}\n\nexport const unsortedSegmentSumConfig: KernelConfig = {\n kernelName: UnsortedSegmentSum,\n backendName: 'cpu',\n kernelFunc: unsortedSegmentSum as {} 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// We explicitly import the modular kernels so they get registered in the\n// global registry when we compile the library. A modular build would replace\n// the contents of this file and import only the kernels that are needed.\nimport {KernelConfig, registerKernel} from '@tensorflow/tfjs-core';\n\nimport {_fusedMatMulConfig} from './kernels/_FusedMatMul';\nimport {absConfig} from './kernels/Abs';\nimport {acosConfig} from './kernels/Acos';\nimport {acoshConfig} from './kernels/Acosh';\nimport {addConfig} from './kernels/Add';\nimport {addNConfig} from './kernels/AddN';\nimport {allConfig} from './kernels/All';\nimport {anyConfig} from './kernels/Any';\nimport {argMaxConfig} from './kernels/ArgMax';\nimport {argMinConfig} from './kernels/ArgMin';\nimport {asinConfig} from './kernels/Asin';\nimport {asinhConfig} from './kernels/Asinh';\nimport {atanConfig} from './kernels/Atan';\nimport {atan2Config} from './kernels/Atan2';\nimport {atanhConfig} from './kernels/Atanh';\nimport {avgPoolConfig} from './kernels/AvgPool';\nimport {avgPool3DConfig} from './kernels/AvgPool3D';\nimport {avgPool3DGradConfig} from './kernels/AvgPool3DGrad';\nimport {avgPoolGradConfig} from './kernels/AvgPoolGrad';\nimport {batchMatMulConfig} from './kernels/BatchMatMul';\nimport {batchNormConfig} from './kernels/BatchNorm';\nimport {batchToSpaceNDConfig} from './kernels/BatchToSpaceND';\nimport {bincountConfig} from './kernels/Bincount';\nimport {castConfig} from './kernels/Cast';\nimport {ceilConfig} from './kernels/Ceil';\nimport {clipConfig} from './kernels/Clip';\nimport {complexConfig} from './kernels/Complex';\nimport {complexAbsConfig} from './kernels/ComplexAbs';\nimport {concatConfig} from './kernels/Concat';\nimport {conv2DConfig} from './kernels/Conv2D';\nimport {conv2DBackpropFilterConfig} from './kernels/Conv2DBackpropFilter';\nimport {conv2DBackpropInputConfig} from './kernels/Conv2DBackpropInput';\nimport {conv3DConfig} from './kernels/Conv3D';\nimport {conv3DBackpropFilterV2Config} from './kernels/Conv3DBackpropFilterV2';\nimport {conv3DBackpropInputV2Config} from './kernels/Conv3DBackpropInputV2';\nimport {cosConfig} from './kernels/Cos';\nimport {coshConfig} from './kernels/Cosh';\nimport {cropAndResizeConfig} from './kernels/CropAndResize';\nimport {cumsumConfig} from './kernels/Cumsum';\nimport {denseBincountConfig} from './kernels/DenseBincount';\nimport {depthToSpaceConfig} from './kernels/DepthToSpace';\nimport {depthwiseConv2dNativeConfig} from './kernels/DepthwiseConv2dNative';\nimport {depthwiseConv2dNativeBackpropFilterConfig} from './kernels/DepthwiseConv2dNativeBackpropFilter';\nimport {depthwiseConv2dNativeBackpropInputConfig} from './kernels/DepthwiseConv2dNativeBackpropInput';\nimport {diagConfig} from './kernels/Diag';\nimport {dilation2dConfig} from './kernels/Dilation2D';\nimport {dilation2dBackpropFilterConfig} from './kernels/Dilation2DBackpropFilter';\nimport {dilation2dBackpropInputConfig} from './kernels/Dilation2DBackpropInput';\nimport {einsumConfig} from './kernels/Einsum';\nimport {eluConfig} from './kernels/Elu';\nimport {eluGradConfig} from './kernels/EluGrad';\nimport {equalConfig} from './kernels/Equal';\nimport {erfConfig} from './kernels/Erf';\nimport {expConfig} from './kernels/Exp';\nimport {expandDimsConfig} from './kernels/ExpandDims';\nimport {expm1Config} from './kernels/Expm1';\nimport {fftConfig} from './kernels/FFT';\nimport {fillConfig} from './kernels/Fill';\nimport {flipLeftRightConfig} from './kernels/FlipLeftRight';\nimport {floorConfig} from './kernels/Floor';\nimport {floorDivConfig} from './kernels/FloorDiv';\nimport {fusedConv2DConfig} from './kernels/FusedConv2D';\nimport {fusedDepthwiseConv2DConfig} from './kernels/FusedDepthwiseConv2D';\nimport {gatherNdConfig} from './kernels/GatherNd';\nimport {gatherV2Config} from './kernels/GatherV2';\nimport {greaterConfig} from './kernels/Greater';\nimport {greaterEqualConfig} from './kernels/GreaterEqual';\nimport {identityConfig} from './kernels/Identity';\nimport {ifftConfig} from './kernels/IFFT';\nimport {imagConfig} from './kernels/Imag';\nimport {isFiniteConfig} from './kernels/IsFinite';\nimport {isInfConfig} from './kernels/IsInf';\nimport {isNaNConfig} from './kernels/IsNaN';\nimport {leakyReluConfig} from './kernels/LeakyRelu';\nimport {lessConfig} from './kernels/Less';\nimport {lessEqualConfig} from './kernels/LessEqual';\nimport {linSpaceConfig} from './kernels/LinSpace';\nimport {logConfig} from './kernels/Log';\nimport {log1pConfig} from './kernels/Log1p';\nimport {logicalAndConfig} from './kernels/LogicalAnd';\nimport {logicalNotConfig} from './kernels/LogicalNot';\nimport {logicalOrConfig} from './kernels/LogicalOr';\nimport {lRNConfig} from './kernels/LRN';\nimport {lRNGradConfig} from './kernels/LRNGrad';\nimport {maxConfig} from './kernels/Max';\nimport {maximumConfig} from './kernels/Maximum';\nimport {maxPoolConfig} from './kernels/MaxPool';\nimport {maxPool3DConfig} from './kernels/MaxPool3D';\nimport {maxPool3DGradConfig} from './kernels/MaxPool3DGrad';\nimport {maxPoolGradConfig} from './kernels/MaxPoolGrad';\nimport {maxPoolWithArgmaxConfig} from './kernels/MaxPoolWithArgmax';\nimport {meanConfig} from './kernels/Mean';\nimport {minConfig} from './kernels/Min';\nimport {minimumConfig} from './kernels/Minimum';\nimport {mirrorPadConfig} from './kernels/MirrorPad';\nimport {modConfig} from './kernels/Mod';\nimport {multinomialConfig} from './kernels/Multinomial';\nimport {multiplyConfig} from './kernels/Multiply';\nimport {negConfig} from './kernels/Neg';\nimport {nonMaxSuppressionV3Config} from './kernels/NonMaxSuppressionV3';\nimport {nonMaxSuppressionV4Config} from './kernels/NonMaxSuppressionV4';\nimport {nonMaxSuppressionV5Config} from './kernels/NonMaxSuppressionV5';\nimport {notEqualConfig} from './kernels/NotEqual';\nimport {oneHotConfig} from './kernels/OneHot';\nimport {onesLikeConfig} from './kernels/OnesLike';\nimport {packConfig} from './kernels/Pack';\nimport {padV2Config} from './kernels/PadV2';\nimport {powConfig} from './kernels/Pow';\nimport {preluConfig} from './kernels/Prelu';\nimport {prodConfig} from './kernels/Prod';\nimport {rangeConfig} from './kernels/Range';\nimport {realConfig} from './kernels/Real';\nimport {realDivConfig} from './kernels/RealDiv';\nimport {reciprocalConfig} from './kernels/Reciprocal';\nimport {reluConfig} from './kernels/Relu';\nimport {relu6Config} from './kernels/Relu6';\nimport {reshapeConfig} from './kernels/Reshape';\nimport {resizeBilinearConfig} from './kernels/ResizeBilinear';\nimport {resizeBilinearGradConfig} from './kernels/ResizeBilinearGrad';\nimport {resizeNearestNeighborConfig} from './kernels/ResizeNearestNeighbor';\nimport {resizeNearestNeighborGradConfig} from './kernels/ResizeNearestNeighborGrad';\nimport {reverseConfig} from './kernels/Reverse';\nimport {rotateWithOffsetConfig} from './kernels/RotateWithOffset';\nimport {roundConfig} from './kernels/Round';\nimport {rsqrtConfig} from './kernels/Rsqrt';\nimport {scatterNdConfig} from './kernels/ScatterNd';\nimport {selectConfig} from './kernels/Select';\nimport {seluConfig} from './kernels/Selu';\nimport {sigmoidConfig} from './kernels/Sigmoid';\nimport {signConfig} from './kernels/Sign';\nimport {sinConfig} from './kernels/Sin';\nimport {sinhConfig} from './kernels/Sinh';\nimport {sliceConfig} from './kernels/Slice';\nimport {softmaxConfig} from './kernels/Softmax';\nimport {softplusConfig} from './kernels/Softplus';\nimport {spaceToBatchNDConfig} from './kernels/SpaceToBatchND';\nimport {sparseFillEmptyRowsConfig} from './kernels/SparseFillEmptyRows';\nimport {sparseReshapeConfig} from './kernels/SparseReshape';\nimport {sparseSegmentMeanConfig} from './kernels/SparseSegmentMean';\nimport {sparseSegmentSumConfig} from './kernels/SparseSegmentSum';\nimport {sparseToDenseConfig} from './kernels/SparseToDense';\nimport {splitVConfig} from './kernels/SplitV';\nimport {sqrtConfig} from './kernels/Sqrt';\nimport {squareConfig} from './kernels/Square';\nimport {squaredDifferenceConfig} from './kernels/SquaredDifference';\nimport {stepConfig} from './kernels/Step';\nimport {stridedSliceConfig} from './kernels/StridedSlice';\nimport {stringNGramsConfig} from './kernels/StringNGrams';\nimport {stringSplitConfig} from './kernels/StringSplit';\nimport {stringToHashBucketFastConfig} from './kernels/StringToHashBucketFast';\nimport {subConfig} from './kernels/Sub';\nimport {sumConfig} from './kernels/Sum';\nimport {tanConfig} from './kernels/Tan';\nimport {tanhConfig} from './kernels/Tanh';\nimport {tileConfig} from './kernels/Tile';\nimport {topKConfig} from './kernels/TopK';\nimport {transformConfig} from './kernels/Transform';\nimport {transposeConfig} from './kernels/Transpose';\nimport {uniqueConfig} from './kernels/Unique';\nimport {unpackConfig} from './kernels/Unpack';\nimport {unsortedSegmentSumConfig} from './kernels/UnsortedSegmentSum';\nimport {zerosLikeConfig} from './kernels/ZerosLike';\n\n// List all kernel configs here\nconst kernelConfigs: KernelConfig[] = [\n _fusedMatMulConfig,\n absConfig,\n acosConfig,\n acoshConfig,\n addConfig,\n addNConfig,\n allConfig,\n anyConfig,\n argMaxConfig,\n argMinConfig,\n asinConfig,\n asinhConfig,\n atanConfig,\n atan2Config,\n atanhConfig,\n avgPoolConfig,\n avgPool3DConfig,\n avgPool3DGradConfig,\n avgPoolGradConfig,\n batchMatMulConfig,\n batchNormConfig,\n batchToSpaceNDConfig,\n bincountConfig,\n castConfig,\n ceilConfig,\n clipConfig,\n complexConfig,\n complexAbsConfig,\n concatConfig,\n conv2DBackpropFilterConfig,\n conv2DBackpropInputConfig,\n conv2DConfig,\n conv3DBackpropFilterV2Config,\n conv3DBackpropInputV2Config,\n conv3DConfig,\n cosConfig,\n coshConfig,\n cropAndResizeConfig,\n cumsumConfig,\n denseBincountConfig,\n depthToSpaceConfig,\n depthwiseConv2dNativeConfig,\n depthwiseConv2dNativeBackpropFilterConfig,\n depthwiseConv2dNativeBackpropInputConfig,\n diagConfig,\n dilation2dConfig,\n dilation2dBackpropInputConfig,\n dilation2dBackpropFilterConfig,\n realDivConfig,\n einsumConfig,\n eluConfig,\n eluGradConfig,\n equalConfig,\n erfConfig,\n expConfig,\n expandDimsConfig,\n expm1Config,\n fftConfig,\n fillConfig,\n flipLeftRightConfig,\n floorConfig,\n floorDivConfig,\n fusedConv2DConfig,\n fusedDepthwiseConv2DConfig,\n gatherNdConfig,\n gatherV2Config,\n greaterConfig,\n greaterEqualConfig,\n identityConfig,\n ifftConfig,\n imagConfig,\n isFiniteConfig,\n isInfConfig,\n isNaNConfig,\n leakyReluConfig,\n lessConfig,\n lessEqualConfig,\n linSpaceConfig,\n logConfig,\n log1pConfig,\n logicalAndConfig,\n logicalNotConfig,\n logicalOrConfig,\n lRNConfig,\n lRNGradConfig,\n maximumConfig,\n maxPoolConfig,\n maxPool3DConfig,\n maxPool3DGradConfig,\n maxPoolGradConfig,\n maxPoolWithArgmaxConfig,\n maxConfig,\n meanConfig,\n minConfig,\n minimumConfig,\n mirrorPadConfig,\n modConfig,\n multinomialConfig,\n multiplyConfig,\n negConfig,\n nonMaxSuppressionV3Config,\n nonMaxSuppressionV4Config,\n nonMaxSuppressionV5Config,\n notEqualConfig,\n oneHotConfig,\n onesLikeConfig,\n packConfig,\n padV2Config,\n powConfig,\n preluConfig,\n prodConfig,\n rangeConfig,\n realConfig,\n reciprocalConfig,\n reluConfig,\n relu6Config,\n reshapeConfig,\n resizeBilinearConfig,\n resizeBilinearGradConfig,\n resizeNearestNeighborConfig,\n resizeNearestNeighborGradConfig,\n reverseConfig,\n rotateWithOffsetConfig,\n roundConfig,\n rsqrtConfig,\n scatterNdConfig,\n selectConfig,\n seluConfig,\n sigmoidConfig,\n signConfig,\n sinConfig,\n sinhConfig,\n sliceConfig,\n softmaxConfig,\n softplusConfig,\n spaceToBatchNDConfig,\n sparseFillEmptyRowsConfig,\n sparseReshapeConfig,\n sparseSegmentMeanConfig,\n sparseSegmentSumConfig,\n sparseToDenseConfig,\n splitVConfig,\n sqrtConfig,\n squareConfig,\n squaredDifferenceConfig,\n stepConfig,\n stridedSliceConfig,\n stringNGramsConfig,\n stringSplitConfig,\n stringToHashBucketFastConfig,\n subConfig,\n sumConfig,\n tanConfig,\n tanhConfig,\n tileConfig,\n topKConfig,\n transposeConfig,\n transformConfig,\n uniqueConfig,\n unpackConfig,\n unsortedSegmentSumConfig,\n zerosLikeConfig\n];\n\nfor (const kernelConfig of kernelConfigs) {\n registerKernel(kernelConfig);\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// All exports from this package should be in base.\nexport * from './base';\nimport './register_all_kernels';\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, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {getWebGLContext} from './canvas_util';\nimport {getTextureConfig} from './tex_util';\n\nexport function callAndCheck<T>(gl: WebGLRenderingContext, func: () => T): T {\n const returnValue = func();\n if (env().getBool('DEBUG')) {\n checkWebGLError(gl);\n }\n return returnValue;\n}\n\nfunction checkWebGLError(gl: WebGLRenderingContext) {\n const error = gl.getError();\n if (error !== gl.NO_ERROR) {\n throw new Error('WebGL Error: ' + getWebGLErrorMessage(gl, error));\n }\n}\n\n// https://en.wikipedia.org/wiki/Half-precision_floating-point_format\nconst MIN_FLOAT16 = 5.96e-8;\nconst MAX_FLOAT16 = 65504;\n\nexport function canBeRepresented(num: number): boolean {\n if (env().getBool('WEBGL_RENDER_FLOAT32_ENABLED') || num === 0 ||\n (MIN_FLOAT16 < Math.abs(num) && Math.abs(num) < MAX_FLOAT16)) {\n return true;\n }\n return false;\n}\n\nexport function getWebGLErrorMessage(\n gl: WebGLRenderingContext, status: number): string {\n switch (status) {\n case gl.NO_ERROR:\n return 'NO_ERROR';\n case gl.INVALID_ENUM:\n return 'INVALID_ENUM';\n case gl.INVALID_VALUE:\n return 'INVALID_VALUE';\n case gl.INVALID_OPERATION:\n return 'INVALID_OPERATION';\n case gl.INVALID_FRAMEBUFFER_OPERATION:\n return 'INVALID_FRAMEBUFFER_OPERATION';\n case gl.OUT_OF_MEMORY:\n return 'OUT_OF_MEMORY';\n case gl.CONTEXT_LOST_WEBGL:\n return 'CONTEXT_LOST_WEBGL';\n default:\n return `Unknown error code ${status}`;\n }\n}\n\nexport function getExtensionOrThrow(\n gl: WebGLRenderingContext, extensionName: string): {} {\n return throwIfNull<{}>(\n gl, () => gl.getExtension(extensionName),\n 'Extension \"' + extensionName + '\" not supported on this browser.');\n}\n\nexport function createVertexShader(\n gl: WebGLRenderingContext, vertexShaderSource: string): WebGLShader {\n const vertexShader: WebGLShader = throwIfNull<WebGLShader>(\n gl, () => gl.createShader(gl.VERTEX_SHADER),\n 'Unable to create vertex WebGLShader.');\n callAndCheck(gl, () => gl.shaderSource(vertexShader, vertexShaderSource));\n callAndCheck(gl, () => gl.compileShader(vertexShader));\n if (gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS) === false) {\n console.log(gl.getShaderInfoLog(vertexShader));\n throw new Error('Failed to compile vertex shader.');\n }\n return vertexShader;\n}\n\nexport function createFragmentShader(\n gl: WebGLRenderingContext, fragmentShaderSource: string): WebGLShader {\n const fragmentShader: WebGLShader = throwIfNull<WebGLShader>(\n gl, () => gl.createShader(gl.FRAGMENT_SHADER),\n 'Unable to create fragment WebGLShader.');\n callAndCheck(gl, () => gl.shaderSource(fragmentShader, fragmentShaderSource));\n callAndCheck(gl, () => gl.compileShader(fragmentShader));\n if (gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS) === false) {\n logShaderSourceAndInfoLog(\n fragmentShaderSource, gl.getShaderInfoLog(fragmentShader));\n throw new Error('Failed to compile fragment shader.');\n }\n return fragmentShader;\n}\n\nconst lineNumberRegex = /ERROR: [0-9]+:([0-9]+):/g;\nfunction logShaderSourceAndInfoLog(\n shaderSource: string, shaderInfoLog: string) {\n const lineNumberRegexResult = lineNumberRegex.exec(shaderInfoLog);\n if (lineNumberRegexResult == null) {\n console.log(`Couldn't parse line number in error: ${shaderInfoLog}`);\n console.log(shaderSource);\n return;\n }\n\n const lineNumber = +lineNumberRegexResult[1];\n\n const shaderLines = shaderSource.split('\\n');\n const pad = shaderLines.length.toString().length + 2;\n const linesWithLineNumbers = shaderLines.map(\n (line, lineNumber) =>\n util.rightPad((lineNumber + 1).toString(), pad) + line);\n let maxLineLength = 0;\n for (let i = 0; i < linesWithLineNumbers.length; i++) {\n maxLineLength = Math.max(linesWithLineNumbers[i].length, maxLineLength);\n }\n\n const beforeErrorLines = linesWithLineNumbers.slice(0, lineNumber - 1);\n const errorLine = linesWithLineNumbers.slice(lineNumber - 1, lineNumber);\n const afterErrorLines = linesWithLineNumbers.slice(lineNumber);\n\n console.log(beforeErrorLines.join('\\n'));\n console.log(shaderInfoLog.split('\\n')[0]);\n console.log(\n `%c ${util.rightPad(errorLine[0], maxLineLength)}`,\n 'border:1px solid red; background-color:#e3d2d2; color:#a61717');\n console.log(afterErrorLines.join('\\n'));\n}\n\nexport function createProgram(gl: WebGLRenderingContext): WebGLProgram {\n return throwIfNull<WebGLProgram>(\n gl, () => gl.createProgram(), 'Unable to create WebGLProgram.');\n}\n\nexport function linkProgram(gl: WebGLRenderingContext, program: WebGLProgram) {\n callAndCheck(gl, () => gl.linkProgram(program));\n if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {\n console.log(gl.getProgramInfoLog(program));\n throw new Error('Failed to link vertex and fragment shaders.');\n }\n}\n\nexport function validateProgram(\n gl: WebGLRenderingContext, program: WebGLProgram) {\n callAndCheck(gl, () => gl.validateProgram(program));\n if (gl.getProgramParameter(program, gl.VALIDATE_STATUS) === false) {\n console.log(gl.getProgramInfoLog(program));\n throw new Error('Shader program validation failed.');\n }\n}\n\nexport function createStaticVertexBuffer(\n gl: WebGLRenderingContext, data: Float32Array): WebGLBuffer {\n const buffer: WebGLBuffer = throwIfNull<WebGLBuffer>(\n gl, () => gl.createBuffer(), 'Unable to create WebGLBuffer');\n callAndCheck(gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, buffer));\n callAndCheck(gl, () => gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW));\n return buffer;\n}\n\nexport function createStaticIndexBuffer(\n gl: WebGLRenderingContext, data: Uint16Array): WebGLBuffer {\n const buffer: WebGLBuffer = throwIfNull<WebGLBuffer>(\n gl, () => gl.createBuffer(), 'Unable to create WebGLBuffer');\n callAndCheck(gl, () => gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer));\n callAndCheck(\n gl, () => gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW));\n return buffer;\n}\n\nexport function getNumChannels(): number {\n if (env().getNumber('WEBGL_VERSION') === 2) {\n return 1;\n }\n return 4;\n}\n\nexport function createTexture(gl: WebGLRenderingContext): WebGLTexture {\n return throwIfNull<WebGLTexture>(\n gl, () => gl.createTexture(), 'Unable to create WebGLTexture.');\n}\n\nexport function validateTextureSize(width: number, height: number) {\n const maxTextureSize = env().getNumber('WEBGL_MAX_TEXTURE_SIZE');\n if ((width <= 0) || (height <= 0)) {\n const requested = `[${width}x${height}]`;\n throw new Error('Requested texture size ' + requested + ' is invalid.');\n }\n if ((width > maxTextureSize) || (height > maxTextureSize)) {\n const requested = `[${width}x${height}]`;\n const max = `[${maxTextureSize}x${maxTextureSize}]`;\n throw new Error(\n 'Requested texture size ' + requested +\n ' greater than WebGL maximum on this browser / GPU ' + max + '.');\n }\n}\n\nexport function createFramebuffer(gl: WebGLRenderingContext): WebGLFramebuffer {\n return throwIfNull<WebGLFramebuffer>(\n gl, () => gl.createFramebuffer(), 'Unable to create WebGLFramebuffer.');\n}\n\nexport function bindVertexBufferToProgramAttribute(\n gl: WebGLRenderingContext, program: WebGLProgram, attribute: string,\n buffer: WebGLBuffer, arrayEntriesPerItem: number, itemStrideInBytes: number,\n itemOffsetInBytes: number): boolean {\n const loc = gl.getAttribLocation(program, attribute);\n if (loc === -1) {\n // The GPU compiler decided to strip out this attribute because it's unused,\n // thus no need to bind.\n return false;\n }\n callAndCheck(gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, buffer));\n callAndCheck(\n gl,\n () => gl.vertexAttribPointer(\n loc, arrayEntriesPerItem, gl.FLOAT, false, itemStrideInBytes,\n itemOffsetInBytes));\n callAndCheck(gl, () => gl.enableVertexAttribArray(loc));\n return true;\n}\n\nexport function bindTextureUnit(\n gl: WebGLRenderingContext, texture: WebGLTexture, textureUnit: number) {\n validateTextureUnit(gl, textureUnit);\n callAndCheck(gl, () => gl.activeTexture(gl.TEXTURE0 + textureUnit));\n callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, texture));\n}\n\nexport function unbindTextureUnit(\n gl: WebGLRenderingContext, textureUnit: number) {\n validateTextureUnit(gl, textureUnit);\n callAndCheck(gl, () => gl.activeTexture(gl.TEXTURE0 + textureUnit));\n callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n}\n\nexport function getProgramUniformLocationOrThrow(\n gl: WebGLRenderingContext, program: WebGLProgram,\n uniformName: string): WebGLUniformLocation {\n return throwIfNull<WebGLUniformLocation>(\n gl, () => gl.getUniformLocation(program, uniformName),\n 'uniform \"' + uniformName + '\" not present in program.');\n}\n\nexport function getProgramUniformLocation(\n gl: WebGLRenderingContext, program: WebGLProgram,\n uniformName: string): WebGLUniformLocation {\n return gl.getUniformLocation(program, uniformName);\n}\n\nexport function bindTextureToProgramUniformSampler(\n gl: WebGLRenderingContext, texture: WebGLTexture,\n uniformSamplerLocation: WebGLUniformLocation, textureUnit: number) {\n callAndCheck(gl, () => bindTextureUnit(gl, texture, textureUnit));\n callAndCheck(gl, () => gl.uniform1i(uniformSamplerLocation, textureUnit));\n}\n\nexport function bindCanvasToFramebuffer(gl: WebGLRenderingContext) {\n callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, null));\n callAndCheck(gl, () => gl.viewport(0, 0, gl.canvas.width, gl.canvas.height));\n callAndCheck(gl, () => gl.scissor(0, 0, gl.canvas.width, gl.canvas.height));\n}\n\nexport function bindColorTextureToFramebuffer(\n gl: WebGLRenderingContext, texture: WebGLTexture,\n framebuffer: WebGLFramebuffer) {\n callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer));\n callAndCheck(\n gl,\n () => gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0));\n}\n\nexport function unbindColorTextureFromFramebuffer(\n gl: WebGLRenderingContext, framebuffer: WebGLFramebuffer) {\n callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer));\n callAndCheck(\n gl,\n () => gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0));\n}\n\nexport function validateFramebuffer(gl: WebGLRenderingContext) {\n const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);\n if (status !== gl.FRAMEBUFFER_COMPLETE) {\n throw new Error(\n 'Error binding framebuffer: ' + getFramebufferErrorMessage(gl, status));\n }\n}\n\nexport function getFramebufferErrorMessage(\n gl: WebGLRenderingContext, status: number): string {\n switch (status) {\n case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n return 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT';\n case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n return 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT';\n case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:\n return 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS';\n case gl.FRAMEBUFFER_UNSUPPORTED:\n return 'FRAMEBUFFER_UNSUPPORTED';\n default:\n return `unknown error ${status}`;\n }\n}\n\nfunction throwIfNull<T>(\n gl: WebGLRenderingContext, returnTOrNull: () => T | null,\n failureMessage: string): T {\n const tOrNull: T|null = callAndCheck(gl, () => returnTOrNull());\n if (tOrNull == null) {\n throw new Error(failureMessage);\n }\n return tOrNull;\n}\n\nfunction validateTextureUnit(gl: WebGLRenderingContext, textureUnit: number) {\n const maxTextureUnit = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1;\n const glTextureUnit = textureUnit + gl.TEXTURE0;\n if (glTextureUnit < gl.TEXTURE0 || glTextureUnit > maxTextureUnit) {\n const textureUnitRange = `[gl.TEXTURE0, gl.TEXTURE${maxTextureUnit}]`;\n throw new Error(`textureUnit must be in ${textureUnitRange}.`);\n }\n}\n\nexport function getBatchDim(shape: number[], dimsToSkip = 2): number {\n return util.sizeFromShape(shape.slice(0, shape.length - dimsToSkip));\n}\n\nexport function getRowsCols(shape: number[]): [number, number] {\n if (shape.length === 0) {\n throw Error('Cannot get rows and columns of an empty shape array.');\n }\n\n return [\n shape.length > 1 ? shape[shape.length - 2] : 1, shape[shape.length - 1]\n ];\n}\n\nexport function getShapeAs3D(shape: number[]): [number, number, number] {\n let shapeAs3D: [number, number, number] = [1, 1, 1];\n const isScalar = shape.length === 0 || (shape.length === 1 && shape[0] === 1);\n if (!isScalar) {\n shapeAs3D =\n [getBatchDim(shape), ...getRowsCols(shape)] as [number, number, number];\n }\n return shapeAs3D;\n}\n\nexport function getTextureShapeFromLogicalShape(\n logShape: number[], isPacked = false): [number, number] {\n let maxTexSize = env().getNumber('WEBGL_MAX_TEXTURE_SIZE');\n if (isPacked) {\n maxTexSize = maxTexSize * 2;\n\n // This logic ensures we accurately count the number of packed texels needed\n // to accommodate the tensor. We can only pack values in the same texel if\n // they are from adjacent pairs of rows/cols within the same batch. So if a\n // tensor has 3 rows, we pretend it has 4 rows in order to account for the\n // fact that the texels containing the third row are half empty.\n logShape = logShape.map(\n (d, i) => i >= logShape.length - 2 ?\n util.nearestLargerEven(logShape[i]) :\n logShape[i]);\n\n // Packed texture height is at least 2 (the channel height of a single\n // texel).\n if (logShape.length === 1) {\n logShape = [2, logShape[0]];\n }\n }\n\n // If logical shape is 2, we don't squeeze, since we want to match physical.\n if (logShape.length !== 2) {\n const squeezeResult = util.squeezeShape(logShape);\n logShape = squeezeResult.newShape;\n }\n\n let size = util.sizeFromShape(logShape);\n if (logShape.length <= 1 && size <= maxTexSize) {\n return [1, size];\n } else if (\n logShape.length === 2 && logShape[0] <= maxTexSize &&\n logShape[1] <= maxTexSize) {\n return logShape as [number, number];\n } else if (\n logShape.length === 3 && logShape[0] * logShape[1] <= maxTexSize &&\n logShape[2] <= maxTexSize) {\n return [logShape[0] * logShape[1], logShape[2]];\n } else if (\n logShape.length === 3 && logShape[0] <= maxTexSize &&\n logShape[1] * logShape[2] <= maxTexSize) {\n return [logShape[0], logShape[1] * logShape[2]];\n } else if (\n logShape.length === 4 &&\n logShape[0] * logShape[1] * logShape[2] <= maxTexSize &&\n logShape[3] <= maxTexSize) {\n return [logShape[0] * logShape[1] * logShape[2], logShape[3]];\n } else if (\n logShape.length === 4 && logShape[0] <= maxTexSize &&\n logShape[1] * logShape[2] * logShape[3] <= maxTexSize) {\n return [logShape[0], logShape[1] * logShape[2] * logShape[3]];\n } else {\n if (isPacked) {\n // For packed textures size equals the number of channels required to\n // accommodate the texture data. However in order to squarify such that\n // inner dimensions stay even, we rewrite size to equal the number of\n // texels. Then in the return statement we rehydrate the squarified\n // dimensions to channel units.\n\n const batchDim = getBatchDim(logShape);\n let rows = 2, cols = 2;\n if (logShape.length) {\n [rows, cols] = getRowsCols(logShape);\n }\n size = batchDim * (rows / 2) * (cols / 2);\n return util.sizeToSquarishShape(size).map(d => d * 2) as [number, number];\n }\n return util.sizeToSquarishShape(size);\n }\n}\n\nfunction isEven(n: number): boolean {\n return n % 2 === 0;\n}\n\n/**\n * This determines whether reshaping a packed texture requires rearranging\n * the data within the texture, assuming 2x2 packing.\n */\nexport function isReshapeFree(shape1: number[], shape2: number[]): boolean {\n shape1 = shape1.slice(-2);\n shape2 = shape2.slice(-2);\n\n if (util.arraysEqual(shape1, shape2)) {\n return true;\n }\n\n if (!shape1.length || !shape2.length) { // One of the shapes is a scalar.\n return true;\n }\n\n if (shape1[0] === 0 || shape1[1] === 0 || shape2[0] === 0 ||\n shape2[1] === 0) {\n return true;\n }\n\n if (shape1.length !== shape2.length) { // One of the shapes is a vector.\n const shape1Cols = shape1.slice(-1)[0];\n const shape2Cols = shape2.slice(-1)[0];\n if (shape1Cols === shape2Cols) {\n return true;\n }\n\n if (isEven(shape1Cols) && isEven(shape2Cols) &&\n (shape1[0] === 1 || shape2[0] === 1)) {\n return true;\n }\n }\n return shape1[1] === shape2[1] && isEven(shape1[0]) && isEven(shape2[0]);\n}\n\n// We cache webgl params because the environment gets reset between\n// unit tests and we don't want to constantly query the WebGLContext for\n// MAX_TEXTURE_SIZE.\nlet MAX_TEXTURE_SIZE: number;\nlet MAX_TEXTURES_IN_SHADER: number;\n\nexport function getWebGLMaxTextureSize(webGLVersion: number): number {\n if (MAX_TEXTURE_SIZE == null) {\n const gl = getWebGLContext(webGLVersion);\n MAX_TEXTURE_SIZE = gl.getParameter(gl.MAX_TEXTURE_SIZE);\n }\n return MAX_TEXTURE_SIZE;\n}\n\nexport function resetMaxTextureSize() {\n MAX_TEXTURE_SIZE = null;\n}\nexport function resetMaxTexturesInShader() {\n MAX_TEXTURES_IN_SHADER = null;\n}\n\nexport function getMaxTexturesInShader(webGLVersion: number): number {\n if (MAX_TEXTURES_IN_SHADER == null) {\n const gl = getWebGLContext(webGLVersion);\n MAX_TEXTURES_IN_SHADER = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);\n }\n // We cap at 16 to avoid spurious runtime \"memory exhausted\" error.\n return Math.min(16, MAX_TEXTURES_IN_SHADER);\n}\n\nexport function getWebGLDisjointQueryTimerVersion(webGLVersion: number):\n number {\n if (webGLVersion === 0) {\n return 0;\n }\n\n let queryTimerVersion: number;\n const gl = getWebGLContext(webGLVersion);\n\n if (hasExtension(gl, 'EXT_disjoint_timer_query_webgl2') &&\n webGLVersion === 2) {\n queryTimerVersion = 2;\n } else if (hasExtension(gl, 'EXT_disjoint_timer_query')) {\n queryTimerVersion = 1;\n } else {\n queryTimerVersion = 0;\n }\n return queryTimerVersion;\n}\n\nexport function hasExtension(gl: WebGLRenderingContext, extensionName: string) {\n const ext = gl.getExtension(extensionName);\n return ext != null;\n}\n\nexport function isWebGLVersionEnabled(webGLVersion: 1|2) {\n try {\n const gl = getWebGLContext(webGLVersion);\n if (gl != null) {\n return true;\n }\n } catch (e) {\n console.log('Error when getting WebGL context: ', e);\n return false;\n }\n return false;\n}\n\nexport function isCapableOfRenderingToFloatTexture(webGLVersion: number):\n boolean {\n if (webGLVersion === 0) {\n return false;\n }\n\n const gl = getWebGLContext(webGLVersion);\n\n if (webGLVersion === 1) {\n if (!hasExtension(gl, 'OES_texture_float')) {\n return false;\n }\n } else {\n if (!hasExtension(gl, 'EXT_color_buffer_float')) {\n return false;\n }\n }\n\n const isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);\n return isFrameBufferComplete;\n}\n\n/**\n * Check if we can download values from a float/half-float texture.\n *\n * Note that for performance reasons we use binding a texture to a framebuffer\n * as a proxy for ability to download float values later using readPixels. The\n * texture params of this texture will not match those in readPixels exactly\n * but if we are unable to bind some kind of float texture to the frameBuffer\n * then we definitely will not be able to read float values from it.\n */\nexport function isDownloadFloatTextureEnabled(webGLVersion: number): boolean {\n if (webGLVersion === 0) {\n return false;\n }\n\n const gl = getWebGLContext(webGLVersion);\n\n if (webGLVersion === 1) {\n if (!hasExtension(gl, 'OES_texture_float')) {\n return false;\n }\n if (!hasExtension(gl, 'WEBGL_color_buffer_float')) {\n return false;\n }\n } else {\n if (hasExtension(gl, 'EXT_color_buffer_float')) {\n return createFloatTextureAndBindToFramebuffer(gl);\n }\n\n const COLOR_BUFFER_HALF_FLOAT = 'EXT_color_buffer_half_float';\n if (hasExtension(gl, COLOR_BUFFER_HALF_FLOAT)) {\n const textureHalfFloatExtension =\n gl.getExtension(COLOR_BUFFER_HALF_FLOAT);\n return createHalfFloatTextureAndBindToFramebuffer(\n gl, textureHalfFloatExtension);\n }\n\n return false;\n }\n\n const isFrameBufferComplete = createFloatTextureAndBindToFramebuffer(gl);\n return isFrameBufferComplete;\n}\n\nfunction createFloatTextureAndBindToFramebuffer(gl: WebGLRenderingContext):\n boolean {\n const texConfig = getTextureConfig(gl);\n\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n const width = 1;\n const height = 1;\n gl.texImage2D(\n gl.TEXTURE_2D, 0, texConfig.internalFormatFloat, width, height, 0,\n texConfig.textureFormatFloat, texConfig.textureTypeFloat, null);\n\n const frameBuffer = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n const isFrameBufferComplete =\n gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.deleteTexture(texture);\n gl.deleteFramebuffer(frameBuffer);\n\n return isFrameBufferComplete;\n}\n\nfunction createHalfFloatTextureAndBindToFramebuffer(\n // tslint:disable-next-line:no-any\n gl: WebGLRenderingContext, textureHalfFloatExtension: any): boolean {\n const texConfig = getTextureConfig(gl, textureHalfFloatExtension);\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n const width = 1;\n const height = 1;\n gl.texImage2D(\n gl.TEXTURE_2D, 0, texConfig.internalFormatHalfFloat, width, height, 0,\n texConfig.textureFormatFloat, texConfig.textureTypeHalfFloat, null);\n\n const frameBuffer = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n const isFrameBufferComplete =\n gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.deleteTexture(texture);\n gl.deleteFramebuffer(frameBuffer);\n\n return isFrameBufferComplete;\n}\n\nexport function isWebGLFenceEnabled(webGLVersion: number) {\n if (webGLVersion !== 2) {\n return false;\n }\n const gl = getWebGLContext(webGLVersion);\n\n // tslint:disable-next-line:no-any\n const isEnabled = (gl as any).fenceSync != null;\n return isEnabled;\n}\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 () => `${opName} does not support complex64 tensors ` +\n 'in the WebGL backend.');\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\nconst contexts: {[key: string]: WebGLRenderingContext} = {};\n\nconst WEBGL_ATTRIBUTES: WebGLContextAttributes = {\n alpha: false,\n antialias: false,\n premultipliedAlpha: false,\n preserveDrawingBuffer: false,\n depth: false,\n stencil: false,\n failIfMajorPerformanceCaveat: true\n};\n\nexport function clearWebGLContext(webGLVersion: number) {\n delete contexts[webGLVersion];\n}\n\nexport function setWebGLContext(\n webGLVersion: number, gl: WebGLRenderingContext) {\n contexts[webGLVersion] = gl;\n}\n\nexport function getWebGLContext(webGLVersion: number): WebGLRenderingContext {\n if (!(webGLVersion in contexts)) {\n const newCtx = getWebGLRenderingContext(webGLVersion);\n if (newCtx !== null) {\n contexts[webGLVersion] = newCtx;\n } else {\n console.log('Could not get context for WebGL version', webGLVersion);\n return null;\n }\n }\n const gl = contexts[webGLVersion];\n if (gl.isContextLost()) {\n delete contexts[webGLVersion];\n return getWebGLContext(webGLVersion);\n }\n\n gl.disable(gl.DEPTH_TEST);\n gl.disable(gl.STENCIL_TEST);\n gl.disable(gl.BLEND);\n gl.disable(gl.DITHER);\n gl.disable(gl.POLYGON_OFFSET_FILL);\n gl.disable(gl.SAMPLE_COVERAGE);\n gl.enable(gl.SCISSOR_TEST);\n gl.enable(gl.CULL_FACE);\n gl.cullFace(gl.BACK);\n\n return contexts[webGLVersion];\n}\n\nfunction createCanvas(webGLVersion: number) {\n if (typeof OffscreenCanvas !== 'undefined' && webGLVersion === 2) {\n return new OffscreenCanvas(300, 150);\n } else if (typeof document !== 'undefined') {\n return document.createElement('canvas');\n } else {\n throw new Error('Cannot create a canvas in this context');\n }\n}\n\nfunction getWebGLRenderingContext(webGLVersion: number): WebGLRenderingContext {\n if (webGLVersion !== 1 && webGLVersion !== 2) {\n throw new Error('Cannot get WebGL rendering context, WebGL is disabled.');\n }\n const canvas = createCanvas(webGLVersion);\n\n canvas.addEventListener('webglcontextlost', (ev: Event) => {\n ev.preventDefault();\n delete contexts[webGLVersion];\n }, false);\n if (webGLVersion === 1) {\n return (canvas.getContext('webgl', WEBGL_ATTRIBUTES) ||\n canvas.getContext('experimental-webgl', WEBGL_ATTRIBUTES)) as\n WebGLRenderingContext;\n }\n return canvas.getContext('webgl2', WEBGL_ATTRIBUTES) as WebGLRenderingContext;\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 {backend_util, DataId, DataType, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nexport enum PackingScheme {\n /**\n * All values in a single texel are densely packed without any constraints.\n *\n * This is how the shader encodes a tensor with shape = [2, 3, 4]\n * (indices are [batch, row, col]).\n *\n * 000|001 010|011 020|021\n * ------- ------- -------\n * 002|003 012|013 022|023\n *\n * 100|101 110|111 120|121\n * ------- ------- -------\n * 102|103 112|113 122|123\n *\n */\n DENSE,\n\n /**\n * Single texels contain only values from the same batch, and from adjacent\n * rows and columns.\n *\n * This is how the shader encodes a tensor with shape = [2, 3, 5]\n * (indices are [batch, row, col]).\n *\n * 000|001 002|003 004|xxx 020|021 022|023 024|xxx\n * ------- ------- ------- ------- ------- -------\n * 010|011 012|013 014|xxx xxx|xxx xxx|xxx xxx|xxx\n *\n * 100|101 102|103 104|xxx 120|121 122|123 124|xxx\n * ------- ------- ------- ------- ------- -------\n * 110|111 112|113 114|xxx xxx|xxx xxx|xxx xxx|xxx\n *\n */\n SHARED_BATCH\n}\n\nexport enum TextureUsage {\n RENDER,\n UPLOAD,\n PIXELS,\n DOWNLOAD\n}\n\nexport enum PhysicalTextureType {\n UNPACKED_FLOAT16,\n UNPACKED_FLOAT32,\n PACKED_4X1_UNSIGNED_BYTE,\n PACKED_2X2_FLOAT32,\n PACKED_2X2_FLOAT16\n}\n\nexport interface TextureData {\n // Required.\n shape: number[];\n dtype: DataType;\n\n // Optional.\n values?: backend_util.BackendValues;\n texture?: WebGLTexture;\n // For complex numbers, the real and imaginary parts are stored as their own\n // individual tensorInfos, with a parent joining the two with the\n // complexTensors field. When this is defined, texture will be null.\n complexTensorInfos?: {real: TensorInfo, imag: TensorInfo};\n /** [rows, columns] shape of the texture. */\n texShape?: [number, number];\n usage?: TextureUsage;\n isPacked?: boolean;\n\n refCount: number;\n\n // Available when the tensor has been sliced.\n slice?: {\n // Offset in the 'flat index' space.\n flatOffset: number;\n // Used for counting how many sliced tensors point to the same texture.\n origDataId: DataId;\n };\n}\n\nexport function getUnpackedMatrixTextureShapeWidthHeight(\n rows: number, columns: number): [number, number] {\n return [columns, rows];\n}\n\nexport function getUnpackedArraySizeFromMatrixSize(\n matrixSize: number, channelsPerTexture: number): number {\n return matrixSize * channelsPerTexture;\n}\n\nexport function getColorMatrixTextureShapeWidthHeight(\n rows: number, columns: number): [number, number] {\n return [columns * 4, rows];\n}\n\n/**\n * Get shape for densely packed RGBA texture.\n */\nexport function getDenseTexShape(shape: number[]): [number, number] {\n const size = util.sizeFromShape(shape);\n const texelsNeeded = Math.ceil(size / 4);\n return util.sizeToSquarishShape(texelsNeeded);\n}\n\nexport function getMatrixSizeFromUnpackedArraySize(\n unpackedSize: number, channelsPerTexture: number): number {\n if (unpackedSize % channelsPerTexture !== 0) {\n throw new Error(\n `unpackedSize (${unpackedSize}) must be a multiple of ` +\n `${channelsPerTexture}`);\n }\n return unpackedSize / channelsPerTexture;\n}\n\nexport function decodeMatrixFromUnpackedColorRGBAArray(\n unpackedArray: Float32Array, matrix: Float32Array, channels: number) {\n const requiredSize = unpackedArray.length * channels / 4;\n if (matrix.length < requiredSize) {\n throw new Error(\n `matrix length (${matrix.length}) must be >= ${requiredSize}`);\n }\n let dst = 0;\n for (let src = 0; src < unpackedArray.length; src += 4) {\n for (let c = 0; c < channels; c++) {\n matrix[dst++] = unpackedArray[src + c];\n }\n }\n}\n\nexport function getPackedMatrixTextureShapeWidthHeight(\n rows: number, columns: number): [number, number] {\n return [\n Math.max(1, Math.ceil(columns / 2)), Math.max(1, Math.ceil(rows / 2))\n ];\n}\n\nexport function getPackedRGBAArraySizeFromMatrixShape(\n rows: number, columns: number): number {\n const [w, h] = getPackedMatrixTextureShapeWidthHeight(rows, columns);\n return w * h * 4;\n}\n\nexport interface TextureConfig {\n internalFormatFloat: number;\n textureFormatFloat: number;\n internalFormatPackedHalfFloat: number;\n internalFormatHalfFloat: number;\n internalFormatPackedFloat: number;\n\n // The format to use during a gl.readPixels call.\n downloadTextureFormat: number;\n // How many channels need to be unpacked after a gl.readPixels call.\n downloadUnpackNumChannels: number;\n\n defaultNumChannels: number;\n textureTypeHalfFloat: number;\n textureTypeFloat: number;\n}\n\nexport function getTextureConfig(\n // tslint:disable-next-line:no-any\n gl: WebGLRenderingContext, textureHalfFloatExtension?: any): TextureConfig {\n // tslint:disable-next-line:no-any\n const glany = gl as any;\n\n let internalFormatFloat: number;\n let internalFormatHalfFloat: number;\n let internalFormatPackedHalfFloat: number;\n let internalFormatPackedFloat: number;\n let textureFormatFloat: number;\n\n let downloadTextureFormat: number;\n let downloadUnpackNumChannels: number;\n\n let defaultNumChannels: number;\n let textureTypeHalfFloat: number;\n let textureTypeFloat: number;\n\n if (env().getNumber('WEBGL_VERSION') === 2) {\n internalFormatFloat = glany.R32F;\n internalFormatHalfFloat = glany.R16F;\n internalFormatPackedHalfFloat = glany.RGBA16F;\n internalFormatPackedFloat = glany.RGBA32F;\n textureFormatFloat = glany.RED;\n downloadUnpackNumChannels = 4;\n defaultNumChannels = 1;\n textureTypeHalfFloat = glany.HALF_FLOAT;\n textureTypeFloat = glany.FLOAT;\n } else {\n internalFormatFloat = gl.RGBA;\n internalFormatHalfFloat = gl.RGBA;\n internalFormatPackedHalfFloat = gl.RGBA;\n internalFormatPackedFloat = glany.RGBA;\n textureFormatFloat = gl.RGBA;\n downloadUnpackNumChannels = 4;\n defaultNumChannels = 4;\n textureTypeHalfFloat = textureHalfFloatExtension != null ?\n textureHalfFloatExtension.HALF_FLOAT_OES :\n null;\n textureTypeFloat = gl.FLOAT;\n }\n downloadTextureFormat = gl.RGBA;\n\n return {\n internalFormatFloat,\n internalFormatHalfFloat,\n internalFormatPackedHalfFloat,\n internalFormatPackedFloat,\n textureFormatFloat,\n downloadTextureFormat,\n downloadUnpackNumChannels,\n defaultNumChannels,\n textureTypeHalfFloat,\n textureTypeFloat\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 {device_util, env} from '@tensorflow/tfjs-core';\n\nimport {getMaxTexturesInShader, getWebGLDisjointQueryTimerVersion, getWebGLMaxTextureSize, isCapableOfRenderingToFloatTexture, isDownloadFloatTextureEnabled, isWebGLFenceEnabled, isWebGLVersionEnabled} from './webgl_util';\n\nconst ENV = env();\n\n/**\n * This file contains WebGL-specific flag registrations.\n */\n\n/**\n * True if WebGL is supported.\n */\nENV.registerFlag('HAS_WEBGL', () => ENV.getNumber('WEBGL_VERSION') > 0);\n\n/** 0: No WebGL, 1: WebGL 1.0, 2: WebGL 2.0. */\nENV.registerFlag('WEBGL_VERSION', () => {\n if (isWebGLVersionEnabled(2)) {\n return 2;\n } else if (isWebGLVersionEnabled(1)) {\n return 1;\n }\n return 0;\n});\n\n/** Whether to check for numerical representation problems. */\nENV.registerFlag('WEBGL_CHECK_NUMERICAL_PROBLEMS', () => false);\n\nENV.registerFlag(\n 'WEBGL_BUFFER_SUPPORTED', () => ENV.get('WEBGL_VERSION') === 2);\n\n/** Whether the WebGL backend will sometimes forward ops to the CPU. */\nENV.registerFlag('WEBGL_CPU_FORWARD', () => true);\n\n/** Whether the WebGL backend will always use f16 textures for rendering. */\nENV.registerFlag('WEBGL_FORCE_F16_TEXTURES', () => false);\n\n/** Whether to turn all packing related flags on. */\nENV.registerFlag('WEBGL_PACK', () => ENV.getBool('HAS_WEBGL'));\n\n/** Whether we will pack the batchnormalization op. */\nENV.registerFlag('WEBGL_PACK_NORMALIZATION', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack the clip op. */\nENV.registerFlag('WEBGL_PACK_CLIP', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack the depthwise conv op. */\nENV.registerFlag('WEBGL_PACK_DEPTHWISECONV', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack binary ops. */\nENV.registerFlag(\n 'WEBGL_PACK_BINARY_OPERATIONS', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack unary ops. */\nENV.registerFlag(\n 'WEBGL_PACK_UNARY_OPERATIONS', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack array ops. */\nENV.registerFlag(\n 'WEBGL_PACK_ARRAY_OPERATIONS', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack image ops. */\nENV.registerFlag(\n 'WEBGL_PACK_IMAGE_OPERATIONS', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will pack reduce ops. */\nENV.registerFlag('WEBGL_PACK_REDUCE', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether packed WebGL kernels lazily unpack their outputs. */\nENV.registerFlag('WEBGL_LAZILY_UNPACK', () => ENV.getBool('WEBGL_PACK'));\n\n/** Whether we will use the im2col algorithm to speed up convolutions. */\nENV.registerFlag('WEBGL_CONV_IM2COL', () => ENV.getBool('WEBGL_PACK'));\n\n/** The maximum texture dimension. */\nENV.registerFlag(\n 'WEBGL_MAX_TEXTURE_SIZE',\n () => getWebGLMaxTextureSize(ENV.getNumber('WEBGL_VERSION')));\n\n/** The maximum texture dimension. */\nENV.registerFlag(\n 'WEBGL_MAX_TEXTURES_IN_SHADER',\n () => getMaxTexturesInShader(ENV.getNumber('WEBGL_VERSION')));\n\n/**\n * The disjoint_query_timer extension version.\n * 0: disabled, 1: EXT_disjoint_timer_query, 2:\n * EXT_disjoint_timer_query_webgl2.\n * In Firefox with WebGL 2.0,\n * EXT_disjoint_timer_query_webgl2 is not available, so we must use the\n * WebGL 1.0 extension.\n */\nENV.registerFlag('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION', () => {\n const webGLVersion = ENV.getNumber('WEBGL_VERSION');\n\n if (webGLVersion === 0) {\n return 0;\n }\n return getWebGLDisjointQueryTimerVersion(webGLVersion);\n});\n\n/**\n * Whether the timer object from the disjoint_query_timer extension gives\n * timing information that is reliable.\n */\nENV.registerFlag(\n 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE',\n () => ENV.getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0 &&\n !device_util.isMobile());\n\n/**\n * Whether the device is physically capable of rendering to float32 textures.\n */\nENV.registerFlag(\n 'WEBGL_RENDER_FLOAT32_CAPABLE',\n () => isCapableOfRenderingToFloatTexture(ENV.getNumber('WEBGL_VERSION')));\n\n/**\n * Whether rendering to float32 textures is enabled. If disabled, renders to\n * float16 textures.\n */\nENV.registerFlag('WEBGL_RENDER_FLOAT32_ENABLED', () => {\n return ENV.getBool('WEBGL_FORCE_F16_TEXTURES') ?\n false :\n ENV.getBool('WEBGL_RENDER_FLOAT32_CAPABLE');\n});\n\n/**\n * Whether downloading float textures is enabled (16 or 32 bit). If disabled,\n * uses IEEE 754 encoding of the float32 values to 4 uint8 when downloading.\n */\nENV.registerFlag(\n 'WEBGL_DOWNLOAD_FLOAT_ENABLED',\n () => isDownloadFloatTextureEnabled(ENV.getNumber('WEBGL_VERSION')));\n\n/** Whether the fence API is available. */\nENV.registerFlag(\n 'WEBGL_FENCE_API_ENABLED',\n () => isWebGLFenceEnabled(ENV.getNumber('WEBGL_VERSION')));\n\n/**\n * Tensors with size <= than this will be uploaded as uniforms, not textures.\n */\nENV.registerFlag('WEBGL_SIZE_UPLOAD_UNIFORM', () => {\n // Use uniform uploads only when 32bit floats are supported. In\n // 16bit\n // environments there are problems with comparing a 16bit texture value\n // with a 32bit uniform value.\n const useUniforms = ENV.getBool('WEBGL_RENDER_FLOAT32_ENABLED');\n return useUniforms ? 4 : 0;\n});\n\n/**\n * If the total number of bytes allocated on the GPU is greater than this\n * number, we will aggressively delete textures upon disposal with\n * gl.deleteMatrixTexture, rather than making them available for reuse.\n *\n * Default value -1 indicates that we will never aggressively delete textures.\n */\nENV.registerFlag(\n 'WEBGL_DELETE_TEXTURE_THRESHOLD',\n () => {\n return -1;\n },\n threshold => {\n if (threshold < 0 && threshold !== -1) {\n throw new Error(\n `WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never ` +\n `delete) or at least 0, but got ${threshold}.`);\n }\n });\n\n/**\n * Trigger a manual GL command flush if the threshold of time has passed since\n * previous Kernel execution. This can be useful for Andorid device where GL\n * command flush are delayed un til the end of javascript task. This value is\n * measured in millisecond. Typically you want to set this value to close to 1.\n *\n * Default value 1 for mobile chrome, and -1 for rest cases. -1 indicates that\n * we will not enforce manual flush and depend on system default flush schedule.\n */\nENV.registerFlag(\n 'WEBGL_FLUSH_THRESHOLD',\n () => {\n return device_util.isMobile() && ENV.getBool('IS_CHROME') ? 1 : -1;\n },\n threshold => {\n if (threshold < 0 && threshold !== -1) {\n throw new Error(\n `WEBGL_FLUSH_THRESHOLD must be -1 (indicating never ` +\n `manual flush) or at least 0, but got ${threshold}.`);\n }\n });\n\n/**\n * Threshold for input tensor size that determines whether WebGL backend will\n * delegate computation to CPU.\n *\n * Default value is 128.\n */\nENV.registerFlag('CPU_HANDOFF_SIZE_THRESHOLD', () => 128);\n\n/** Whether we will use shapes uniforms. */\nENV.registerFlag('WEBGL_USE_SHAPES_UNIFORMS', () => false);\n\n/**\n * Threshold for last dimension of input tensor that determines whether\n * WebGL backend for the Top K op will delegate computation to CPU. If input\n * is smaller than threshold then CPU will be used\n *\n * Default value is 100000.\n */\nENV.registerFlag('TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD', () => 100000);\n\n/**\n * Threshold for K that determines whether\n * WebGL backend for the Top K op will delegate computation to CPU. If k\n * is larger than threshold then CPU will be used\n *\n * Default value is 128.\n */\nENV.registerFlag('TOPK_K_CPU_HANDOFF_THRESHOLD', () => 128);\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 {env} from '@tensorflow/tfjs-core';\n\nexport type GLSL = {\n version: string,\n attribute: string,\n varyingVs: string,\n varyingFs: string,\n texture2D: string,\n output: string,\n defineOutput: string,\n defineSpecialNaN: string,\n defineSpecialInf: string,\n defineRound: string\n};\n\nexport function getGlslDifferences(): GLSL {\n let version: string;\n let attribute: string;\n let varyingVs: string;\n let varyingFs: string;\n let texture2D: string;\n let output: string;\n let defineOutput: string;\n let defineSpecialNaN: string;\n let defineSpecialInf: string;\n let defineRound: string;\n\n if (env().getNumber('WEBGL_VERSION') === 2) {\n version = '#version 300 es';\n attribute = 'in';\n varyingVs = 'out';\n varyingFs = 'in';\n texture2D = 'texture';\n output = 'outputColor';\n defineOutput = 'out vec4 outputColor;';\n\n // Use custom isnan definition to work across differences between\n // implementations on various platforms. While this should happen in ANGLE\n // we still see differences between android and windows (on chrome) when\n // using isnan directly.\n defineSpecialNaN = `\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n `;\n // In webgl 2 we do not need to specify a custom isinf so there is no\n // need for a special INFINITY constant.\n defineSpecialInf = ``;\n defineRound = `\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n `;\n } else {\n version = '';\n attribute = 'attribute';\n varyingVs = 'varying';\n varyingFs = 'varying';\n texture2D = 'texture2D';\n output = 'gl_FragColor';\n defineOutput = '';\n // WebGL1 has no built in isnan so we define one here.\n defineSpecialNaN = `\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n `;\n defineSpecialInf = `\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n `;\n defineRound = `\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n `;\n }\n\n return {\n version,\n attribute,\n varyingVs,\n varyingFs,\n texture2D,\n output,\n defineOutput,\n defineSpecialNaN,\n defineSpecialInf,\n defineRound\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 {util} from '@tensorflow/tfjs-core';\n\n/**\n * Produces GLSL code that derives logical coordinates from a flat\n * index. The code performs integer division with each stride and decrements\n * the index until the index equals the final dimension coordinate.\n */\nexport function getLogicalCoordinatesFromFlatIndex(\n coords: string[], shape: number[], index = 'index'): string {\n const strides = util.computeStrides(shape);\n return strides\n .map((stride, i) => {\n const line1 = `int ${coords[i]} = ${index} / ${stride}`;\n const line2 = i === strides.length - 1 ?\n `int ${coords[i + 1]} = ${index} - ${coords[i]} * ${stride}` :\n `index -= ${coords[i]} * ${stride}`;\n return `${line1}; ${line2};`;\n })\n .join('');\n}\n\nexport function getLogicalCoordinatesFromFlatIndexByUniform(\n coords: string[], shape: number[], index = 'index'): string {\n const strides = util.computeStrides(shape);\n return strides\n .map((_, i) => {\n const line1 = `int ${coords[i]} = ${index} / outShapeStrides[${i}]`;\n const line2 = i === strides.length - 1 ?\n `int ${coords[i + 1]} = ${index} - ${coords[i]} * outShapeStrides[${\n i}]` :\n `index -= ${coords[i]} * outShapeStrides[${i}]`;\n return `${line1}; ${line2};`;\n })\n .join('');\n}\n\nfunction buildVec(x: string[]): string {\n if (x.length === 1) {\n return `${x[0]}`;\n }\n return `vec${x.length}(${x.join(',')})`;\n}\n\n/**\n * Produces GLSL code that computes the dot product of the input x and y\n * vectors. Handles splitting inputs into increments of vec4s when necessary.\n */\nexport function dotify(x: string[], y: string[]): string {\n if (x.length !== y.length) {\n throw new Error(\n `Vectors to be dotted must be of the same length -` +\n `got ${x.length} and ${y.length}`);\n }\n\n const slices: string[] = [];\n const nearestVec4 = Math.floor(x.length / 4);\n const nearestVec4Remainder = x.length % 4;\n\n for (let i = 0; i < nearestVec4; i++) {\n const xSlice = x.slice(i * 4, i * 4 + 4);\n const ySlice = y.slice(i * 4, i * 4 + 4);\n slices.push(`${buildVec(xSlice)}, ${buildVec(ySlice)}`);\n }\n\n if (nearestVec4Remainder !== 0) {\n let xSlice = x.slice(nearestVec4 * 4);\n let ySlice = y.slice(nearestVec4 * 4);\n if (xSlice.length === 1) {\n xSlice = xSlice.map(d => `float(${d})`);\n ySlice = ySlice.map(d => `float(${d})`);\n }\n slices.push(`${buildVec(xSlice)}, ${buildVec(ySlice)}`);\n }\n\n return slices.map((d, i) => `dot(${d})`).join('+');\n}\n\n/**\n * Produces GLSL that computes the flat index from 3D coordinates.\n */\nexport function getFlatIndexFrom3D(shape: [number, number, number]): string {\n const strides = util.computeStrides(shape).map(d => d.toString());\n\n return `\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${strides[0]} + coords.y * ${strides[1]} + coords.z;\n }\n`;\n}\n\nexport const ENCODE_FLOAT_SNIPPET = `\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\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 {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\nimport {getDenseTexShape, PackingScheme} from './tex_util';\n\nexport class DecodeMatrixProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: [number, number, number];\n packedInputs = false;\n packedOutput = true;\n outPackingScheme = PackingScheme.DENSE;\n\n constructor(outputShape: [number, number, number]) {\n const texShape = getDenseTexShape(outputShape);\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n\n this.userCode = `\n ivec3 outCoordsFromFlatIndex(int index) {\n ${\n shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd'], outputShape)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = 4 * (resTexRC.x * ${texShape[1]} + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${glsl.output} = result;\n }\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 {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\nimport {getDenseTexShape, PackingScheme} from './tex_util';\n\nexport class DecodeMatrixPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n outputShape: [number, number, number];\n outPackingScheme = PackingScheme.DENSE;\n\n constructor(outputShape: [number, number, number]) {\n const texShape = getDenseTexShape(outputShape);\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n\n this.userCode = `\n ivec3 outCoordsFromFlatIndex(int index) {\n ${\n shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd'], outputShape)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = 4 * (resTexRC.x * ${texShape[1]} + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${glsl.output} = result;\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 {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {ENCODE_FLOAT_SNIPPET} from './shader_compiler_util';\nimport {TextureUsage} from './tex_util';\n\nexport class EncodeFloatProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n outTexUsage = TextureUsage.DOWNLOAD;\n\n constructor(outputShape: number[]) {\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n this.userCode = `\n ${ENCODE_FLOAT_SNIPPET}\n\n void main() {\n float x = getAAtOutCoords();\n ${glsl.output} = encode_float(x);\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 {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport {ENCODE_FLOAT_SNIPPET} from './shader_compiler_util';\nimport {TextureUsage} from './tex_util';\n\nexport class EncodeFloatPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n packedInputs = true;\n packedOutput = false;\n outTexUsage = TextureUsage.DOWNLOAD;\n\n constructor(outputShape: [number, number, number]) {\n const glsl = getGlslDifferences();\n this.outputShape = outputShape;\n this.userCode = `\n ${ENCODE_FLOAT_SNIPPET}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${glsl.output} = encode_float(x);\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 {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\n\nexport class EncodeMatrixProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n\n constructor(\n outputShape: [number, number, number], texShape: [number, number],\n inputIsUnsignedByte = false) {\n const glsl = getGlslDifferences();\n const [height, width] = texShape;\n this.outputShape = outputShape;\n\n let output = `result`;\n if (inputIsUnsignedByte) {\n output = `floor(result * 255. + 0.5)`;\n }\n\n this.userCode = `\n ${shader_util.getFlatIndexFrom3D(outputShape)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / ${width};\n int c = imod(flatIndex, ${width});\n vec2 uv = (vec2(c, r) + halfCR) / vec2(${width}.0, ${height}.0);\n vec4 values = ${glsl.texture2D}(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n ${glsl.output} = vec4(${output}, 0., 0., 0.);\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 {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\n\n/*\nThis is how the shader encodes a tensor with shape = [2, 3, 5]\n(indices are [batch, row, col]).\n\n000|001 002|003 004|xxx 020|021 022|023 024|xxx\n------- ------- ------- ------- ------- -------\n010|011 012|013 014|xxx xxx|xxx xxx|xxx xxx|xxx\n\n100|101 102|103 104|xxx 120|121 122|123 124|xxx\n------- ------- ------- ------- ------- -------\n110|111 112|113 114|xxx xxx|xxx xxx|xxx xxx|xxx\n\nSingle texels contain only values from the same batch, and from adjacent rows\nand columns.\n */\n\nexport class EncodeMatrixPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n packedInputs = false;\n packedOutput = true;\n\n constructor(\n outputShape: [number, number, number], texShape: [number, number],\n inputIsUnsignedByte = false) {\n const glsl = getGlslDifferences();\n const [height, width] = texShape;\n this.outputShape = outputShape;\n\n let mainLoop = '';\n let output = 'result';\n if (inputIsUnsignedByte) {\n output = 'floor(result * 255. + 0.5)';\n }\n\n for (let row = 0; row <= 1; row++) {\n for (let col = 0; col <= 1; col++) {\n const channel = row * 2 + col;\n\n mainLoop += `\n localCoords = coords;\n if(localCoords[2] + ${col} < ${outputShape[2]}) {\n localCoords[2] += ${col};\n if(localCoords[1] + ${row} < ${outputShape[1]}) {\n localCoords[1] += ${row};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / ${width};\n c = imod(flatIndex, ${width});\n uv = (vec2(c, r) + halfCR) / vec2(${width}.0, ${height}.0);\n values = ${glsl.texture2D}(A, uv);\n\n if(offset == 0) {\n result[${channel}] = values[0];\n } else if(offset == 1) {\n result[${channel}] = values[1];\n } else if(offset == 2) {\n result[${channel}] = values[2];\n } else {\n result[${channel}] = values[3];\n }\n }\n }\n `;\n }\n }\n\n this.userCode = `\n ${shader_util.getFlatIndexFrom3D(outputShape)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n ${mainLoop}\n\n ${glsl.output} = ${output};\n }\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\nimport {PixelData, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {getGlslDifferences} from './glsl_version';\nimport * as tex_util from './tex_util';\nimport {TextureConfig} from './tex_util';\nimport * as webgl_util from './webgl_util';\n\nexport function createVertexShader(gl: WebGLRenderingContext): WebGLShader {\n const glsl = getGlslDifferences();\n const vertexShaderSource = `${glsl.version}\n precision highp float;\n ${glsl.attribute} vec3 clipSpacePos;\n ${glsl.attribute} vec2 uv;\n ${glsl.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`;\n return webgl_util.createVertexShader(gl, vertexShaderSource);\n}\n\nexport function createVertexBuffer(gl: WebGLRenderingContext): WebGLBuffer {\n // [x y z u v] * [upper-left, lower-left, upper-right, lower-right]\n const vertexArray = new Float32Array(\n [-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);\n return webgl_util.createStaticVertexBuffer(gl, vertexArray);\n}\n\nexport function createIndexBuffer(gl: WebGLRenderingContext): WebGLBuffer {\n // OpenGL (and WebGL) have \"CCW == front\" winding\n const triangleVertexIndices = new Uint16Array([0, 1, 2, 2, 1, 3]);\n return webgl_util.createStaticIndexBuffer(gl, triangleVertexIndices);\n}\n\nfunction createAndConfigureTexture(\n gl: WebGLRenderingContext, width: number, height: number,\n internalFormat: number, textureFormat: number,\n textureType: number): WebGLTexture {\n webgl_util.validateTextureSize(width, height);\n const texture = webgl_util.createTexture(gl);\n\n const tex2d = gl.TEXTURE_2D;\n webgl_util.callAndCheck(gl, () => gl.bindTexture(tex2d, texture));\n webgl_util.callAndCheck(\n gl, () => gl.texParameteri(tex2d, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE));\n webgl_util.callAndCheck(\n gl, () => gl.texParameteri(tex2d, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE));\n webgl_util.callAndCheck(\n gl, () => gl.texParameteri(tex2d, gl.TEXTURE_MIN_FILTER, gl.NEAREST));\n webgl_util.callAndCheck(\n gl, () => gl.texParameteri(tex2d, gl.TEXTURE_MAG_FILTER, gl.NEAREST));\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n tex2d, 0, internalFormat, width, height, 0, textureFormat,\n textureType, null));\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n return texture;\n}\n\nexport function getInternalFormatForFloat32MatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.internalFormatFloat;\n}\n\nexport function createFloat32MatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height,\n getInternalFormatForFloat32MatrixTexture(textureConfig),\n textureConfig.textureFormatFloat, gl.FLOAT);\n}\n\nexport function getInternalFormatForFloat16MatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.internalFormatHalfFloat;\n}\n\nexport function createFloat16MatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height,\n getInternalFormatForFloat16MatrixTexture(textureConfig),\n textureConfig.textureFormatFloat, textureConfig.textureTypeHalfFloat);\n}\n\nexport function getInternalFormatForUnsignedBytesMatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.downloadTextureFormat;\n}\n\nexport function createUnsignedBytesMatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height,\n getInternalFormatForUnsignedBytesMatrixTexture(textureConfig), gl.RGBA,\n gl.UNSIGNED_BYTE);\n}\n\nexport function getInternalFormatForPackedMatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.internalFormatPackedFloat;\n}\n\nexport function createPackedMatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height, getInternalFormatForPackedMatrixTexture(textureConfig),\n gl.RGBA, gl.FLOAT);\n}\n\nexport function getInternalFormatForFloat16PackedMatrixTexture(\n textureConfig: TextureConfig) {\n return textureConfig.internalFormatPackedHalfFloat;\n}\n\nexport function createFloat16PackedMatrixTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLTexture {\n const [width, height] =\n tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns);\n return createAndConfigureTexture(\n gl, width, height,\n getInternalFormatForFloat16PackedMatrixTexture(textureConfig), gl.RGBA,\n textureConfig.textureTypeHalfFloat);\n}\n\nexport function bindVertexProgramAttributeStreams(\n gl: WebGLRenderingContext, program: WebGLProgram,\n vertexBuffer: WebGLBuffer): boolean {\n const posOffset = 0; // x is the first buffer element\n const uvOffset = 3 * 4; // uv comes after [x y z]\n const stride = (3 * 4) + (2 * 4); // xyz + uv, each entry is 4-byte float.\n webgl_util.callAndCheck(\n gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer));\n const success = webgl_util.bindVertexBufferToProgramAttribute(\n gl, program, 'clipSpacePos', vertexBuffer, 3, stride, posOffset);\n return success &&\n webgl_util.bindVertexBufferToProgramAttribute(\n gl, program, 'uv', vertexBuffer, 2, stride, uvOffset);\n}\n\nexport function uploadDenseMatrixToTexture(\n gl: WebGLRenderingContext, texture: WebGLTexture, width: number,\n height: number, data: TypedArray, textureConfig: TextureConfig) {\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, texture));\n\n let dataForUpload: TypedArray, texelDataType: number, internalFormat: number;\n if (data instanceof Uint8Array) {\n dataForUpload = new Uint8Array(width * height * 4);\n texelDataType = gl.UNSIGNED_BYTE;\n internalFormat = gl.RGBA;\n } else {\n dataForUpload = new Float32Array(width * height * 4);\n texelDataType = gl.FLOAT;\n internalFormat = textureConfig.internalFormatPackedFloat;\n }\n\n dataForUpload.set(data);\n\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA,\n texelDataType, dataForUpload));\n\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n}\n\nexport function uploadPixelDataToTexture(\n gl: WebGLRenderingContext, texture: WebGLTexture,\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement|ImageBitmap) {\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, texture));\n if ((pixels as PixelData).data instanceof Uint8Array) {\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n gl.TEXTURE_2D, 0, gl.RGBA, pixels.width, pixels.height, 0, gl.RGBA,\n gl.UNSIGNED_BYTE, (pixels as PixelData).data));\n } else {\n webgl_util.callAndCheck(\n gl,\n () => gl.texImage2D(\n gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,\n pixels as ImageData | HTMLImageElement | HTMLCanvasElement |\n HTMLVideoElement|ImageBitmap));\n }\n\n webgl_util.callAndCheck(gl, () => gl.bindTexture(gl.TEXTURE_2D, null));\n}\n\nexport function createBufferFromOutputTexture(\n gl2: WebGL2RenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig): WebGLBuffer {\n // Create and bind the buffer.\n const buffer = gl2.createBuffer();\n webgl_util.callAndCheck(\n gl2, () => gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer));\n\n // Initialize the buffer to the size of the texture in bytes.\n const bytesPerFloat = 4;\n const valuesPerTexel = 4;\n const bufferSizeBytes = bytesPerFloat * valuesPerTexel * rows * columns;\n\n webgl_util.callAndCheck(\n gl2,\n () => gl2.bufferData(\n gl2.PIXEL_PACK_BUFFER, bufferSizeBytes, gl2.STREAM_READ));\n\n // Enqueue a command on the GPU command queue to copy of texture into the\n // buffer.\n webgl_util.callAndCheck(\n gl2, () => gl2.readPixels(0, 0, columns, rows, gl2.RGBA, gl2.FLOAT, 0));\n\n webgl_util.callAndCheck(\n gl2, () => gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null));\n\n return buffer;\n}\n\nexport function downloadFloat32MatrixFromBuffer(\n gl: WebGLRenderingContext, buffer: WebGLBuffer,\n size: number): Float32Array {\n const gl2 = gl as WebGL2RenderingContext;\n\n const downloadTarget = new Float32Array(size);\n\n gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);\n gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);\n gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);\n\n return downloadTarget;\n}\n\nexport function downloadByteEncodedFloatMatrixFromOutputTexture(\n gl: WebGLRenderingContext, rows: number, columns: number,\n textureConfig: TextureConfig) {\n const [w, h] =\n tex_util.getUnpackedMatrixTextureShapeWidthHeight(rows, columns);\n\n const numChannels = 4;\n const downloadTarget = new Uint8Array(\n tex_util.getUnpackedArraySizeFromMatrixSize(rows * columns, numChannels));\n\n webgl_util.callAndCheck(\n gl,\n () => gl.readPixels(\n 0, 0, w, h, textureConfig.downloadTextureFormat, gl.UNSIGNED_BYTE,\n downloadTarget));\n\n // By wrapping the buffer in a Float32Array, we use native browser IEEE 754\n // decoding of the 4 bytes that back each 32 bit float.\n return new Float32Array(downloadTarget.buffer);\n}\n\nexport function downloadPackedMatrixFromBuffer(\n gl: WebGLRenderingContext, buffer: WebGLBuffer, batch: number, rows: number,\n cols: number, physicalRows: number, physicalCols: number,\n textureConfig: TextureConfig): Float32Array {\n const gl2 = gl as WebGL2RenderingContext;\n\n const downloadTarget =\n new Float32Array(tex_util.getPackedRGBAArraySizeFromMatrixShape(\n physicalRows, physicalCols));\n\n gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, buffer);\n gl2.getBufferSubData(gl2.PIXEL_PACK_BUFFER, 0, downloadTarget);\n gl2.bindBuffer(gl2.PIXEL_PACK_BUFFER, null);\n\n return downloadTarget;\n}\n\nexport function downloadMatrixFromPackedOutputTexture(\n gl: WebGLRenderingContext, physicalRows: number,\n physicalCols: number): Float32Array {\n const packedRGBA = new Float32Array(physicalRows * physicalCols * 4);\n webgl_util.callAndCheck(\n gl,\n () => gl.readPixels(\n 0, 0, physicalCols, physicalRows, gl.RGBA, gl.FLOAT, packedRGBA));\n\n return packedRGBA;\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, PixelData, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {getWebGLContext, setWebGLContext} from './canvas_util';\nimport * as gpgpu_util from './gpgpu_util';\nimport * as tex_util from './tex_util';\nimport {TextureConfig} from './tex_util';\nimport {WebGL1DisjointQueryTimerExtension, WebGL2DisjointQueryTimerExtension} from './webgl_types';\nimport * as webgl_util from './webgl_util';\n\nexport interface FenceContext {\n query: WebGLQuery|WebGLSync;\n isFencePassed(): boolean;\n}\n\nexport class GPGPUContext {\n gl: WebGLRenderingContext;\n textureFloatExtension: {};\n textureHalfFloatExtension: {};\n colorBufferFloatExtension: {};\n colorBufferHalfFloatExtension: {};\n disjointQueryTimerExtension: WebGL2DisjointQueryTimerExtension|\n WebGL1DisjointQueryTimerExtension;\n vertexBuffer: WebGLBuffer;\n indexBuffer: WebGLBuffer;\n framebuffer: WebGLFramebuffer;\n outputTexture: WebGLTexture|null = null;\n program: WebGLProgram|null = null;\n private disposed = false;\n private disjoint: boolean;\n private vertexShader: WebGLShader;\n textureConfig: TextureConfig;\n\n constructor(gl?: WebGLRenderingContext) {\n const glVersion = env().getNumber('WEBGL_VERSION');\n if (gl != null) {\n this.gl = gl;\n setWebGLContext(glVersion, gl);\n } else {\n this.gl = getWebGLContext(glVersion);\n }\n // WebGL 2.0 enables texture floats without an extension.\n let COLOR_BUFFER_FLOAT = 'WEBGL_color_buffer_float';\n const COLOR_BUFFER_HALF_FLOAT = 'EXT_color_buffer_half_float';\n if (env().getNumber('WEBGL_VERSION') === 1) {\n const TEXTURE_FLOAT = 'OES_texture_float';\n const TEXTURE_HALF_FLOAT = 'OES_texture_half_float';\n\n this.textureFloatExtension =\n webgl_util.getExtensionOrThrow(this.gl, TEXTURE_FLOAT);\n if (webgl_util.hasExtension(this.gl, TEXTURE_HALF_FLOAT)) {\n this.textureHalfFloatExtension =\n webgl_util.getExtensionOrThrow(this.gl, TEXTURE_HALF_FLOAT);\n } else if (env().get('WEBGL_FORCE_F16_TEXTURES')) {\n throw new Error(\n 'GL context does not support half float textures, yet the ' +\n 'environment flag WEBGL_FORCE_F16_TEXTURES is set to true.');\n }\n\n this.colorBufferFloatExtension = this.gl.getExtension(COLOR_BUFFER_FLOAT);\n if (webgl_util.hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {\n this.colorBufferHalfFloatExtension =\n webgl_util.getExtensionOrThrow(this.gl, COLOR_BUFFER_HALF_FLOAT);\n } else if (env().get('WEBGL_FORCE_F16_TEXTURES')) {\n throw new Error(\n 'GL context does not support color renderable half floats, yet ' +\n 'the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.');\n }\n } else {\n COLOR_BUFFER_FLOAT = 'EXT_color_buffer_float';\n if (webgl_util.hasExtension(this.gl, COLOR_BUFFER_FLOAT)) {\n this.colorBufferFloatExtension =\n this.gl.getExtension(COLOR_BUFFER_FLOAT);\n } else if (webgl_util.hasExtension(this.gl, COLOR_BUFFER_HALF_FLOAT)) {\n this.colorBufferHalfFloatExtension =\n this.gl.getExtension(COLOR_BUFFER_HALF_FLOAT);\n } else {\n throw new Error('GL context does not support color renderable floats');\n }\n }\n\n this.vertexBuffer = gpgpu_util.createVertexBuffer(this.gl);\n this.indexBuffer = gpgpu_util.createIndexBuffer(this.gl);\n this.framebuffer = webgl_util.createFramebuffer(this.gl);\n\n this.textureConfig =\n tex_util.getTextureConfig(this.gl, this.textureHalfFloatExtension);\n }\n\n private get debug(): boolean {\n return env().getBool('DEBUG');\n }\n\n public dispose() {\n if (this.disposed) {\n return;\n }\n if (this.program != null) {\n console.warn(\n 'Disposing a GPGPUContext that still has a bound WebGLProgram.' +\n ' This is probably a resource leak, delete the program with ' +\n 'GPGPUContext.deleteProgram before disposing.');\n }\n if (this.outputTexture != null) {\n console.warn(\n 'Disposing a GPGPUContext that still has a bound output matrix ' +\n 'texture. This is probably a resource leak, delete the output ' +\n 'matrix texture with GPGPUContext.deleteMatrixTexture before ' +\n 'disposing.');\n }\n const gl = this.gl;\n webgl_util.callAndCheck(gl, () => gl.finish());\n webgl_util.callAndCheck(gl, () => gl.bindFramebuffer(gl.FRAMEBUFFER, null));\n webgl_util.callAndCheck(gl, () => gl.deleteFramebuffer(this.framebuffer));\n webgl_util.callAndCheck(gl, () => gl.bindBuffer(gl.ARRAY_BUFFER, null));\n webgl_util.callAndCheck(\n gl, () => gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null));\n webgl_util.callAndCheck(gl, () => gl.deleteBuffer(this.indexBuffer));\n this.disposed = true;\n }\n\n public createFloat32MatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createFloat32MatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public createFloat16MatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createFloat16MatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public createUnsignedBytesMatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createUnsignedBytesMatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public uploadPixelDataToTexture(\n texture: WebGLTexture,\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n ImageBitmap) {\n this.throwIfDisposed();\n gpgpu_util.uploadPixelDataToTexture(this.gl, texture, pixels);\n }\n\n public uploadDenseMatrixToTexture(\n texture: WebGLTexture, width: number, height: number, data: TypedArray) {\n this.throwIfDisposed();\n gpgpu_util.uploadDenseMatrixToTexture(\n this.gl, texture, width, height, data, this.textureConfig);\n }\n\n public createFloat16PackedMatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createFloat16PackedMatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public createPackedMatrixTexture(rows: number, columns: number):\n WebGLTexture {\n this.throwIfDisposed();\n return gpgpu_util.createPackedMatrixTexture(\n this.gl, rows, columns, this.textureConfig);\n }\n\n public deleteMatrixTexture(texture: WebGLTexture) {\n this.throwIfDisposed();\n if (this.outputTexture === texture) {\n webgl_util.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);\n this.outputTexture = null;\n }\n webgl_util.callAndCheck(this.gl, () => this.gl.deleteTexture(texture));\n }\n\n public downloadByteEncodedFloatMatrixFromOutputTexture(\n texture: WebGLTexture, rows: number, columns: number): Float32Array {\n return this.downloadMatrixDriver(\n texture,\n () => gpgpu_util.downloadByteEncodedFloatMatrixFromOutputTexture(\n this.gl, rows, columns, this.textureConfig));\n }\n\n public downloadPackedMatrixFromBuffer(\n buffer: WebGLBuffer, batch: number, rows: number, columns: number,\n physicalRows: number, physicalCols: number): Float32Array {\n return gpgpu_util.downloadPackedMatrixFromBuffer(\n this.gl, buffer, batch, rows, columns, physicalRows, physicalCols,\n this.textureConfig);\n }\n\n public downloadFloat32MatrixFromBuffer(buffer: WebGLBuffer, size: number):\n Float32Array {\n return gpgpu_util.downloadFloat32MatrixFromBuffer(this.gl, buffer, size);\n }\n\n public createBufferFromTexture(\n texture: WebGLTexture, rows: number, columns: number): WebGLBuffer {\n this.bindTextureToFrameBuffer(texture);\n const result = gpgpu_util.createBufferFromOutputTexture(\n this.gl as WebGL2RenderingContext, rows, columns, this.textureConfig);\n this.unbindTextureToFrameBuffer();\n return result;\n }\n\n public createAndWaitForFence(): Promise<void> {\n const fenceContext = this.createFence(this.gl);\n return this.pollFence(fenceContext);\n }\n\n private createFence(gl: WebGLRenderingContext): FenceContext {\n let query: WebGLQuery|WebGLSync;\n let isFencePassed: () => boolean;\n\n if (env().getBool('WEBGL_FENCE_API_ENABLED')) {\n const gl2 = gl as WebGL2RenderingContext;\n\n const sync = gl2.fenceSync(gl2.SYNC_GPU_COMMANDS_COMPLETE, 0);\n gl.flush();\n\n isFencePassed = () => {\n const status = gl2.clientWaitSync(sync, 0, 0);\n return status === gl2.ALREADY_SIGNALED ||\n status === gl2.CONDITION_SATISFIED;\n };\n\n query = sync;\n } else if (\n env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') > 0) {\n query = this.beginQuery();\n this.endQuery();\n isFencePassed = () => this.isQueryAvailable(\n query,\n env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION'));\n } else {\n // If we have no way to fence, return true immediately. This will fire in\n // WebGL 1.0 when there is no disjoint query timer. In this case, because\n // the fence passes immediately, we'll immediately ask for a download of\n // the texture, which will cause the UI thread to hang.\n isFencePassed = () => true;\n }\n\n return {query, isFencePassed};\n }\n\n public downloadMatrixFromPackedTexture(\n texture: WebGLTexture, physicalRows: number,\n physicalCols: number): Float32Array {\n return this.downloadMatrixDriver(\n texture,\n () => gpgpu_util.downloadMatrixFromPackedOutputTexture(\n this.gl, physicalRows, physicalCols));\n }\n\n private vertexAttrsAreBound = false;\n\n public createProgram(fragmentShaderSource: string): WebGLProgram {\n this.throwIfDisposed();\n const gl = this.gl;\n const fragmentShader: WebGLShader =\n webgl_util.createFragmentShader(gl, fragmentShaderSource);\n if (this.vertexShader == null) {\n this.vertexShader = gpgpu_util.createVertexShader(gl);\n }\n const program: WebGLProgram = webgl_util.createProgram(gl);\n webgl_util.callAndCheck(\n gl, () => gl.attachShader(program, this.vertexShader));\n webgl_util.callAndCheck(gl, () => gl.attachShader(program, fragmentShader));\n webgl_util.linkProgram(gl, program);\n if (this.debug) {\n webgl_util.validateProgram(gl, program);\n }\n if (!this.vertexAttrsAreBound) {\n this.setProgram(program);\n this.vertexAttrsAreBound = gpgpu_util.bindVertexProgramAttributeStreams(\n gl, this.program, this.vertexBuffer);\n }\n return program;\n }\n\n public deleteProgram(program: WebGLProgram) {\n this.throwIfDisposed();\n if (program === this.program) {\n this.program = null;\n }\n if (program != null) {\n webgl_util.callAndCheck(this.gl, () => this.gl.deleteProgram(program));\n }\n }\n\n public setProgram(program: WebGLProgram|null) {\n this.throwIfDisposed();\n this.program = program;\n if ((this.program != null) && this.debug) {\n webgl_util.validateProgram(this.gl, this.program);\n }\n webgl_util.callAndCheck(this.gl, () => this.gl.useProgram(program));\n }\n\n public getUniformLocation(\n program: WebGLProgram, uniformName: string,\n shouldThrow = true): WebGLUniformLocation {\n this.throwIfDisposed();\n if (shouldThrow) {\n return webgl_util.getProgramUniformLocationOrThrow(\n this.gl, program, uniformName);\n } else {\n return webgl_util.getProgramUniformLocation(\n this.gl, program, uniformName);\n }\n }\n\n public getAttributeLocation(program: WebGLProgram, attribute: string):\n number {\n this.throwIfDisposed();\n return webgl_util.callAndCheck(\n this.gl, () => this.gl.getAttribLocation(program, attribute));\n }\n\n public getUniformLocationNoThrow(program: WebGLProgram, uniformName: string):\n WebGLUniformLocation {\n this.throwIfDisposed();\n return this.gl.getUniformLocation(program, uniformName);\n }\n\n public setInputMatrixTexture(\n inputMatrixTexture: WebGLTexture, uniformLocation: WebGLUniformLocation,\n textureUnit: number) {\n this.throwIfDisposed();\n this.throwIfNoProgram();\n webgl_util.bindTextureToProgramUniformSampler(\n this.gl, inputMatrixTexture, uniformLocation, textureUnit);\n }\n\n public setOutputMatrixTexture(\n outputMatrixTexture: WebGLTexture, rows: number, columns: number) {\n this.setOutputMatrixTextureDriver(outputMatrixTexture, columns, rows);\n }\n\n public setOutputPackedMatrixTexture(\n outputPackedMatrixTexture: WebGLTexture, rows: number, columns: number) {\n this.throwIfDisposed();\n const [width, height] =\n tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns);\n this.setOutputMatrixTextureDriver(outputPackedMatrixTexture, width, height);\n }\n\n public setOutputMatrixWriteRegion(\n startRow: number, numRows: number, startColumn: number,\n numColumns: number) {\n this.setOutputMatrixWriteRegionDriver(\n startColumn, startRow, numColumns, numRows);\n }\n\n public setOutputPackedMatrixWriteRegion(\n startRow: number, numRows: number, startColumn: number,\n numColumns: number) {\n throw new Error('setOutputPackedMatrixWriteRegion not implemented.');\n }\n\n public debugValidate() {\n if (this.program != null) {\n webgl_util.validateProgram(this.gl, this.program);\n }\n webgl_util.validateFramebuffer(this.gl);\n }\n\n public executeProgram() {\n this.throwIfDisposed();\n this.throwIfNoProgram();\n const gl = this.gl;\n if (this.debug) {\n this.debugValidate();\n }\n webgl_util.callAndCheck(\n gl, () => gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0));\n }\n\n public blockUntilAllProgramsCompleted() {\n this.throwIfDisposed();\n webgl_util.callAndCheck(this.gl, () => this.gl.finish());\n }\n\n private getQueryTimerExtension(): WebGL1DisjointQueryTimerExtension\n |WebGL2DisjointQueryTimerExtension {\n if (this.disjointQueryTimerExtension == null) {\n this.disjointQueryTimerExtension =\n webgl_util.getExtensionOrThrow(\n this.gl,\n env().getNumber(\n 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2 ?\n 'EXT_disjoint_timer_query_webgl2' :\n 'EXT_disjoint_timer_query') as\n WebGL1DisjointQueryTimerExtension |\n WebGL2DisjointQueryTimerExtension;\n }\n return this.disjointQueryTimerExtension;\n }\n\n private getQueryTimerExtensionWebGL2(): WebGL2DisjointQueryTimerExtension {\n return this.getQueryTimerExtension();\n }\n\n private getQueryTimerExtensionWebGL1(): WebGL1DisjointQueryTimerExtension {\n return this.getQueryTimerExtension() as WebGL1DisjointQueryTimerExtension;\n }\n\n beginQuery(): WebGLQuery {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2) {\n const gl2 = this.gl as WebGL2RenderingContext;\n const ext = this.getQueryTimerExtensionWebGL2();\n\n const query = gl2.createQuery();\n gl2.beginQuery(ext.TIME_ELAPSED_EXT, query);\n return query;\n }\n const ext = this.getQueryTimerExtensionWebGL1();\n const query = ext.createQueryEXT() as WebGLQuery;\n ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, query);\n return query;\n }\n\n endQuery() {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION') === 2) {\n const gl2 = this.gl as WebGL2RenderingContext;\n const ext = this.getQueryTimerExtensionWebGL2();\n gl2.endQuery(ext.TIME_ELAPSED_EXT);\n return;\n }\n const ext = this.getQueryTimerExtensionWebGL1();\n ext.endQueryEXT(ext.TIME_ELAPSED_EXT);\n }\n\n public async waitForQueryAndGetTime(query: WebGLQuery): Promise<number> {\n await util.repeatedTry(\n () => this.disposed || // while testing contexts are created / disposed\n // in rapid succession, so without this check we\n // may poll for the query timer indefinitely\n this.isQueryAvailable(\n query,\n env().getNumber(\n 'WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION')));\n return this.getQueryTime(\n query, env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION'));\n }\n\n private getQueryTime(query: WebGLQuery, queryTimerVersion: number): number {\n if (queryTimerVersion === 0) {\n return null;\n }\n\n if (queryTimerVersion === 2) {\n const gl2 = this.gl as WebGL2RenderingContext;\n\n const timeElapsedNanos = gl2.getQueryParameter(query, gl2.QUERY_RESULT);\n // Return milliseconds.\n return timeElapsedNanos / 1000000;\n } else {\n const ext = this.getQueryTimerExtensionWebGL1();\n\n const timeElapsedNanos =\n ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);\n // Return milliseconds.\n return timeElapsedNanos / 1000000;\n }\n }\n\n private isQueryAvailable(query: WebGLQuery, queryTimerVersion: number):\n boolean {\n if (queryTimerVersion === 0) {\n return true;\n }\n\n if (queryTimerVersion === 2) {\n const gl2 = this.gl as WebGL2RenderingContext;\n const ext = this.getQueryTimerExtensionWebGL2();\n\n const available =\n gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE);\n if (this.disjoint == null) {\n this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);\n }\n\n return available && !this.disjoint;\n } else {\n const ext = this.getQueryTimerExtensionWebGL1();\n\n const available =\n ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);\n if (this.disjoint == null) {\n this.disjoint = this.gl.getParameter(ext.GPU_DISJOINT_EXT);\n }\n\n return available && !this.disjoint;\n }\n }\n\n pollFence(fenceContext: FenceContext) {\n return new Promise<void>(resolve => {\n this.addItemToPoll(() => fenceContext.isFencePassed(), () => resolve());\n });\n }\n\n private itemsToPoll: PollItem[] = [];\n\n pollItems(): void {\n // Find the last query that has finished.\n const index = linearSearchLastTrue(this.itemsToPoll.map(x => x.isDoneFn));\n for (let i = 0; i <= index; ++i) {\n const {resolveFn} = this.itemsToPoll[i];\n resolveFn();\n }\n this.itemsToPoll = this.itemsToPoll.slice(index + 1);\n }\n\n private addItemToPoll(isDoneFn: () => boolean, resolveFn: () => void) {\n this.itemsToPoll.push({isDoneFn, resolveFn});\n if (this.itemsToPoll.length > 1) {\n // We already have a running loop that polls.\n return;\n }\n // Start a new loop that polls.\n util.repeatedTry(() => {\n this.pollItems();\n // End the loop if no more items to poll.\n return this.itemsToPoll.length === 0;\n });\n }\n\n private bindTextureToFrameBuffer(texture: WebGLTexture) {\n this.throwIfDisposed();\n webgl_util.bindColorTextureToFramebuffer(\n this.gl, texture, this.framebuffer);\n if (this.debug) {\n webgl_util.validateFramebuffer(this.gl);\n }\n }\n\n private unbindTextureToFrameBuffer() {\n if (this.outputTexture != null) {\n webgl_util.bindColorTextureToFramebuffer(\n this.gl, this.outputTexture, this.framebuffer);\n if (this.debug) {\n webgl_util.validateFramebuffer(this.gl);\n }\n } else {\n webgl_util.unbindColorTextureFromFramebuffer(this.gl, this.framebuffer);\n }\n }\n\n private downloadMatrixDriver(\n texture: WebGLTexture,\n downloadAndDecode: () => Float32Array): Float32Array {\n this.bindTextureToFrameBuffer(texture);\n const result = downloadAndDecode();\n this.unbindTextureToFrameBuffer();\n\n return result;\n }\n\n private setOutputMatrixTextureDriver(\n outputMatrixTextureMaybePacked: WebGLTexture, width: number,\n height: number) {\n this.throwIfDisposed();\n const gl = this.gl;\n webgl_util.bindColorTextureToFramebuffer(\n gl, outputMatrixTextureMaybePacked, this.framebuffer);\n if (this.debug) {\n webgl_util.validateFramebuffer(gl);\n }\n this.outputTexture = outputMatrixTextureMaybePacked;\n webgl_util.callAndCheck(gl, () => gl.viewport(0, 0, width, height));\n webgl_util.callAndCheck(gl, () => gl.scissor(0, 0, width, height));\n }\n\n private setOutputMatrixWriteRegionDriver(\n x: number, y: number, width: number, height: number) {\n this.throwIfDisposed();\n webgl_util.callAndCheck(\n this.gl, () => this.gl.scissor(x, y, width, height));\n }\n\n private throwIfDisposed() {\n if (this.disposed) {\n throw new Error('Attempted to use disposed GPGPUContext.');\n }\n }\n\n private throwIfNoProgram() {\n if (this.program == null) {\n throw new Error('No GPU program is currently set.');\n }\n }\n}\n\ntype PollItem = {\n isDoneFn: () => boolean,\n resolveFn: () => void\n};\n\n/**\n * Finds the index of the last true element using linear search.\n * Note: We can't do binary search because Chrome expects us to explicitly\n * test all fences before download:\n * https://github.com/tensorflow/tfjs/issues/1145\n */\nexport function linearSearchLastTrue(arr: Array<() => boolean>): number {\n let i = 0;\n for (; i < arr.length; ++i) {\n const isDone = arr[i]();\n if (!isDone) {\n break;\n }\n }\n return i - 1;\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// Please make sure the shaker key in makeShaderKey in gpgpu_math.ts is well\n// mapped if any shader source code is changed in this file.\n\nimport {backend_util, util} from '@tensorflow/tfjs-core';\nconst {getBroadcastDims} = backend_util;\nimport {getGlslDifferences, GLSL} from './glsl_version';\nimport * as shader_util from './shader_compiler_util';\n\nexport type ShapeInfo = {\n logicalShape: number[],\n texShape: [number, number],\n isUniform: boolean,\n isPacked: boolean,\n flatOffset: number\n};\n\nexport type InputInfo = {\n name: string,\n shapeInfo: ShapeInfo\n};\n\nexport type UniformType =\n 'float'|'vec2'|'vec3'|'vec4'|'int'|'ivec2'|'ivec3'|'ivec4';\n\ninterface ProgramParams {\n userCode: string;\n enableShapeUniforms?: boolean;\n packedInputs?: boolean;\n customUniforms?:\n Array<{name: string; arrayIndex?: number; type: UniformType;}>;\n}\n\nexport function makeShader(\n inputsInfo: InputInfo[], outputShape: ShapeInfo,\n program: ProgramParams): string {\n const prefixSnippets: string[] = [];\n inputsInfo.forEach(x => {\n const size = util.sizeFromShape(x.shapeInfo.logicalShape);\n\n // Snippet when we decided to upload the values as uniform.\n if (x.shapeInfo.isUniform) {\n prefixSnippets.push(\n `uniform float ${x.name}${size > 1 ? `[${size}]` : ''};`);\n } else {\n prefixSnippets.push(`uniform sampler2D ${x.name};`);\n prefixSnippets.push(`uniform int offset${x.name};`);\n }\n\n if (program.enableShapeUniforms) {\n const {uniformShape} = getUniformInfoFromShape(\n program.packedInputs, x.shapeInfo.logicalShape, x.shapeInfo.texShape);\n switch (uniformShape.length) {\n case 1:\n prefixSnippets.push(`uniform int ${x.name}Shape;`);\n break;\n case 2:\n prefixSnippets.push(`uniform ivec2 ${x.name}Shape;`);\n break;\n case 3:\n prefixSnippets.push(`uniform ivec3 ${x.name}Shape;`);\n break;\n case 4:\n prefixSnippets.push(`uniform ivec4 ${x.name}Shape;`);\n break;\n default:\n break;\n }\n prefixSnippets.push(`uniform ivec2 ${x.name}TexShape;`);\n }\n });\n\n if (program.enableShapeUniforms) {\n switch (outputShape.logicalShape.length) {\n case 1:\n prefixSnippets.push(`uniform int outShape;`);\n break;\n case 2:\n prefixSnippets.push(`uniform ivec2 outShape;`);\n prefixSnippets.push(`uniform int outShapeStrides;`);\n break;\n case 3:\n prefixSnippets.push(`uniform ivec3 outShape;`);\n prefixSnippets.push(`uniform ivec2 outShapeStrides;`);\n break;\n case 4:\n prefixSnippets.push(`uniform ivec4 outShape;`);\n prefixSnippets.push(`uniform ivec3 outShapeStrides;`);\n break;\n default:\n break;\n }\n prefixSnippets.push(`uniform ivec2 outTexShape;`);\n }\n if (program.customUniforms) {\n program.customUniforms.forEach((d) => {\n prefixSnippets.push(`uniform ${d.type} ${d.name}${\n d.arrayIndex ? `[${d.arrayIndex}]` : ''};`);\n });\n }\n const inputPrefixSnippet = prefixSnippets.join('\\n');\n\n const inputSamplingSnippet = inputsInfo\n .map(\n x => getInputSamplingSnippet(\n x, outputShape, program.packedInputs,\n program.enableShapeUniforms))\n .join('\\n');\n const outTexShape = outputShape.texShape;\n const glsl = getGlslDifferences();\n const floatTextureSampleSnippet = getFloatTextureSampleSnippet(glsl);\n let outputSamplingSnippet: string;\n let floatTextureSetOutputSnippet: string;\n let shaderPrefix = getShaderPrefix(glsl);\n\n if (outputShape.isPacked) {\n outputSamplingSnippet = getPackedOutputSamplingSnippet(\n outputShape.logicalShape, outTexShape, program.enableShapeUniforms);\n floatTextureSetOutputSnippet = getFloatTextureSetRGBASnippet(glsl);\n } else {\n outputSamplingSnippet = getOutputSamplingSnippet(\n outputShape.logicalShape, outTexShape, program.enableShapeUniforms);\n floatTextureSetOutputSnippet = getFloatTextureSetRSnippet(glsl);\n }\n\n if (program.packedInputs) {\n shaderPrefix += SHADER_PACKED_PREFIX;\n }\n\n const source = [\n shaderPrefix, floatTextureSampleSnippet, floatTextureSetOutputSnippet,\n inputPrefixSnippet, outputSamplingSnippet, inputSamplingSnippet,\n program.userCode\n ].join('\\n');\n return source;\n}\n\nfunction getSamplerFromInInfo(\n inInfo: InputInfo, enableShapeUniforms = false): string {\n const shape = inInfo.shapeInfo.logicalShape;\n switch (shape.length) {\n case 0:\n return getSamplerScalar(inInfo, enableShapeUniforms);\n case 1:\n return getSampler1D(inInfo, enableShapeUniforms);\n case 2:\n return getSampler2D(inInfo, enableShapeUniforms);\n case 3:\n return getSampler3D(inInfo, enableShapeUniforms);\n case 4:\n return getSampler4D(inInfo, enableShapeUniforms);\n case 5:\n return getSampler5D(inInfo);\n case 6:\n return getSampler6D(inInfo);\n default:\n throw new Error(\n `${shape.length}-D input sampling` +\n ` is not yet supported`);\n }\n}\n\nfunction getPackedSamplerFromInInfo(\n inInfo: InputInfo, enableShapeUniforms: boolean): string {\n const shape = inInfo.shapeInfo.logicalShape;\n switch (shape.length) {\n case 0:\n return getPackedSamplerScalar(inInfo);\n case 1:\n return getPackedSampler1D(inInfo, enableShapeUniforms);\n case 2:\n return getPackedSampler2D(inInfo, enableShapeUniforms);\n case 3:\n return getPackedSampler3D(inInfo, enableShapeUniforms);\n default:\n return getPackedSamplerND(inInfo, enableShapeUniforms);\n }\n}\n\nfunction getInputSamplingSnippet(\n inInfo: InputInfo, outShapeInfo: ShapeInfo, usesPackedTextures = false,\n enableShapeUniforms: boolean): string {\n let res = '';\n if (usesPackedTextures) {\n res += getPackedSamplerFromInInfo(inInfo, enableShapeUniforms);\n } else {\n res += getSamplerFromInInfo(inInfo, enableShapeUniforms);\n }\n\n const inShape = inInfo.shapeInfo.logicalShape;\n const outShape = outShapeInfo.logicalShape;\n if (inShape.length <= outShape.length) {\n if (usesPackedTextures) {\n res += getPackedSamplerAtOutputCoords(inInfo, outShapeInfo);\n } else {\n res += getSamplerAtOutputCoords(inInfo, outShapeInfo);\n }\n }\n return res;\n}\n\nfunction getPackedOutputSamplingSnippet(\n outShape: number[], outTexShape: [number, number],\n enableShapeUniforms: boolean): string {\n switch (outShape.length) {\n case 0:\n return getOutputScalarCoords();\n case 1:\n return getOutputPacked1DCoords(\n outShape as [number], outTexShape, enableShapeUniforms);\n case 2:\n return getOutputPacked2DCoords(\n outShape as [number, number], outTexShape, enableShapeUniforms);\n case 3:\n return getOutputPacked3DCoords(\n outShape as [number, number, number], outTexShape,\n enableShapeUniforms);\n default:\n return getOutputPackedNDCoords(\n outShape, outTexShape, enableShapeUniforms);\n }\n}\n\nfunction getOutputSamplingSnippet(\n outShape: number[], outTexShape: [number, number],\n enableShapeUniforms: boolean): string {\n switch (outShape.length) {\n case 0:\n return getOutputScalarCoords();\n case 1:\n return getOutput1DCoords(\n outShape as [number], outTexShape, enableShapeUniforms);\n case 2:\n return getOutput2DCoords(\n outShape as [number, number], outTexShape, enableShapeUniforms);\n case 3:\n return getOutput3DCoords(\n outShape as [number, number, number], outTexShape,\n enableShapeUniforms);\n case 4:\n return getOutput4DCoords(\n outShape as [number, number, number, number], outTexShape,\n enableShapeUniforms);\n case 5:\n return getOutput5DCoords(\n outShape as [number, number, number, number, number], outTexShape);\n case 6:\n return getOutput6DCoords(\n outShape as [number, number, number, number, number, number],\n outTexShape);\n default:\n throw new Error(\n `${outShape.length}-D output sampling is not yet supported`);\n }\n}\n\nfunction getFloatTextureSampleSnippet(glsl: GLSL): string {\n return `\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${glsl.texture2D}(textureSampler, uv).r;\n }\n `;\n}\n\nfunction getFloatTextureSetRSnippet(glsl: GLSL): string {\n return `\n void setOutput(float val) {\n ${glsl.output} = vec4(val, 0, 0, 0);\n }\n `;\n}\n\nfunction getFloatTextureSetRGBASnippet(glsl: GLSL): string {\n return `\n void setOutput(vec4 val) {\n ${glsl.output} = val;\n }\n `;\n}\n\nfunction getShaderPrefix(glsl: GLSL): string {\n const SHADER_PREFIX = `${glsl.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${glsl.varyingFs} vec2 resultUV;\n ${glsl.defineOutput}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n ${glsl.defineSpecialNaN}\n ${glsl.defineSpecialInf}\n ${glsl.defineRound}\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n ${SAMPLE_1D_SNIPPET}\n ${SAMPLE_2D_SNIPPET}\n ${SAMPLE_3D_SNIPPET}\n `;\n\n return SHADER_PREFIX;\n}\n\nconst SAMPLE_1D_SNIPPET = `\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;\n\nconst SAMPLE_2D_SNIPPET = `\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;\n\nconst SAMPLE_3D_SNIPPET = `\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n`;\n\nconst SHADER_PACKED_PREFIX = `\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n`;\n\nfunction getOutputScalarCoords() {\n return `\n int getOutputCoords() {\n return 0;\n }\n `;\n}\n\nfunction getOutputPacked1DCoords(\n shape: [number], texShape: [number, number],\n enableShapeUniforms: boolean): string {\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n if (packedTexShape[0] === 1) {\n if (enableShapeUniforms) {\n return `\n int getOutputCoords() {\n return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n }\n `;\n }\n\n return `\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${packedTexShape[1]}.0);\n }\n `;\n }\n\n if (packedTexShape[1] === 1) {\n if (enableShapeUniforms) {\n return `\n int getOutputCoords() {\n return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n }\n `;\n }\n\n return `\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${packedTexShape[0]}.0);\n }\n `;\n }\n\n if (enableShapeUniforms) {\n return `\n int getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\n }\n `;\n }\n\n return `\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${packedTexShape[0]}, ${packedTexShape[1]}));\n return 2 * (resTexRC.x * ${packedTexShape[1]} + resTexRC.y);\n }\n `;\n}\n\nfunction getOutput1DCoords(\n shape: [number], texShape: [number, number],\n enableShapeUniforms: boolean): string {\n if (texShape[0] === 1) {\n if (enableShapeUniforms) {\n return `\n int getOutputCoords() {\n return int(resultUV.x * float(outTexShape[1]));\n }\n `;\n }\n return `\n int getOutputCoords() {\n return int(resultUV.x * ${texShape[1]}.0);\n }\n `;\n }\n if (texShape[1] === 1) {\n if (enableShapeUniforms) {\n return `\n int getOutputCoords() {\n return int(resultUV.y * float(outTexShape[0]));\n }\n `;\n }\n return `\n int getOutputCoords() {\n return int(resultUV.y * ${texShape[0]}.0);\n }\n `;\n }\n if (enableShapeUniforms) {\n return `\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n return resTexRC.x * outTexShape[1] + resTexRC.y;\n }\n `;\n }\n return `\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n return resTexRC.x * ${texShape[1]} + resTexRC.y;\n }\n `;\n}\n\nfunction getOutputPacked3DCoords(\n shape: [number, number, number], texShape: [number, number],\n enableShapeUniforms: boolean): string {\n if (enableShapeUniforms) {\n return `\n ivec3 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec3(b, r, c);\n }\n `;\n }\n\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n const texelsInLogicalRow = Math.ceil(shape[2] / 2);\n const texelsInBatch = texelsInLogicalRow * Math.ceil(shape[1] / 2);\n\n return `\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${packedTexShape[0]}, ${packedTexShape[1]}));\n int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;\n\n int b = index / ${texelsInBatch};\n index -= b * ${texelsInBatch};\n\n int r = 2 * (index / ${texelsInLogicalRow});\n int c = imod(index, ${texelsInLogicalRow}) * 2;\n\n return ivec3(b, r, c);\n }\n `;\n}\n\nfunction getOutput3DCoords(\n shape: [number, number, number], texShape: [number, number],\n enableShapeUniforms: boolean): string {\n if (enableShapeUniforms) {\n const coordsFromIndexSnippet =\n shader_util.getLogicalCoordinatesFromFlatIndexByUniform(\n ['r', 'c', 'd'], shape);\n\n return `\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${coordsFromIndexSnippet}\n return ivec3(r, c, d);\n }\n`;\n }\n const coordsFromIndexSnippet =\n shader_util.getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd'], shape);\n\n return `\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n ${coordsFromIndexSnippet}\n return ivec3(r, c, d);\n }\n `;\n}\n\nfunction getOutputPackedNDCoords(\n shape: number[], texShape: [number, number],\n enableShapeUniforms: boolean): string {\n if (enableShapeUniforms) {\n // TODO: support 5d and 6d\n return `\n ivec4 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatchN = texelsInBatch * outShape[1];\n\n int b2 = index / texelsInBatchN;\n index -= b2 * texelsInBatchN;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec4(b2, b, r, c);\n }\n `;\n }\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n\n const texelsInLogicalRow = Math.ceil(shape[shape.length - 1] / 2);\n const texelsInBatch =\n texelsInLogicalRow * Math.ceil(shape[shape.length - 2] / 2);\n let texelsInBatchN = texelsInBatch;\n let batches = ``;\n let coords = 'b, r, c';\n\n for (let b = 2; b < shape.length - 1; b++) {\n texelsInBatchN *= shape[shape.length - b - 1];\n batches = `\n int b${b} = index / ${texelsInBatchN};\n index -= b${b} * ${texelsInBatchN};\n ` + batches;\n coords = `b${b}, ` + coords;\n }\n\n return `\n ivec${shape.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${packedTexShape[0]}, ${packedTexShape[1]}));\n int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;\n\n ${batches}\n\n int b = index / ${texelsInBatch};\n index -= b * ${texelsInBatch};\n\n int r = 2 * (index / ${texelsInLogicalRow});\n int c = imod(index, ${texelsInLogicalRow}) * 2;\n\n return ivec${shape.length}(${coords});\n }\n `;\n}\n\nfunction getOutput4DCoords(\n shape: [number, number, number, number], texShape: [number, number],\n enableShapeUniforms: boolean): string {\n if (enableShapeUniforms) {\n const coordsFromIndexSnippet =\n shader_util.getLogicalCoordinatesFromFlatIndexByUniform(\n ['r', 'c', 'd', 'd2'], shape);\n\n return `\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${coordsFromIndexSnippet}\n return ivec4(r, c, d, d2);\n }\n `;\n }\n const coordsFromIndexSnippet = shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd', 'd2'], shape);\n\n return `\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n ${coordsFromIndexSnippet}\n return ivec4(r, c, d, d2);\n }\n `;\n}\n\nfunction getOutput5DCoords(\n shape: [number, number, number, number, number],\n texShape: [number, number]): string {\n const coordsFromIndexSnippet = shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd', 'd2', 'd3'], shape);\n\n return `\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(${texShape[0]},\n ${texShape[1]}));\n\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n\n ${coordsFromIndexSnippet}\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n `;\n}\n\nfunction getOutput6DCoords(\n shape: [number, number, number, number, number, number],\n texShape: [number, number]): string {\n const coordsFromIndexSnippet = shader_util.getLogicalCoordinatesFromFlatIndex(\n ['r', 'c', 'd', 'd2', 'd3', 'd4'], shape);\n\n return `\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n\n ${coordsFromIndexSnippet}\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n `;\n}\n\nfunction getOutputPacked2DCoords(\n shape: [number, number], texShape: [number, number],\n enableShapeUniforms: boolean): string {\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n if (util.arraysEqual(shape, texShape)) {\n if (enableShapeUniforms) {\n return `\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n }\n `;\n }\n\n return `\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${packedTexShape[0]}, ${\n packedTexShape[1]}));\n }\n `;\n }\n\n // texels needed to accommodate a logical row\n const texelsInLogicalRow = Math.ceil(shape[1] / 2);\n\n /**\n * getOutputCoords\n *\n * resTexRC: The rows and columns of the texels. If you move over one\n * texel to the right in the packed texture, you are moving over one column\n * (not two).\n *\n * index: The texel index\n */\n if (enableShapeUniforms) {\n return `\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec2(r, c);\n }\n `;\n }\n\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${packedTexShape[0]}, ${packedTexShape[1]}));\n\n int index = resTexRC.x * ${packedTexShape[1]} + resTexRC.y;\n int r = 2 * (index / ${texelsInLogicalRow});\n int c = imod(index, ${texelsInLogicalRow}) * 2;\n\n return ivec2(r, c);\n }\n `;\n}\n\nfunction getOutput2DCoords(\n shape: [number, number], texShape: [number, number],\n enableShapeUniforms: boolean): string {\n if (util.arraysEqual(shape, texShape)) {\n if (enableShapeUniforms) {\n return `\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n }\n `;\n }\n return `\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(${texShape[0]}, ${texShape[1]}));\n }\n `;\n }\n if (shape[1] === 1) {\n if (enableShapeUniforms) {\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(index, 0);\n }\n `;\n }\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n return ivec2(index, 0);\n }\n `;\n }\n if (shape[0] === 1) {\n if (enableShapeUniforms) {\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(0, index);\n }\n `;\n }\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n return ivec2(0, index);\n }\n `;\n }\n if (enableShapeUniforms) {\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n int r = index / outShape[1];\n int c = index - r * outShape[1];\n return ivec2(r, c);\n }\n `;\n }\n return `\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${texShape[0]}, ${texShape[1]}));\n int index = resTexRC.x * ${texShape[1]} + resTexRC.y;\n int r = index / ${shape[1]};\n int c = index - r * ${shape[1]};\n return ivec2(r, c);\n }\n `;\n}\n\nfunction getFlatOffsetUniformName(texName: string): string {\n return `offset${texName}`;\n}\n\nfunction getPackedSamplerScalar(inputInfo: InputInfo): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const glsl = getGlslDifferences();\n return `\n vec4 ${funcName}() {\n return ${glsl.texture2D}(${texName}, halfCR);\n }\n `;\n}\n\nfunction getSamplerScalar(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n if (inputInfo.shapeInfo.isUniform) {\n return `float ${funcName}() {return ${texName};}`;\n }\n const [texNumR, texNumC] = inputInfo.shapeInfo.texShape;\n if (texNumR === 1 && texNumC === 1) {\n return `\n float ${funcName}() {\n return sampleTexture(${texName}, halfCR);\n }\n `;\n }\n\n const offset = getFlatOffsetUniformName(texName);\n if (enableShapeUniforms) {\n return `\n float ${funcName}() {\n vec2 uv = uvFromFlat(${texName}TexShape[0], ${texName}TexShape[1], ${\n offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const [tNumR, tNumC] = inputInfo.shapeInfo.texShape;\n return `\n float ${funcName}() {\n vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, ${offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getPackedSampler1D(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n const glsl = getGlslDifferences();\n if (enableShapeUniforms) {\n return `\n vec4 ${funcName}(int index) {\n ivec2 packedTexShape = ivec2(ceil(float(${\n texName}TexShape[0]) / 2.0), ceil(float(${texName}TexShape[1]) / 2.0));\n vec2 uv = packedUVfrom1D(\n packedTexShape[0], packedTexShape[1], index);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n }\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n return `\n vec4 ${funcName}(int index) {\n vec2 uv = packedUVfrom1D(\n ${packedTexShape[0]}, ${packedTexShape[1]}, index);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler1D(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int index) {\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const texShape = inputInfo.shapeInfo.texShape;\n const tNumR = texShape[0];\n const tNumC = texShape[1];\n\n if (tNumC === 1 && tNumR === 1) {\n return `\n float ${funcName}(int index) {\n return sampleTexture(${texName}, halfCR);\n }\n `;\n }\n const offset = getFlatOffsetUniformName(texName);\n if (tNumC === 1) {\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${offset}) + 0.5) / float(${\n texName}TexShape[0]));\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n return `\n float ${funcName}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${offset}) + 0.5) / ${tNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n if (tNumR === 1) {\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int index) {\n vec2 uv = vec2((float(index + ${offset}) + 0.5) / float(${\n texName}TexShape[1]), 0.5);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n return `\n float ${funcName}(int index) {\n vec2 uv = vec2((float(index + ${offset}) + 0.5) / ${tNumC}.0, 0.5);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int index) {\n vec2 uv = uvFromFlat(${texName}TexShape[0], ${\n texName}TexShape[1], index + ${offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n return `\n float ${funcName}(int index) {\n vec2 uv = uvFromFlat(${tNumR}, ${tNumC}, index + ${offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getPackedSampler2D(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n const glsl = getGlslDifferences();\n if (texShape != null && util.arraysEqual(shape, texShape)) {\n if (enableShapeUniforms) {\n return `\n vec4 ${funcName}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${texName}TexShape[1], ${\n texName}TexShape[0]);\n\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n }\n return `\n vec4 ${funcName}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);\n\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n }\n\n if (enableShapeUniforms) {\n return `\n vec4 ${funcName}(int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${\n texName}TexShape[0]) / 2.0), ceil(float(${texName}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${texName}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n }\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n const valuesPerRow = Math.ceil(shape[1] / 2);\n\n return `\n vec4 ${funcName}(int row, int col) {\n vec2 uv = packedUVfrom2D(${valuesPerRow}, ${packedTexShape[0]}, ${\n packedTexShape[1]}, row, col);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler2D(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n\n if (texShape != null && util.arraysEqual(shape, texShape)) {\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${texName}TexShape[1], ${\n texName}TexShape[0]);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n return `\n float ${funcName}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n const squeezedShape = newShape;\n if (squeezedShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);\n const params = ['row', 'col'];\n return `\n ${getSamplerFromInInfo(newInputInfo, enableShapeUniforms)}\n float ${funcName}(int row, int col) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col) {\n int index = round(dot(vec2(row, col), vec2(${shape[1]}, 1)));\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n const offset = getFlatOffsetUniformName(texName);\n if (texNumC === 1) {\n // index is used directly as physical (no risk of float16 overflow).\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col) {\n float index = dot(vec3(row, col, ${offset}), vec3(${\n texName}Shape[1], 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / float(${texName}TexShape[0]));\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col) {\n float index = dot(vec3(row, col, ${offset}), vec3(${shape[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n if (texNumR === 1) {\n // index is used directly as physical (no risk of float16 overflow).\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col) {\n float index = dot(vec3(row, col, ${offset}), vec3(${\n texName}Shape[1], 1, 1));\n vec2 uv = vec2((index + 0.5) / float(${texName}TexShape[1]), 0.5);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col) {\n float index = dot(vec3(row, col, ${offset}), vec3(${shape[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${texNumC}.0, 0.5);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${texName}Shape[1] + col + ${offset};\n vec2 uv = uvFromFlat(${texName}TexShape[0], ${\n texName}TexShape[1], index);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${shape[1]} + col + ${offset};\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);\n return sampleTexture(${texName}, uv);\n }\n`;\n}\n\nfunction getPackedSampler3D(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const texShape = inputInfo.shapeInfo.texShape;\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n\n if (shape[0] === 1) {\n const squeezedShape = shape.slice(1);\n const keptDims = [1, 2];\n const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);\n const params = ['b', 'row', 'col'];\n return `\n ${getPackedSamplerFromInInfo(newInputInfo, enableShapeUniforms)}\n vec4 ${funcName}(int b, int row, int col) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n const glsl = getGlslDifferences();\n if (enableShapeUniforms) {\n return `\n vec4 ${funcName}(int b, int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${\n texName}TexShape[0]) / 2.0), ceil(float(${texName}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${texName}Shape[2]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${\n texName}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom3D(\n packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n }\n\n const texNumR = packedTexShape[0];\n const texNumC = packedTexShape[1];\n\n const valuesPerRow = Math.ceil(shape[2] / 2);\n const texelsInBatch = valuesPerRow * Math.ceil(shape[1] / 2);\n\n return `\n vec4 ${funcName}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${texNumR}, ${texNumC}, ${texelsInBatch}, ${valuesPerRow}, b, row, col);\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler3D(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const stride0 = shape[1] * shape[2];\n const stride1 = shape[2];\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n const squeezedShape = newShape;\n if (squeezedShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, squeezedShape);\n const params = ['row', 'col', 'depth'];\n return `\n ${getSamplerFromInInfo(newInputInfo, enableShapeUniforms)}\n float ${funcName}(int row, int col, int depth) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3(${stride0}, ${stride1}, 1)));\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const texShape = inputInfo.shapeInfo.texShape;\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n const flatOffset = inputInfo.shapeInfo.flatOffset;\n if (texNumC === stride0 && flatOffset == null) {\n // texC is used directly as physical (no risk of float16 overflow).\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col, int depth) {\n int stride1 = ${texName}Shape[2];\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(stride1, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texName}TexShape[1], ${texName}TexShape[0]);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(${stride1}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n if (texNumC === stride1 && flatOffset == null) {\n // texR is used directly as physical (no risk of float16 overflow).\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${texName}Shape[1], 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texName}TexShape[1], ${\n texName}TexShape[0]);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${shape[1]}, 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const offset = getFlatOffsetUniformName(texName);\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int stride0 = ${texName}Shape[1] * ${texName}Shape[2];\n int stride1 = ${texName}Shape[2];\n int index = row * ${stride0} + col * ${stride1} + depth + ${offset};\n vec2 uv = uvFromFlat(${texName}TexShape[0], ${texName}TexShape[1], index);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${stride0} + col * ${stride1} + depth + ${offset};\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getPackedSamplerND(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const glsl = getGlslDifferences();\n if (enableShapeUniforms) {\n // TODO: support 5d and 6d\n return `\n vec4 ${funcName}(int b2, int b, int row, int col) {\n int valuesPerRow = int(ceil(float(${texName}Shape[3]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${\n texName}Shape[2]) / 2.0));\n int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n texelsInBatch *= ${texName}Shape[1];\n index = b2 * texelsInBatch + index;\n ivec2 packedTexShape = ivec2(ceil(float(${\n texName}TexShape[0]) / 2.0), ceil(float(${texName}TexShape[1]) / 2.0));\n int texR = index / packedTexShape[1];\n int texC = index - texR * packedTexShape[1];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${\n glsl.texture2D}(${texName}, uv);\n }\n `;\n }\n const shape = inputInfo.shapeInfo.logicalShape;\n const rank = shape.length;\n const texShape = inputInfo.shapeInfo.texShape;\n const packedTexShape =\n [Math.ceil(texShape[0] / 2), Math.ceil(texShape[1] / 2)];\n const texNumR = packedTexShape[0];\n const texNumC = packedTexShape[1];\n\n const valuesPerRow = Math.ceil(shape[rank - 1] / 2);\n let texelsInBatch = valuesPerRow * Math.ceil(shape[rank - 2] / 2);\n let params = `int b, int row, int col`;\n let index = `b * ${texelsInBatch} + (row / 2) * ${valuesPerRow} + (col / 2)`;\n for (let b = 2; b < rank - 1; b++) {\n params = `int b${b}, ` + params;\n texelsInBatch *= shape[rank - b - 1];\n index = `b${b} * ${texelsInBatch} + ` + index;\n }\n return `\n vec4 ${funcName}(${params}) {\n int index = ${index};\n int texR = index / ${texNumC};\n int texC = index - texR * ${texNumC};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${texNumC}, ${texNumR});\n return ${glsl.texture2D}(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler4D(\n inputInfo: InputInfo, enableShapeUniforms: boolean): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const stride2 = shape[3];\n const stride1 = shape[2] * stride2;\n const stride0 = shape[1] * stride1;\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n if (newShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, newShape);\n const params = ['row', 'col', 'depth', 'depth2'];\n return `\n ${getSamplerFromInInfo(newInputInfo, enableShapeUniforms)}\n float ${funcName}(int row, int col, int depth, int depth2) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4(${stride0}, ${stride1}, ${stride2}, 1)));\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const flatOffset = inputInfo.shapeInfo.flatOffset;\n const texShape = inputInfo.shapeInfo.texShape;\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n\n const stride2Str = `int stride2 = ${texName}Shape[3];`;\n const stride1Str = `int stride1 = ${texName}Shape[2] * stride2;`;\n const stride0Str = `int stride0 = ${texName}Shape[1] * stride1;`;\n if (texNumC === stride0 && flatOffset == null) {\n // texC is used directly as physical (no risk of float16 overflow).\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n ${stride2Str}\n ${stride1Str}\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(stride1, stride2, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texName}TexShape[1], ${texName}TexShape[0]);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(${stride1}, ${stride2}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n if (texNumC === stride2 && flatOffset == null) {\n // texR is used directly as physical (no risk of float16 overflow).\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${texName}Shape[1] * ${texName}Shape[2], ${\n texName}Shape[2], 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texName}TexShape[1], ${texName}TexShape[0]);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${shape[1] * shape[2]}, ${shape[2]}, 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const offset = getFlatOffsetUniformName(texName);\n if (enableShapeUniforms) {\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n ${stride2Str}\n ${stride1Str}\n ${stride0Str}\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2;\n vec2 uv = uvFromFlat(${texName}TexShape[0], ${\n texName}TexShape[1], index + ${offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n return `\n float ${funcName}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${stride0} + col * ${stride1} +\n depth * ${stride2} + depth2;\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index + ${offset});\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler5D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n const stride3 = shape[4];\n const stride2 = shape[3] * stride3;\n const stride1 = shape[2] * stride2;\n const stride0 = shape[1] * stride1;\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n if (newShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, newShape);\n const params = ['row', 'col', 'depth', 'depth2', 'depth3'];\n return `\n ${getSamplerFromInInfo(newInputInfo)}\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4(${stride0}, ${stride1}, ${stride2}, ${stride3})) +\n depth3;\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const flatOffset = inputInfo.shapeInfo.flatOffset;\n const texShape = inputInfo.shapeInfo.texShape;\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n\n if (texNumC === stride0 && flatOffset == null) {\n // texC is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${stride1}, ${stride2}, ${stride3}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n if (texNumC === stride3 && flatOffset == null) {\n // texR is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4(${shape[1] * shape[2] * shape[3]},\n ${shape[2] * shape[3]}, ${shape[3]}, 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n\n const offset = getFlatOffsetUniformName(texName);\n return `\n float ${funcName}(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +\n depth2 * ${stride3} + depth3 + ${offset};\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getSampler6D(inputInfo: InputInfo): string {\n const shape = inputInfo.shapeInfo.logicalShape;\n const texName = inputInfo.name;\n const funcName = 'get' + texName.charAt(0).toUpperCase() + texName.slice(1);\n\n const {newShape, keptDims} = util.squeezeShape(shape);\n if (newShape.length < shape.length) {\n const newInputInfo = squeezeInputInfo(inputInfo, newShape);\n const params = ['row', 'col', 'depth', 'depth2', 'depth3', 'depth4'];\n return `\n ${getSamplerFromInInfo(newInputInfo)}\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${funcName}(${getSqueezedParams(params, keptDims)});\n }\n `;\n }\n\n const stride4 = shape[5];\n const stride3 = shape[4] * stride4;\n const stride2 = shape[3] * stride3;\n const stride1 = shape[2] * stride2;\n const stride0 = shape[1] * stride1;\n\n if (inputInfo.shapeInfo.isUniform) {\n // Uniform arrays will be less than 65505 (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4(${stride0}, ${stride1}, ${stride2}, ${stride3})) +\n dot(\n vec2(depth3, depth4),\n vec2(${stride4}, 1)));\n ${getUniformSampler(inputInfo)}\n }\n `;\n }\n\n const flatOffset = inputInfo.shapeInfo.flatOffset;\n const texShape = inputInfo.shapeInfo.texShape;\n const texNumR = texShape[0];\n const texNumC = texShape[1];\n if (texNumC === stride0 && flatOffset == null) {\n // texC is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${stride1}, ${stride2}, ${stride3}, ${stride4})) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n if (texNumC === stride4 && flatOffset == null) {\n // texR is used directly as physical (no risk of float16 overflow).\n return `\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4(${shape[1] * shape[2] * shape[3] * shape[4]},\n ${shape[2] * shape[3] * shape[4]},\n ${shape[3] * shape[4]},\n ${shape[4]})) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${texNumC}.0, ${texNumR}.0);\n return sampleTexture(${texName}, uv);\n }\n `;\n }\n const offset = getFlatOffsetUniformName(texName);\n return `\n float ${funcName}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${stride0} + col * ${stride1} + depth * ${stride2} +\n depth2 * ${stride3} + depth3 * ${stride4} + depth4 + ${offset};\n vec2 uv = uvFromFlat(${texNumR}, ${texNumC}, index);\n return sampleTexture(${texName}, uv);\n }\n `;\n}\n\nfunction getUniformSampler(inputInfo: InputInfo): string {\n const texName = inputInfo.name;\n const inSize = util.sizeFromShape(inputInfo.shapeInfo.logicalShape);\n\n if (inSize < 2) {\n return `return ${texName};`;\n }\n\n return `\n for (int i = 0; i < ${inSize}; i++) {\n if (i == index) {\n return ${texName}[i];\n }\n }\n `;\n}\n\nfunction getPackedSamplerAtOutputCoords(\n inputInfo: InputInfo, outShapeInfo: ShapeInfo) {\n const texName = inputInfo.name;\n const texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);\n const funcName = 'get' + texFuncSnippet + 'AtOutCoords';\n const inRank = inputInfo.shapeInfo.logicalShape.length;\n const outRank = outShapeInfo.logicalShape.length;\n\n const broadcastDims = getBroadcastDims(\n inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);\n\n const type = getCoordsDataType(outRank);\n const rankDiff = outRank - inRank;\n let coordsSnippet: string;\n const fields = ['x', 'y', 'z', 'w', 'u', 'v'];\n\n if (inRank === 0) {\n coordsSnippet = '';\n } else if (outRank < 2 && broadcastDims.length >= 1) {\n coordsSnippet = 'coords = 0;';\n } else {\n coordsSnippet =\n broadcastDims.map(d => `coords.${fields[d + rankDiff]} = 0;`)\n .join('\\n');\n }\n let unpackedCoordsSnippet = '';\n if (outRank < 2 && inRank > 0) {\n unpackedCoordsSnippet = 'coords';\n } else {\n unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape\n .map((s, i) => `coords.${fields[i + rankDiff]}`)\n .join(', ');\n }\n\n let output = `return outputValue;`;\n const inSize = util.sizeFromShape(inputInfo.shapeInfo.logicalShape);\n const isInputScalar = inSize === 1;\n const outSize = util.sizeFromShape(outShapeInfo.logicalShape);\n const isOutputScalar = outSize === 1;\n\n if (inRank === 1 && !isInputScalar && !isOutputScalar) {\n output = `\n return vec4(outputValue.xy, outputValue.xy);\n `;\n } else if (isInputScalar && !isOutputScalar) {\n if (outRank === 1) {\n output = `\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n `;\n } else {\n output = `\n return vec4(outputValue.x);\n `;\n }\n } else if (broadcastDims.length) {\n const rows = inRank - 2;\n const cols = inRank - 1;\n\n if (broadcastDims.indexOf(rows) > -1 && broadcastDims.indexOf(cols) > -1) {\n output = `return vec4(outputValue.x);`;\n } else if (broadcastDims.indexOf(rows) > -1) {\n output = `return vec4(outputValue.x, outputValue.y, ` +\n `outputValue.x, outputValue.y);`;\n } else if (broadcastDims.indexOf(cols) > -1) {\n output = `return vec4(outputValue.xx, outputValue.zz);`;\n }\n }\n\n return `\n vec4 ${funcName}() {\n ${type} coords = getOutputCoords();\n ${coordsSnippet}\n vec4 outputValue = get${texFuncSnippet}(${unpackedCoordsSnippet});\n ${output}\n }\n `;\n}\n\nfunction getSamplerAtOutputCoords(\n inputInfo: InputInfo, outShapeInfo: ShapeInfo) {\n const texName = inputInfo.name;\n const texFuncSnippet = texName.charAt(0).toUpperCase() + texName.slice(1);\n const funcName = 'get' + texFuncSnippet + 'AtOutCoords';\n const outTexShape = outShapeInfo.texShape;\n const inTexShape = inputInfo.shapeInfo.texShape;\n const inRank = inputInfo.shapeInfo.logicalShape.length;\n const outRank = outShapeInfo.logicalShape.length;\n\n if (!inputInfo.shapeInfo.isUniform && inRank === outRank &&\n inputInfo.shapeInfo.flatOffset == null &&\n util.arraysEqual(inTexShape, outTexShape)) {\n return `\n float ${funcName}() {\n return sampleTexture(${texName}, resultUV);\n }\n `;\n }\n\n const type = getCoordsDataType(outRank);\n const broadcastDims = getBroadcastDims(\n inputInfo.shapeInfo.logicalShape, outShapeInfo.logicalShape);\n const rankDiff = outRank - inRank;\n let coordsSnippet: string;\n const fields = ['x', 'y', 'z', 'w', 'u', 'v'];\n\n if (inRank === 0) {\n coordsSnippet = '';\n } else if (outRank < 2 && broadcastDims.length >= 1) {\n coordsSnippet = 'coords = 0;';\n } else {\n coordsSnippet =\n broadcastDims.map(d => `coords.${fields[d + rankDiff]} = 0;`)\n .join('\\n');\n }\n let unpackedCoordsSnippet = '';\n if (outRank < 2 && inRank > 0) {\n unpackedCoordsSnippet = 'coords';\n } else {\n unpackedCoordsSnippet = inputInfo.shapeInfo.logicalShape\n .map((s, i) => `coords.${fields[i + rankDiff]}`)\n .join(', ');\n }\n\n return `\n float ${funcName}() {\n ${type} coords = getOutputCoords();\n ${coordsSnippet}\n return get${texFuncSnippet}(${unpackedCoordsSnippet});\n }\n `;\n}\n\nexport function getCoordsDataType(rank: number): string {\n if (rank <= 1) {\n return 'int';\n } else if (rank === 2) {\n return 'ivec2';\n } else if (rank === 3) {\n return 'ivec3';\n } else if (rank === 4) {\n return 'ivec4';\n } else if (rank === 5) {\n return 'ivec5';\n } else if (rank === 6) {\n return 'ivec6';\n } else {\n throw Error(`GPU for rank ${rank} is not yet supported`);\n }\n}\n\nexport function getUniformInfoFromShape(\n isPacked: boolean, shape: number[], texShape: number[]) {\n const {newShape} = util.squeezeShape(shape);\n const rank = shape.length;\n const useSqueezePackedShape = isPacked && rank === 3 && shape[0] === 1;\n const squeezeShape = useSqueezePackedShape ? shape.slice(1) : newShape;\n const useSqueezeShape =\n (!isPacked && rank > 1 && !util.arraysEqual(shape, texShape) &&\n newShape.length < rank) ||\n useSqueezePackedShape;\n const uniformShape = useSqueezeShape ? squeezeShape : shape;\n return {useSqueezeShape, uniformShape};\n}\n\n/** Returns a new input info (a copy) that has a squeezed logical shape. */\nexport function squeezeInputInfo(\n inInfo: InputInfo, squeezedShape: number[]): InputInfo {\n // Deep copy.\n const newInputInfo: InputInfo = JSON.parse(JSON.stringify(inInfo));\n newInputInfo.shapeInfo.logicalShape = squeezedShape;\n return newInputInfo;\n}\n\nfunction getSqueezedParams(params: string[], keptDims: number[]): string {\n return keptDims.map(d => params[d]).join(', ');\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 {backend_util, env, Tensor, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUContext} from './gpgpu_context';\nimport * as shader_compiler from './shader_compiler';\nimport {InputInfo, ShapeInfo, UniformType} from './shader_compiler';\nimport {PackingScheme, TextureData, TextureUsage} from './tex_util';\n\nexport interface GPGPUProgram {\n variableNames: string[];\n outputShape: number[];\n userCode: string;\n enableShapeUniforms?: boolean;\n /** If true, this program expects packed input textures. Defaults to false. */\n packedInputs?: boolean;\n /** If true, this program produces a packed texture. Defaults to false. */\n packedOutput?: boolean;\n /**\n * Affects what type of texture we allocate for the output. Defaults to\n * `TextureUsage.RENDER`.\n */\n outTexUsage?: TextureUsage;\n /**\n * The type of scheme to use when packing texels for the output values.\n * See `PackingScheme` for details. Defaults to `PackingScheme.SHARED_BATCH`.\n */\n outPackingScheme?: PackingScheme;\n customUniforms?:\n Array<{name: string; arrayIndex?: number; type: UniformType;}>;\n}\n\nexport interface GPGPUBinary {\n webGLProgram: WebGLProgram;\n program: GPGPUProgram;\n uniformLocations: {[name: string]: WebGLUniformLocation};\n customUniformLocations?: WebGLUniformLocation[];\n source: string;\n inShapeInfos: ShapeInfo[];\n outShapeInfo: ShapeInfo;\n infLoc: WebGLUniformLocation;\n nanLoc: WebGLUniformLocation;\n inShapesLocations?: {[name: string]: WebGLUniformLocation};\n inTexShapesLocations?: {[name: string]: WebGLUniformLocation};\n outShapeLocation?: WebGLUniformLocation;\n outShapeStridesLocation?: WebGLUniformLocation;\n outTexShapeLocation?: WebGLUniformLocation;\n}\n\nexport interface TensorData {\n shape: number[];\n texData: TextureData;\n isUniform: boolean;\n // Available when we decide to upload as uniform instead of texture.\n uniformValues?: TypedArray;\n}\n\nexport function compileProgram<T extends Tensor, K extends Tensor>(\n gpgpu: GPGPUContext, program: GPGPUProgram, inputs: TensorData[],\n output: TensorData): GPGPUBinary {\n const inputInfos: InputInfo[] = inputs.map((input, i) => {\n const shapeInfo: ShapeInfo = {\n logicalShape: input.shape,\n texShape: input.isUniform ? null : input.texData.texShape,\n isUniform: input.isUniform,\n isPacked: input.isUniform ? false : input.texData.isPacked,\n flatOffset: null\n };\n if (input.texData != null && input.texData.slice != null &&\n input.texData.slice.flatOffset > 0) {\n shapeInfo.flatOffset = input.texData.slice.flatOffset;\n }\n return {name: program.variableNames[i], shapeInfo};\n });\n const inShapeInfos = inputInfos.map(x => x.shapeInfo);\n const outShapeInfo: ShapeInfo = {\n logicalShape: output.shape,\n texShape: output.texData.texShape,\n isUniform: false,\n isPacked: output.texData.isPacked,\n flatOffset: null\n };\n const source = shader_compiler.makeShader(inputInfos, outShapeInfo, program);\n\n const webGLProgram = gpgpu.createProgram(source);\n\n // Add special uniforms (NAN, INFINITY)\n let infLoc: WebGLUniformLocation = null;\n const nanLoc = gpgpu.getUniformLocation(webGLProgram, 'NAN', false);\n if (env().getNumber('WEBGL_VERSION') === 1) {\n infLoc = gpgpu.getUniformLocation(webGLProgram, 'INFINITY', false);\n }\n\n // Add user-defined uniforms\n const shouldThrow = false;\n const uniformLocations: {[name: string]: WebGLUniformLocation} = {};\n const inShapesLocations: {[name: string]: WebGLUniformLocation} = {};\n const inTexShapesLocations: {[name: string]: WebGLUniformLocation} = {};\n for (let i = 0; i < program.variableNames.length; i++) {\n const varName = program.variableNames[i];\n uniformLocations[varName] =\n gpgpu.getUniformLocation(webGLProgram, varName, shouldThrow);\n uniformLocations[`offset${varName}`] =\n gpgpu.getUniformLocation(webGLProgram, `offset${varName}`, shouldThrow);\n if (program.enableShapeUniforms) {\n inShapesLocations[`${varName}Shape`] = gpgpu.getUniformLocation(\n webGLProgram, `${varName}Shape`, shouldThrow);\n inTexShapesLocations[`${varName}TexShape`] = gpgpu.getUniformLocation(\n webGLProgram, `${varName}TexShape`, shouldThrow);\n }\n }\n\n let outShapeLocation: WebGLUniformLocation;\n let outTexShapeLocation: WebGLUniformLocation;\n let outShapeStridesLocation: WebGLUniformLocation;\n if (program.enableShapeUniforms) {\n outShapeLocation =\n gpgpu.getUniformLocation(webGLProgram, 'outShape', shouldThrow);\n outShapeStridesLocation =\n gpgpu.getUniformLocation(webGLProgram, 'outShapeStrides', shouldThrow);\n outTexShapeLocation =\n gpgpu.getUniformLocation(webGLProgram, 'outTexShape', shouldThrow);\n }\n\n const customUniformLocations: WebGLUniformLocation[] = [];\n if (program.customUniforms) {\n program.customUniforms.forEach((d, i) => {\n customUniformLocations[i] =\n gpgpu.getUniformLocation(webGLProgram, d.name, shouldThrow);\n });\n }\n\n return {\n program,\n source,\n webGLProgram,\n uniformLocations,\n customUniformLocations,\n inShapeInfos,\n outShapeInfo,\n infLoc,\n nanLoc,\n inShapesLocations,\n inTexShapesLocations,\n outShapeLocation,\n outShapeStridesLocation,\n outTexShapeLocation\n };\n}\n\nfunction validateBinaryAndProgram(\n shapeInfos: ShapeInfo[], inputs: TensorData[]) {\n if (shapeInfos.length !== inputs.length) {\n throw Error(\n `Binary was compiled with ${shapeInfos.length} inputs, but ` +\n `was executed with ${inputs.length} inputs`);\n }\n\n shapeInfos.forEach((s, i) => {\n const shapeA = s.logicalShape;\n const input = inputs[i];\n const shapeB = input.shape;\n\n if (!util.arraysEqual(shapeA, shapeB)) {\n throw Error(\n `Binary was compiled with different shapes than ` +\n `the current args. Shapes ${shapeA} and ${shapeB} must match`);\n }\n // The input is uploaded as uniform.\n if (s.isUniform && input.isUniform) {\n return;\n }\n\n const texShapeA = s.texShape;\n const texShapeB = input.isUniform ? null : input.texData.texShape;\n if (!util.arraysEqual(texShapeA, texShapeB)) {\n throw Error(\n `Binary was compiled with different texture shapes than the` +\n ` current args. Shape ${texShapeA} and ${texShapeB} must match`);\n }\n });\n}\n\nexport function runProgram<T extends Tensor, K extends Tensor>(\n gpgpu: GPGPUContext, binary: GPGPUBinary, inputs: TensorData[],\n output: TensorData, customUniformValues?: number[][]): void {\n if (!binary.program.enableShapeUniforms) {\n validateBinaryAndProgram(binary.inShapeInfos, inputs);\n validateBinaryAndProgram([binary.outShapeInfo], [output]);\n }\n\n const outTex = output.texData.texture;\n const outTexShape = output.texData.texShape;\n if (output.texData.isPacked) {\n gpgpu.setOutputPackedMatrixTexture(outTex, outTexShape[0], outTexShape[1]);\n } else {\n gpgpu.setOutputMatrixTexture(outTex, outTexShape[0], outTexShape[1]);\n }\n gpgpu.setProgram(binary.webGLProgram);\n\n // Set special uniforms (NAN, INFINITY)\n if (env().getNumber('WEBGL_VERSION') === 1) {\n if (binary.infLoc !== null) {\n gpgpu.gl.uniform1f(binary.infLoc, Infinity);\n }\n }\n if (binary.nanLoc !== null) {\n gpgpu.gl.uniform1f(binary.nanLoc, NaN);\n }\n\n // Set user-defined inputs\n inputs.forEach((input, i) => {\n const varName = binary.program.variableNames[i];\n const varLoc = binary.uniformLocations[varName];\n const varOffsetLoc = binary.uniformLocations[`offset${varName}`];\n const varShapeLoc = binary.inShapesLocations[`${varName}Shape`];\n const varTexShapeLoc = binary.inTexShapesLocations[`${varName}TexShape`];\n\n if (varShapeLoc) {\n const {uniformShape} = shader_compiler.getUniformInfoFromShape(\n binary.program.packedInputs, input.shape, input.texData.texShape);\n switch (uniformShape.length) {\n case 1:\n gpgpu.gl.uniform1iv(varShapeLoc, new Int32Array(uniformShape));\n break;\n case 2:\n gpgpu.gl.uniform2iv(varShapeLoc, new Int32Array(uniformShape));\n break;\n case 3:\n gpgpu.gl.uniform3iv(varShapeLoc, new Int32Array(uniformShape));\n break;\n case 4:\n gpgpu.gl.uniform4iv(varShapeLoc, new Int32Array(uniformShape));\n break;\n default:\n break;\n }\n }\n if (varTexShapeLoc) {\n gpgpu.gl.uniform2i(\n varTexShapeLoc, input.texData.texShape[0], input.texData.texShape[1]);\n }\n\n if (varLoc == null) {\n // The compiler inferred that this variable is not used in this shader.\n return;\n }\n\n if (input.isUniform) {\n // Upload the values of the tensor as uniform.\n if (util.sizeFromShape(input.shape) < 2) {\n gpgpu.gl.uniform1f(varLoc, input.uniformValues[0]);\n } else {\n let vals = input.uniformValues;\n if (!(vals instanceof Float32Array)) {\n vals = new Float32Array(vals);\n }\n gpgpu.gl.uniform1fv(varLoc, vals);\n }\n return;\n }\n\n // If the input was sliced, upload the flat offset index.\n if (input.texData.slice != null && varOffsetLoc != null) {\n gpgpu.gl.uniform1i(varOffsetLoc, input.texData.slice.flatOffset);\n }\n\n gpgpu.setInputMatrixTexture(input.texData.texture, varLoc, i);\n });\n\n const outShapeLoc = binary.outShapeLocation;\n if (outShapeLoc) {\n switch (output.shape.length) {\n case 1:\n gpgpu.gl.uniform1iv(outShapeLoc, new Int32Array(output.shape));\n break;\n case 2:\n gpgpu.gl.uniform2iv(outShapeLoc, new Int32Array(output.shape));\n break;\n case 3:\n gpgpu.gl.uniform3iv(outShapeLoc, new Int32Array(output.shape));\n break;\n case 4:\n gpgpu.gl.uniform4iv(outShapeLoc, new Int32Array(output.shape));\n break;\n default:\n break;\n }\n }\n if (binary.outShapeStridesLocation) {\n const strides = util.computeStrides(output.shape);\n switch (output.shape.length) {\n case 2:\n gpgpu.gl.uniform1iv(\n binary.outShapeStridesLocation, new Int32Array(strides));\n break;\n case 3:\n gpgpu.gl.uniform2iv(\n binary.outShapeStridesLocation, new Int32Array(strides));\n break;\n case 4:\n gpgpu.gl.uniform3iv(\n binary.outShapeStridesLocation, new Int32Array(strides));\n break;\n default:\n break;\n }\n }\n if (binary.outTexShapeLocation) {\n gpgpu.gl.uniform2i(\n binary.outTexShapeLocation, output.texData.texShape[0],\n output.texData.texShape[1]);\n }\n\n if (binary.program.customUniforms && customUniformValues) {\n binary.program.customUniforms.forEach((d, i) => {\n const customLoc = binary.customUniformLocations[i];\n const customValue = customUniformValues[i];\n if (d.type === 'float') {\n gpgpu.gl.uniform1fv(customLoc, customValue);\n } else if (d.type === 'vec2') {\n gpgpu.gl.uniform2fv(customLoc, customValue);\n } else if (d.type === 'vec3') {\n gpgpu.gl.uniform3fv(customLoc, customValue);\n } else if (d.type === 'vec4') {\n gpgpu.gl.uniform4fv(customLoc, customValue);\n } else if (d.type === 'int') {\n gpgpu.gl.uniform1iv(customLoc, customValue);\n } else if (d.type === 'ivec2') {\n gpgpu.gl.uniform2iv(customLoc, customValue);\n } else if (d.type === 'ivec3') {\n gpgpu.gl.uniform3iv(customLoc, customValue);\n } else if (d.type === 'ivec4') {\n gpgpu.gl.uniform4iv(customLoc, customValue);\n } else {\n throw Error(`uniform type ${d.type} is not supported yet.`);\n }\n });\n }\n gpgpu.executeProgram();\n}\n\nexport function makeShaderKey(\n program: GPGPUProgram, inputs: TensorData[], output: TensorData): string {\n let keyInputs = '';\n inputs.concat(output).forEach(x => {\n const hasOffset = x.texData != null && x.texData.slice != null &&\n x.texData.slice.flatOffset > 0;\n // TODO: Remove the condition of !x.isUniform.\n if (program.enableShapeUniforms && !x.isUniform) {\n const xTexShape = x.texData.texShape;\n const {useSqueezeShape, uniformShape} =\n shader_compiler.getUniformInfoFromShape(\n program.packedInputs, x.shape, xTexShape);\n let rank1 = '', rank2 = '', rank34 = '';\n if (uniformShape.length === 1 && program.packedInputs) {\n const packedTexShape =\n [Math.ceil(xTexShape[0] / 2), Math.ceil(xTexShape[1] / 2)];\n rank1 = `${packedTexShape[0] > 1}_${packedTexShape[1] > 1}`;\n } else if (uniformShape.length === 2 && !program.packedInputs) {\n rank2 = `${uniformShape[0] > 1}_${uniformShape[1] > 1}`;\n } else if (uniformShape.length > 2 && !program.packedInputs) {\n const strides = util.computeStrides(uniformShape);\n rank34 = `${strides[0] === xTexShape[1]}_${\n strides[strides.length - 1] === xTexShape[1]}`;\n }\n const xRank = x.shape.length;\n const isLogicalShapTexShapeEqual =\n xRank === 2 && util.arraysEqual(x.shape, xTexShape);\n const isScalar = util.sizeFromShape(x.shape) === 1;\n const broadcastDims =\n backend_util.getBroadcastDims(x.shape, output.shape);\n const isInOutTexShapeEqual = !program.packedInputs &&\n xRank === output.shape.length &&\n util.arraysEqual(xTexShape, output.texData.texShape);\n const isTexShapeGreaterThanOne = program.packedInputs || xRank > 2 ?\n '' :\n `${xTexShape[0] > 1}_${xTexShape[1] > 1}`;\n // These key components are needed due to shader_compiler is embedding\n // them in the shader.\n // |xRank| is used to determine the coords length. See\n // get[Packed]SamplerAtOutputCoords.\n // |isInOutTexShapeEqual| is used to determine whether going to an\n // optimization path in getSamplerAtOutputCoords.\n // |useSqueezeShape| is extracted from squeezeInputInfo of\n // getSampler[2|3|4]D/getPackedSampler3D.\n // |isScalar| is extracted from isInputScalar/isOutputScalar in\n // getPackedSamplerAtOutputCoords.\n // |broadcastDims| is extracted from get[Packed]SamplerAtOutputCoords.\n // |isLogicalShapTexShapeEqual| is used in\n // getOutput[Packed]2DCoords/get[Packed]Sampler2D.\n // |rank1| is used in getOutputPacked1DCoords.\n // |rank2| is used in getOutput2DCoords.\n // |rank34| is used in getSampler3D/getSampler4D.\n // |isTexShapeGreaterThanOne| are used in\n // getSampler[Scalar|1D|2D]/getOutput1DCoords.\n keyInputs += `${xRank}_${isInOutTexShapeEqual}_${useSqueezeShape}_${\n uniformShape.length}_${isScalar}_${broadcastDims}_${\n isLogicalShapTexShapeEqual}_${rank1}_${rank2}_${rank34}_${\n isTexShapeGreaterThanOne}_${hasOffset}`;\n } else {\n const texShape = x.isUniform ? 'uniform' : x.texData.texShape;\n keyInputs += `${x.shape}_${texShape}_${hasOffset}`;\n }\n });\n const keyUserCode = program.userCode;\n let key = program.constructor.name;\n // Fast string concat. See https://jsperf.com/string-concatenation/14.\n key += '_' + keyInputs + '_' + keyUserCode +\n `${env().getNumber('WEBGL_VERSION')}`;\n return key;\n}\n\nexport function useShapeUniforms(rank: number) {\n // TODO: Remove the limitaion of rank <= 4.\n return env().getBool('WEBGL_USE_SHAPES_UNIFORMS') && rank <= 4;\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\n// Import shared functionality from tfjs-backend-cpu without triggering\n// side effects.\n// tslint:disable-next-line: no-imports-from-dist\nimport * as shared from '@tensorflow/tfjs-backend-cpu/dist/shared';\n// tslint:disable-next-line: no-imports-from-dist\nimport {SimpleBinaryKernelImpl} from '@tensorflow/tfjs-backend-cpu/dist/shared';\n// tslint:disable-next-line: no-imports-from-dist\nimport {SimpleUnaryImpl} from '@tensorflow/tfjs-backend-cpu/dist/utils/unary_types';\n\nexport type SimpleBinaryKernelImplCPU = SimpleBinaryKernelImpl;\nexport type SimpleUnaryKernelImplCPU = SimpleUnaryImpl;\nconst {\n addImpl: addImplCPU,\n bincountImpl: bincountImplCPU,\n bincountReduceImpl: bincountReduceImplCPU,\n ceilImpl: ceilImplCPU,\n concatImpl: concatImplCPU,\n equalImpl: equalImplCPU,\n expImpl: expImplCPU,\n expm1Impl: expm1ImplCPU,\n floorImpl: floorImplCPU,\n gatherNdImpl: gatherNdImplCPU,\n gatherV2Impl: gatherV2ImplCPU,\n greaterImpl: greaterImplCPU,\n greaterEqualImpl: greaterEqualImplCPU,\n lessImpl: lessImplCPU,\n lessEqualImpl: lessEqualImplCPU,\n linSpaceImpl: linSpaceImplCPU,\n logImpl: logImplCPU,\n maxImpl: maxImplCPU,\n maximumImpl: maximumImplCPU,\n minimumImpl: minimumImplCPU,\n multiplyImpl: multiplyImplCPU,\n negImpl: negImplCPU,\n notEqualImpl: notEqualImplCPU,\n prodImpl: prodImplCPU,\n rangeImpl: rangeImplCPU,\n rsqrtImpl: rsqrtImplCPU,\n simpleAbsImpl: simpleAbsImplCPU,\n sliceImpl: sliceImplCPU,\n sparseFillEmptyRowsImpl: sparseFillEmptyRowsImplCPU,\n sparseReshapeImpl: sparseReshapeImplCPU,\n sparseSegmentReductionImpl: sparseSegmentReductionImplCPU,\n stridedSliceImpl: stridedSliceImplCPU,\n stringNGramsImpl: stringNGramsImplCPU,\n stringSplitImpl: stringSplitImplCPU,\n stringToHashBucketFastImpl: stringToHashBucketFastImplCPU,\n subImpl: subImplCPU,\n tileImpl: tileImplCPU,\n topKImpl: topKImplCPU,\n transposeImpl: transposeImplCPU,\n uniqueImpl: uniqueImplCPU,\n} = shared;\n\nexport {\n addImplCPU,\n bincountImplCPU,\n bincountReduceImplCPU,\n ceilImplCPU,\n concatImplCPU,\n equalImplCPU,\n expImplCPU,\n expm1ImplCPU,\n floorImplCPU,\n gatherNdImplCPU,\n gatherV2ImplCPU,\n greaterEqualImplCPU,\n greaterImplCPU,\n lessEqualImplCPU,\n lessImplCPU,\n linSpaceImplCPU,\n logImplCPU,\n maxImplCPU,\n maximumImplCPU,\n minimumImplCPU,\n multiplyImplCPU,\n negImplCPU,\n notEqualImplCPU,\n prodImplCPU,\n simpleAbsImplCPU,\n sliceImplCPU,\n sparseFillEmptyRowsImplCPU,\n sparseReshapeImplCPU,\n sparseSegmentReductionImplCPU,\n stridedSliceImplCPU,\n stringNGramsImplCPU,\n stringSplitImplCPU,\n stringToHashBucketFastImplCPU,\n subImplCPU,\n rangeImplCPU,\n rsqrtImplCPU,\n tileImplCPU,\n topKImplCPU,\n transposeImplCPU,\n uniqueImplCPU,\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 function getVecChannels(name: string, rank: number): string[] {\n return ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank).map(d => `${name}.${d}`);\n}\n\nexport function getChannels(name: string, rank: number): string[] {\n if (rank === 1) {\n return [name];\n }\n return getVecChannels(name, rank);\n}\n\nexport function getSourceCoords(rank: number, dims: string[]): string {\n if (rank === 1) {\n return 'rc';\n }\n\n let coords = '';\n for (let i = 0; i < rank; i++) {\n coords += dims[i];\n if (i < rank - 1) {\n coords += ',';\n }\n }\n return coords;\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 {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class PackProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n packedInputs = false;\n packedOutput = true;\n\n constructor(\n outputShape:\n number[]) { // TODO(https://github.com/tensorflow/tfjs/issues/893):\n // Only input / output 3D tensors.\n this.outputShape = outputShape;\n const rank = outputShape.length;\n\n if (rank === 0) {\n this.userCode = `\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n `;\n } else {\n const channels = getChannels('rc', rank);\n const dtype = getCoordsDataType(rank);\n const outOfBoundsCondition =\n getOutOfBoundsCondition(rank, outputShape, channels);\n const setup = getSetup(\n rank, outputShape[outputShape.length - 1],\n outputShape[outputShape.length - 2], channels);\n const output = getOutput(outputShape, channels);\n\n this.userCode = `\n void main() {\n ${dtype} rc = getOutputCoords();\n\n if(${outOfBoundsCondition}) {\n setOutput(vec4(0));\n } else {\n ${setup}\n\n setOutput(vec4(${output}));\n }\n }\n `;\n }\n }\n}\n\nfunction getSourceCoordsArr(rank: number, dims: string[]): string[] {\n const coords = [];\n\n for (let row = 0; row <= 1; row++) {\n for (let col = 0; col <= 1; col++) {\n let coord = `${row === 0 ? 'r' : 'rp1'}, ${col === 0 ? 'c' : 'cp1'}`;\n\n for (let d = 2; d < rank; d++) {\n coord = `${dims[dims.length - 1 - d]},` + coord;\n }\n\n coords.push(coord);\n }\n }\n return coords;\n}\n\nfunction getOutOfBoundsCondition(\n rank: number, shape: number[], dims: string[]): string {\n if (rank === 1) {\n return `rc > ${shape[0]}`;\n }\n\n let cond = '';\n for (let i = rank - 2; i < rank; i++) {\n cond += `${dims[i]} >= ${shape[i]}`;\n if (i < rank - 1) {\n cond += '||';\n }\n }\n\n return cond;\n}\n\nfunction getSetup(\n rank: number, cols: number, rows: number, dims: string[]): string {\n if (rank === 1) {\n return '';\n }\n\n const innerDims = dims.slice(-2);\n\n return `\n int r = ${innerDims[0]};\n int c = ${innerDims[1]};\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= ${cols};\n bool rEdge = rp1 >= ${rows};\n `;\n}\n\nfunction getOutput(shape: number[], dims: string[]): string {\n const rank = shape.length;\n const sourceCoords = getSourceCoordsArr(rank, dims);\n if (rank === 1) {\n return `getA(rc),\n rc + 1 >= ${shape[0]} ? 0. : getA(rc + 1),\n 0, 0`;\n }\n\n return `getA(${sourceCoords[0]}),\n cEdge ? 0. : getA(${sourceCoords[1]}),\n rEdge ? 0. : getA(${sourceCoords[2]}),\n rEdge || cEdge ? 0. : getA(${sourceCoords[3]})`;\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 {GPGPUProgram} from './gpgpu_math';\nimport * as shader_util from './shader_compiler_util';\n\nexport class ReshapePackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(outputShape: [number, number, number], inputShape: [\n number, number, number\n ]) {\n this.outputShape = outputShape;\n\n let mainLoop = ``;\n for (let i = 0; i < 4; i++) {\n let thisRC = `thisRC = rc;`;\n if (i % 2 === 1) {\n thisRC += `thisRC.z += 1;`;\n }\n if (i > 1) {\n thisRC += `thisRC.y += 1;`;\n }\n\n mainLoop += `\n ${thisRC}\n ${i > 0 ? `if(thisRC.y < rows && thisRC.z < cols){` : ''}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${i}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${i > 0 ? '}' : ''}\n `;\n }\n\n this.userCode = `\n ${getReshapedInputCoords(inputShape)}\n ${shader_util.getFlatIndexFrom3D(outputShape)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${outputShape[1]};\n int cols = ${outputShape[2]};\n\n ${mainLoop}\n\n setOutput(result);\n }\n `;\n }\n}\n\nfunction getReshapedInputCoords(shape: [number, number, number]): string {\n const coordsFromIndexSnippet =\n shader_util.getLogicalCoordinatesFromFlatIndex(['r', 'c', 'd'], shape);\n\n return `\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${coordsFromIndexSnippet}\n return ivec3(r, c, d);\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\nimport {env} from '@tensorflow/tfjs-core';\n\nimport {GPGPUContext} from './gpgpu_context';\nimport {getInternalFormatForFloat16MatrixTexture, getInternalFormatForFloat16PackedMatrixTexture, getInternalFormatForFloat32MatrixTexture, getInternalFormatForPackedMatrixTexture, getInternalFormatForUnsignedBytesMatrixTexture} from './gpgpu_util';\nimport {getPackedMatrixTextureShapeWidthHeight, getUnpackedMatrixTextureShapeWidthHeight, PhysicalTextureType, TextureConfig, TextureUsage} from './tex_util';\n\nexport class TextureManager {\n private numUsedTextures = 0;\n private numFreeTextures = 0;\n private _numBytesAllocated = 0;\n private _numBytesFree = 0; // How many bytes that have been allocated\n // are available for reuse.\n private freeTextures: {[shape: string]: WebGLTexture[]} = {};\n private logEnabled = false;\n private usedTextures: {[shape: string]: WebGLTexture[]} = {};\n\n constructor(private gpgpu: GPGPUContext) {}\n\n acquireTexture(\n shapeRC: [number, number], usage: TextureUsage,\n isPacked: boolean): WebGLTexture {\n const physicalTexType = getPhysicalFromLogicalTextureType(usage, isPacked);\n\n const shapeKey = getKeyFromTextureShape(shapeRC, physicalTexType, isPacked);\n if (!(shapeKey in this.freeTextures)) {\n this.freeTextures[shapeKey] = [];\n }\n if (!(shapeKey in this.usedTextures)) {\n this.usedTextures[shapeKey] = [];\n }\n\n const texBytes = computeBytes(\n shapeRC, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig,\n isPacked);\n\n if (this.freeTextures[shapeKey].length > 0) {\n this.numFreeTextures--;\n this.numUsedTextures++;\n this._numBytesFree -= texBytes;\n this.log();\n const newTexture = this.freeTextures[shapeKey].shift();\n this.usedTextures[shapeKey].push(newTexture);\n return newTexture;\n }\n\n let newTexture: WebGLTexture;\n if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT32) {\n newTexture = this.gpgpu.createPackedMatrixTexture(shapeRC[0], shapeRC[1]);\n } else if (physicalTexType === PhysicalTextureType.PACKED_2X2_FLOAT16) {\n newTexture =\n this.gpgpu.createFloat16PackedMatrixTexture(shapeRC[0], shapeRC[1]);\n } else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT32) {\n newTexture =\n this.gpgpu.createFloat32MatrixTexture(shapeRC[0], shapeRC[1]);\n } else if (physicalTexType === PhysicalTextureType.UNPACKED_FLOAT16) {\n newTexture =\n this.gpgpu.createFloat16MatrixTexture(shapeRC[0], shapeRC[1]);\n } else if (\n physicalTexType === PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE) {\n newTexture =\n this.gpgpu.createUnsignedBytesMatrixTexture(shapeRC[0], shapeRC[1]);\n }\n this.usedTextures[shapeKey].push(newTexture);\n\n this.numUsedTextures++;\n this._numBytesAllocated += texBytes;\n this.log();\n\n return newTexture;\n }\n\n releaseTexture(\n texture: WebGLTexture, shape: [number, number],\n logicalTexType: TextureUsage, isPacked: boolean): void {\n if (this.freeTextures == null) {\n // Already disposed.\n return;\n }\n const physicalTexType =\n getPhysicalFromLogicalTextureType(logicalTexType, isPacked);\n const shapeKey = getKeyFromTextureShape(shape, physicalTexType, isPacked);\n if (!(shapeKey in this.freeTextures)) {\n this.freeTextures[shapeKey] = [];\n }\n\n const texBytes = computeBytes(\n shape, physicalTexType, this.gpgpu.gl, this.gpgpu.textureConfig,\n isPacked);\n const deleteTexThreshold = env().get('WEBGL_DELETE_TEXTURE_THRESHOLD');\n if (deleteTexThreshold !== -1 &&\n this._numBytesAllocated > deleteTexThreshold) {\n this.gpgpu.deleteMatrixTexture(texture);\n this._numBytesAllocated -= texBytes;\n } else {\n this.freeTextures[shapeKey].push(texture);\n this.numFreeTextures++;\n this._numBytesFree += texBytes;\n }\n\n this.numUsedTextures--;\n\n const texList = this.usedTextures[shapeKey];\n const texIndex = texList.indexOf(texture);\n if (texIndex < 0) {\n throw new Error(\n 'Cannot release a texture that was never provided by this ' +\n 'texture manager');\n }\n texList.splice(texIndex, 1);\n this.log();\n }\n\n private log() {\n if (!this.logEnabled) {\n return;\n }\n const total = this.numFreeTextures + this.numUsedTextures;\n console.log(\n 'Free/Used', `${this.numFreeTextures} / ${this.numUsedTextures}`,\n `(${total})`);\n const freeRatio = this._numBytesFree / this._numBytesAllocated;\n console.log(`Bytes allocated: ${this._numBytesAllocated}`);\n console.log(`Bytes unused: ${this._numBytesFree} (${\n Math.round(100 * freeRatio)}%)`);\n }\n\n get numBytesAllocated(): number {\n return this._numBytesAllocated;\n }\n\n get numBytesFree(): number {\n return this._numBytesFree;\n }\n\n getNumUsedTextures(): number {\n return this.numUsedTextures;\n }\n\n getNumFreeTextures(): number {\n return this.numFreeTextures;\n }\n\n dispose() {\n if (this.freeTextures == null) {\n // Already disposed.\n return;\n }\n for (const texShape in this.freeTextures) {\n this.freeTextures[texShape].forEach(tex => {\n this.gpgpu.deleteMatrixTexture(tex);\n });\n }\n for (const texShape in this.usedTextures) {\n this.usedTextures[texShape].forEach(tex => {\n this.gpgpu.deleteMatrixTexture(tex);\n });\n }\n this.freeTextures = null;\n this.usedTextures = null;\n this.numUsedTextures = 0;\n this.numFreeTextures = 0;\n this._numBytesAllocated = 0;\n this._numBytesFree = 0;\n }\n}\n\nfunction numBytesForInternalFormat(\n gl: WebGLRenderingContext, internalFormat: number): number {\n // tslint:disable-next-line:no-any\n const glany = gl as any;\n if (internalFormat === glany.R32F) {\n return 4;\n } else if (internalFormat === glany.R16F) {\n return 2;\n } else if (internalFormat === glany.RGBA32F) {\n return 16;\n } else if (internalFormat === gl.RGBA) {\n return 16;\n } else if (internalFormat === glany.RGBA16F) {\n return 8;\n }\n throw new Error(`Unknown internal format ${internalFormat}`);\n}\n\nexport function computeBytes(\n shape: [number, number], physicalTexType: PhysicalTextureType,\n gl: WebGLRenderingContext, textureConfig: TextureConfig,\n isPacked: boolean): number {\n // It is not possible to infer packed status from the texture type because\n // depending on the textureConfig, different texture types may resolve to the\n // same internal format (e.g. in WebGL1, the internal format for\n // UNPACKED_FLOAT16 textures is gl.RGBA). Therefore we pass in `isPacked`\n // explicitly.\n const internalFormat =\n internalFormatForPhysicalTexType(physicalTexType, textureConfig);\n\n let numElements: number;\n if (isPacked) {\n const [packedWidth, packedHeight] =\n getPackedMatrixTextureShapeWidthHeight(shape[0], shape[1]);\n numElements = packedWidth * packedHeight;\n\n } else {\n const [width, height] =\n getUnpackedMatrixTextureShapeWidthHeight(shape[0], shape[1]);\n numElements = width * height;\n }\n\n const bytesPerElement = numBytesForInternalFormat(gl, internalFormat);\n return numElements * bytesPerElement;\n}\n\nfunction internalFormatForPhysicalTexType(\n physicalTexType: PhysicalTextureType,\n textureConfig: TextureConfig): number {\n switch (physicalTexType) {\n case PhysicalTextureType.PACKED_2X2_FLOAT32:\n return getInternalFormatForPackedMatrixTexture(textureConfig);\n case PhysicalTextureType.PACKED_2X2_FLOAT16:\n return getInternalFormatForFloat16PackedMatrixTexture(textureConfig);\n case PhysicalTextureType.UNPACKED_FLOAT32:\n return getInternalFormatForFloat32MatrixTexture(textureConfig);\n case PhysicalTextureType.UNPACKED_FLOAT16:\n return getInternalFormatForFloat16MatrixTexture(textureConfig);\n case PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE:\n return getInternalFormatForUnsignedBytesMatrixTexture(textureConfig);\n default:\n throw new Error(`Unknown physical texture type ${physicalTexType}`);\n }\n}\n\nfunction getPhysicalTextureForRendering(isPacked: boolean):\n PhysicalTextureType {\n if (env().getBool('WEBGL_RENDER_FLOAT32_ENABLED')) {\n if (isPacked) {\n return PhysicalTextureType.PACKED_2X2_FLOAT32;\n }\n return PhysicalTextureType.UNPACKED_FLOAT32;\n }\n\n if (isPacked) {\n return PhysicalTextureType.PACKED_2X2_FLOAT16;\n }\n return PhysicalTextureType.UNPACKED_FLOAT16;\n}\n\nfunction getPhysicalFromLogicalTextureType(\n logicalTexType: TextureUsage, isPacked: boolean): PhysicalTextureType {\n if (logicalTexType === TextureUsage.UPLOAD) {\n return PhysicalTextureType.PACKED_2X2_FLOAT32;\n } else if (logicalTexType === TextureUsage.RENDER || logicalTexType == null) {\n return getPhysicalTextureForRendering(isPacked);\n } else if (\n logicalTexType === TextureUsage.DOWNLOAD ||\n logicalTexType === TextureUsage.PIXELS) {\n return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE;\n }\n throw new Error(`Unknown logical texture type ${logicalTexType}`);\n}\n\nfunction getKeyFromTextureShape(\n shapeRowsCol: [number, number], physicalTexType: PhysicalTextureType,\n isPacked: boolean): string {\n return `${shapeRowsCol[0]}_${shapeRowsCol[1]}_${physicalTexType}_${isPacked}`;\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 {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\n\nexport class UnaryOpProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n enableShapeUniforms: boolean;\n\n constructor(aShape: number[], opSnippet: string) {\n this.outputShape = aShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n this.userCode = `\n float unaryOperation(float x) {\n ${opSnippet}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `;\n }\n}\n\nexport const CHECK_NAN_SNIPPET = `if (isnan(x)) return x;`;\n\nexport const LINEAR = `return x;`;\n\nexport const ABS = `return abs(x);`;\n\nexport function STEP(alpha = 0.0) {\n return CHECK_NAN_SNIPPET + `\n return x > 0.0 ? 1.0 : float(${alpha});\n `;\n}\n\nexport const ELU = `return (x >= 0.0) ? x : (exp(x) - 1.0);`;\nexport const RELU = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : x;\n`;\n\nexport const RELU6 = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : min(6.0, x);\n`;\n\nexport const CLONE = 'return x;';\n\nexport const SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;\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 {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\n\nexport const LINEAR = `return x;`;\n\nexport const ELU = `\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n`;\n\nexport const RELU = `\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const RELU6 = `\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;\n\nexport class UnaryOpPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n enableShapeUniforms: boolean;\n outputShape: number[];\n packedInputs = true;\n packedOutput = true;\n\n constructor(aShape: number[], opSnippet: string) {\n this.outputShape = aShape;\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n this.userCode = `\n vec4 unaryOperation(vec4 x) {\n ${opSnippet}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\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 {GPGPUProgram} from './gpgpu_math';\nimport {getChannels, getSourceCoords} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class UnpackProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = false;\n outputShape: number[];\n userCode: string;\n\n constructor(outputShape: number[]) {\n this.outputShape = outputShape;\n const rank = outputShape.length;\n\n const channels = getChannels('rc', rank);\n const dtype = getCoordsDataType(rank);\n const sourceCoords = getSourceCoords(rank, channels);\n const innerDims = channels.slice(-2);\n const coords = rank <= 1 ? 'rc' : `vec2(${innerDims.join(',')})`;\n\n this.userCode = `\n void main() {\n ${dtype} rc = getOutputCoords();\n vec4 packedInput = getA(${sourceCoords});\n\n setOutput(getChannel(packedInput, ${coords}));\n }\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// Import webgl flags.\nimport './flags_webgl';\n\nimport * as tf from '@tensorflow/tfjs-core';\nimport {backend_util, BackendValues, buffer, DataId, DataStorage, DataType, DataValues, engine, env, kernel_impls, KernelBackend, MemoryInfo, NumericDataType, Rank, RecursiveArray, scalar, ShapeMap, Tensor, Tensor2D, TensorBuffer, TensorInfo, tidy, TimingInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {getWebGLContext} from './canvas_util';\nimport {DecodeMatrixProgram} from './decode_matrix_gpu';\nimport {DecodeMatrixPackedProgram} from './decode_matrix_packed_gpu';\nimport {EncodeFloatProgram} from './encode_float_gpu';\nimport {EncodeFloatPackedProgram} from './encode_float_packed_gpu';\nimport {EncodeMatrixProgram} from './encode_matrix_gpu';\nimport {EncodeMatrixPackedProgram} from './encode_matrix_packed_gpu';\nimport {GPGPUContext} from './gpgpu_context';\nimport * as gpgpu_math from './gpgpu_math';\nimport {GPGPUBinary, GPGPUProgram, TensorData} from './gpgpu_math';\nimport {simpleAbsImplCPU} from './kernel_utils/shared';\nimport {PackProgram} from './pack_gpu';\nimport {ReshapePackedProgram} from './reshape_packed_gpu';\nimport * as tex_util from './tex_util';\nimport {TextureData, TextureUsage} from './tex_util';\nimport {TextureManager} from './texture_manager';\nimport * as unary_op from './unaryop_gpu';\nimport {UnaryOpProgram} from './unaryop_gpu';\nimport {UnaryOpPackedProgram} from './unaryop_packed_gpu';\nimport {UnpackProgram} from './unpack_gpu';\nimport * as webgl_util from './webgl_util';\n\nconst whereImpl = kernel_impls.whereImpl;\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\ntype KernelInfo = {\n name: string; query: Promise<number>;\n};\n\nexport type TimerNode = RecursiveArray<KernelInfo>|KernelInfo;\nexport interface CPUTimerQuery {\n startMs: number;\n endMs?: number;\n}\n\nexport interface WebGLMemoryInfo extends MemoryInfo {\n numBytesInGPU: number;\n // Tracks the total number of bytes allocated on the GPU, accounting for the\n // physical texture type.\n numBytesInGPUAllocated: number;\n // Tracks byte size of textures that were created and then made available for\n // reuse (disposed).\n numBytesInGPUFree: number;\n unreliable: boolean;\n}\n\nexport interface WebGLTimingInfo extends TimingInfo {\n uploadWaitMs: number;\n downloadWaitMs: number;\n}\n\nconst binaryCaches: {[webGLVersion: string]: {[key: string]: GPGPUBinary}} = {};\n\nexport function getBinaryCache(webGLVersion: number) {\n if (webGLVersion in binaryCaches) {\n return binaryCaches[webGLVersion];\n }\n binaryCaches[webGLVersion] = {};\n return binaryCaches[webGLVersion];\n}\n\n// Empirically determined constant used to determine size threshold for handing\n// off execution to the CPU.\nconst CPU_HANDOFF_SIZE_THRESHOLD =\n env().getNumber('CPU_HANDOFF_SIZE_THRESHOLD');\n\n// Empirically determined constant used to decide the number of MB on GPU\n// before we warn about high memory use. The MB are this constant * screen area\n// * dpi / 1024 / 1024.\nconst BEFORE_PAGING_CONSTANT = 600;\nfunction numMBBeforeWarning(): number {\n if (env().global.screen == null) {\n return 1024; // 1 GB.\n }\n return (env().global.screen.height * env().global.screen.width *\n window.devicePixelRatio) *\n BEFORE_PAGING_CONSTANT / 1024 / 1024;\n}\n\nexport class MathBackendWebGL extends KernelBackend {\n texData: DataStorage<TextureData>;\n gpgpu: GPGPUContext;\n\n private static nextDataId = 0;\n private nextDataId(): number {\n return MathBackendWebGL.nextDataId++;\n }\n // Maps data ids that have a pending read operation, to list of subscribers.\n private pendingRead = new WeakMap<DataId, Array<(arr: TypedArray) => void>>();\n // List of data ids that are scheduled for disposal, but are waiting on a\n // pending read operation.\n private pendingDisposal = new WeakSet<DataId>();\n\n // Used to count the number of 'shallow' sliced tensors that point to the\n // same data id.\n dataRefCount = new WeakMap<DataId, number>();\n private numBytesInGPU = 0;\n\n private canvas: HTMLCanvasElement|OffscreenCanvas;\n\n private programTimersStack: TimerNode[];\n private activeTimers: TimerNode[];\n // Accumulated time spent (including blocking) in uploading data to webgl.\n private uploadWaitMs = 0;\n // Accumulated time spent (including blocking in downloading data from webgl.\n private downloadWaitMs = 0;\n\n // record the last manual GL Flush time.\n private lastGlFlushTime = 0;\n\n // Number of bits of precision of this backend.\n private floatPrecisionValue: 32|16;\n\n private textureManager: TextureManager;\n private binaryCache: {[key: string]: GPGPUBinary};\n private gpgpuCreatedLocally: boolean;\n private numMBBeforeWarning: number;\n private warnedAboutMemory = false;\n\n constructor(gpgpu?: GPGPUContext) {\n super();\n if (!env().getBool('HAS_WEBGL')) {\n throw new Error('WebGL is not supported on this device');\n }\n\n if (gpgpu == null) {\n const gl = getWebGLContext(env().getNumber('WEBGL_VERSION'));\n this.binaryCache = getBinaryCache(env().getNumber('WEBGL_VERSION'));\n this.gpgpu = new GPGPUContext(gl);\n this.canvas = gl.canvas;\n this.gpgpuCreatedLocally = true;\n } else {\n this.gpgpu = gpgpu;\n this.binaryCache = {};\n this.gpgpuCreatedLocally = false;\n this.canvas = gpgpu.gl.canvas;\n }\n this.textureManager = new TextureManager(this.gpgpu);\n this.numMBBeforeWarning = numMBBeforeWarning();\n\n this.texData = new DataStorage(this, engine());\n }\n\n numDataIds() {\n return this.texData.numDataIds() - this.pendingDeletes;\n }\n\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n if (env().getBool('WEBGL_CHECK_NUMERICAL_PROBLEMS') ||\n env().getBool('DEBUG')) {\n this.checkNumericalProblems(values);\n }\n if (dtype === 'complex64' && values != null) {\n throw new Error(\n `Cannot write to a complex64 dtype. ` +\n `Please use tf.complex(real, imag).`);\n }\n const dataId = {id: this.nextDataId()};\n this.texData.set(\n dataId,\n {shape, dtype, values, usage: TextureUsage.UPLOAD, refCount: 1});\n return dataId;\n }\n\n /** Return refCount of a `TensorData`. */\n refCount(dataId: DataId): number {\n if (this.texData.has(dataId)) {\n const tensorData = this.texData.get(dataId);\n return tensorData.refCount;\n }\n return 0;\n }\n\n /** Increase refCount of a `TextureData`. */\n incRef(dataId: DataId): void {\n const texData = this.texData.get(dataId);\n texData.refCount++;\n }\n\n /** Decrease refCount of a `TextureData`. */\n decRef(dataId: DataId): void {\n if (this.texData.has(dataId)) {\n const texData = this.texData.get(dataId);\n texData.refCount--;\n }\n }\n\n move(\n dataId: DataId, values: BackendValues, shape: number[], dtype: DataType,\n refCount: number): void {\n if (env().getBool('DEBUG')) {\n this.checkNumericalProblems(values);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `Cannot write to a complex64 dtype. ` +\n `Please use tf.complex(real, imag).`);\n }\n this.texData.set(\n dataId, {shape, dtype, values, usage: TextureUsage.UPLOAD, refCount});\n }\n\n disposeIntermediateTensorInfo(tensorInfo: TensorInfo): void {\n this.disposeData(tensorInfo.dataId);\n }\n\n readSync(dataId: DataId): BackendValues {\n const texData = this.texData.get(dataId);\n const {values, dtype, complexTensorInfos, slice, shape, isPacked} = texData;\n\n // The presence of `slice` indicates this tensor is a shallow slice of a\n // different tensor, and is using that original tensor's texture. Run\n // `clone` in order to copy that texture and read from it.\n if (slice != null) {\n let program;\n if (isPacked) {\n program = new UnaryOpPackedProgram(shape, unary_op.CLONE);\n } else {\n program = new UnaryOpProgram(shape, unary_op.CLONE);\n }\n const res =\n this.runWebGLProgram(program, [{dataId, shape, dtype}], dtype);\n const data = this.readSync(res.dataId);\n this.disposeIntermediateTensorInfo(res);\n return data;\n }\n if (values != null) {\n return this.convertAndCacheOnCPU(dataId);\n }\n if (dtype === 'string') {\n return values;\n }\n const shouldTimeProgram = this.activeTimers != null;\n let start: number;\n if (shouldTimeProgram) {\n start = util.now();\n }\n\n let result: Float32Array;\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 result = backend_util.mergeRealAndImagArrays(realValues, imagValues);\n } else {\n result = this.getValuesFromTexture(dataId);\n }\n\n if (shouldTimeProgram) {\n this.downloadWaitMs += util.now() - start;\n }\n return this.convertAndCacheOnCPU(dataId, result);\n }\n\n async read(dataId: DataId): Promise<BackendValues> {\n if (this.pendingRead.has(dataId)) {\n const subscribers = this.pendingRead.get(dataId);\n return new Promise<TypedArray>(resolve => subscribers.push(resolve));\n }\n const texData = this.texData.get(dataId);\n const {values, shape, slice, dtype, complexTensorInfos, isPacked} = texData;\n\n // The presence of `slice` indicates this tensor is a shallow slice of a\n // different tensor, and is using that original tensor's texture. Run\n // `clone` in order to copy that texture and read from it.\n if (slice != null) {\n let program;\n if (isPacked) {\n program = new UnaryOpPackedProgram(shape, unary_op.CLONE);\n } else {\n program = new UnaryOpProgram(shape, unary_op.CLONE);\n }\n const res =\n this.runWebGLProgram(program, [{dataId, shape, dtype}], dtype);\n const data = this.read(res.dataId);\n this.disposeIntermediateTensorInfo(res);\n return data;\n }\n\n if (values != null) {\n return this.convertAndCacheOnCPU(dataId);\n }\n\n if (!env().getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED') &&\n env().getNumber('WEBGL_VERSION') === 2) {\n throw new Error(\n `tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and ` +\n `WEBGL_VERSION=2 not yet supported.`);\n }\n\n let buffer: WebGLBuffer = null;\n let tmpDownloadTarget: TensorInfo;\n\n if (dtype !== 'complex64' && env().get('WEBGL_BUFFER_SUPPORTED')) {\n // Possibly copy the texture into a buffer before inserting a fence.\n tmpDownloadTarget = this.decode(dataId);\n const tmpData = this.texData.get(tmpDownloadTarget.dataId);\n\n buffer = this.gpgpu.createBufferFromTexture(\n tmpData.texture, ...tex_util.getDenseTexShape(shape));\n }\n\n this.pendingRead.set(dataId, []);\n\n if (dtype !== 'complex64') {\n // Create a fence and wait for it to resolve.\n await this.gpgpu.createAndWaitForFence();\n }\n\n // Download the values from the GPU.\n let vals: Float32Array;\n if (dtype === 'complex64') {\n const ps = await Promise.all([\n this.read(complexTensorInfos.real.dataId),\n this.read(complexTensorInfos.imag.dataId)\n ]);\n\n const realValues = ps[0];\n const imagValues = ps[1];\n vals = backend_util.mergeRealAndImagArrays(\n realValues as Float32Array, imagValues as Float32Array);\n } else if (buffer == null) {\n vals = this.getValuesFromTexture(dataId);\n } else {\n const size = util.sizeFromShape(shape);\n vals = this.gpgpu.downloadFloat32MatrixFromBuffer(buffer, size);\n }\n if (tmpDownloadTarget != null) {\n this.disposeIntermediateTensorInfo(tmpDownloadTarget);\n }\n if (buffer != null) {\n const gl = this.gpgpu.gl;\n webgl_util.callAndCheck(gl, () => gl.deleteBuffer(buffer));\n }\n const dTypeVals = this.convertAndCacheOnCPU(dataId, vals);\n\n const subscribers = this.pendingRead.get(dataId);\n this.pendingRead.delete(dataId);\n\n // Notify all pending reads.\n subscribers.forEach(resolve => resolve(dTypeVals));\n if (this.pendingDisposal.has(dataId)) {\n this.pendingDisposal.delete(dataId);\n if (this.disposeData(dataId)) {\n engine().removeDataId(dataId, this);\n }\n this.pendingDeletes--;\n }\n return dTypeVals;\n }\n\n bufferSync<R extends Rank>(t: TensorInfo): TensorBuffer<R> {\n const data = this.readSync(t.dataId);\n let decodedData = data as DataValues;\n if (t.dtype === 'string') {\n try {\n // Decode the bytes into string.\n decodedData = (data as Uint8Array[]).map(d => util.decodeString(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, decodedData) as\n TensorBuffer<R>;\n }\n\n private checkNumericalProblems(values: BackendValues): void {\n if (values == null) {\n return;\n }\n for (let i = 0; i < values.length; i++) {\n const num = values[i] as number;\n if (!webgl_util.canBeRepresented(num)) {\n if (env().getBool('WEBGL_RENDER_FLOAT32_CAPABLE')) {\n throw Error(\n `The value ${num} cannot be represented with your ` +\n `current settings. Consider enabling float32 rendering: ` +\n `'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);\n }\n throw Error(`The value ${num} cannot be represented on this device.`);\n }\n }\n }\n\n private getValuesFromTexture(dataId: DataId): Float32Array {\n const {shape, dtype, isPacked} = this.texData.get(dataId);\n const size = util.sizeFromShape(shape);\n if (env().getBool('WEBGL_DOWNLOAD_FLOAT_ENABLED')) {\n const tmpTarget = this.decode(dataId);\n const tmpData = this.texData.get(tmpTarget.dataId);\n const vals = this.gpgpu\n .downloadMatrixFromPackedTexture(\n tmpData.texture, ...tex_util.getDenseTexShape(shape))\n .subarray(0, size);\n\n this.disposeIntermediateTensorInfo(tmpTarget);\n\n return vals;\n }\n\n const shouldUsePackedProgram =\n env().getBool('WEBGL_PACK') && isPacked === true;\n const outputShape =\n shouldUsePackedProgram ? webgl_util.getShapeAs3D(shape) : shape;\n const program = shouldUsePackedProgram ?\n new EncodeFloatPackedProgram(outputShape as [number, number, number]) :\n new EncodeFloatProgram(outputShape);\n const output = this.runWebGLProgram(\n program, [{shape: outputShape, dtype, dataId}], 'float32');\n const tmpData = this.texData.get(output.dataId);\n const vals =\n this.gpgpu\n .downloadByteEncodedFloatMatrixFromOutputTexture(\n tmpData.texture, tmpData.texShape[0], tmpData.texShape[1])\n .subarray(0, size);\n this.disposeIntermediateTensorInfo(output);\n\n return vals;\n }\n\n timerAvailable(): boolean {\n return env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0;\n }\n\n async time(f: () => void): Promise<WebGLTimingInfo> {\n const oldActiveTimers = this.activeTimers;\n const newActiveTimers: TimerNode[] = [];\n\n let outerMostTime = false;\n if (this.programTimersStack == null) {\n this.programTimersStack = newActiveTimers;\n outerMostTime = true;\n } else {\n this.activeTimers.push(newActiveTimers);\n }\n this.activeTimers = newActiveTimers;\n\n f();\n\n // needing to split these up because util.flatten only accepts certain types\n const flattenedActiveTimerQueries =\n util.flatten(this.activeTimers.map((d: KernelInfo) => d.query))\n .filter(d => d != null);\n const flattenedActiveTimerNames =\n util.flatten(this.activeTimers.map((d: KernelInfo) => d.name))\n .filter(d => d != null);\n\n this.activeTimers = oldActiveTimers;\n\n if (outerMostTime) {\n this.programTimersStack = null;\n }\n\n const res: WebGLTimingInfo = {\n uploadWaitMs: this.uploadWaitMs,\n downloadWaitMs: this.downloadWaitMs,\n kernelMs: null,\n wallMs: null // will be filled by the engine\n };\n\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {\n const kernelMs = await Promise.all(flattenedActiveTimerQueries);\n\n res['kernelMs'] = util.sum(kernelMs);\n res['getExtraProfileInfo'] = () =>\n kernelMs.map((d, i) => ({name: flattenedActiveTimerNames[i], ms: d}))\n .map(d => `${d.name}: ${d.ms}`)\n .join(', ');\n } else {\n res['kernelMs'] = {\n error: 'WebGL query timers are not supported in this environment.'\n };\n }\n\n this.uploadWaitMs = 0;\n this.downloadWaitMs = 0;\n return res;\n }\n memory(): WebGLMemoryInfo {\n return {\n unreliable: false,\n numBytesInGPU: this.numBytesInGPU,\n numBytesInGPUAllocated: this.textureManager.numBytesAllocated,\n numBytesInGPUFree: this.textureManager.numBytesFree\n } as WebGLMemoryInfo;\n }\n\n private startTimer(): WebGLQuery|CPUTimerQuery {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {\n return this.gpgpu.beginQuery();\n }\n return {startMs: util.now(), endMs: null};\n }\n\n private endTimer(query: WebGLQuery|CPUTimerQuery): WebGLQuery|CPUTimerQuery {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {\n this.gpgpu.endQuery();\n return query;\n }\n (query as CPUTimerQuery).endMs = util.now();\n return query;\n }\n\n private async getQueryTime(query: WebGLQuery|CPUTimerQuery): Promise<number> {\n if (env().getNumber('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE') > 0) {\n return this.gpgpu.waitForQueryAndGetTime(query as WebGLQuery);\n }\n const timerQuery = query as CPUTimerQuery;\n return timerQuery.endMs - timerQuery.startMs;\n }\n\n private pendingDeletes = 0;\n\n /**\n * Decrease the RefCount on the dataId and dispose the memory if the dataId\n * has 0 refCount. If there are pending read on the data, the disposal would\n * added to the pending delete queue. Return true if the dataId is removed\n * from backend or the backend does not contain the dataId, false if the\n * dataId is not removed. Memory may or may not be released even when dataId\n * is removed, which also depends on dataRefCount, see `releaseGPU`.\n * @param dataId\n * @oaram force Optional, remove the data regardless of refCount\n */\n disposeData(dataId: DataId, force = false): boolean {\n if (this.pendingDisposal.has(dataId)) {\n return false;\n }\n\n // No-op if already disposed.\n if (!this.texData.has(dataId)) {\n return true;\n }\n\n // if force flag is set, change refCount to 0, this would ensure disposal\n // when added to the pendingDisposal queue. Memory may or may not be\n // released, which also depends on dataRefCount, see `releaseGPU`.\n if (force) {\n this.texData.get(dataId).refCount = 0;\n } else {\n this.texData.get(dataId).refCount--;\n }\n\n if (!force && this.texData.get(dataId).refCount > 0) {\n return false;\n }\n\n if (this.pendingRead.has(dataId)) {\n this.pendingDisposal.add(dataId);\n this.pendingDeletes++;\n return false;\n }\n\n this.releaseGPUData(dataId);\n const {complexTensorInfos} = this.texData.get(dataId);\n if (complexTensorInfos != null) {\n this.disposeData(complexTensorInfos.real.dataId, force);\n this.disposeData(complexTensorInfos.imag.dataId, force);\n }\n\n this.texData.delete(dataId);\n\n return true;\n }\n\n private releaseGPUData(dataId: DataId): void {\n const {texture, dtype, texShape, usage, isPacked, slice} =\n this.texData.get(dataId);\n const key = slice && slice.origDataId || dataId;\n const refCount = this.dataRefCount.get(key);\n\n if (refCount > 1) {\n this.dataRefCount.set(key, refCount - 1);\n } else {\n this.dataRefCount.delete(key);\n if (texture != null) {\n this.numBytesInGPU -= this.computeBytes(texShape, dtype);\n this.textureManager.releaseTexture(texture, texShape, usage, isPacked);\n }\n }\n\n const texData = this.texData.get(dataId);\n texData.texture = null;\n texData.texShape = null;\n texData.isPacked = false;\n texData.slice = null;\n }\n\n getTexture(dataId: DataId): WebGLTexture {\n this.uploadToGPU(dataId);\n return this.texData.get(dataId).texture;\n }\n\n /**\n * Returns internal information for the specific data bucket. Used in unit\n * tests.\n */\n getDataInfo(dataId: DataId): TextureData {\n return this.texData.get(dataId);\n }\n\n /*\n Tests whether all the inputs to an op are small and on the CPU. This heuristic\n determines when it would be faster to execute a kernel on the CPU. WebGL\n kernels opt into running this check and forwarding when appropriate.\n TODO(https://github.com/tensorflow/tfjs/issues/872): Develop a more\n sustainable strategy for optimizing backend execution of ops.\n */\n shouldExecuteOnCPU(\n inputs: TensorInfo[],\n sizeThreshold = CPU_HANDOFF_SIZE_THRESHOLD): boolean {\n return env().getBool('WEBGL_CPU_FORWARD') &&\n inputs.every(\n input => this.texData.get(input.dataId).texture == null &&\n util.sizeFromShape(input.shape) < sizeThreshold);\n }\n\n getGPGPUContext(): GPGPUContext {\n return this.gpgpu;\n }\n\n where(condition: Tensor): Tensor2D {\n backend_util.warn(\n 'tf.where() in webgl locks the UI thread. ' +\n 'Call tf.whereAsync() instead');\n const condVals = condition.dataSync();\n return whereImpl(condition.shape, condVals);\n }\n\n private packedUnaryOp(x: TensorInfo, op: string, dtype: DataType) {\n const program = new UnaryOpPackedProgram(x.shape, op);\n const outInfo = this.compileAndRun(program, [x], dtype);\n return engine().makeTensorFromDataId(\n outInfo.dataId, outInfo.shape, outInfo.dtype);\n }\n\n // TODO(msoulanille) remove this once the backend has been modularized\n // a copy is needed here to break a circular dependency.\n // Also remove the op from unary_op.\n abs<T extends Tensor>(x: T): T {\n // TODO: handle cases when x is complex.\n if (this.shouldExecuteOnCPU([x]) && x.dtype !== 'complex64') {\n const outValues =\n simpleAbsImplCPU(this.texData.get(x.dataId).values as TypedArray);\n return this.makeOutput(x.shape, x.dtype, outValues);\n }\n\n if (env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {\n return this.packedUnaryOp(x, unary_op.ABS, x.dtype) as T;\n }\n\n const program = new UnaryOpProgram(x.shape, unary_op.ABS);\n const outInfo = this.compileAndRun(program, [x]);\n return engine().makeTensorFromDataId(\n outInfo.dataId, outInfo.shape, outInfo.dtype) as T;\n }\n\n makeTensorInfo(\n shape: number[], dtype: DataType,\n values?: BackendValues|string[]): TensorInfo {\n let dataId;\n if (dtype === 'string' && values != null && values.length > 0 &&\n util.isString(values[0])) {\n const encodedValues =\n (values as {} as string[]).map(d => util.encodeString(d));\n\n dataId = this.write(encodedValues, shape, dtype);\n } else {\n dataId = this.write(values as TypedArray, shape, dtype);\n }\n\n this.texData.get(dataId).usage = null;\n return {dataId, shape, dtype};\n }\n\n private makeOutput<T extends Tensor>(\n shape: number[], dtype: DataType, values?: BackendValues): T {\n const {dataId} = this.makeTensorInfo(shape, dtype, values);\n return engine().makeTensorFromDataId(dataId, shape, dtype, this) as T;\n }\n\n unpackTensor(input: TensorInfo): TensorInfo {\n const program = new UnpackProgram(input.shape);\n return this.runWebGLProgram(program, [input], input.dtype);\n }\n\n packTensor(input: TensorInfo): TensorInfo {\n const program = new PackProgram(input.shape);\n const preventEagerUnpackingOutput = true;\n return this.runWebGLProgram(\n program, [input], input.dtype, null /* customUniformValues */,\n preventEagerUnpackingOutput);\n }\n\n private packedReshape(input: TensorInfo, afterShape: number[]): TensorInfo {\n const input3DShape = [\n webgl_util.getBatchDim(input.shape),\n ...webgl_util.getRowsCols(input.shape)\n ] as [number, number, number];\n const input3D: TensorInfo = {\n dtype: input.dtype,\n shape: input3DShape,\n dataId: input.dataId\n };\n const afterShapeAs3D = [\n webgl_util.getBatchDim(afterShape), ...webgl_util.getRowsCols(afterShape)\n ] as [number, number, number];\n\n const program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);\n const preventEagerUnpackingOfOutput = true;\n const output = this.runWebGLProgram(\n program, [input3D], input.dtype, null /* customUniformValues */,\n preventEagerUnpackingOfOutput);\n return {dataId: output.dataId, shape: afterShape, dtype: output.dtype};\n }\n\n private decode(dataId: DataId): TensorInfo {\n const texData = this.texData.get(dataId);\n const {isPacked, shape, dtype} = texData;\n const shapeAs3D =\n webgl_util.getShapeAs3D(shape) as [number, number, number];\n let program;\n if (isPacked) {\n program = new DecodeMatrixPackedProgram(shapeAs3D);\n } else {\n program = new DecodeMatrixProgram(shapeAs3D);\n }\n const preventEagerUnpackingOfOutput = true;\n const out = this.runWebGLProgram(\n program, [{shape: shapeAs3D, dtype, dataId}], dtype,\n null /* customUniformValues */, preventEagerUnpackingOfOutput);\n return {dtype, shape, dataId: out.dataId};\n }\n\n runWebGLProgram(\n program: GPGPUProgram, inputs: TensorInfo[], outputDtype: DataType,\n customUniformValues?: number[][],\n preventEagerUnpackingOfOutput = false): TensorInfo {\n const output = this.makeTensorInfo(program.outputShape, outputDtype);\n const outData = this.texData.get(output.dataId);\n if (program.packedOutput) {\n outData.isPacked = true;\n }\n if (program.outPackingScheme === tex_util.PackingScheme.DENSE) {\n const texelShape = tex_util.getDenseTexShape(program.outputShape);\n // For a densely packed output, we explicitly set texShape\n // so it doesn't get assigned later according to our typical packing\n // scheme wherein a single texel can only contain values from adjacent\n // rows/cols.\n outData.texShape = texelShape.map(d => d * 2) as [number, number];\n }\n if (program.outTexUsage != null) {\n outData.usage = program.outTexUsage;\n }\n if (util.sizeFromShape(output.shape) === 0) {\n // Short-circuit the computation since the result is empty (has 0 in its\n // shape).\n outData.values =\n util.getTypedArrayFromDType(output.dtype as 'float32', 0);\n return output;\n }\n\n const dataToDispose: TensorInfo[] = [];\n const inputsData: TensorData[] = inputs.map(input => {\n if (input.dtype === 'complex64') {\n throw new Error(\n `GPGPUProgram does not support complex64 input. For complex64 ` +\n `dtypes, please separate the program into real and imaginary ` +\n `parts.`);\n }\n\n let texData = this.texData.get(input.dataId);\n\n if (texData.texture == null) {\n if (!program.packedInputs &&\n util.sizeFromShape(input.shape) <=\n env().getNumber('WEBGL_SIZE_UPLOAD_UNIFORM')) {\n // Upload small tensors that live on the CPU as uniforms, not as\n // textures. Do this only when the environment supports 32bit floats\n // due to problems when comparing 16bit floats with 32bit floats.\n // TODO(https://github.com/tensorflow/tfjs/issues/821): Make it\n // possible for packed shaders to sample from uniforms.\n return {\n shape: input.shape,\n texData: null,\n isUniform: true,\n uniformValues: texData.values as TypedArray\n };\n }\n\n // This ensures that if a packed program's inputs have not yet been\n // uploaded to the GPU, they get uploaded as packed right off the bat.\n if (program.packedInputs) {\n texData.isPacked = true;\n texData.shape = input.shape;\n }\n } else if (!!texData.isPacked !== !!program.packedInputs) {\n input = texData.isPacked ? this.unpackTensor(input) :\n this.packTensor(input);\n dataToDispose.push(input);\n texData = this.texData.get(input.dataId);\n } else if (\n texData.isPacked &&\n !webgl_util.isReshapeFree(texData.shape, input.shape)) {\n // This is a special case where a texture exists for a tensor\n // but the shapes are incompatible (due to packing constraints) because\n // the tensor did not have a chance to go through the packed reshape\n // shader. This only happens when we reshape the *same* tensor to form\n // *distinct* inputs to an op, e.g. dotting a vector with itself. This\n // case will disappear once packed uploading is the default.\n\n const savedInput = input;\n const targetShape = input.shape;\n\n input.shape = texData.shape;\n input = this.packedReshape(input as Tensor, targetShape);\n dataToDispose.push(input);\n texData = this.texData.get(input.dataId);\n\n savedInput.shape = targetShape;\n }\n\n this.uploadToGPU(input.dataId);\n return {shape: input.shape, texData, isUniform: false};\n });\n\n this.uploadToGPU(output.dataId);\n const outputData:\n TensorData = {shape: output.shape, texData: outData, isUniform: false};\n const key = gpgpu_math.makeShaderKey(program, inputsData, outputData);\n const binary = this.getAndSaveBinary(key, () => {\n return gpgpu_math.compileProgram(\n this.gpgpu, program, inputsData, outputData);\n });\n const shouldTimeProgram = this.activeTimers != null;\n let query: WebGLQuery|CPUTimerQuery;\n if (shouldTimeProgram) {\n query = this.startTimer();\n }\n\n gpgpu_math.runProgram(\n this.gpgpu, binary, inputsData, outputData, customUniformValues);\n\n dataToDispose.forEach(info => this.disposeIntermediateTensorInfo(info));\n\n if (shouldTimeProgram) {\n query = this.endTimer(query);\n this.activeTimers.push(\n {name: program.constructor.name, query: this.getQueryTime(query)});\n }\n\n const glFlushThreshold = env().get('WEBGL_FLUSH_THRESHOLD');\n // Manually GL flush requested\n if (glFlushThreshold > 0) {\n const time = util.now();\n if ((time - this.lastGlFlushTime) > glFlushThreshold) {\n this.gpgpu.gl.flush();\n this.lastGlFlushTime = time;\n }\n }\n\n if (!env().getBool('WEBGL_LAZILY_UNPACK') && outData.isPacked &&\n preventEagerUnpackingOfOutput === false) {\n const unpacked = this.unpackTensor(output);\n this.disposeIntermediateTensorInfo(output);\n return unpacked;\n }\n return output;\n }\n\n compileAndRun(\n program: GPGPUProgram, inputs: TensorInfo[], outputDtype?: DataType,\n customUniformValues?: number[][],\n preventEagerUnpackingOfOutput = false): TensorInfo {\n outputDtype = outputDtype || inputs[0].dtype;\n const outInfo = this.runWebGLProgram(\n program, inputs, outputDtype, customUniformValues,\n preventEagerUnpackingOfOutput);\n return outInfo;\n }\n\n private getAndSaveBinary(key: string, getBinary: () => GPGPUBinary):\n GPGPUBinary {\n if (!(key in this.binaryCache)) {\n this.binaryCache[key] = getBinary();\n }\n return this.binaryCache[key];\n }\n\n getTextureManager(): TextureManager {\n return this.textureManager;\n }\n\n private disposed = false;\n\n dispose() {\n if (this.disposed) {\n return;\n }\n // Avoid disposing the compiled webgl programs during unit testing because\n // it slows down test execution.\n if (!env().getBool('IS_TEST')) {\n const allKeys = Object.keys(this.binaryCache);\n allKeys.forEach(key => {\n this.gpgpu.deleteProgram(this.binaryCache[key].webGLProgram);\n delete this.binaryCache[key];\n });\n }\n this.textureManager.dispose();\n if (this.canvas != null &&\n (typeof (HTMLCanvasElement) !== 'undefined' &&\n this.canvas instanceof HTMLCanvasElement)) {\n this.canvas.remove();\n } else {\n this.canvas = null;\n }\n if (this.gpgpuCreatedLocally) {\n this.gpgpu.program = null;\n this.gpgpu.dispose();\n }\n this.disposed = true;\n }\n\n floatPrecision(): 16|32 {\n if (this.floatPrecisionValue == null) {\n this.floatPrecisionValue = tidy(() => {\n if (!env().get('WEBGL_RENDER_FLOAT32_ENABLED')) {\n // Momentarily switching DEBUG flag to false so we don't throw an\n // error trying to upload a small value.\n const debugFlag = env().getBool('DEBUG');\n env().set('DEBUG', false);\n const underflowCheckValue = this.abs(scalar(1e-8)).dataSync()[0];\n env().set('DEBUG', debugFlag);\n\n if (underflowCheckValue > 0) {\n return 32;\n }\n }\n return 16;\n });\n }\n return this.floatPrecisionValue;\n }\n\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n\n uploadToGPU(dataId: DataId): void {\n const texData = this.texData.get(dataId);\n const {shape, dtype, values, texture, usage, isPacked} = texData;\n\n if (texture != null) {\n // Array is already on GPU. No-op.\n return;\n }\n const shouldTimeProgram = this.activeTimers != null;\n let start: number;\n if (shouldTimeProgram) {\n start = util.now();\n }\n\n let texShape = texData.texShape;\n if (texShape == null) {\n texShape = webgl_util.getTextureShapeFromLogicalShape(shape, isPacked);\n texData.texShape = texShape;\n }\n\n if (values != null) {\n const shapeAs3D = webgl_util.getShapeAs3D(shape);\n\n let program;\n let width = texShape[1], height = texShape[0];\n const isByteArray = values instanceof Uint8Array;\n\n if (isPacked) {\n [width, height] = tex_util.getPackedMatrixTextureShapeWidthHeight(\n texShape[0], texShape[1]);\n program = new EncodeMatrixPackedProgram(\n shapeAs3D, [height, width], isByteArray);\n } else {\n program =\n new EncodeMatrixProgram(shapeAs3D, [height, width], isByteArray);\n }\n\n const tempDenseInputHandle = this.makeTensorInfo([height, width], dtype);\n if (isByteArray) {\n this.texData.get(tempDenseInputHandle.dataId).usage =\n TextureUsage.PIXELS;\n } else {\n this.texData.get(tempDenseInputHandle.dataId).usage =\n TextureUsage.UPLOAD;\n }\n this.gpgpu.uploadDenseMatrixToTexture(\n this.getTexture(tempDenseInputHandle.dataId), width, height,\n values as TypedArray);\n\n // We want the output to remain packed regardless of the value of\n // WEBGL_PACK.\n const preventEagerUnpacking = true;\n const encodedOutputTarget = this.runWebGLProgram(\n program, [tempDenseInputHandle], dtype, null, preventEagerUnpacking);\n\n // Have the original texture assume the identity of the encoded output.\n const outputTexData = this.texData.get(encodedOutputTarget.dataId);\n texData.texture = outputTexData.texture;\n texData.texShape = outputTexData.texShape;\n texData.isPacked = outputTexData.isPacked;\n texData.usage = outputTexData.usage;\n\n this.disposeIntermediateTensorInfo(tempDenseInputHandle);\n this.texData.delete(encodedOutputTarget.dataId);\n\n // Once uploaded, don't store the values on cpu.\n texData.values = null;\n if (shouldTimeProgram) {\n this.uploadWaitMs += util.now() - start;\n }\n } else {\n const newTexture = this.acquireTexture(texShape, usage, dtype, isPacked);\n texData.texture = newTexture;\n }\n }\n\n private convertAndCacheOnCPU(dataId: DataId, float32Values?: Float32Array):\n TypedArray {\n const texData = this.texData.get(dataId);\n const {dtype} = texData;\n\n this.releaseGPUData(dataId);\n\n if (float32Values != null) {\n texData.values = float32ToTypedArray(float32Values, dtype as 'float32');\n }\n return texData.values as TypedArray;\n }\n\n private acquireTexture(\n texShape: [number, number], texType: TextureUsage, dtype: DataType,\n isPacked: boolean): WebGLTexture {\n this.numBytesInGPU += this.computeBytes(texShape, dtype);\n if (!this.warnedAboutMemory &&\n this.numBytesInGPU > this.numMBBeforeWarning * 1024 * 1024) {\n const mb = (this.numBytesInGPU / 1024 / 1024).toFixed(2);\n this.warnedAboutMemory = true;\n console.warn(\n `High memory usage in GPU: ${mb} MB, ` +\n `most likely due to a memory leak`);\n }\n return this.textureManager.acquireTexture(texShape, texType, isPacked);\n }\n\n private computeBytes(shape: [number, number], dtype: DataType) {\n return shape[0] * shape[1] * util.bytesPerElement(dtype);\n }\n}\n\nfunction float32ToTypedArray<D extends NumericDataType>(\n a: Float32Array, dtype: D): tf.DataTypeMap[D] {\n if (dtype === 'float32' || dtype === 'complex64') {\n return a as tf.DataTypeMap[D];\n } else if (dtype === 'int32' || dtype === 'bool') {\n const result = (dtype === 'int32') ? new Int32Array(a.length) :\n new Uint8Array(a.length);\n for (let i = 0; i < result.length; ++i) {\n result[i] = Math.round(a[i]);\n }\n return result as tf.DataTypeMap[D];\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.8.0';\nexport {version};\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 {env} from '@tensorflow/tfjs-core';\n\nimport * as gpgpu_util from './gpgpu_util';\nimport * as webgl_util from './webgl_util';\n\nexport {MathBackendWebGL, WebGLMemoryInfo, WebGLTimingInfo} from './backend_webgl';\nexport {setWebGLContext} from './canvas_util';\nexport {GPGPUContext} from './gpgpu_context';\nexport {GPGPUProgram} from './gpgpu_math';\n// WebGL specific utils.\nexport {gpgpu_util, webgl_util};\n\n/**\n * Enforce use of half precision textures if available on the platform.\n *\n * @doc {heading: 'Environment', namespace: 'webgl'}\n */\nexport function forceHalfFloat(): void {\n env().set('WEBGL_FORCE_F16_TEXTURES', true);\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// base.ts is the webgl backend without auto kernel registration.\n\nimport {device_util, registerBackend} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from './backend_webgl';\nexport {version as version_webgl} from './version';\n\nif (device_util.isBrowser()) {\n registerBackend('webgl', () => new MathBackendWebGL(), 2 /* priority */);\n}\n\n// Export webgl utilities\nexport * from './webgl';\n\n// Export forceHalfFlost under webgl namespace for the union bundle.\nimport {forceHalfFloat} from './webgl';\nexport const webgl = {forceHalfFloat};\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 {backend_util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\n\nexport const CHECK_NAN_SNIPPET = `\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n`;\n\nexport const SQUARED_DIFFERENCE = 'return (a - b) * (a - b);';\nexport class BinaryOpProgram implements GPGPUProgram {\n variableNames = ['A', 'B'];\n outputShape: number[];\n userCode: string;\n enableShapeUniforms: boolean;\n\n constructor(op: string, aShape: number[], bShape: number[]) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);\n this.userCode = `\n float binaryOperation(float a, float b) {\n ${op}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\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 {backend_util, util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram, useShapeUniforms} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport const CHECK_NAN_SNIPPET = `\n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n`;\n\nexport const ELU_DER = `\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n`;\n\nexport const NOT_EQUAL = `\n return vec4(notEqual(a, b));\n`;\n\nexport class BinaryOpPackedProgram implements GPGPUProgram {\n variableNames = ['A', 'B'];\n outputShape: number[];\n userCode: string;\n supportsBroadcasting = true;\n packedInputs = true;\n packedOutput = true;\n enableShapeUniforms: boolean;\n\n constructor(\n op: string, aShape: number[], bShape: number[],\n checkOutOfBounds = false) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n const rank = this.outputShape.length;\n this.enableShapeUniforms = useShapeUniforms(rank);\n let checkOutOfBoundsString = '';\n if (checkOutOfBounds) {\n if (rank === 0 || util.sizeFromShape(this.outputShape) === 1) {\n checkOutOfBoundsString = `\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n `;\n } else {\n const dtype = getCoordsDataType(rank);\n checkOutOfBoundsString = `\n ${dtype} coords = getOutputCoords();\n `;\n if (rank === 1) {\n if (this.enableShapeUniforms) {\n checkOutOfBoundsString += `\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;\n } else {\n checkOutOfBoundsString += `\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;\n }\n } else {\n const channels = getChannels('coords', rank);\n if (this.enableShapeUniforms) {\n checkOutOfBoundsString += `\n bool nextRowOutOfBounds =\n (${channels[rank - 2]} + 1) >= outShape[${rank} - 2];\n bool nextColOutOfBounds =\n (${channels[rank - 1]} + 1) >= outShape[${rank} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `;\n } else {\n checkOutOfBoundsString += `\n bool nextRowOutOfBounds =\n (${channels[rank - 2]} + 1) >= ${this.outputShape[rank - 2]};\n bool nextColOutOfBounds =\n (${channels[rank - 1]} + 1) >= ${this.outputShape[rank - 1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `;\n }\n }\n }\n }\n\n this.userCode = `\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${op}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${checkOutOfBoundsString}\n\n setOutput(result);\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 */\n\nimport {Identity, IdentityInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function identity(\n args: {inputs: IdentityInputs, backend: MathBackendWebGL}): 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: 'webgl',\n kernelFunc: identity as {} 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 {Complex, ComplexInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\n/**\n * In WebGL data is stored in GPU textures which can't be efficiently copied, so\n * complex tensors share data with their real and imaginary components. Complex\n * tensors' reference to the components is tracked by refCount on the individual\n * component. The refCounts are increased by the identity call.\n *\n * When a complex tensor is disposed, it will reduce the refCount on the\n * components by calling disposeData on each.\n */\nexport function complex(\n args: {inputs: ComplexInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {real, imag} = inputs;\n\n const complexInfo = backend.makeTensorInfo(real.shape, 'complex64');\n const complex = backend.texData.get(complexInfo.dataId);\n\n const realTensorInfo = identity({inputs: {x: real}, backend});\n\n const imagTensorInfo = identity({inputs: {x: imag}, backend});\n\n complex.complexTensorInfos = {real: realTensorInfo, imag: imagTensorInfo};\n\n return complexInfo;\n}\n\nexport const complexConfig: KernelConfig = {\n kernelName: Complex,\n backendName: 'webgl',\n kernelFunc: complex as {} 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 {env, KernelConfig, KernelFunc, LeakyRelu, LeakyReluAttrs, LeakyReluInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\n\nexport const LEAKYRELU = `return (a < 0.) ? b * a : a;`;\nexport const LEAKYRELU_PACKED = `\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n`;\n\nexport function leakyRelu(args: {\n inputs: LeakyReluInputs,\n backend: MathBackendWebGL,\n attrs: LeakyReluAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {alpha} = attrs;\n\n const $alpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(alpha as {} as 'float32', 'float32'));\n\n const program = env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?\n new BinaryOpPackedProgram(LEAKYRELU_PACKED, x.shape, $alpha.shape) :\n new BinaryOpProgram(LEAKYRELU, x.shape, $alpha.shape);\n const result = backend.runWebGLProgram(program, [x, $alpha], x.dtype);\n\n backend.disposeIntermediateTensorInfo($alpha);\n\n return result;\n}\n\nexport const leakyReluConfig: KernelConfig = {\n kernelName: LeakyRelu,\n backendName: 'webgl',\n kernelFunc: leakyRelu as {} 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 {env, KernelConfig, KernelFunc, Prelu, PreluInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\n\nexport const PRELU = `return (a < 0.) ? b * a : a;`;\nexport const PRELU_PACKED = `\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n`;\n\nexport function prelu(args: {inputs: PreluInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x, alpha} = inputs;\n\n const program = env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?\n new BinaryOpPackedProgram(PRELU_PACKED, x.shape, alpha.shape) :\n new BinaryOpProgram(PRELU, x.shape, alpha.shape);\n return backend.runWebGLProgram(program, [x, alpha], x.dtype);\n}\n\nexport const preluConfig: KernelConfig = {\n kernelName: Prelu,\n backendName: 'webgl',\n kernelFunc: prelu as {} 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, BinaryInputs, DataType, env, KernelFunc, TypedArray, UnaryInputs, upcastType} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\nimport {complex} from '../kernels/Complex';\nimport {LEAKYRELU, LEAKYRELU_PACKED} from '../kernels/LeakyRelu';\nimport {PRELU, PRELU_PACKED} from '../kernels/Prelu';\nimport * as unary_op from '../unaryop_gpu';\nimport {UnaryOpProgram} from '../unaryop_gpu';\nimport * as unary_packed_op from '../unaryop_packed_gpu';\nimport {UnaryOpPackedProgram} from '../unaryop_packed_gpu';\n\nimport {SimpleBinaryKernelImplCPU, SimpleUnaryKernelImplCPU} from './shared';\n\nexport const CHECK_NAN_SNIPPET_UNARY = `if (isnan(x)) return x;`;\n\nexport const CHECK_NAN_SNIPPET_BINARY = `\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n`;\n\nexport const CHECK_NAN_SNIPPET_BINARY_PACKED = `\n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n`;\n\ntype UnaryKernelFuncConfig = {\n opSnippet: string,\n packedOpSnippet?: string,\n cpuKernelImpl?: SimpleUnaryKernelImplCPU,\n dtype?: DataType\n};\n\n/**\n * Template that creates a `KernelFunc` for unary ops.\n * @param opSnippet Op snippet to create `UnaryOpProgram`.\n * @param packedOpSnippet Op snippet to create `UnaryOpPackedProgram`.\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 unaryKernelFunc(\n {opSnippet, packedOpSnippet, cpuKernelImpl, dtype}: UnaryKernelFuncConfig):\n KernelFunc {\n return ({inputs, backend}) => {\n const {x} = inputs as UnaryInputs;\n const webglBackend = backend as MathBackendWebGL;\n\n const $dtype = dtype || x.dtype;\n if (webglBackend.shouldExecuteOnCPU([x]) && cpuKernelImpl != null) {\n const xData = webglBackend.texData.get(x.dataId);\n const outValues = cpuKernelImpl(xData.values as TypedArray, $dtype);\n return webglBackend.makeTensorInfo(x.shape, $dtype, outValues);\n }\n\n const shouldUsePackedProgram =\n env().getBool('WEBGL_PACK_UNARY_OPERATIONS') && packedOpSnippet != null;\n let program: UnaryOpProgram|UnaryOpPackedProgram;\n if (shouldUsePackedProgram) {\n program = new UnaryOpPackedProgram(x.shape, packedOpSnippet);\n } else {\n program = new UnaryOpProgram(x.shape, opSnippet);\n }\n\n return webglBackend.runWebGLProgram(program, [x], $dtype);\n };\n}\n\ntype BinaryKernelFuncConfig = {\n opSnippet: string,\n packedOpSnippet?: string,\n checkOutOfBounds?: boolean,\n supportsComplex?: boolean,\n cpuKernelImpl?: SimpleBinaryKernelImplCPU,\n dtype?: DataType\n};\n\n/**\n * Template that creates a `KernelFunc` for binary ops.\n * @param opSnippet Op snippet to create `BinaryOpProgram`.\n * @param packedOpSnippet Op snippet to create `BinaryOpPackedProgram`.\n * @param checkOutOfBoundsForPackedProgram Whether to set checkOutOfBounds=true\n * when creating BinaryOpPackedProgram.\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 opSnippet,\n packedOpSnippet,\n checkOutOfBounds = false,\n supportsComplex = false,\n cpuKernelImpl,\n dtype\n}: BinaryKernelFuncConfig): KernelFunc {\n return ({inputs, backend}) => {\n const {a, b} = inputs as BinaryInputs;\n const webglBackend = backend as MathBackendWebGL;\n\n if (supportsComplex && a.dtype === 'complex64') {\n const aData = webglBackend.texData.get(a.dataId);\n const bData = webglBackend.texData.get(b.dataId);\n\n const [real, imag] = [\n [aData.complexTensorInfos.real, bData.complexTensorInfos.real],\n [aData.complexTensorInfos.imag, bData.complexTensorInfos.imag]\n ].map(complexParts => {\n const [aPart, bPart] = complexParts;\n\n const aHandle = {\n dataId: aPart.dataId,\n dtype: aPart.dtype,\n shape: a.shape\n };\n const bHandle = {\n dataId: bPart.dataId,\n dtype: bPart.dtype,\n shape: b.shape\n };\n\n const program = new BinaryOpProgram(opSnippet, a.shape, b.shape);\n return webglBackend.runWebGLProgram(\n program, [aHandle, bHandle], upcastType(aPart.dtype, bPart.dtype));\n });\n\n const complexOutput =\n complex({inputs: {real, imag}, backend: webglBackend});\n\n webglBackend.disposeIntermediateTensorInfo(real);\n webglBackend.disposeIntermediateTensorInfo(imag);\n\n // TODO(annxingyuan): Implement CPU forwarding for complex inputs.\n\n return complexOutput;\n }\n\n const $dtype = dtype || upcastType(a.dtype, b.dtype);\n if ((a.dtype === 'string' || b.dtype === 'string' ||\n webglBackend.shouldExecuteOnCPU([a, b])) &&\n cpuKernelImpl != null) {\n const aVals = webglBackend.texData.get(a.dataId).values as TypedArray;\n const bVals = webglBackend.texData.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 [outValues, outShape] =\n cpuKernelImpl(a.shape, b.shape, decodedAVals, decodedBVals, $dtype);\n\n const out = webglBackend.makeTensorInfo(outShape, $dtype);\n const outData = webglBackend.texData.get(out.dataId);\n outData.values = outValues;\n return out;\n }\n\n const shouldUsePackedProgram =\n env().getBool('WEBGL_PACK_BINARY_OPERATIONS') &&\n packedOpSnippet != null;\n let program: BinaryOpProgram|BinaryOpPackedProgram;\n if (shouldUsePackedProgram) {\n program = new BinaryOpPackedProgram(\n packedOpSnippet, a.shape, b.shape, checkOutOfBounds);\n } else {\n program = new BinaryOpProgram(opSnippet, a.shape, b.shape);\n }\n\n return webglBackend.runWebGLProgram(program, [a, b], $dtype);\n };\n}\n\nexport function mapActivationToShaderProgram(\n activation: backend_util.Activation, packed = false): string {\n if (activation === 'linear') {\n if (packed) {\n return unary_packed_op.LINEAR;\n }\n return unary_op.LINEAR;\n } else if (activation === 'relu') {\n if (packed) {\n return unary_packed_op.RELU;\n }\n return unary_op.RELU;\n } else if (activation === 'elu') {\n if (packed) {\n return unary_packed_op.ELU;\n }\n return unary_op.ELU;\n } else if (activation === 'relu6') {\n if (packed) {\n return unary_packed_op.RELU6;\n }\n return unary_op.RELU6;\n } else if (activation === 'prelu') {\n if (packed) {\n return PRELU_PACKED;\n }\n return PRELU;\n } else if (activation === 'leakyrelu') {\n if (packed) {\n return LEAKYRELU_PACKED;\n }\n return LEAKYRELU;\n } else if (activation === 'sigmoid') {\n if (packed) {\n return unary_packed_op.SIGMOID;\n }\n return unary_op.SIGMOID;\n }\n throw new Error(`Activation ${\n activation} has not been implemented for the WebGL backend.`);\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class MatMulPackedProgram implements GPGPUProgram {\n variableNames = ['matrixA', 'matrixB'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n aShape: [number, number, number], bShape: [number, number, number],\n outputShape: [number, number, number], transposeA = false,\n transposeB = false, addBias = false, activation: string = null,\n hasPreluActivation = false, hasLeakyreluActivation = false) {\n this.outputShape = outputShape;\n\n const sharedDim = transposeA ? aShape[1] : aShape[2];\n const sharedDimensionPacked = Math.ceil(sharedDim / 2);\n\n const aSample = transposeA ? 'i * 2, rc.y' : 'rc.y, i * 2';\n const bSample = transposeB ? 'rc.z, i * 2' : 'i * 2, rc.z';\n const aSwizzle = transposeA ? ['a.xxyy', 'a.zzww'] : ['a.xxzz', 'a.yyww'];\n const bSwizzle = transposeB ? ['b.xzxz', 'b.ywyw'] : ['b.xyxy', 'b.zwzw'];\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivation) {\n activationSnippet = `vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyreluActivation) {\n activationSnippet = `vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `vec4 activation(vec4 x) {\n ${activation}\n }`;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivation) {\n this.variableNames.push('preluActivationWeights');\n }\n\n if (hasLeakyreluActivation) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n let batchASnippet = 'rc.x';\n let batchBSnippet = 'rc.x';\n if (aShape[0] < bShape[0]) {\n batchASnippet = `int(min(float(rc.x), ${aShape[0] - 1}.))`;\n } else if (bShape[0] < aShape[0]) {\n batchBSnippet = `int(min(float(rc.x), ${bShape[0] - 1}.))`;\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const float sharedDimension = ${sharedDimensionPacked}.0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < ${sharedDimensionPacked}; i++) {\n int batchA = ${batchASnippet};\n int batchB = ${batchBSnippet};\n vec4 a = getMatrixA(batchA, ${aSample});\n vec4 b = getMatrixB(batchB, ${bSample});\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (${aSwizzle[0]} * ${bSwizzle[0]});\n result += (${aSwizzle[1]} * ${bSwizzle[1]});\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n ${addBiasSnippet}\n\n ${applyActivationSnippet}\n\n setOutput(result);\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\n// (Ar + Ai)(Br + Bi) =\n// ArBr + ArBi + AiBr + AiBi = ArBr - AB + ArBi + AiBr\n// Yr = ArBr - AB\n// Yi = ArBi + AiBr\nexport const COMPLEX_MULTIPLY = {\n REAL: 'return areal * breal - aimag * bimag;',\n IMAG: 'return areal * bimag + aimag * breal;'\n};\n\nexport class BinaryOpComplexProgram implements GPGPUProgram {\n variableNames = ['AReal', 'AImag', 'BReal', 'BImag'];\n userCode: string;\n outputShape: number[];\n\n constructor(op: string, aShape: number[], bShape: number[]) {\n this.outputShape = backend_util.assertAndGetBroadcastShape(aShape, bShape);\n\n this.userCode = `\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n ${op}\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\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 */\n\nimport {backend_util, BinaryInputs, env, KernelConfig, Multiply, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport * as binaryop_complex_gpu from '../binaryop_complex_gpu';\nimport {BinaryOpComplexProgram} from '../binaryop_complex_gpu';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\nimport {multiplyImplCPU as cpuMultiply} from '../kernel_utils/shared';\n\nimport {complex} from './Complex';\n\nconst MUL = 'return a * b;';\n\nexport function multiply(\n args: {inputs: BinaryInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {a, b} = inputs;\n const dtype = backend_util.upcastType(a.dtype, b.dtype);\n\n if (a.dtype === 'complex64') {\n const aData = backend.texData.get(a.dataId);\n const bData = backend.texData.get(b.dataId);\n\n const realProgram = new BinaryOpComplexProgram(\n binaryop_complex_gpu.COMPLEX_MULTIPLY.REAL, a.shape, b.shape);\n const imagProgram = new BinaryOpComplexProgram(\n binaryop_complex_gpu.COMPLEX_MULTIPLY.IMAG, a.shape, b.shape);\n\n const inputs = [\n {\n dataId: aData.complexTensorInfos.real.dataId,\n dtype: aData.complexTensorInfos.real.dtype,\n shape: a.shape\n },\n {\n dataId: aData.complexTensorInfos.imag.dataId,\n dtype: aData.complexTensorInfos.imag.dtype,\n shape: a.shape\n },\n {\n dataId: bData.complexTensorInfos.real.dataId,\n dtype: bData.complexTensorInfos.real.dtype,\n shape: b.shape\n },\n {\n dataId: bData.complexTensorInfos.imag.dataId,\n dtype: bData.complexTensorInfos.imag.dtype,\n shape: b.shape\n }\n ];\n\n const realPart = backend.runWebGLProgram(realProgram, inputs, 'float32');\n const imagPart = backend.runWebGLProgram(imagProgram, inputs, 'float32');\n\n const complexOutput =\n complex({inputs: {real: realPart, imag: imagPart}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(imagPart);\n\n // TODO(annxingyuan): CPU forwarding for complex inputs.\n return complexOutput;\n }\n\n if (backend.shouldExecuteOnCPU([a, b])) {\n const aData = backend.texData.get(a.dataId);\n const bData = backend.texData.get(b.dataId);\n const [outValues, outShape] = cpuMultiply(\n a.shape, b.shape, aData.values as TypedArray,\n bData.values as TypedArray, dtype);\n\n const out = backend.makeTensorInfo(outShape, dtype);\n const outData = backend.texData.get(out.dataId);\n outData.values = outValues;\n return out;\n }\n\n let program: BinaryOpProgram|BinaryOpPackedProgram;\n if (env().getBool('WEBGL_PACK_BINARY_OPERATIONS')) {\n program = new BinaryOpPackedProgram(MUL, a.shape, b.shape);\n } else {\n program = new BinaryOpProgram(MUL, a.shape, b.shape);\n }\n\n return backend.runWebGLProgram(program, [a, b], dtype);\n}\n\nexport const multiplyConfig: KernelConfig = {\n kernelName: Multiply,\n backendName: 'webgl',\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 {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ReshapePackedProgram} from '../reshape_packed_gpu';\nimport {getBatchDim, getRowsCols} from '../webgl_util';\n\nexport function packedReshape(\n input: TensorInfo, afterShape: number[],\n backend: MathBackendWebGL): TensorInfo {\n const input3DShape =\n [getBatchDim(input.shape),\n ...getRowsCols(input.shape)] as [number, number, number];\n const input3D: TensorInfo = {\n dtype: input.dtype,\n shape: input3DShape,\n dataId: input.dataId\n };\n const afterShapeAs3D =\n [getBatchDim(afterShape),\n ...getRowsCols(afterShape)] as [number, number, number];\n\n const program = new ReshapePackedProgram(afterShapeAs3D, input3DShape);\n const preventEagerUnpackingOfOutput = true;\n const output = backend.runWebGLProgram(\n program, [input3D], input.dtype, null /* customSetup */,\n preventEagerUnpackingOfOutput);\n return {dataId: output.dataId, shape: afterShape, dtype: output.dtype};\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 {MathBackendWebGL} from '../backend_webgl';\nimport {packedReshape} from '../kernel_utils/reshape';\nimport {isReshapeFree} from '../webgl_util';\n\nexport function reshape(args: {\n inputs: ReshapeInputs,\n backend: MathBackendWebGL,\n attrs: ReshapeAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {shape} = attrs;\n const webglBackend = backend;\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 const xTexData = webglBackend.texData.get(x.dataId);\n if (xTexData.isPacked && !isReshapeFree(x.shape, $shape) &&\n !(xTexData.texture !== null && isReshapeFree(xTexData.shape, $shape))) {\n return packedReshape(x, $shape, webglBackend);\n }\n\n webglBackend.incRef(x.dataId);\n\n return {dataId: x.dataId, shape: $shape, dtype: x.dtype};\n}\n\nexport const reshapeConfig: KernelConfig = {\n kernelName: Reshape,\n backendName: 'webgl',\n kernelFunc: reshape as {} 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, util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class MeanProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(reduceInfo: backend_util.ReduceInfo, divisor?: number) {\n const {windowSize, batchSize, inSize, outSize} = reduceInfo;\n this.outputShape = [batchSize, outSize];\n\n const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;\n const windowSizeVec4Remainder = windowSize % 4;\n\n let updateSnippet = `sumValue += dot(values, ones);`;\n if (divisor != null) {\n const denominator = 1 / divisor;\n updateSnippet = `sumValue += dot(values * ${\n util.isInt(denominator) ? denominator.toPrecision(2) :\n denominator}, ones);`;\n }\n\n let checkOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return 0.0;\n }\n `;\n }\n\n this.userCode = `\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${checkOutOfBounds}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${windowSize};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${updateSnippet}\n }\n\n int inIdx = inOffset + ${windowSizeNearestVec4};\n if (${windowSizeVec4Remainder === 1}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 2}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 3}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${updateSnippet}\n }\n setOutput(sumValue);\n }\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\nimport {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ReduceProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n reduceInfo: backend_util.ReduceInfo,\n reduceType: 'all'|'any'|'max'|'min'|'sum'|'prod') {\n const {windowSize, batchSize, inSize, outSize} = reduceInfo;\n this.outputShape = [batchSize, outSize];\n\n let initializationValue = '0.0';\n let compareOp = ``;\n\n if (reduceType === 'prod') {\n initializationValue = '1.0';\n } else if (reduceType === 'min') {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '1.0 / 1e-20';\n compareOp = `min`;\n } else if (reduceType === 'max') {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '-1.0 / 1e-20';\n compareOp = `max`;\n }\n\n let returnValue = `${reduceType}(${reduceType}(${reduceType}(` +\n 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';\n\n if (reduceType === 'sum') {\n returnValue = `sumValue`;\n } else if (reduceType === 'prod') {\n returnValue = `prodValue`;\n } else if (reduceType === 'all') {\n returnValue = `allValue`;\n } else if (reduceType === 'any') {\n returnValue = `anyValue`;\n }\n\n const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;\n const windowSizeVec4Remainder = windowSize % 4;\n\n let updateSnippet = `\n if (${reduceType === 'sum'}) {\n sumValue += dot(values, ones);\n } else if (${reduceType === 'prod'}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${compareOp}(values, minMaxValue);\n if (${reduceType === 'min'} || ${reduceType === 'max'}) {\n minMaxValue = ${compareOp}(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n `;\n\n let vecType = `vec4`;\n\n if (reduceType === 'all') {\n initializationValue = '1.0';\n updateSnippet = `\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n `;\n vecType = `bvec4`;\n } else if (reduceType === 'any') {\n initializationValue = '0.0';\n updateSnippet = `\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n `;\n vecType = `bvec4`;\n }\n\n let checkOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return initializationValue;\n }\n `;\n }\n this.userCode = `\n const float initializationValue = ${initializationValue};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${checkOutOfBounds}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${windowSize};\n\n vec4 minMaxValue = vec4(${initializationValue});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {\n int inIdx = inOffset + i;\n ${vecType} values = ${vecType}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${updateSnippet}\n }\n\n int inIdx = inOffset + ${windowSizeNearestVec4};\n if (${windowSizeVec4Remainder === 1}) {\n ${vecType} values = ${vecType}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 2}) {\n ${vecType} values = ${vecType}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 3}) {\n ${vecType} values = ${vecType}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${updateSnippet}\n }\n setOutput(${returnValue});\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 */\n\nimport {backend_util, DataType, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MeanProgram} from '../mean_gpu';\nimport {ReduceProgram} from '../reduce_gpu';\n\ntype ReduceTypes = 'all'|'any'|'max'|'min'|'sum'|'prod'|'mean';\n\n// Returns an array of configuration objects that describe each stage of the\n// reduction.\nfunction getReductionStages(inShape: number[]):\n Array<{inSize: number, windowSize: number, outSize: number}> {\n const stages = [];\n\n while (stages.length === 0 || stages[stages.length - 1].outSize !== 1) {\n const outSize: number =\n stages.length ? stages[stages.length - 1].outSize : inShape[1];\n const windowSize = backend_util.computeOptimalWindowSize(outSize);\n stages.push({\n inSize: outSize,\n windowSize,\n outSize: Math.ceil(outSize / windowSize)\n });\n }\n\n return stages;\n}\n\nexport function reduce(\n x: TensorInfo, dtype: DataType, reductionType: ReduceTypes,\n backend: MathBackendWebGL): TensorInfo {\n const reductionStages = getReductionStages(x.shape);\n\n let result = x;\n for (let i = 0; i < reductionStages.length; i++) {\n const {inSize, windowSize, outSize} = reductionStages[i];\n\n let program: ReduceProgram|MeanProgram;\n let previousResult: TensorInfo;\n if (reductionType === 'mean') {\n program = i === 0 ?\n new MeanProgram(\n {windowSize, inSize, batchSize: x.shape[0], outSize}, inSize) :\n new MeanProgram({windowSize, inSize, batchSize: x.shape[0], outSize});\n } else {\n program = new ReduceProgram(\n {windowSize, inSize, batchSize: x.shape[0], outSize}, reductionType);\n }\n\n previousResult = result;\n result = backend.runWebGLProgram(program, [result], dtype);\n\n if (previousResult.dataId !== x.dataId) {\n backend.disposeIntermediateTensorInfo(previousResult);\n }\n }\n\n return result;\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class TransposeProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n constructor(aShape: number[], newDim: number[]) {\n const outputShape: number[] = new Array(aShape.length);\n for (let i = 0; i < outputShape.length; i++) {\n outputShape[i] = aShape[newDim[i]];\n }\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n const dtype = getCoordsDataType(this.rank);\n const switched = getSwitchedCoords(newDim);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n setOutput(getA(${switched}));\n }\n `;\n }\n}\n\nfunction getSwitchedCoords(newDim: number[]): string {\n const rank = newDim.length;\n if (rank > 6) {\n throw Error(`Transpose for rank ${rank} is not yet supported`);\n }\n const originalOrder =\n ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u', 'resRC.v'];\n const switchedCoords = new Array(rank);\n for (let i = 0; i < newDim.length; i++) {\n switchedCoords[newDim[i]] = originalOrder[i];\n }\n return switchedCoords.join();\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 {GPGPUProgram} from './gpgpu_math';\nimport {getVecChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class TransposePackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n rank: number;\n packedInputs = true;\n packedOutput = true;\n\n constructor(aShape: number[], newDim: number[]) {\n const outputShape: number[] = new Array(aShape.length);\n for (let i = 0; i < outputShape.length; i++) {\n outputShape[i] = aShape[newDim[i]];\n }\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n if (this.rank > 6) {\n throw Error(\n `Packed transpose for rank ${this.rank} is not yet supported.`);\n }\n const dtype = getCoordsDataType(this.rank);\n\n const outputOrder = getVecChannels('rc', this.rank);\n const switchedOrder = new Array(this.rank);\n for (let i = 0; i < newDim.length; i++) {\n switchedOrder[newDim[i]] = outputOrder[i];\n }\n const innerDims = `vec2(${switchedOrder.slice(-2).join()})`;\n const nextColumn =\n `++${outputOrder[this.rank - 1]} < ${outputShape[this.rank - 1]}`;\n const getc = `getChannel(getA(${switchedOrder.join()}), ${innerDims})`;\n\n this.userCode = `\n void main() {\n ${dtype} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = ${getc};\n if(${nextColumn}) {\n result[1] = ${getc};\n }\n --${outputOrder[this.rank - 1]};\n if(++${outputOrder[this.rank - 2]} < ${outputShape[this.rank - 2]}) {\n result[2] = ${getc};\n if(${nextColumn}) {\n result[3] = ${getc};\n }\n }\n setOutput(result);\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 */\n\nimport {env, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {transposeImplCPU} from '../kernel_utils/shared';\nimport {TransposeProgram} from '../transpose_gpu';\nimport {TransposePackedProgram} from '../transpose_packed_gpu';\n\nexport function transposeImpl(\n x: TensorInfo, perm: number[], backend: MathBackendWebGL): TensorInfo {\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new TransposePackedProgram(x.shape, perm) :\n new TransposeProgram(x.shape, perm);\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport {transposeImplCPU};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, sumOutType, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from './Reshape';\n\nimport {transposeImpl} from './Transpose_impl';\n\nexport function sumImpl(\n x: TensorInfo, axis: number|number[], keepDims: boolean,\n backend: MathBackendWebGL): TensorInfo {\n const reductionIndices = axis;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(reductionIndices, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n const sumInputIsTransposed = permutedAxes != null;\n\n let sumInput = x;\n if (sumInputIsTransposed) {\n sumInput = transposeImpl(x, permutedAxes, backend);\n\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('sum', axes, xRank);\n const [sumOutShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(sumInput.shape, axes);\n\n let outShape = sumOutShape;\n if (keepDims) {\n // rather than reshape at the end, set the target shape here.\n outShape = backend_util.expandShapeToKeepDim(sumOutShape, origAxes);\n }\n\n const inSize = util.sizeFromShape(reduceShape);\n const xSize = util.sizeFromShape(x.shape);\n const batchSize = xSize / inSize;\n const reshapedInput = reshape(\n {inputs: {x: sumInput}, attrs: {shape: [batchSize, inSize]}, backend});\n\n const outType = sumOutType(x.dtype);\n\n const reduced = reduce(reshapedInput, outType, 'sum', backend);\n const out =\n reshape({inputs: {x: reduced}, attrs: {shape: outShape}, backend});\n\n backend.disposeIntermediateTensorInfo(reshapedInput);\n backend.disposeIntermediateTensorInfo(reduced);\n if (sumInputIsTransposed) {\n backend.disposeIntermediateTensorInfo(sumInput);\n }\n\n return out;\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, Sum, SumAttrs, SumInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {sumImpl} from './Sum_impl';\n\nexport function sum(\n args: {inputs: SumInputs, attrs: SumAttrs, backend: MathBackendWebGL}) {\n const {inputs, backend, attrs} = args;\n\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n return sumImpl(x, axis, keepDims, backend);\n}\n\nexport const sumConfig: KernelConfig = {\n kernelName: Sum,\n backendName: 'webgl',\n kernelFunc: sum as {} 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 {MathBackendWebGL} from '../backend_webgl';\n\nimport {transposeImpl} from './Transpose_impl';\nimport {transposeImplCPU as cpuTranspose} from './Transpose_impl';\n\nexport function transpose(args: {\n inputs: TransposeInputs,\n attrs: TransposeAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {perm} = attrs;\n const webglBackend = backend;\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 let out: TensorInfo;\n if (webglBackend.shouldExecuteOnCPU([x])) {\n const xTexData = webglBackend.texData.get(x.dataId);\n const values = xTexData.values as TypedArray;\n const outValues = cpuTranspose(values, x.shape, x.dtype, perm, newShape);\n\n out = webglBackend.makeTensorInfo(newShape, x.dtype);\n const outData = webglBackend.texData.get(out.dataId);\n outData.values = outValues;\n } else {\n out = transposeImpl(x, perm, webglBackend);\n }\n return out;\n}\n\nexport const transposeConfig: KernelConfig = {\n kernelName: Transpose,\n backendName: 'webgl',\n kernelFunc: transpose as {} 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, TensorInfo, upcastType, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {mapActivationToShaderProgram} from '../kernel_utils/kernel_funcs_utils';\nimport {MatMulPackedProgram} from '../mulmat_packed_gpu';\n\nimport {multiply} from './Multiply';\nimport {reshape} from './Reshape';\nimport {sum} from './Sum';\nimport {transpose} from './Transpose';\n\n// Empirically determined minimal shared dimension in matmul before we forward\n// to a.mul(b).sum() in order to take advantage of GPU parallelism. See\n// https://github.com/tensorflow/tfjs-core/pull/1379 for benchmarks.\nexport const MATMUL_SHARED_DIM_THRESHOLD = 1000;\n\ntype BatchMatMulConfig = {\n a: TensorInfo,\n b: TensorInfo,\n transposeA: boolean,\n transposeB: boolean,\n backend: MathBackendWebGL,\n bias?: TensorInfo,\n preluActivationWeights?: TensorInfo,\n leakyreluAlpha?: number,\n activation?: backend_util.Activation\n};\n\nexport function batchMatMulImpl({\n a,\n b,\n transposeA,\n transposeB,\n backend,\n bias = null,\n preluActivationWeights = null,\n leakyreluAlpha = 0,\n activation = null\n}: BatchMatMulConfig): TensorInfo {\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 batchDimsCompatible =\n batchDimA === batchDimB || batchDimA === 1 || batchDimB === 1;\n\n util.assert(\n aRank >= 2 && bRank >= 2 && batchDimsCompatible,\n () => `Error in matMul: the input batch dimensions must either be the ` +\n `same or at least one input batch dimension must be 1. Got input ` +\n `batch dimensions of (${outerDimsA}) and (${outerDimsB}).`);\n\n const outShapeOuterDims =\n batchDimA > batchDimB ? 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: [number, number, number] = transposeA ?\n [batchDimA, innerShapeA, outerShapeA] :\n [batchDimA, outerShapeA, innerShapeA];\n const b3dShape: [number, number, number] = transposeB ?\n [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 intermediates: TensorInfo[] = [a3d, b3d];\n\n const batchDim = Math.max(batchDimA, batchDimB);\n const sharedDim = transposeA ? a3d.shape[1] : a3d.shape[2];\n\n const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n const fusedActivation = activation != null ?\n mapActivationToShaderProgram(activation, true) :\n null;\n const containsFusedOps = hasBias || hasPreluActivationWeights ||\n hasLeakyreluAlpha || fusedActivation != null;\n let out: TensorInfo;\n\n // Since the matrices are vectors, it is faster to call mul().sum()\n // because sum() is O(sqrt(N)) due to divide-and-conquer.\n if ((outerShapeA === 1 || outerShapeB === 1) &&\n sharedDim > MATMUL_SHARED_DIM_THRESHOLD && containsFusedOps === false) {\n let aVec = a3d;\n let bVec = b3d;\n if (transposeA) {\n aVec = transpose({inputs: {x: a3d}, backend, attrs: {perm: [0, 2, 1]}});\n intermediates.push(aVec);\n }\n if (transposeB) {\n bVec = transpose({inputs: {x: b3d}, backend, attrs: {perm: [0, 2, 1]}});\n intermediates.push(bVec);\n }\n\n const shouldReshapeA = outerShapeB !== 1;\n const shouldReshapeB = outerShapeB === 1;\n\n let aVec3d = aVec;\n if (shouldReshapeA) {\n aVec3d = reshape({\n inputs: {x: aVec},\n backend,\n attrs: {shape: [batchDim, sharedDim, 1]}\n });\n\n intermediates.push(aVec3d);\n }\n\n const axis = outerShapeB === 1 ? 2 : 1;\n\n let bVec3d = bVec;\n if (shouldReshapeB) {\n bVec3d = reshape({\n inputs: {x: bVec},\n backend,\n attrs: {shape: [batchDim, 1, sharedDim]}\n });\n\n intermediates.push(bVec3d);\n }\n\n const product = multiply({inputs: {a: aVec3d, b: bVec3d}, backend});\n out = sum({inputs: {x: product}, backend, attrs: {axis, keepDims: true}});\n intermediates.push(product);\n } else {\n const dtype = upcastType(a.dtype, b.dtype);\n\n const program = new MatMulPackedProgram(\n a3dShape, b3dShape, [batchDim, outerShapeA, outerShapeB], transposeA,\n transposeB, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n\n const inputs: TensorInfo[] = [a3d, b3d];\n if (bias != null) {\n inputs.push(bias);\n }\n if (hasPreluActivationWeights) {\n inputs.push(preluActivationWeights);\n }\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as {} as 'float32', 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n\n out = backend.runWebGLProgram(program, inputs, dtype);\n }\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: outShape}});\n intermediates.push(out);\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n return outReshaped;\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 {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {batchMatMulImpl} from './BatchMatMul_impl';\n\nexport function _fusedMatMul(args: {\n inputs: _FusedMatMulInputs,\n attrs: _FusedMatMulAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b, bias, preluActivationWeights} = inputs;\n const {transposeA, transposeB, activation, leakyreluAlpha} = attrs;\n\n return batchMatMulImpl({\n a,\n b,\n transposeA,\n transposeB,\n backend,\n bias,\n preluActivationWeights,\n leakyreluAlpha,\n activation\n });\n}\n\nexport const _fusedMatMulConfig: KernelConfig = {\n kernelName: _FusedMatMul,\n backendName: 'webgl',\n kernelFunc: _fusedMatMul as {} 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 {Abs, AbsInputs, env, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {simpleAbsImplCPU} from '../kernel_utils/shared';\nimport {UnaryOpProgram} from '../unaryop_gpu';\nimport {UnaryOpPackedProgram} from '../unaryop_packed_gpu';\n\nconst ABS = `return abs(x);`;\n\nexport function abs(args: {inputs: AbsInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n // TODO: handle cases when x is complex. Once the cpu implementation\n // can handle complex values, refactor to use unaryKernelFunc.\n if (backend.shouldExecuteOnCPU([x]) && x.dtype !== 'complex64') {\n const xData = backend.texData.get(x.dataId);\n const outValues = simpleAbsImplCPU(xData.values as TypedArray);\n return backend.makeTensorInfo(x.shape, x.dtype, outValues);\n }\n\n let program: UnaryOpProgram|UnaryOpPackedProgram;\n if (env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {\n program = new UnaryOpPackedProgram(x.shape, ABS);\n } else {\n program = new UnaryOpProgram(x.shape, ABS);\n }\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const absConfig: KernelConfig = {\n kernelName: Abs,\n backendName: 'webgl',\n kernelFunc: abs as {} 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 {Acos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ACOS = CHECK_NAN_SNIPPET + `\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n`;\n\nexport const acos = unaryKernelFunc({opSnippet: ACOS});\n\nexport const acosConfig: KernelConfig = {\n kernelName: Acos,\n backendName: 'webgl',\n kernelFunc: acos,\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 {Acosh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ACOSH = CHECK_NAN_SNIPPET + `\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));`;\n\nexport const acosh = unaryKernelFunc({opSnippet: ACOSH});\n\nexport const acoshConfig: KernelConfig = {\n kernelName: Acosh,\n backendName: 'webgl',\n kernelFunc: acosh,\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 {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {addImplCPU as cpuAdd} from '../kernel_utils/shared';\n\nconst ADD = 'return a + b;';\n\nexport const addKernelFunc = binaryKernelFunc({\n opSnippet: ADD,\n packedOpSnippet: ADD,\n supportsComplex: true,\n cpuKernelImpl: cpuAdd\n});\n\nexport const addConfig: KernelConfig = {\n kernelName: Add,\n backendName: 'webgl',\n kernelFunc: addKernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class AddNProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(outputShape: number[], shapes: number[][]) {\n this.outputShape = outputShape;\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const snippets: string[] = [];\n // Get target elements from every input tensor.\n this.variableNames.forEach(variable => {\n snippets.push(`float v${variable} = get${variable}AtOutCoords();`);\n });\n\n // Calculate the sum of all elements.\n const operation = this.variableNames\n .map(variable => {\n return `v${variable}`;\n })\n .join(' + ');\n\n this.userCode = `\n void main() {\n ${snippets.join('\\n ')}\n\n float result = ${operation};\n setOutput(result);\n }\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class AddNPackedProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(outputShape: number[], shapes: number[][]) {\n this.outputShape = outputShape;\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const snippets: string[] = [];\n // Get target elements from every input tensor.\n this.variableNames.forEach(variable => {\n snippets.push(`vec4 v${variable} = get${variable}AtOutCoords();`);\n });\n\n // Calculate the sum of all elements.\n const operation = this.variableNames\n .map(variable => {\n return `v${variable}`;\n })\n .join(' + ');\n\n this.userCode = `\n void main() {\n ${snippets.join('\\n ')}\n\n vec4 result = ${operation};\n setOutput(result);\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 */\n\nimport {AddN, AddNInputs, env, KernelConfig, KernelFunc, TensorInfo, upcastType} from '@tensorflow/tfjs-core';\n\nimport {AddNProgram} from '../addn_gpu';\nimport {AddNPackedProgram} from '../addn_packed_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function addN(args: {inputs: AddNInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n\n const tensors = inputs;\n if (tensors.length === 1) {\n return identity({inputs: {x: tensors[0]}, backend});\n }\n\n // Limit the number of uploaded textures for optimization.\n if (tensors.length > env().get('WEBGL_MAX_TEXTURES_IN_SHADER')) {\n const midIndex = Math.floor(tensors.length / 2);\n const leftSide = addN({inputs: tensors.slice(0, midIndex), backend});\n const rightSide = addN({inputs: tensors.slice(midIndex), backend});\n return addN({inputs: [leftSide, rightSide], backend});\n }\n\n const dtype =\n tensors.map(t => t.dtype).reduce((d1, d2) => upcastType(d1, d2));\n const shapes = tensors.map(t => t.shape);\n // We can make sure shapes are identical in op level.\n const usePackedOp = env().getBool('WEBGL_PACK');\n const program = usePackedOp ?\n new AddNPackedProgram(tensors[0].shape, shapes) :\n new AddNProgram(tensors[0].shape, shapes);\n return backend.runWebGLProgram(program, tensors, dtype);\n}\n\nexport const addNConfig: KernelConfig = {\n kernelName: AddN,\n backendName: 'webgl',\n kernelFunc: addN as {} 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 {All, AllAttrs, AllInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\n\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function all(\n args: {inputs: AllInputs, backend: MathBackendWebGL, attrs: AllAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let permutedX = x;\n if (permutedAxes != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('all', axes, xRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n const reduced = reduce(a2D, a2D.dtype, 'all', backend);\n\n let res;\n if (keepDims) {\n const newShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: newShape}});\n } else {\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n }\n\n backend.disposeIntermediateTensorInfo(a2D);\n backend.disposeIntermediateTensorInfo(reduced);\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo(permutedX);\n }\n\n return res;\n}\n\nexport const allConfig: KernelConfig = {\n kernelName: All,\n backendName: 'webgl',\n kernelFunc: all as {} 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 {Any, AnyAttrs, AnyInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function any(\n args: {inputs: AnyInputs, backend: MathBackendWebGL, attrs: AnyAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let permutedX = x;\n if (permutedAxes != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('any', axes, xRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n const reduced = reduce(a2D, a2D.dtype, 'any', backend);\n\n let res;\n if (keepDims) {\n const newShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: newShape}});\n } else {\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n }\n\n backend.disposeIntermediateTensorInfo(a2D);\n backend.disposeIntermediateTensorInfo(reduced);\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo(permutedX);\n }\n\n return res;\n}\n\nexport const anyConfig: KernelConfig = {\n kernelName: Any,\n backendName: 'webgl',\n kernelFunc: any as {} as KernelFunc\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ArgMinMaxProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n reduceInfo: backend_util.ReduceInfo, op: 'max'|'min',\n firstPass: boolean) {\n const {windowSize, batchSize, outSize} = reduceInfo;\n if (!firstPass) {\n this.variableNames.push('bestIndicesA');\n }\n this.outputShape = [batchSize, outSize];\n const compOp = (op === 'max') ? '>' : '<';\n const indexSnippet = firstPass ?\n 'inOffset + i;' :\n 'round(getBestIndicesA(batch, inOffset + i));';\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${windowSize};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${windowSize}; i++) {\n int inIdx = ${indexSnippet};\n float candidate = getA(batch, inIdx);\n if (candidate ${compOp} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\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 {util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ArgMinMaxPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n shape: number[], windowSize: number, op: 'max'|'min',\n firstPass: boolean) {\n util.assert(\n shape.length > 2,\n () => `Packed arg${\n op.charAt(0).toUpperCase() +\n op.slice(1)} supports only inputs with rank above 2.`);\n const inSize = shape[shape.length - 1];\n const outSize = Math.ceil(inSize / windowSize);\n this.outputShape = shape.slice(0, -1);\n if (outSize > 1) {\n this.outputShape.push(outSize);\n }\n if (!firstPass) {\n this.variableNames.push('bestIndicesA');\n }\n const outShape = this.outputShape;\n const rank = outShape.length;\n const dtype = getCoordsDataType(rank);\n const coords = getChannels('coords', rank);\n\n let sourceLocSetup;\n let sourceRank;\n if (outSize === 1) {\n sourceRank = rank + 1;\n const sourceLocDType = getCoordsDataType(sourceRank);\n sourceLocSetup = `\n ${sourceLocDType} sourceLocR = ${sourceLocDType}(${coords.join()}, 0);\n ++${coords[rank - 1]};\n ${sourceLocDType} sourceLocG = ${sourceLocDType}(${coords.join()}, 0);\n ++${coords[rank - 2]};\n ${sourceLocDType} sourceLocA = ${sourceLocDType}(${coords.join()}, 0);\n --${coords[rank - 1]};\n ${sourceLocDType} sourceLocB = ${sourceLocDType}(${coords.join()}, 0);\n --${coords[rank - 2]};`;\n } else {\n sourceRank = rank;\n sourceLocSetup = `\n ${dtype} sourceLocR = coords;\n ++${coords[rank - 1]};\n ${dtype} sourceLocG = coords;\n ++${coords[rank - 2]};\n ${dtype} sourceLocA = coords;\n --${coords[rank - 1]};\n ${dtype} sourceLocB = coords;\n --${coords[rank - 2]};`;\n }\n const channels = ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, sourceRank);\n const inChannel = '.' + channels[sourceRank - 1]; // e.g. \".b\" for rank 3.\n const intChannels = channels.map(x => 'int ' + x);\n const srcRCoords =\n getChannels('sourceLocR', sourceRank - 1).concat('inIdx.r');\n const srcGCoords =\n getChannels('sourceLocG', sourceRank - 1).concat('inIdx.g');\n const srcBCoords =\n getChannels('sourceLocB', sourceRank - 1).concat('inIdx.b');\n const srcACoords =\n getChannels('sourceLocA', sourceRank - 1).concat('inIdx.a');\n\n const compOp = (op === 'max') ? 'greaterThan' : 'lessThan';\n const fetchCandidateIdx = firstPass ? '' : `\n inIdx = round(vec4(getBestIndicesAChannel(${srcRCoords.join()}),\n getBestIndicesAChannel(${srcGCoords.join()}),\n getBestIndicesAChannel(${srcBCoords.join()}),\n getBestIndicesAChannel(${srcACoords.join()})));`;\n\n const fetchValue = `vec4(\n getAChannel(${srcRCoords.join()}),\n hasNextCol ? getAChannel(${srcGCoords.join()}) : 0.,\n hasNextRow ? getAChannel(${srcBCoords.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${srcACoords.join()}) : 0.)`;\n\n const getBestIndicesAChannelSnippet = firstPass ? '' : `\n float getBestIndicesAChannel(${intChannels.join()}) {\n return getChannel(getBestIndicesA(${channels.join()}),\n vec2(${channels.slice(-2).join()}));\n }`;\n\n this.userCode = `\n float getAChannel(${intChannels.join()}) {\n return getChannel(getA(${channels.join()}),\n vec2(${channels.slice(-2).join()}));\n }\n ${getBestIndicesAChannelSnippet}\n void main() {\n ${dtype} coords = getOutputCoords();\n bool hasNextCol = ${coords[rank - 1]} < ${outShape[rank - 1] - 1};\n bool hasNextRow = ${coords[rank - 2]} < ${outShape[rank - 2] - 1};\n ${sourceLocSetup}\n ivec4 srcIdx = ivec4(sourceLocR${inChannel}, sourceLocG${inChannel},\n sourceLocB${inChannel}, sourceLocA${inChannel}) * ${windowSize};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${fetchValue};\n\n for (int i = 0; i < ${windowSize}; i++) {\n inIdx = srcIdx;\n ${fetchCandidateIdx}\n vec4 candidate = ${fetchValue};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${compOp}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\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 */\n\nimport {backend_util, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {ArgMinMaxProgram} from '../argminmax_gpu';\nimport {ArgMinMaxPackedProgram} from '../argminmax_packed_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reshape} from '../kernels/Reshape';\n\nfunction argReduce(\n backend: MathBackendWebGL, x: TensorInfo, reduceType: 'max'|'min',\n bestIndicesA: TensorInfo = null): TensorInfo {\n let batchSize = x.shape[0];\n let inSize = x.shape[1];\n if (bestIndicesA != null) {\n batchSize = bestIndicesA.shape[0];\n inSize = bestIndicesA.shape[1];\n }\n const windowSize = backend_util.computeOptimalWindowSize(inSize);\n const reduceInfo =\n {windowSize, inSize, batchSize, outSize: Math.ceil(inSize / windowSize)};\n const program =\n new ArgMinMaxProgram(reduceInfo, reduceType, bestIndicesA == null);\n const inputs = [x];\n if (bestIndicesA != null) {\n inputs.push(bestIndicesA);\n }\n const output = backend.runWebGLProgram(program, inputs, 'int32');\n // No need to run another GPGPU program.\n if (output.shape[1] === 1) {\n return output;\n }\n const result = argReduce(backend, x, reduceType, output);\n backend.disposeIntermediateTensorInfo(output);\n return result;\n}\n\nfunction argReducePacked(\n backend: MathBackendWebGL, x: TensorInfo, reduceType: 'max'|'min',\n bestIndicesA: TensorInfo = null): TensorInfo {\n const inShape = bestIndicesA != null ? bestIndicesA.shape : x.shape;\n const inSize = inShape[inShape.length - 1];\n const windowSize = backend_util.computeOptimalWindowSize(inSize);\n const program = new ArgMinMaxPackedProgram(\n inShape, windowSize, reduceType, bestIndicesA == null);\n const inputs = bestIndicesA == null ? [x] : [x, bestIndicesA];\n const output = backend.runWebGLProgram(program, inputs, 'int32');\n if (output.shape.length === x.shape.length) {\n const result = argReducePacked(backend, x, reduceType, output);\n backend.disposeIntermediateTensorInfo(output);\n return result;\n }\n return output;\n}\n\nexport function argMinMaxReduce(\n backend: MathBackendWebGL, x: TensorInfo, axis: number,\n reduceType: 'min'|'max'): TensorInfo {\n const axes = [axis];\n backend_util.assertAxesAreInnerMostDims(\n 'arg' + reduceType.charAt(0).toUpperCase() + reduceType.slice(1), axes,\n x.shape.length);\n if (!env().getBool('WEBGL_PACK_REDUCE') || x.shape.length <= 2) {\n const intermediateTensorInfos = [];\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(x.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n const a2D = reshape({inputs: {x}, backend, attrs: {shape: [-1, inSize]}});\n intermediateTensorInfos.push(a2D);\n\n const reduced = argReduce(backend, a2D, reduceType);\n intermediateTensorInfos.push(reduced);\n const reshaped =\n reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n return reshaped;\n }\n return argReducePacked(backend, x, reduceType);\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 {ArgMax, ArgMaxAttrs, ArgMaxInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {argMinMaxReduce} from '../kernel_utils/arg_min_max';\n\nimport {transpose} from './Transpose';\n\nexport function argMax(\n args:\n {inputs: ArgMaxInputs, backend: MathBackendWebGL, attrs: ArgMaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('argMax', [axes[0]], $x.shape.length);\n const out = argMinMaxReduce(backend, $x, axes[0], 'max');\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n return out;\n}\n\nexport const argMaxConfig: KernelConfig = {\n kernelName: ArgMax,\n backendName: 'webgl',\n kernelFunc: argMax as {} 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 {ArgMin, ArgMinAttrs, ArgMinInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {argMinMaxReduce} from '../kernel_utils/arg_min_max';\nimport {transpose} from './Transpose';\n\nexport function argMin(\n args:\n {inputs: ArgMinInputs, backend: MathBackendWebGL, attrs: ArgMinAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis} = attrs;\n\n let axes = util.parseAxisParam(axis, x.shape);\n const permutedAxes = backend_util.getAxesPermutation(axes, x.shape.length);\n let $x = x;\n const intermediateTensorInfos = [];\n if (permutedAxes != null) {\n $x = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n intermediateTensorInfos.push($x);\n axes = backend_util.getInnerMostAxes(axes.length, $x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('argMin', [axes[0]], $x.shape.length);\n\n const out = argMinMaxReduce(backend, $x, axes[0], 'min');\n\n intermediateTensorInfos.forEach(\n t => backend.disposeIntermediateTensorInfo(t));\n return out;\n}\n\nexport const argMinConfig: KernelConfig = {\n kernelName: ArgMin,\n backendName: 'webgl',\n kernelFunc: argMin as {} 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 {Asin, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ASIN = CHECK_NAN_SNIPPET + `\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n`;\n\nexport const asin = unaryKernelFunc({opSnippet: ASIN});\n\nexport const asinConfig: KernelConfig = {\n kernelName: Asin,\n backendName: 'webgl',\n kernelFunc: asin,\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 {Asinh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ASINH = CHECK_NAN_SNIPPET + `return log(x + sqrt(x * x + 1.0));`;\n\nexport const asinh = unaryKernelFunc({opSnippet: ASINH});\n\nexport const asinhConfig: KernelConfig = {\n kernelName: Asinh,\n backendName: 'webgl',\n kernelFunc: asinh,\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 {Atan, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ATAN = CHECK_NAN_SNIPPET + `\n return atan(x);\n`;\n\nexport const atan = unaryKernelFunc({opSnippet: ATAN});\n\nexport const atanConfig: KernelConfig = {\n kernelName: Atan,\n backendName: 'webgl',\n kernelFunc: atan,\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 {Atan2} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc, CHECK_NAN_SNIPPET_BINARY, CHECK_NAN_SNIPPET_BINARY_PACKED} from '../kernel_utils/kernel_funcs_utils';\n\nconst ATAN2 = CHECK_NAN_SNIPPET_BINARY + `\n return atan(a, b);\n`;\n\nconst ATAN2_PACKED = `\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n ` +\n CHECK_NAN_SNIPPET_BINARY_PACKED + `\n return result;\n`;\n\nexport const atan2 =\n binaryKernelFunc({opSnippet: ATAN2, packedOpSnippet: ATAN2_PACKED});\n\nexport const atan2Config: KernelConfig = {\n kernelName: Atan2,\n backendName: 'webgl',\n kernelFunc: atan2,\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 {Atanh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst ATANH = CHECK_NAN_SNIPPET + `\n if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;`;\n\nexport const atanh = unaryKernelFunc({opSnippet: ATANH});\n\nexport const atanhConfig: KernelConfig = {\n kernelName: Atanh,\n backendName: 'webgl',\n kernelFunc: atanh,\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Pool2DProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, poolType: 'max'|'avg',\n computePositions: boolean, flattenPositions = false,\n includeBatchInIndex = false) {\n if (poolType === 'avg' && computePositions) {\n throw new Error('Cannot compute positions for average pool.');\n }\n\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n this.outputShape = convInfo.outShape;\n\n const isAvgPool = poolType === 'avg';\n const batchFlattenPositionStr = `((batch * ${convInfo.inHeight} + xR) * ${\n convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`;\n const flattenPositionStr =\n `(xR * ${convInfo.inWidth} + xC) * ${convInfo.inChannels} + d`;\n\n let initializationValue = '0.0';\n if (!isAvgPool) {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '-1.0 / 1e-20';\n }\n\n if (computePositions) {\n const compareOp = '>=';\n\n this.userCode = `\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${compareOp} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${\n flattenPositions ? (includeBatchInIndex ? batchFlattenPositionStr :\n flattenPositionStr) :\n `wR * ${effectiveFilterWidth} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `;\n return;\n }\n\n const compareOp = 'max';\n\n let returnValue = `${poolType}(${poolType}(${poolType}(` +\n 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';\n if (poolType === 'avg') {\n returnValue = `avgValue / count`;\n }\n\n const filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;\n const filterWidthVec4Remainder = filterWidth % 4;\n\n const updateSnippet = `\n if (${isAvgPool}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = ${compareOp}(values, minMaxValue);\n }\n `;\n\n this.userCode = `\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n const float initializationValue = ${initializationValue};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${initializationValue});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidthNearestVec4}; wC += 4) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${dilationWidth}, d),\n getValue(batch, xR, xC + 2 * ${dilationWidth}, d),\n getValue(batch, xR, xC + 3 * ${dilationWidth}, d)\n );\n\n ${updateSnippet}\n }\n\n int xC = xCCorner + ${filterWidthNearestVec4};\n if (${filterWidthVec4Remainder === 1}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${filterWidthVec4Remainder === 2}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${dilationWidth}, d),\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${filterWidthVec4Remainder === 3}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${dilationWidth}, d),\n getValue(batch, xR, xC + 2 * ${dilationWidth}, d),\n initializationValue\n );\n\n ${updateSnippet}\n }\n }\n setOutput(${returnValue});\n }\n `;\n }\n}\n\nexport class Pool3DProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv3DInfo, poolType: 'max'|'avg',\n computePositions: boolean, flattenPositions = false,\n includeBatchInIndex = false) {\n if (poolType === 'avg' && computePositions) {\n throw new Error('Cannot compute positions for average pool.');\n }\n\n const filterWidth = convInfo.filterWidth;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n this.outputShape = convInfo.outShape;\n\n const isAvgPool = poolType === 'avg';\n\n let initializationValue = '0.0';\n if (!isAvgPool) {\n // WebGL on Firefox Linux can't compile 1/0 so we do 1/eps.\n initializationValue = '-1.0 / 1e-20';\n }\n\n if (computePositions) {\n const compareOp = '>=';\n\n this.userCode = `\n const ivec3 strides =\n ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${compareOp} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${\n flattenPositions ?\n (includeBatchInIndex ?\n `(((batch * ${convInfo.inDepth} + xD) * ${\n convInfo.inHeight} + xR) * ${convInfo.inWidth} + xC) * ${\n convInfo.inChannels} + ch` :\n `((xD * ${convInfo.inHeight} + xR) * ${\n convInfo.inWidth} + xC) * ${convInfo.inChannels} + ch`) :\n `wD * ${effectiveFilterHeight} * ${effectiveFilterWidth} +\n wR * ${effectiveFilterWidth} + wC`};\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `;\n return;\n }\n\n const compareOp = 'max';\n\n let returnValue = `${poolType}(${poolType}(${poolType}(` +\n 'minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])';\n if (poolType === 'avg') {\n returnValue = `avgValue / count`;\n }\n\n const filterWidthNearestVec4 = Math.floor(filterWidth / 4) * 4;\n const filterWidthVec4Remainder = filterWidth % 4;\n\n const updateSnippet = `\n if (${isAvgPool}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = ${compareOp}(values, minMaxValue);\n }\n `;\n\n this.userCode = `\n const ivec3 strides =\n ivec3(${strideDepth}, ${strideHeight}, ${strideWidth});\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n const float initializationValue = ${initializationValue};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4(${initializationValue});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidthNearestVec4}; wC += 4) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${dilationWidth}, ch),\n getValue(batch, xD, xR, xC + 2 * ${dilationWidth}, ch),\n getValue(batch, xD, xR, xC + 3 * ${dilationWidth}, ch)\n );\n\n ${updateSnippet}\n }\n\n int xC = xCCorner + ${filterWidthNearestVec4};\n if (${filterWidthVec4Remainder === 1}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${filterWidthVec4Remainder === 2}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${dilationWidth}, ch),\n initializationValue,\n initializationValue\n );\n\n ${updateSnippet}\n } else if (${filterWidthVec4Remainder === 3}) {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + ${dilationWidth}, ch),\n getValue(batch, xD, xR, xC + 2 * ${dilationWidth}, ch),\n initializationValue\n );\n\n ${updateSnippet}\n }\n }\n setOutput(${returnValue});\n }\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 {AvgPool, AvgPoolAttrs, AvgPoolInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool2DProgram} from '../pool_gpu';\nimport {assertNotComplex} from '../webgl_util';\nimport {identity} from './Identity';\n\nexport function avgPool(args: {\n inputs: AvgPoolInputs,\n backend: MathBackendWebGL,\n attrs: AvgPoolAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n assertNotComplex(x, 'avgPool');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations = 1;\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in avgPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&\n util.arraysEqual(convInfo.inShape, convInfo.outShape)) {\n return identity({inputs: {x}, backend});\n }\n const avgPoolProgram = new Pool2DProgram(convInfo, 'avg', false);\n return backend.runWebGLProgram(avgPoolProgram, [x], 'float32');\n}\n\nexport const avgPoolConfig: KernelConfig = {\n kernelName: AvgPool,\n backendName: 'webgl',\n kernelFunc: avgPool as {} 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 */\nimport {AvgPool3D, AvgPool3DAttrs, AvgPool3DInputs, backend_util, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool3DProgram} from '../pool_gpu';\n\nexport function avgPool3D(args: {\n inputs: AvgPool3DInputs,\n backend: MathBackendWebGL,\n attrs: AvgPool3DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {filterSize, strides, pad, dimRoundingMode, dataFormat} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode, dataFormat);\n const avgPoolProgram = new Pool3DProgram(convInfo, 'avg', false);\n return backend.runWebGLProgram(avgPoolProgram, [x], 'float32');\n}\n\nexport const avgPool3DConfig: KernelConfig = {\n kernelName: AvgPool3D,\n backendName: 'webgl',\n kernelFunc: avgPool3D as {} as KernelFunc\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class AvgPool2DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const avgMultiplier = 1 / (filterHeight * filterWidth);\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n const float avgMultiplier = float(${avgMultiplier});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC+= ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class AvgPool3DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const avgMultiplier = 1 / (filterDepth * filterHeight * filterWidth);\n\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n const float avgMultiplier = float(${avgMultiplier});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n float dyD = float(dyDCorner + wD) / ${strideDepth}.0;\n\n if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\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 {AvgPool3DGrad, AvgPool3DGradAttrs, AvgPool3DGradInputs, backend_util, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {AvgPool3DBackpropProgram} from '../avg_pool_backprop_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function avgPool3DGrad(args: {\n inputs: AvgPool3DGradInputs,\n backend: MathBackendWebGL,\n attrs: AvgPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n const avgPoolBackpropProgram = new AvgPool3DBackpropProgram(convInfo);\n return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);\n}\n\nexport const avgPoolGrad3DConfig: KernelConfig = {\n kernelName: AvgPool3DGrad,\n backendName: 'webgl',\n kernelFunc: avgPool3DGrad as {} 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 */\nimport {AvgPoolGrad, AvgPoolGradAttrs, AvgPoolGradInputs, backend_util, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {AvgPool2DBackpropProgram} from '../avg_pool_backprop_gpu';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {assertNotComplex} from '../webgl_util';\n\nexport function avgPoolGrad(args: {\n inputs: AvgPoolGradInputs,\n backend: MathBackendWebGL,\n attrs: AvgPoolGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n assertNotComplex([dy, input], 'avgPoolGrad');\n const {filterSize, strides, pad} = attrs;\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad);\n const avgPoolBackpropProgram = new AvgPool2DBackpropProgram(convInfo);\n return backend.runWebGLProgram(avgPoolBackpropProgram, [dy], x.dtype);\n}\n\nexport const avgPoolGradConfig: KernelConfig = {\n kernelName: AvgPoolGrad,\n backendName: 'webgl',\n kernelFunc: avgPoolGrad as {} 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, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {batchMatMulImpl} from './BatchMatMul_impl';\n\nexport function batchMatMul(args: {\n inputs: BatchMatMulInputs,\n attrs: BatchMatMulAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b} = inputs;\n const {transposeA, transposeB} = attrs;\n\n return batchMatMulImpl({a, b, transposeA, transposeB, backend});\n}\n\nexport const batchMatMulConfig: KernelConfig = {\n kernelName: BatchMatMul,\n backendName: 'webgl',\n kernelFunc: batchMatMul as {} as KernelFunc,\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class BatchNormProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n xShape: number[], meanShape: number[], varianceShape: number[],\n offsetShape: number[]|null, scaleShape: number[]|null,\n varianceEpsilon: number) {\n this.variableNames = ['x', 'mean', 'variance'];\n backend_util.assertAndGetBroadcastShape(xShape, meanShape);\n backend_util.assertAndGetBroadcastShape(xShape, varianceShape);\n\n let offsetSnippet = '0.0';\n if (offsetShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, offsetShape);\n this.variableNames.push('offset');\n offsetSnippet = 'getOffsetAtOutCoords()';\n }\n\n let scaleSnippet = '1.0';\n if (scaleShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, scaleShape);\n this.variableNames.push('scale');\n scaleSnippet = 'getScaleAtOutCoords()';\n }\n\n this.outputShape = xShape;\n this.userCode = `\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = ${offsetSnippet};\n float scale = ${scaleSnippet};\n float inv = scale * inversesqrt(variance + float(${varianceEpsilon}));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class BatchNormPackedProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n xShape: number[], meanShape: number[], varianceShape: number[],\n offsetShape: number[]|null, scaleShape: number[]|null,\n varianceEpsilon: number) {\n this.variableNames = ['x', 'mean', 'variance'];\n backend_util.assertAndGetBroadcastShape(xShape, meanShape);\n backend_util.assertAndGetBroadcastShape(xShape, varianceShape);\n\n let offsetSnippet = 'vec4(0.0)';\n if (offsetShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, offsetShape);\n this.variableNames.push('offset');\n offsetSnippet = 'getOffsetAtOutCoords()';\n }\n\n let scaleSnippet = 'vec4(1.0)';\n if (scaleShape != null) {\n backend_util.assertAndGetBroadcastShape(xShape, scaleShape);\n this.variableNames.push('scale');\n scaleSnippet = 'getScaleAtOutCoords()';\n }\n\n this.outputShape = xShape;\n this.userCode = `\n void main() {\n vec4 offset = ${offsetSnippet};\n vec4 scale = ${scaleSnippet};\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4(${varianceEpsilon}));\n\n setOutput((x - mean) * inv + offset);\n }\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 */\n\nimport {env, FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BatchNormProgram} from '../batchnorm_gpu';\nimport {BatchNormPackedProgram} from '../batchnorm_packed_gpu';\n\nexport const batchNorm: (params: {\n inputs: FusedBatchNormInputs,\n backend: MathBackendWebGL,\n attrs: FusedBatchNormAttrs\n}) => TensorInfo = ({inputs, backend, attrs}) => {\n const {x, mean, variance, offset, scale} = inputs;\n\n util.assert(\n mean.shape.length === variance.shape.length,\n () => 'Batch normalization gradient requires mean and variance to have ' +\n 'equal ranks.');\n util.assert(\n offset == null || mean.shape.length === offset.shape.length,\n () => 'Batch normalization gradient requires mean and offset to have ' +\n 'equal ranks.');\n util.assert(\n scale == null || mean.shape.length === scale.shape.length,\n () => 'Batch normalization gradient requires mean and scale to have ' +\n 'equal ranks.');\n\n let {varianceEpsilon} = attrs;\n if (varianceEpsilon == null) {\n varianceEpsilon = 0.001;\n }\n\n const finalInputs = [x, mean, variance];\n\n let offsetShape = null;\n if (offset != null) {\n offsetShape = offset.shape;\n finalInputs.push(offset);\n }\n\n let scaleShape = null;\n if (scale != null) {\n scaleShape = scale.shape;\n finalInputs.push(scale);\n }\n\n const program = env().getBool('WEBGL_PACK_NORMALIZATION') ?\n new BatchNormPackedProgram(\n x.shape, mean.shape, variance.shape, offsetShape, scaleShape,\n varianceEpsilon) :\n new BatchNormProgram(\n x.shape, mean.shape, variance.shape, offsetShape, scaleShape,\n varianceEpsilon);\n const output =\n backend.runWebGLProgram(program, finalInputs, finalInputs[0].dtype);\n\n return output;\n};\n\nexport const batchNormConfig: KernelConfig = {\n kernelName: FusedBatchNorm,\n backendName: 'webgl',\n kernelFunc: batchNorm as {} as KernelFunc,\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class SliceProgram implements GPGPUProgram {\n variableNames = ['source'];\n outputShape: number[];\n userCode: string;\n rank: number;\n customUniforms: Array<{name: string; arrayIndex: number; type: UniformType;}>;\n\n constructor(destSize: number[]) {\n this.outputShape = destSize;\n this.rank = destSize.length;\n\n const dtype = getCoordsDataType(this.rank);\n this.customUniforms = [{name: 'start', arrayIndex: this.rank, type: 'int'}];\n const sourceCoords = getCoords(this.rank);\n\n let body: string;\n const coordSum = destSize.map((_, i) => {\n return `sourceLoc.${coords[i]} = start[${i}] + coords.${coords[i]};`;\n });\n body = `\n ${dtype} sourceLoc;\n ${dtype} coords = getOutputCoords();\n ${coordSum.join('\\n')}\n `;\n this.userCode = `\n void main() {\n ${body}\n setOutput(getSource(${sourceCoords}));\n }\n `;\n }\n}\n\nconst coords = ['x', 'y', 'z', 'w', 'u', 'v'];\n\nfunction getCoords(rank: number): string {\n if (rank === 1) {\n return 'sourceLoc';\n } else if (rank <= 6) {\n return coords.slice(0, rank).map(x => 'sourceLoc.' + x).join(',');\n } else {\n throw Error(`Slicing for rank ${rank} is not yet supported`);\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 {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class SlicePackedProgram implements GPGPUProgram {\n variableNames = ['source'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n rank: number;\n customUniforms: Array<{name: string; arrayIndex: number; type: UniformType;}>;\n\n constructor(destSize: number[]) {\n this.outputShape = destSize;\n this.rank = destSize.length;\n this.customUniforms = [{name: 'start', arrayIndex: this.rank, type: 'int'}];\n const dtype = getCoordsDataType(this.rank);\n const coords = getChannels('coords', this.rank);\n const sourceLoc = getChannels('sourceLoc', this.rank);\n\n const innerDims =\n this.rank === 1 ? 'sourceLoc' : `vec2(${sourceLoc.slice(-2).join()})`;\n const getChannel =\n `getChannel(getSource(${sourceLoc.join()}), ${innerDims})`;\n const upperRow = `\n result.x = ${getChannel};\n if (++${coords[this.rank - 1]} < ${destSize[this.rank - 1]}) {\n ++${sourceLoc[this.rank - 1]};\n result.y = ${getChannel};\n --${sourceLoc[this.rank - 1]};\n }\n `;\n const lowerRow = this.rank === 1 ? '' : `\n --${coords[this.rank - 1]};\n if (++${coords[this.rank - 2]} < ${destSize[this.rank - 2]}) {\n ++${sourceLoc[this.rank - 2]};\n result.z = ${getChannel};\n if (++${coords[this.rank - 1]} < ${destSize[this.rank - 1]}) {\n ++${sourceLoc[this.rank - 1]};\n result.w = ${getChannel};\n }\n }\n `;\n\n const sourceLocSetup = this.rank <= 4 ?\n `sourceLoc = coords +\n ${dtype}(${destSize.map((_, i) => `start[${i}]`).join()});` :\n destSize.map((_, i) => `${sourceLoc[i]} = ${coords[i]} + start[${i}];`)\n .join('\\n');\n this.userCode = `\n void main() {\n ${dtype} coords = getOutputCoords();\n ${dtype} sourceLoc;\n ${sourceLocSetup}\n vec4 result = vec4(0.);\n ${upperRow}\n ${lowerRow}\n setOutput(result);\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 */\n\nimport {env, KernelConfig, KernelFunc, Slice, slice_util, SliceAttrs, SliceInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sliceImplCPU} from '../kernel_utils/shared';\nimport {SliceProgram} from '../slice_gpu';\nimport {SlicePackedProgram} from '../slice_packed_gpu';\n\nfunction shallowSlice(\n x: TensorInfo, begin: number[], size: number[], backend: MathBackendWebGL) {\n const xTexData = backend.texData.get(x.dataId);\n const t = backend.makeTensorInfo(size, x.dtype);\n const newTexData = backend.texData.get(t.dataId);\n // Copy texture data from the original tensor.\n Object.assign(newTexData, xTexData);\n newTexData.refCount = 1;\n newTexData.shape = size;\n newTexData.dtype = x.dtype;\n let flatOffset =\n slice_util.computeFlatOffset(begin, util.computeStrides(x.shape));\n if (xTexData.slice) {\n // We are slicing an already sliced tensor, so we have to accumulate\n // the offset.\n flatOffset += xTexData.slice.flatOffset;\n }\n newTexData.slice = {\n flatOffset,\n // Point to the original dataId, which is used to do ref counting.\n origDataId: xTexData.slice && xTexData.slice.origDataId || x.dataId\n };\n\n // Increase the ref count for that data bucket.\n const refCount = backend.dataRefCount.get(newTexData.slice.origDataId) || 1;\n backend.dataRefCount.set(newTexData.slice.origDataId, refCount + 1);\n return t;\n}\n\nexport function slice(\n args: {inputs: SliceInputs, backend: MathBackendWebGL, attrs: SliceAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {begin, size} = attrs;\n\n const [$begin, $size] = slice_util.parseSliceParams(x, begin, size);\n slice_util.assertParamsValid(x, $begin, $size);\n\n if (util.sizeFromShape($size) === 0) {\n return backend.makeTensorInfo($size, x.dtype, []);\n }\n\n // Run on cpu if dtype is string. For string, the backend represents it\n // as Uint8Array[], where each Uint8Array is a character. Given that the\n // computation is only on the outer array, uploading the whole data onto\n // gpu is wasteful. Also, currently webgl doesn't have a design to\n // upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we\n // just run the kernel on cpu if dtype is string.\n if (backend.shouldExecuteOnCPU([x]) || x.dtype === 'string') {\n const xTexData = backend.texData.get(x.dataId);\n const outValues = sliceImplCPU(\n xTexData.values as TypedArray, $begin, $size, x.shape, x.dtype);\n return backend.makeTensorInfo($size, x.dtype, outValues);\n }\n\n const {isPacked} = backend.texData.get(x.dataId);\n const isContinous = slice_util.isSliceContinous(x.shape, $begin, $size);\n if (isPacked || !isContinous) {\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new SlicePackedProgram($size) :\n new SliceProgram($size);\n const customValues = [$begin];\n return backend.runWebGLProgram(program, [x], x.dtype, customValues);\n }\n backend.uploadToGPU(x.dataId);\n return shallowSlice(x, $begin, $size, backend);\n}\n\nexport const sliceConfig: KernelConfig = {\n kernelName: Slice,\n backendName: 'webgl',\n kernelFunc: slice as {} 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, BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\nimport {transpose} from './Transpose';\n\nexport const batchToSpaceND = (args: {\n inputs: BatchToSpaceNDInputs,\n backend: MathBackendWebGL,\n attrs: BatchToSpaceNDAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, crops} = attrs;\n\n util.assert(\n x.shape.length <= 4,\n () => 'batchToSpaceND for rank > 4 with a WebGL backend not ' +\n 'implemented yet');\n const prod = blockShape.reduce((a, b) => a * b);\n\n const reshaped = backend_util.getReshaped(x.shape, blockShape, prod);\n const permuted = backend_util.getPermuted(reshaped.length, blockShape.length);\n const reshapedPermuted =\n backend_util.getReshapedPermuted(x.shape, blockShape, prod);\n const sliceBeginCoords =\n backend_util.getSliceBeginCoords(crops, blockShape.length);\n const sliceSize =\n backend_util.getSliceSize(reshapedPermuted, crops, blockShape.length);\n\n const toDispose = [];\n\n const reshapedIntermediate =\n reshape({inputs: {x}, backend, attrs: {shape: reshaped}});\n const transposedIntermediate = transpose(\n {inputs: {x: reshapedIntermediate}, backend, attrs: {perm: permuted}});\n const reshapedIntermediate2 = reshape({\n inputs: {x: transposedIntermediate},\n backend,\n attrs: {shape: reshapedPermuted}\n });\n const sliced = slice({\n inputs: {x: reshapedIntermediate2},\n backend,\n attrs: {begin: sliceBeginCoords, size: sliceSize}\n });\n\n toDispose.push(reshapedIntermediate);\n toDispose.push(transposedIntermediate);\n toDispose.push(reshapedIntermediate2);\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return sliced;\n};\n\nexport const batchToSpaceNDConfig: KernelConfig = {\n kernelName: BatchToSpaceND,\n backendName: 'webgl',\n kernelFunc: batchToSpaceND as {} 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 {Bincount, BincountAttrs, BincountInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {bincountImplCPU} from '../kernel_utils/shared';\n\nexport function bincount(args: {\n inputs: BincountInputs,\n backend: MathBackendWebGL,\n attrs: BincountAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, weights} = inputs;\n const {size} = attrs;\n\n const xVals = backend.readSync(x.dataId) as TypedArray;\n const weightsVals = backend.readSync(weights.dataId) as TypedArray;\n\n const outVals =\n bincountImplCPU(xVals, weightsVals, weights.dtype, weights.shape, size);\n\n return backend.makeTensorInfo([size], weights.dtype, outVals);\n}\n\nexport const bincountConfig: KernelConfig = {\n kernelName: Bincount,\n backendName: 'webgl',\n kernelFunc: bincount as {} 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 {NotEqual} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {notEqualImplCPU} from '../kernel_utils/shared';\n\nconst NOT_EQUAL = `return float(a != b);`;\n\nexport const notEqual = binaryKernelFunc(\n {opSnippet: NOT_EQUAL, cpuKernelImpl: notEqualImplCPU, dtype: 'bool'});\n\nexport const notEqualConfig: KernelConfig = {\n kernelName: NotEqual,\n backendName: 'webgl',\n kernelFunc: notEqual,\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 {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function real(args: {inputs: RealInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n const inputData = backend.texData.get(input.dataId);\n\n return identity({inputs: {x: inputData.complexTensorInfos.real}, backend});\n}\n\nexport const realConfig: KernelConfig = {\n kernelName: Real,\n backendName: 'webgl',\n kernelFunc: real as {} 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 {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {UnaryOpProgram} from '../unaryop_gpu';\n\nconst TO_INT = `return float(int(x));`;\n\nexport function int(input: TensorInfo, backend: MathBackendWebGL): TensorInfo {\n const program = new UnaryOpProgram(input.shape, TO_INT);\n const output = backend.runWebGLProgram(program, [input], 'int32');\n return {dataId: output.dataId, shape: output.shape, dtype: output.dtype};\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 * as tf from '@tensorflow/tfjs-core';\nimport {BinaryInputs, Cast, CastAttrs, CastInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {complex} from './Complex';\nimport {identity} from './Identity';\nimport {notEqual} from './NotEqual';\nimport {real} from './Real';\n\nimport {int} from '../kernel_utils/int';\n\nexport function cast(\n args: {inputs: CastInputs, backend: MathBackendWebGL, 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 // TODO(annxingyuan): Import kernel function once zeros is modularized.\n const zerosTensor = tf.zeros(x.shape);\n const floatX = cast({inputs: {x}, backend, attrs: {dtype: 'float32'}});\n\n const result =\n complex({inputs: {real: floatX, imag: zerosTensor}, backend});\n\n zerosTensor.dispose();\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 backend.disposeIntermediateTensorInfo(realPart);\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 if (dtype === 'int32') {\n return int(x, backend);\n }\n\n if (dtype === 'bool') {\n const zerosTensorInfo = backend.makeTensorInfo(\n [], 'bool', util.getTypedArrayFromDType('bool', 1));\n\n const binaryInputs: BinaryInputs = {a: x, b: zerosTensorInfo};\n\n const result = notEqual({inputs: binaryInputs, backend}) as TensorInfo;\n backend.disposeIntermediateTensorInfo(zerosTensorInfo);\n return result;\n }\n\n throw new Error(`Error in Cast: failed to cast ${x.dtype} to ${dtype}`);\n}\n\nexport const castConfig: KernelConfig = {\n kernelName: Cast,\n backendName: 'webgl',\n kernelFunc: cast as {} 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 {Ceil, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {ceilImplCPU} from '../kernel_utils/shared';\n\nconst CEIL = `return ceil(x);`;\n\nexport const ceil = unaryKernelFunc(\n {opSnippet: CEIL, packedOpSnippet: CEIL, cpuKernelImpl: ceilImplCPU});\n\nexport const ceilConfig: KernelConfig = {\n kernelName: Ceil,\n backendName: 'webgl',\n kernelFunc: ceil as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class ClipProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n customUniforms = [\n {name: 'minVal', type: 'float' as UniformType},\n {name: 'maxVal', type: 'float' as UniformType}\n ];\n\n constructor(aShape: number[]) {\n this.outputShape = aShape;\n this.userCode = `\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\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 {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class ClipPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n userCode: string;\n outputShape: number[];\n customUniforms = [\n {name: 'minVal', type: 'float' as UniformType},\n {name: 'maxVal', type: 'float' as UniformType}\n ];\n\n constructor(aShape: number[]) {\n this.outputShape = aShape;\n this.userCode = `\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\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 */\n\nimport {ClipByValue, ClipByValueAttrs, ClipByValueInputs, env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ClipProgram} from '../clip_gpu';\nimport {ClipPackedProgram} from '../clip_packed_gpu';\n\nexport function clipByValue(args: {\n inputs: ClipByValueInputs,\n backend: MathBackendWebGL,\n attrs: ClipByValueAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {clipValueMin, clipValueMax} = attrs;\n\n let program;\n if (env().getBool('WEBGL_PACK_CLIP')) {\n program = new ClipPackedProgram(x.shape);\n } else {\n program = new ClipProgram(x.shape);\n }\n const customValues = [[clipValueMin], [clipValueMax]];\n return backend.runWebGLProgram(program, [x], x.dtype, customValues);\n}\n\nexport const clipByValueConfig: KernelConfig = {\n kernelName: ClipByValue,\n backendName: 'webgl',\n kernelFunc: clipByValue as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class ComplexAbsProgram implements GPGPUProgram {\n variableNames = ['real', 'imag'];\n userCode: string;\n outputShape: number[];\n\n constructor(shape: number[]) {\n this.outputShape = shape;\n this.userCode = `\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\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 */\n\nimport {ComplexAbs, ComplexAbsInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ComplexAbsProgram} from '../complex_abs_gpu';\n\n// Returns a TensorInfo with the complex shape and the dataId of the\n// underlying part. We need to do this because a reshaped complex tensor is\n// not reflected in its parts.\nfunction makeComplexComponentTensorInfo(\n complexTensor: TensorInfo, complexPart: TensorInfo): TensorInfo {\n return {\n dataId: complexPart.dataId,\n dtype: complexPart.dtype,\n shape: complexTensor.shape\n };\n}\n\nexport function complexAbs(\n args: {inputs: ComplexAbsInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n const xData = backend.texData.get(x.dataId);\n\n const program = new ComplexAbsProgram(x.shape);\n const programInputs = [\n makeComplexComponentTensorInfo(x, xData.complexTensorInfos.real),\n makeComplexComponentTensorInfo(x, xData.complexTensorInfos.imag),\n ];\n\n return backend.runWebGLProgram(\n program, programInputs, programInputs[0].dtype);\n}\n\nexport const complexAbsConfig: KernelConfig = {\n kernelName: ComplexAbs,\n backendName: 'webgl',\n kernelFunc: complexAbs as {} as KernelFunc\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class ConcatProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n\n // Concats 2d tensors along axis=1. See comments in MathBackendWebGL.concat().\n constructor(shapes: Array<[number, number]>) {\n this.outputShape = backend_util.computeOutShape(shapes, 1 /* axis */);\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const offsets: number[] = new Array(shapes.length - 1);\n offsets[0] = shapes[0][1];\n for (let i = 1; i < offsets.length; i++) {\n offsets[i] = offsets[i - 1] + shapes[i][1];\n }\n\n const snippets = [`if (yC < ${offsets[0]}) setOutput(getT0(yR, yC));`];\n for (let i = 1; i < offsets.length; i++) {\n const shift = offsets[i - 1];\n snippets.push(\n `else if (yC < ${offsets[i]}) ` +\n `setOutput(getT${i}(yR, yC-${shift}));`);\n }\n const lastIndex = offsets.length;\n const lastShift = offsets[offsets.length - 1];\n snippets.push(`else setOutput(getT${lastIndex}(yR, yC-${lastShift}));`);\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n ${snippets.join('\\n ')}\n }\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 {backend_util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ConcatPackedProgram implements GPGPUProgram {\n variableNames: string[];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(shapes: number[][], axis: number) {\n this.outputShape = backend_util.computeOutShape(shapes, axis);\n const shape = this.outputShape;\n const rank = shape.length;\n const dtype = getCoordsDataType(rank);\n const coords = getChannels('coords', rank);\n const channels = ['x', 'y', 'z', 'w', 'u', 'v'].slice(0, rank);\n this.variableNames = shapes.map((_, i) => `T${i}`);\n\n const offsets: number[] = new Array(shapes.length - 1);\n offsets[0] = shapes[0][axis];\n for (let i = 1; i < offsets.length; i++) {\n offsets[i] = offsets[i - 1] + shapes[i][axis];\n }\n\n const channel = channels[axis];\n const lastChannels = channels.slice(-2);\n const allChannels = channels.join();\n\n let getValueSnippet = `if (${channel} < ${offsets[0]}) {\n return getChannel(\n getT0(${allChannels}), vec2(${lastChannels.join()}));\n }`;\n for (let i = 1; i < offsets.length; i++) {\n const shift = offsets[i - 1];\n // Note: the >= comparison below may seem unnecessary given the check\n // above but is needed to workaround branch execution issues on some\n // devices. It makes all the conditions exclusive without relying on\n // execution order.\n getValueSnippet += `\n if (${channel} < ${offsets[i]} && ${channel} >= ${offsets[i - 1]}) {\n return getChannel(\n getT${i}(${shiftedChannels(channels, channel, shift)}),\n vec2(${shiftedChannels(lastChannels, channel, shift)}));\n }`;\n }\n const lastIndex = offsets.length;\n const shift = offsets[offsets.length - 1];\n getValueSnippet += `\n return getChannel(\n getT${lastIndex}(${shiftedChannels(channels, channel, shift)}),\n vec2(${shiftedChannels(lastChannels, channel, shift)}));`;\n\n this.userCode = `\n float getValue(${channels.map(x => 'int ' + x)}) {\n ${getValueSnippet}\n }\n\n void main() {\n ${dtype} coords = getOutputCoords();\n vec4 result = vec4(getValue(${coords}), 0., 0., 0.);\n\n ${coords[rank - 1]} = ${coords[rank - 1]} + 1;\n if (${coords[rank - 1]} < ${shape[rank - 1]}) {\n result.g = getValue(${coords});\n }\n\n ${coords[rank - 2]} = ${coords[rank - 2]} + 1;\n if (${coords[rank - 2]} < ${shape[rank - 2]}) {\n result.a = getValue(${coords});\n }\n\n ${coords[rank - 1]} = ${coords[rank - 1]} - 1;\n if (${coords[rank - 2]} < ${shape[rank - 2]} &&\n ${coords[rank - 1]} < ${shape[rank - 1]}) {\n result.b = getValue(${coords});\n }\n setOutput(result);\n }\n `;\n }\n}\n\n/**\n * Return an expression for coordinates into a vector where a given channel\n * will be offset by [shift].\n *\n * @param channels the channels to consider\n * @param channel the channel we want shifted\n * @param shift the amount to subtract from the channel.\n *\n * @returns a string of the form 'x, y-[shift], z' where any one channel can\n * have the shift applied.\n */\nfunction shiftedChannels(channels: string[], channel: string, shift: number) {\n const channelIdx = channels.indexOf(channel);\n const res = channels.map((c, idx) => {\n if (idx === channelIdx) {\n return `${c} - ${shift}`;\n } else {\n return c;\n }\n });\n return res.join();\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 {MathBackendWebGL} from '../backend_webgl';\nimport {identity} from './Identity';\n\nexport function imag(args: {inputs: ImagInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n const inputData = backend.texData.get(input.dataId);\n\n return identity({inputs: {x: inputData.complexTensorInfos.imag}, backend});\n}\n\nexport const imagConfig: KernelConfig = {\n kernelName: Imag,\n backendName: 'webgl',\n kernelFunc: imag as {} 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, ConcatInputs, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ConcatProgram} from '../concat_gpu';\nimport {ConcatPackedProgram} from '../concat_packed_gpu';\nimport {concatImplCPU} from '../kernel_utils/shared';\n\nimport {complex} from './Complex';\nimport {imag} from './Imag';\nimport {real} from './Real';\nimport {reshape} from './Reshape';\n\nexport function concatImpl(\n inputs: ConcatInputs, axis: number, backend: MathBackendWebGL): TensorInfo {\n const dtype = inputs[0].dtype;\n if (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 = concatImpl(reals, axis, backend);\n const imagConcated = concatImpl(imags, axis, backend);\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 let runOnCpu = backend.shouldExecuteOnCPU(inputs);\n\n // Run on cpu if dtype is string. For string, the backend represents it\n // as Uint8Array[], where each Uint8Array is a character. Given that the\n // computation is only on the outer array, uploading the whole data onto\n // gpu is wasteful. Also, currently webgl doesn't have a design to\n // upload and retrieve Uint8Array[] between cpu and gpu. Therefore, we\n // just run the kernel on cpu if dtype is string.\n if (dtype === 'string') {\n runOnCpu = true;\n }\n\n if (runOnCpu) {\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 tensors2D = 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 = tensors2D.map(t => {\n return {vals: backend.readSync(t.dataId), shape: t.shape};\n });\n\n // Concats 2d tensors along axis=1.\n const outShape =\n backend_util.computeOutShape(tensors2D.map(t => t.shape), 1 /* axis */);\n const simplyConcat = tensors2D[0].shape[0] === 1;\n const outVals =\n concatImplCPU(inputsValShapes, outShape, dtype, simplyConcat);\n\n const finalOutShape =\n backend_util.computeOutShape(inputs.map(t => t.shape), axis);\n\n const outInfo = backend.makeTensorInfo(finalOutShape, dtype, outVals);\n\n tensors2D.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return outInfo;\n }\n\n if (inputs.length > env().getNumber('WEBGL_MAX_TEXTURES_IN_SHADER')) {\n const midIndex = Math.floor(inputs.length / 2);\n const leftSide = concatImpl(inputs.slice(0, midIndex), axis, backend);\n const rightSide = concatImpl(inputs.slice(midIndex), axis, backend);\n\n const result = concatImpl([leftSide, rightSide], axis, backend);\n\n backend.disposeIntermediateTensorInfo(leftSide);\n backend.disposeIntermediateTensorInfo(rightSide);\n\n return result;\n }\n\n if (env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') &&\n inputs[0].shape.length > 1) {\n const program = new ConcatPackedProgram(inputs.map(t => t.shape), axis);\n return backend.runWebGLProgram(program, inputs, dtype);\n }\n\n const {tensors2D, outShape} = computeTensors2D(inputs, axis, backend);\n const program =\n new ConcatProgram(tensors2D.map(t => t.shape as [number, number]));\n const result = backend.runWebGLProgram(program, tensors2D, dtype);\n\n tensors2D.forEach(r => backend.disposeIntermediateTensorInfo(r));\n const reshapedResult =\n reshape({inputs: {x: result}, attrs: {shape: outShape}, backend});\n backend.disposeIntermediateTensorInfo(result);\n\n return reshapedResult;\n}\n\nfunction computeTensors2D(\n inputs: ConcatInputs, axis: number, backend: MathBackendWebGL) {\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 outShape = backend_util.computeOutShape(inputs.map(t => t.shape), axis);\n const tensors2D = inputs.map(\n x => reshape({\n inputs: {x},\n attrs: {shape: [-1, util.sizeFromShape(x.shape.slice(axis))]},\n backend\n }));\n\n return {tensors2D, outShape};\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 {MathBackendWebGL} from '../backend_webgl';\nimport {concatImpl} from './Concat_impl';\nimport {identity} from './Identity';\n\nexport function concat(\n args:\n {inputs: ConcatInputs, attrs: ConcatAttrs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, inputs[0].shape)[0];\n const outShape =\n 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 const shapes = $inputs.map(t => t.shape);\n backend_util.assertParamsConsistent(shapes, $axis);\n\n return concatImpl($inputs, $axis, backend);\n}\n\nexport const concatConfig: KernelConfig = {\n kernelName: Concat,\n backendName: 'webgl',\n kernelFunc: concat as {} as KernelFunc\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Conv2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, addBias = false,\n activation: string = null, hasPreluActivationWeights = false,\n hasLeakyreluAlpha = false) {\n this.outputShape = convInfo.outShape;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;\n const inputDepthVec4Remainder = convInfo.inChannels % 4;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n const rowDim = isChannelsLast ? 1 : 2;\n const colDim = isChannelsLast ? 2 : 3;\n const channelDim = isChannelsLast ? 3 : 1;\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivationWeights) {\n activationSnippet = `float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyreluAlpha) {\n activationSnippet = `float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `\n float activation(float x) {\n ${activation}\n }\n `;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivationWeights) {\n this.variableNames.push('preluActivationWeights');\n }\n\n if (hasLeakyreluAlpha) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${channelDim}];\n\n ivec2 xRCCorner =\n ivec2(coords[${rowDim}], coords[${colDim}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n int xR = xRCorner + wR * ${dilationHeight};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${inputDepthNearestVec4}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${isChannelsLast}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${inputDepthVec4Remainder === 1}) {\n\n if (${isChannelsLast}) {\n dotProd +=\n getX(batch, xR, xC, ${inputDepthNearestVec4}) *\n getW(wR, wC, ${inputDepthNearestVec4}, d2);\n } else {\n dotProd +=\n getX(batch, ${inputDepthNearestVec4}, xR, xC) *\n getW(wR, wC, ${inputDepthNearestVec4}, d2);\n }\n\n } else if (${inputDepthVec4Remainder === 2}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 1, d2)\n );\n\n if (${isChannelsLast}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${inputDepthNearestVec4}, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${inputDepthVec4Remainder === 3}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 1, d2),\n getW(wR, wC, ${inputDepthNearestVec4} + 2, d2)\n );\n\n if (${isChannelsLast}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 1),\n getX(batch, xR, xC, ${inputDepthNearestVec4} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${inputDepthNearestVec4}, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 1, xR, xC),\n getX(batch, ${inputDepthNearestVec4} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${addBiasSnippet}\n ${applyActivationSnippet}\n setOutput(result);\n }\n `;\n }\n}\n\nexport class Conv3DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.outShape;\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n\n const inputDepthNearestVec4 = Math.floor(convInfo.inChannels / 4) * 4;\n const inputDepthVec4Remainder = convInfo.inChannels % 4;\n\n this.userCode = `\n const ivec3 strides = ivec3(${strideDepth}, ${strideHeight}, ${\n strideWidth});\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < ${filterDepth}; wF++) {\n int xF = xFCorner + wF * ${dilationDepth};\n\n if (xF < 0 || xF >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n int xR = xRCorner + wR * ${dilationHeight};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${inputDepthNearestVec4}; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if (${inputDepthVec4Remainder === 1}) {\n dotProd +=\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}) *\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2);\n } else if (${inputDepthVec4Remainder === 2}) {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if (${inputDepthVec4Remainder === 3}) {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4}),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 1),\n getX(batch, xF, xR, xC, ${inputDepthNearestVec4} + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, ${inputDepthNearestVec4}, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 1, d2),\n getW(wF, wR, wC, ${inputDepthNearestVec4} + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {getGlslDifferences} from './glsl_version';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Im2ColPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n outputShape: number[], inputShape: number[],\n convInfo: backend_util.Conv2DInfo) {\n this.outputShape = outputShape;\n\n const {\n filterWidth,\n inChannels,\n strideWidth,\n strideHeight,\n padInfo,\n outWidth,\n dilationWidth,\n dilationHeight,\n dataFormat\n } = convInfo;\n const {left, top} = padInfo;\n const itemsPerBlockRow = inChannels * filterWidth;\n const glsl = getGlslDifferences();\n const isChannelsLast = dataFormat === 'channelsLast';\n const rowDim = isChannelsLast ? 0 : 1;\n const colDim = isChannelsLast ? 1 : 2;\n\n let unrolled = ``;\n\n for (let row = 0; row <= 1; row++) {\n for (let col = 0; col <= 1; col++) {\n unrolled += `\n blockIndex = rc.y + ${col};\n pos = rc.x + ${row};\n\n if(blockIndex < ${outputShape[1]} && pos < ${outputShape[0]}) {\n offsetY = int(blockIndex / (${outWidth})) * ${strideHeight} - ${\n top};\n d0 = offsetY + ${dilationHeight} * (pos / ${itemsPerBlockRow});\n\n if(d0 < ${inputShape[rowDim]} && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), ${outWidth}.) * ${\n strideWidth}. - ${left}.);\n d1 = offsetX + ${dilationWidth} * (int(mod(float(pos), ${\n itemsPerBlockRow}.) / ${inChannels}.));\n\n if(d1 < ${inputShape[colDim]} && d1 >= 0) {\n\n ch = int(mod(float(pos), ${inChannels}.));\n\n if (${isChannelsLast}) {\n innerDims = vec2(d1, ch);\n result[${row * 2 + col}] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${row * 2 + col}] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;\n }\n }\n\n this.userCode = `\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${unrolled}\n\n ${glsl.output} = result;\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 */\n\nimport {backend_util, env, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Im2ColPackedProgram} from '../im2col_packed_gpu';\nimport {mapActivationToShaderProgram} from '../kernel_utils/kernel_funcs_utils';\nimport {MatMulPackedProgram} from '../mulmat_packed_gpu';\nimport * as webgl_util from '../webgl_util';\n\nimport {batchMatMulImpl, MATMUL_SHARED_DIM_THRESHOLD} from './BatchMatMul_impl';\nimport {identity} from './Identity';\nimport {reshape} from './Reshape';\n\ntype Conv2DConfig = {\n x: TensorInfo,\n filter: TensorInfo,\n convInfo: backend_util.Conv2DInfo,\n backend: MathBackendWebGL,\n bias?: TensorInfo,\n preluActivationWeights?: TensorInfo,\n leakyreluAlpha?: number,\n activation?: backend_util.Activation\n};\n\n// For 1x1 kernels that iterate through every point in the input, convolution\n// can be expressed as matrix multiplication (without need for memory\n// remapping).\nexport function conv2dByMatMul({\n x,\n filter,\n convInfo,\n backend,\n bias = null,\n preluActivationWeights = null,\n leakyreluAlpha = 0,\n activation = null\n}: Conv2DConfig) {\n // Reshapes conv2D input to 2D tensors, uses matMul and then reshape the\n // result from 2D to 4D.\n const xShape = x.shape;\n const xTexData = backend.texData.get(x.dataId);\n const sharedMatMulDim = convInfo.inChannels;\n const outerShapeX = xShape[0] * xShape[1] * xShape[2];\n const outerShapeFilter = convInfo.outChannels;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n const transposeA = false;\n const transposeB = false;\n\n let out: TensorInfo;\n const intermediates: TensorInfo[] = [];\n\n // TODO: Once reduction ops are packed, batchMatMul will always be packed\n // and we can remove this condition.\n const batchMatMulWillBeUnpacked =\n (outerShapeX === 1 || outerShapeFilter === 1) &&\n sharedMatMulDim > MATMUL_SHARED_DIM_THRESHOLD;\n const reshapeWillBeExpensive = xShape[2] % 2 !== 0 && !!xTexData.isPacked;\n\n if (batchMatMulWillBeUnpacked || !env().getBool('WEBGL_LAZILY_UNPACK') ||\n !env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ||\n !reshapeWillBeExpensive) {\n const targetShape = isChannelsLast ? xShape[0] * xShape[1] * xShape[2] :\n xShape[0] * xShape[2] * xShape[3];\n const xReshaped = reshape({\n inputs: {x},\n backend,\n attrs: {shape: [1, targetShape, convInfo.inChannels]}\n });\n const filterReshaped = reshape({\n inputs: {x: filter},\n backend,\n attrs: {shape: [1, convInfo.inChannels, convInfo.outChannels]}\n });\n const result = batchMatMulImpl({\n a: xReshaped,\n b: filterReshaped,\n transposeA,\n transposeB,\n backend,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n\n out = reshape(\n {inputs: {x: result}, backend, attrs: {shape: convInfo.outShape}});\n\n intermediates.push(xReshaped);\n intermediates.push(filterReshaped);\n intermediates.push(result);\n } else {\n // Following optimization is specific to packed |x| with odd row count\n // (For example, in channelLast mode, 'row count' refers to x.shape[2]):\n // we avoid expensive packed 2x2 reshape by padding row count to next,\n // even number. When x.shape[2] is odd, the result of packed batchMatMul is\n // the same (has the same texture layout and and values in the texture) as\n // it is for even x.shape[2] + 1. We make the odd-rows tensor to look like\n // even-rows tensor before the operation and, after the batchMatMul,\n // fix the even-rows result to have odd number of rows.\n const targetShape = isChannelsLast ?\n xShape[0] * xShape[1] * (xShape[2] + 1) :\n xShape[0] * xShape[2] * (xShape[3] + 1);\n const xReshaped: TensorInfo = {\n dataId: x.dataId,\n shape: [1, targetShape, convInfo.inChannels],\n dtype: x.dtype\n };\n // xTexData.shape gets referenced from GPGPUBinary.inShapeInfos.\n // Decrementing row count, after batchMatMul->...->compileProgram leads to\n // invalid row count within the reference in GPGPUBinary.inShapeInfos.\n // Alternative fix would be to provide a copy to GPGPUBinary.inShapeInfos\n // in compileProgram method, but that would affect compilation of all\n // programs - instead, provide a copy here, with even row count, before\n // calling batchMatMul->...->compileProgram and after that, the original\n // xTexData.shape is restored.\n const originalXTexDataShape = xTexData.shape;\n xTexData.shape = xTexData.shape.slice();\n xTexData.shape[xTexData.shape.length - 2]++;\n util.assert(\n webgl_util.isReshapeFree(xTexData.shape, xReshaped.shape),\n () => `packed reshape ${xTexData.shape} to ${\n xReshaped.shape} isn't free`);\n const filterReshaped = reshape({\n inputs: {x: filter},\n backend,\n attrs: {shape: [1, convInfo.inChannels, convInfo.outChannels]}\n });\n intermediates.push(filterReshaped);\n const pointwiseConv = batchMatMulImpl({\n a: xReshaped,\n b: filterReshaped,\n backend,\n transposeA,\n transposeB,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n\n const pointwiseConvTexData = backend.texData.get(pointwiseConv.dataId);\n util.assert(\n pointwiseConvTexData.isPacked,\n () => 'batchMatMul result is expected to be packed');\n // Restore the input shape to original.\n xTexData.shape = originalXTexDataShape;\n // Set the output shape - there is no need for expensive reshape as data\n // layout is already correct.\n pointwiseConvTexData.shape = convInfo.outShape;\n\n out = identity({inputs: {x: pointwiseConv}, backend});\n out.shape = convInfo.outShape;\n\n intermediates.push(pointwiseConv);\n }\n\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n\n return out;\n}\n\n// Implements the im2row algorithm as outlined in \"High Performance\n// Convolutional Neural Networks for Document Processing\" (Suvisoft, 2006)\nexport function conv2dWithIm2Row({\n x,\n filter,\n convInfo,\n backend,\n bias = null,\n preluActivationWeights = null,\n leakyreluAlpha = 0,\n activation = null\n}: Conv2DConfig) {\n // Rearranges conv2d input so each block to be convolved over forms the\n // column of a new matrix with shape [filterWidth * filterHeight *\n // inChannels, outHeight * outWidth]. The filter is also rearranged so each\n // output channel forms a row of a new matrix with shape [outChannels,\n // filterWidth * filterHeight * inChannels]. The convolution is then\n // computed by multiplying these matrices and reshaping the result.\n const {\n filterWidth,\n filterHeight,\n inChannels,\n outWidth,\n outHeight,\n dataFormat\n } = convInfo;\n\n const isChannelsLast = dataFormat === 'channelsLast';\n\n const sharedDim = filterWidth * filterHeight * inChannels;\n const numCols = outHeight * outWidth;\n const x2ColShape = [sharedDim, numCols];\n const transposeA = true;\n const transposeB = false;\n\n const intermediates: TensorInfo[] = [];\n\n const xSqueezed =\n reshape({inputs: {x}, backend, attrs: {shape: x.shape.slice(1)}});\n const w2Row = reshape({\n inputs: {x: filter},\n backend,\n attrs: {shape: [1, sharedDim, util.sizeFromShape(filter.shape) / sharedDim]}\n });\n\n intermediates.push(xSqueezed);\n intermediates.push(w2Row);\n\n const im2ColProgram =\n new Im2ColPackedProgram(x2ColShape, xSqueezed.shape, convInfo);\n const im2Col = backend.runWebGLProgram(im2ColProgram, [xSqueezed], 'float32');\n const im2ColReshaped = reshape({\n inputs: {x: im2Col},\n backend,\n attrs: {shape: [1, x2ColShape[0], x2ColShape[1]]}\n });\n\n intermediates.push(im2Col);\n intermediates.push(im2ColReshaped);\n\n const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n const fusedActivation =\n activation ? mapActivationToShaderProgram(activation, true) : null;\n const matmulProgram = new MatMulPackedProgram(\n im2ColReshaped.shape as [number, number, number],\n w2Row.shape as [number, number, number],\n [1, numCols, convInfo.outChannels], transposeA, transposeB, hasBias,\n fusedActivation, hasPreluActivationWeights, hasLeakyreluAlpha);\n const inputs: TensorInfo[] = [im2ColReshaped, w2Row];\n if (bias) {\n inputs.push(bias);\n }\n if (hasPreluActivationWeights) {\n inputs.push(preluActivationWeights);\n }\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as {} as 'float32', 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n const product = backend.runWebGLProgram(matmulProgram, inputs, 'float32');\n\n const outShape = isChannelsLast ?\n [1, outHeight, outWidth, convInfo.outChannels] :\n [1, convInfo.outChannels, outHeight, outWidth];\n const out =\n reshape({inputs: {x: product}, backend, attrs: {shape: outShape}});\n\n intermediates.push(product);\n for (const i of intermediates) {\n backend.disposeIntermediateTensorInfo(i);\n }\n\n return out;\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, Conv2D, Conv2DAttrs, Conv2DInputs, env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DProgram} from '../conv_gpu';\nimport {conv2dByMatMul, conv2dWithIm2Row} from './Conv2D_impl';\nimport {reshape} from './Reshape';\n\nexport function conv2d(\n args:\n {inputs: Conv2DInputs, attrs: Conv2DAttrs, backend: MathBackendWebGL}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dataFormat, dilations, dimRoundingMode} = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, dilations, pad,\n dimRoundingMode, false /* depthwise */, $dataFormat);\n let out: TensorInfo;\n\n if (convInfo.filterHeight === 1 && convInfo.filterWidth === 1 &&\n convInfo.dilationHeight === 1 && convInfo.dilationWidth === 1 &&\n convInfo.strideHeight === 1 && convInfo.strideWidth === 1 &&\n (convInfo.padInfo.type === 'SAME' || convInfo.padInfo.type === 'VALID')) {\n out = conv2dByMatMul({x, filter, convInfo, backend});\n } else if (env().getBool('WEBGL_CONV_IM2COL') && x.shape[0] === 1) {\n out = conv2dWithIm2Row({x, filter, convInfo, backend});\n } else {\n const program = new Conv2DProgram(convInfo);\n out = backend.runWebGLProgram(program, [x, filter], 'float32');\n }\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: convInfo.outShape}});\n backend.disposeIntermediateTensorInfo(out);\n\n return outReshaped;\n}\n\nexport const conv2DConfig: KernelConfig = {\n kernelName: Conv2D,\n backendName: 'webgl',\n kernelFunc: conv2d as {} as KernelFunc,\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Conv2DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < ${convInfo.batchSize}; b++) {\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n if (${isChannelsLast}) {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class Conv2DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n\n const rowDim = isChannelsLast ? 1 : 2;\n const colDim = isChannelsLast ? 2 : 3;\n const channelDim = isChannelsLast ? 3 : 1;\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${channelDim}];\n\n ivec2 dyCorner = ivec2(coords[${rowDim}], coords[${colDim}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {\n\n if (${isChannelsLast}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class Conv3DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padFront = convInfo.padInfo.front;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n\n this.userCode = `\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < ${convInfo.batchSize}; b++) {\n for (int yF = 0; yF < ${convInfo.outDepth}; yF++) {\n int xF = wF + yF * ${strideDepth} - ${padFront};\n\n if (xF < 0 || xF >= ${convInfo.inDepth}) {\n continue;\n }\n\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class Conv3DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterDepth = convInfo.filterDepth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n\n const padFront = filterDepth - 1 - convInfo.padInfo.front;\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < ${filterDepth}; wF++) {\n float dyF = float(dyFCorner + wF) / ${strideDepth}.0;\n\n if (dyF < 0.0 || dyF >= ${convInfo.outDepth}.0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = ${filterDepth} - 1 - wF;\n\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n for (int d2 = 0; d2 < ${convInfo.outChannels}; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\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 */\n\nimport {backend_util, Conv2DBackpropFilter, Conv2DBackpropFilterAttrs, Conv2DBackpropFilterInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DDerFilterProgram} from '../conv_backprop_gpu';\n\nexport function conv2DBackpropFilter(args: {\n inputs: Conv2DBackpropFilterInputs,\n attrs: Conv2DBackpropFilterAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, dataFormat, dimRoundingMode, filterShape} = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad, dimRoundingMode, false /* depthwise */,\n $dataFormat);\n\n const program = new Conv2DDerFilterProgram(convInfo);\n return backend.runWebGLProgram(program, [x, dy], 'float32');\n}\n\nexport const conv2DBackpropFilterConfig: KernelConfig = {\n kernelName: Conv2DBackpropFilter,\n backendName: 'webgl',\n kernelFunc: conv2DBackpropFilter as {} 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, Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DDerInputProgram} from '../conv_backprop_gpu';\n\nexport function conv2DBackpropInput(args: {\n inputs: Conv2DBackpropInputInputs,\n attrs: Conv2DBackpropInputAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {inputShape, strides, pad, dataFormat, dimRoundingMode} = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n 1 /* dilations */, pad, dimRoundingMode, false, $dataFormat);\n\n const program = new Conv2DDerInputProgram(convInfo);\n return backend.runWebGLProgram(program, [dy, filter], 'float32');\n}\n\nexport const conv2DBackpropInputConfig: KernelConfig = {\n kernelName: Conv2DBackpropInput,\n backendName: 'webgl',\n kernelFunc: conv2DBackpropInput as {} 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, Conv3D, Conv3DAttrs, Conv3DInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv3DProgram} from '../conv_gpu';\n\nexport function conv3D(\n args:\n {inputs: Conv3DInputs, attrs: Conv3DAttrs, backend: MathBackendWebGL}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations} = attrs;\n\n const convInfo = backend_util.computeConv3DInfo(\n x.shape as [number, number, number, number, number],\n filter.shape as [number, number, number, number, number], strides,\n dilations, pad);\n\n const program = new Conv3DProgram(convInfo);\n return backend.runWebGLProgram(program, [x, filter], 'float32');\n}\n\nexport const conv3DConfig: KernelConfig = {\n kernelName: Conv3D,\n backendName: 'webgl',\n kernelFunc: conv3D as {} 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, Conv3DBackpropFilterV2, Conv3DBackpropFilterV2Attrs, Conv3DBackpropFilterV2Inputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv3DDerFilterProgram} from '../conv_backprop_gpu';\n\nexport function conv3DBackpropFilterV2(args: {\n inputs: Conv3DBackpropFilterV2Inputs,\n attrs: Conv3DBackpropFilterV2Attrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, pad, filterShape} = attrs;\n\n const convInfo = backend_util.computeConv3DInfo(\n x.shape as [number, number, number, number, number], filterShape, strides,\n 1 /* dilations */, pad);\n\n const program = new Conv3DDerFilterProgram(convInfo);\n return backend.runWebGLProgram(program, [x, dy], 'float32');\n}\n\nexport const conv3DBackpropFilterV2Config: KernelConfig = {\n kernelName: Conv3DBackpropFilterV2,\n backendName: 'webgl',\n kernelFunc: conv3DBackpropFilterV2 as {} 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, Conv3DBackpropInputV2, Conv3DBackpropInputV2Attrs, Conv3DBackpropInputV2Inputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv3DDerInputProgram} from '../conv_backprop_gpu';\n\nexport function conv3DBackpropInput(args: {\n inputs: Conv3DBackpropInputV2Inputs,\n attrs: Conv3DBackpropInputV2Attrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {pad, strides, inputShape} = attrs;\n\n const convInfo = backend_util.computeConv3DInfo(\n inputShape, filter.shape as [number, number, number, number, number],\n strides, 1 /* dilations */, pad);\n\n const program = new Conv3DDerInputProgram(convInfo);\n return backend.runWebGLProgram(program, [dy, filter], 'float32');\n}\n\nexport const conv3DBackpropInputConfig: KernelConfig = {\n kernelName: Conv3DBackpropInputV2,\n backendName: 'webgl',\n kernelFunc: conv3DBackpropInput as {} 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 {Cos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_UNARY, unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst COS = CHECK_NAN_SNIPPET_UNARY + `\n return cos(x);\n`;\n\nexport const cos = unaryKernelFunc({opSnippet: COS});\n\nexport const cosConfig: KernelConfig = {\n kernelName: Cos,\n backendName: 'webgl',\n kernelFunc: cos,\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 {Cosh, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst COSH = `\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n`;\n\nexport const cosh = unaryKernelFunc({opSnippet: COSH});\n\nexport const coshConfig: KernelConfig = {\n kernelName: Cosh,\n backendName: 'webgl',\n kernelFunc: cosh,\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class CropAndResizeProgram implements GPGPUProgram {\n variableNames = ['Image', 'Boxes', 'BoxInd'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n imageShape: [number, number, number, number], boxShape: [number, number],\n cropSize: [number, number], method: 'bilinear'|'nearest',\n extrapolationValue: number) {\n const [batch, imageHeight, imageWidth, depth] = imageShape;\n const [numBoxes, ] = boxShape;\n const [cropHeight, cropWidth] = cropSize;\n this.outputShape = [numBoxes, cropHeight, cropWidth, depth];\n const methodId = method === 'bilinear' ? 1 : 0;\n\n const [inputHeightFloat, inputWidthFloat] =\n [`${imageHeight - 1}.0`, `${imageWidth - 1}.0`];\n\n const [heightRatio, heightScale, inY] = cropHeight > 1 ?\n [\n `${(imageHeight - 1) / (cropHeight - 1)}`,\n '(y2-y1) * height_ratio',\n `y1*${inputHeightFloat} + float(y)*(height_scale)`,\n ] :\n [\n '0.0',\n '0.0',\n `0.5 * (y1+y2) * ${inputHeightFloat}`,\n ];\n const [widthRatio, widthScale, inX] = cropWidth > 1 ?\n [\n `${(imageWidth - 1) / (cropWidth - 1)}`,\n '(x2-x1) * width_ratio',\n `x1*${inputWidthFloat} + float(x)*(width_scale)`,\n ] :\n [\n '0.0',\n '0.0',\n `0.5 * (x1+x2) * ${inputWidthFloat}`,\n ];\n\n // Reference implementation\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/crop_and_resize_op_gpu.cu.cc\n this.userCode = `\n const float height_ratio = float(${heightRatio});\n const float width_ratio = float(${widthRatio});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${batch}) {\n return;\n }\n\n float height_scale = ${heightScale};\n float width_scale = ${widthScale};\n\n float in_y = ${inY};\n if( in_y < 0.0 || in_y > ${inputHeightFloat} ) {\n setOutput(float(${extrapolationValue}));\n return;\n }\n float in_x = ${inX};\n if( in_x < 0.0 || in_x > ${inputWidthFloat} ) {\n setOutput(float(${extrapolationValue}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${methodId} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\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 */\n\nimport {CropAndResize, CropAndResizeAttrs, CropAndResizeInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CropAndResizeProgram} from '../crop_and_resize_gpu';\n\nexport const cropAndResize = (args: {\n inputs: CropAndResizeInputs,\n backend: MathBackendWebGL,\n attrs: CropAndResizeAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {image, boxes, boxInd} = inputs;\n const {cropSize, method, extrapolationValue} = attrs;\n\n const program = new CropAndResizeProgram(\n image.shape as [number, number, number, number],\n boxes.shape as [number, number], cropSize, method, extrapolationValue);\n return backend.runWebGLProgram(program, [image, boxes, boxInd], 'float32');\n};\n\nexport const cropAndResizeConfig: KernelConfig = {\n kernelName: CropAndResize,\n backendName: 'webgl',\n kernelFunc: cropAndResize as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class CumSumProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n customUniforms = [{name: 'index', type: 'float' as UniformType}];\n\n constructor(shape: number[], exclusive: boolean, reverse: boolean) {\n this.outputShape = shape;\n const rank = shape.length;\n const val = exclusive ? '0.0' : `getX(${getCoords(rank, 'coords')})`;\n const length = shape[shape.length - 1];\n let condition = '';\n let idxString = '';\n // When exclusive is set, the cumsum op becomes roll op that copies the\n // value from the previous index based on the direction specified by the\n // reverse flag.\n if (exclusive) {\n condition = reverse ? `end != ${length - 1}` : 'end != 0';\n idxString = reverse ? 'end + 1' : 'end - 1';\n } else {\n condition = reverse ? `end + pow2 < ${length}` : 'end >= pow2';\n idxString = (reverse ? 'end + pow2' : 'end - pow2');\n }\n\n this.userCode = `\n void main() {\n ${getCoordsDataType(rank)} coords = getOutputCoords();\n int end = ${getFinalCoord(rank, 'coords')};\n float val = ${val};\n int pow2 = int(pow(2.0, index));\n if (${condition}) {\n int idx = ${idxString};\n ${getFinalCoord(rank, 'coords')} = idx;\n val += getX(${getCoords(rank, 'coords')});\n }\n setOutput(val);\n }\n `;\n }\n}\n\nfunction getCoords(rank: number, name: string): string {\n if (rank === 1) {\n return `${name}`;\n } else if (rank === 2) {\n return `${name}.x, ${name}.y`;\n } else if (rank === 3) {\n return `${name}.x, ${name}.y, ${name}.z`;\n } else if (rank === 4) {\n return `${name}.x, ${name}.y, ${name}.z, ${name}.w`;\n } else {\n throw Error(`Cumulative sum for rank ${rank} is not yet supported`);\n }\n}\n\nfunction getFinalCoord(rank: number, name: string): string {\n if (rank === 1) {\n return `${name}`;\n } else if (rank === 2) {\n return `${name}.y`;\n } else if (rank === 3) {\n return `${name}.z`;\n } else if (rank === 4) {\n return `${name}.w`;\n } else {\n throw Error(`Cumulative sum for rank ${rank} is not yet supported`);\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, Cumsum, CumsumAttrs, CumsumInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CumSumProgram} from '../cumsum_gpu';\n\nimport {identity} from './Identity';\nimport {transpose} from './Transpose';\n\nexport function cumsum(\n args:\n {inputs: CumsumInputs, backend: MathBackendWebGL, attrs: CumsumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, exclusive, reverse} = attrs;\n\n const xRank = x.shape.length;\n const permutation = backend_util.getAxesPermutation([axis], xRank);\n let permutedX = x;\n if (permutation != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n }\n const permutedAxis = backend_util.getInnerMostAxes(1, xRank)[0];\n\n if (permutedAxis !== xRank - 1) {\n throw new Error(\n `WebGL cumsum shader expects an inner-most axis=${\n x.shape.length - 1} ` +\n `but got axis=${axis}`);\n }\n const size = permutedX.shape[permutedAxis];\n let result = identity({inputs: {x: permutedX}, backend});\n // Use cumsum parallel algorithm, ref:\n // https://developer.nvidia.com/gpugems/gpugems3/part-vi-gpu-computing/chapter-39-parallel-prefix-sum-scan-cuda\n\n for (let i = 0; i <= Math.ceil(Math.log2(size)) - 1; i++) {\n const program = new CumSumProgram(permutedX.shape, false, reverse);\n const customValues = [[i]];\n const prevResult = result;\n result =\n backend.runWebGLProgram(program, [result], result.dtype, customValues);\n backend.disposeIntermediateTensorInfo(prevResult);\n }\n // For exclusive cumsum, shift the end result in the direction of sum\n // and add 0 to the front index.\n if (exclusive) {\n const program = new CumSumProgram(permutedX.shape, exclusive, reverse);\n const prevResult = result;\n result = backend.runWebGLProgram(program, [result], result.dtype);\n backend.disposeIntermediateTensorInfo(prevResult);\n }\n\n if (permutation != null) {\n const reversePermutation = backend_util.getUndoAxesPermutation(permutation);\n const reverseTransposedResult = transpose(\n {inputs: {x: result}, backend, attrs: {perm: reversePermutation}});\n\n backend.disposeIntermediateTensorInfo(result);\n backend.disposeIntermediateTensorInfo(permutedX);\n\n return reverseTransposedResult;\n }\n\n return result;\n}\n\nexport const cumsumConfig: KernelConfig = {\n kernelName: Cumsum,\n backendName: 'webgl',\n kernelFunc: cumsum as {} 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 {DenseBincount, DenseBincountAttrs, DenseBincountInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {bincountImplCPU, bincountReduceImplCPU} from '../kernel_utils/shared';\n\nexport function denseBincount(args: {\n inputs: DenseBincountInputs,\n backend: MathBackendWebGL,\n attrs: DenseBincountAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, weights} = inputs;\n const {size, binaryOutput} = attrs;\n\n if (x.shape.length === 1) {\n const xVals = backend.readSync(x.dataId) as TypedArray;\n const weightsVals = backend.readSync(weights.dataId) as TypedArray;\n\n const outVals =\n bincountImplCPU(xVals, weightsVals, weights.dtype, weights.shape, size);\n\n return backend.makeTensorInfo([size], weights.dtype, outVals);\n } else if (x.shape.length === 2) {\n const xBuf = backend.bufferSync(x);\n const weightsBuf = backend.bufferSync(weights);\n\n const outBuf = bincountReduceImplCPU(xBuf, weightsBuf, size, binaryOutput);\n\n return backend.makeTensorInfo(outBuf.shape, weights.dtype, outBuf.values);\n }\n\n throw new Error(\n `Error in denseBincount: input must be at most rank 2, but got rank` +\n `${x.shape.length}.`);\n}\n\nexport const denseBincountConfig: KernelConfig = {\n kernelName: DenseBincount,\n backendName: 'webgl',\n kernelFunc: denseBincount as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthToSpaceProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n blockSize: number;\n dataFormat: string;\n\n constructor(\n outputShape: number[], blockSize: number, dataFormat: 'NHWC'|'NCHW') {\n this.outputShape = outputShape;\n this.blockSize = blockSize;\n this.dataFormat = dataFormat;\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = ${this.getHeightCoordString()};\n int w = ${this.getWidthCoordString()};\n int d = ${this.getDepthCoordString()};\n\n int in_h = h / ${blockSize};\n int offset_h = imod(h, ${blockSize});\n int in_w = w / ${blockSize};\n int offset_w = imod(w, ${blockSize});\n int offset_d = (offset_h * ${blockSize} + offset_w) *\n ${this.getOutputDepthSize()};\n int in_d = d + offset_d;\n\n float result = ${this.getInputSamplingString()};\n setOutput(result);\n }\n `;\n }\n\n private getHeightCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[1]`;\n } else {\n return `coords[2]`;\n }\n }\n\n private getWidthCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[2]`;\n } else {\n return `coords[3]`;\n }\n }\n\n private getDepthCoordString(): string {\n if (this.dataFormat === 'NHWC') {\n return `coords[3]`;\n } else {\n return `coords[1]`;\n }\n }\n\n private getOutputDepthSize(): number {\n if (this.dataFormat === 'NHWC') {\n return this.outputShape[3];\n } else {\n return this.outputShape[1];\n }\n }\n\n private getInputSamplingString(): string {\n if (this.dataFormat === 'NHWC') {\n return `getX(b, in_h, in_w, in_d)`;\n } else {\n return `getX(b, in_d, in_h, in_w)`;\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 {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthToSpaceProgram} from '../depth_to_space_gpu';\n\nexport function depthToSpace(args: {\n inputs: DepthToSpaceInputs,\n backend: MathBackendWebGL,\n attrs: DepthToSpaceAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockSize, dataFormat} = attrs;\n\n util.assert(\n blockSize > 1,\n () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);\n\n const batchSize = x.shape[0];\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 const outputHeight = inputHeight * blockSize;\n const outputWidth = inputWidth * blockSize;\n const outputDepth = inputDepth / (blockSize * blockSize);\n\n const outputShape = (dataFormat === 'NHWC') ?\n [batchSize, outputHeight, outputWidth, outputDepth] :\n [batchSize, outputDepth, outputHeight, outputWidth];\n\n const program = new DepthToSpaceProgram(outputShape, blockSize, dataFormat);\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const depthToSpaceConfig: KernelConfig = {\n kernelName: DepthToSpace,\n backendName: 'webgl',\n kernelFunc: depthToSpace as {} as KernelFunc\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthwiseConv2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, addBias = false,\n activation: string = null, hasPreluActivation = false,\n hasLeakyReluAlpha = false) {\n this.outputShape = convInfo.outShape;\n\n const xNumRows = convInfo.inHeight;\n const xNumCols = convInfo.inWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivation) {\n activationSnippet = `float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyReluAlpha) {\n activationSnippet = `float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `\n float activation(float x) {\n ${activation}\n }\n `;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivation) {\n this.variableNames.push('preluActivationWeights');\n }\n if (hasLeakyReluAlpha) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${channelMul};\n int q = d2 - d1 * ${channelMul};\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n int xR = xRCorner + wR * ${dilationHeight};\n\n if (xR < 0 || xR >= ${xNumRows}) {\n continue;\n }\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n int xC = xCCorner + wC * ${dilationWidth};\n\n if (xC < 0 || xC >= ${xNumCols}) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${addBiasSnippet}\n ${applyActivationSnippet}\n setOutput(result);\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 {backend_util, util} from '@tensorflow/tfjs-core';\n\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthwiseConvPacked2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n convInfo: backend_util.Conv2DInfo, addBias = false,\n activation: string = null, hasPreluActivation = false,\n hasLeakyReluAlpha = false) {\n this.outputShape = convInfo.outShape;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n const xNumRows = convInfo.inHeight;\n const xNumCols = convInfo.inWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const texelsAcross = filterWidth;\n\n let mainLoop = `\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;`;\n\n for (let c = 0; c < filterWidth; c++) {\n mainLoop += `\n vec4 xTexelC${c * 2};\n int xTexelC${c * 2}Ready;\n vec4 xTexelC${c * 2 + 1};\n int xTexelC${c * 2 + 1}Ready;\n vec4 xC${c};`;\n }\n\n /**\n * This vectorized implementation works by gathering the values needed for\n * each output channel's dot product into vec4's and then multiplying them\n * all together (this happens in the final double for-loop below). Most of\n * the main loop consists of constructing these vec4's with the minimum\n * number of texture2D calls, which means making use of all four returned\n * values from a texture2D call at once.\n */\n for (let r = 0; r < filterHeight; r++) {\n for (let c = 0; c < filterWidth; c++) {\n mainLoop += `\n xTexelC${c * 2} = vec4(0.0);\n xTexelC${c * 2}Ready = 0;\n xTexelC${c * 2 + 1} = vec4(0.0);\n xTexelC${c * 2 + 1}Ready = 0;\n xC${c} = vec4(0.0);`;\n }\n mainLoop += `\n xR = xRCorner + ${r * dilationHeight};\n if (xR >=0 && xR < ${xNumRows}) {\n `;\n\n for (let texelC = 0; texelC < (texelsAcross + 1) / 2; texelC++) {\n const colIndex = texelC * 2;\n const c = colIndex * dilationWidth;\n\n mainLoop += `\n xC = xCCorner + ${c};\n `;\n\n if (strideWidth === 1) {\n if (colIndex < filterWidth) {\n // If padding is odd, the outer texels have to be composed.\n if (padLeft % 2 === 1) {\n // TODO: Ensure vec4 previous does not result in redundant sample,\n // and avoid setting xTexelRC's that exceed the boundary in the\n // first place rather than resetting them to vec4(0)).\n\n // To compute xCOffset:\n // - If padding is odd, we must add 1 to ensure we ask for an\n // even-numbered row.\n // - We subtract 2 to access the previous texel.\n\n mainLoop += `\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= ${xNumCols}) {\n xTexelC${colIndex}.zw = vec2(0.0);\n }\n xTexelC${colIndex}Ready = 1;\n }\n `;\n // This texel has been read in previous iteration if the dilation\n // is 1.\n if (dilationWidth === 1 && c > 0) {\n mainLoop += `\n xC${colIndex} = vec4(xTexelC${colIndex - 2}.zw, xTexelC${\n colIndex}.xy);\n `;\n } else {\n mainLoop += `\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < ${xNumCols}) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= ${xNumCols}) {\n previous.zw = vec2(0.0);\n }\n\n xC${colIndex} = vec4(previous.zw, xTexelC${colIndex}.xy);\n } else {\n xC${colIndex} = vec4(0.0, 0.0, xTexelC${colIndex}.xy);\n }\n `;\n }\n } else {\n // Padding is even, so xRC corresponds to a single texel.\n mainLoop += `\n if (xC >= 0 && xC < ${xNumCols} && xTexelC${\n colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xC, d1);\n if (xC + 1 >= ${xNumCols}) {\n xTexelC${colIndex}.zw = vec2(0.0);\n }\n xTexelC${colIndex}Ready = 1;\n }\n\n xC${colIndex} = xTexelC${colIndex};\n `;\n }\n\n if (c + 1 < filterWidth) {\n // If dilation is even, the second entry should match the first\n // (either both are composed or both are single samples). But if\n // dilation is odd, then the second entry should be the opposite\n // of the first (if the first is composed, the second is a single\n // sample, and vice versa.)\n\n const nextTexelOffset = padLeft % 2 === 0 ?\n util.nearestLargerEven(dilationWidth) :\n dilationWidth;\n\n if ((dilationWidth % 2 === 0 && padLeft % 2 === 1) ||\n (dilationWidth % 2 !== 0 && padLeft % 2 !== 1)) {\n mainLoop += `\n xCOffset = xC + ${padLeft % 2} + ${nextTexelOffset};\n\n if (xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n colIndex + 1}Ready == 0) {\n xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= ${xNumCols}) {\n xTexelC${colIndex + 1}.zw = vec2(0.0);\n }\n xTexelC${colIndex + 1}Ready = 1;\n }\n `;\n\n // If dilation > 1 then the xRC's will not be able to share any\n // values, so each xRC will require two unique calls to getX.\n if (dilationWidth > 1) {\n mainLoop += `\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xCOffset, d1);\n xTexelC${colIndex}Ready = 1;\n }\n `;\n }\n\n mainLoop += `\n xC${colIndex + 1} = vec4(xTexelC${colIndex}.zw, xTexelC${\n colIndex + 1}.xy);\n `;\n } else {\n // If dilation is 1 and padding is odd, we have already read the\n // texel when constructing the previous x value. Here we can\n // simply skip the texture read.\n if (nextTexelOffset === 1) {\n mainLoop += `\n xC${colIndex + 1} = xTexelC${colIndex};\n `;\n } else {\n mainLoop += `\n xCOffset = xC + ${nextTexelOffset};\n\n if (xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n colIndex + 1}Ready == 0) {\n xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= ${xNumCols}) {\n xTexelC${colIndex + 1}.zw = vec2(0.0);\n }\n xTexelC${colIndex + 1}Ready = 1;\n }\n\n xC${colIndex + 1} = xTexelC${colIndex + 1};\n `;\n }\n }\n }\n }\n } else { // stride === 2\n if (c < filterWidth) {\n // Depending on whether padLeft is even or odd, we want either the\n // xy or zw channels from X texels for xC${colIndex}. If padLeft is\n // even, xC${colIndex +1} is simply the zw channels of texels we've\n // already sampled. But if padLeft is odd, xC{$c + 1}.zw will\n // need to come from the xy channels of a new texel, hence the `\n // vec4\n // final` initialized below.\n if (padLeft % 2 === 1) {\n mainLoop += `\n xCOffset = xC + 1 - ${strideWidth};\n if(xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= ${xNumCols}) {\n xTexelC${colIndex}.zw = vec2(0.0);\n }\n xTexelC${colIndex}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < ${xNumCols} && xTexelC${\n colIndex + 1}Ready == 0) {\n xTexelC${colIndex + 1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= ${xNumCols}) {\n xTexelC${colIndex + 1}.zw = vec2(0.0);\n }\n xTexelC${colIndex + 1}Ready = 1;\n }\n\n xC${colIndex} = vec4(xTexelC${colIndex}.zw, xTexelC${\n colIndex + 1}.zw);\n `;\n\n if (c + 1 < filterWidth) {\n mainLoop += `\n final = vec4(0.0);\n xCOffset = xC + 1 + ${strideWidth};\n if(xCOffset >= 0 && xCOffset < ${xNumCols}) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${colIndex + 1} = vec4(xTexelC${colIndex + 1}.xy, final.xy);\n `;\n }\n } else {\n mainLoop += `\n if(xC >= 0 && xC < ${xNumCols} && xTexelC${\n colIndex}Ready == 0) {\n xTexelC${colIndex} = getX(batch, xR, xC, d1);\n if (xC + 1 >= ${xNumCols}) {\n xTexelC${colIndex}.zw = vec2(0.0);\n }\n xTexelC${colIndex}Ready = 1;\n }\n\n xCOffset = xC + ${strideWidth};\n if(xCOffset >= 0 && xCOffset < ${xNumCols} && xTexelC${\n colIndex + 1}Ready == 0) {\n xTexelC${colIndex + 1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= ${xNumCols}) {\n xTexelC${colIndex + 1}.zw = vec2(0.);\n }\n xTexelC${colIndex + 1}Ready = 1;\n }\n\n xC${colIndex} = vec4(\n xTexelC${colIndex}.xy, xTexelC${colIndex + 1}.xy);\n `;\n\n if (c + 1 < filterWidth) {\n mainLoop += `\n xC${colIndex + 1} = vec4(xTexelC${colIndex}.zw, xTexelC${\n colIndex + 1}.zw);\n `;\n }\n }\n }\n }\n\n // localize the dotProd accumulation within the loop, the theory is for\n // GPU with limited cache, accumulate sum across large amount of\n // veriables will cause lots of cache misses. (i.e. 5x5 filter will have\n // 50 variables)\n if (colIndex < filterWidth) {\n mainLoop += `\n wTexel = getW(${r}, ${c}, d1, q);\n dotProd += xC${colIndex} * vec4(wTexel.xz, wTexel.xz);\n `;\n\n if (c + 1 < filterWidth) {\n mainLoop += `\n wTexel = getW(${r}, ${c + 1}, d1, q);\n dotProd += xC${colIndex + 1} * vec4(wTexel.xz, wTexel.xz);\n `;\n }\n }\n }\n mainLoop += `\n }\n `;\n }\n\n let activationSnippet = '', applyActivationSnippet = '';\n if (activation) {\n if (hasPreluActivation) {\n activationSnippet = `vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${activation}\n }`;\n } else if (hasLeakyReluAlpha) {\n activationSnippet = `vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${activation}\n }`;\n } else {\n activationSnippet = `vec4 activation(vec4 x) {\n ${activation}\n }`;\n }\n\n applyActivationSnippet = `result = activation(result);`;\n }\n\n const addBiasSnippet = addBias ? 'result += getBiasAtOutCoords();' : '';\n if (addBias) {\n this.variableNames.push('bias');\n }\n\n if (hasPreluActivation) {\n this.variableNames.push('preluActivationWeights');\n }\n if (hasLeakyReluAlpha) {\n this.variableNames.push('leakyreluAlpha');\n }\n\n this.userCode = `\n ${activationSnippet}\n\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${channelMul};\n int q = d2 - d1 * ${channelMul};\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${mainLoop}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${addBiasSnippet}\n ${applyActivationSnippet}\n setOutput(result);\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 */\n\nimport {backend_util, DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs, env, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DProgram} from '../conv_gpu_depthwise';\nimport {DepthwiseConvPacked2DProgram} from '../conv_packed_gpu_depthwise';\n\nexport function depthwiseConv2dNative(args: {\n inputs: DepthwiseConv2dNativeInputs,\n attrs: DepthwiseConv2dNativeAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations, dimRoundingMode} = attrs;\n\n let $dilations = dilations;\n if ($dilations == null) {\n $dilations = [1, 1];\n }\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, $dilations),\n () => 'Error in depthwiseConv2d: Either strides or dilations must be ' +\n `1. Got strides ${strides} and dilations '${$dilations}'`);\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, $dilations,\n pad, dimRoundingMode, true /* depthwise */);\n\n let program: DepthwiseConv2DProgram|DepthwiseConvPacked2DProgram;\n if (env().getBool('WEBGL_PACK_DEPTHWISECONV') && convInfo.strideWidth <= 2 &&\n convInfo.outChannels / convInfo.inChannels === 1) {\n program = new DepthwiseConvPacked2DProgram(convInfo);\n } else {\n program = new DepthwiseConv2DProgram(convInfo);\n }\n return backend.runWebGLProgram(program, [x, filter], 'float32');\n}\n\nexport const depthwiseConv2dNativeConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNative,\n backendName: 'webgl',\n kernelFunc: depthwiseConv2dNative as {} as KernelFunc,\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class DepthwiseConv2DDerFilterProgram implements GPGPUProgram {\n variableNames = ['x', 'dy'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.filterShape;\n\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const padTop = convInfo.padInfo.top;\n const padLeft = convInfo.padInfo.left;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * ${channelMul} + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < ${convInfo.batchSize}; b++) {\n for (int yR = 0; yR < ${convInfo.outHeight}; yR++) {\n int xR = wR + yR * ${strideHeight} - ${padTop};\n\n if (xR < 0 || xR >= ${convInfo.inHeight}) {\n continue;\n }\n\n for (int yC = 0; yC < ${convInfo.outWidth}; yC++) {\n int xC = wC + yC * ${strideWidth} - ${padLeft};\n\n if (xC < 0 || xC >= ${convInfo.inWidth}) {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class DepthwiseConv2DDerInputProgram implements GPGPUProgram {\n variableNames = ['dy', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n\n const padTop = filterHeight - 1 - convInfo.padInfo.top;\n const padLeft = filterWidth - 1 - convInfo.padInfo.left;\n const channelMul = convInfo.outChannels / convInfo.inChannels;\n\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < ${filterHeight}; wR++) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${filterHeight} - 1 - wR;\n\n for (int wC = 0; wC < ${filterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${filterWidth} - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < ${channelMul}; dm++) {\n int d2 = d1 * ${channelMul} + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\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 */\n\nimport {backend_util, DepthwiseConv2dNativeBackpropFilter, DepthwiseConv2dNativeBackpropFilterAttrs, DepthwiseConv2dNativeBackpropFilterInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DDerFilterProgram} from '../conv_backprop_gpu_depthwise';\n\nexport function depthwiseConv2dNativeBackpropFilter(args: {\n inputs: DepthwiseConv2dNativeBackpropFilterInputs,\n attrs: DepthwiseConv2dNativeBackpropFilterAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, dy} = inputs;\n const {strides, dilations, pad, dimRoundingMode, filterShape} = attrs;\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number], filterShape, strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const program = new DepthwiseConv2DDerFilterProgram(convInfo);\n return backend.runWebGLProgram(program, [x, dy], 'float32');\n}\n\nexport const depthwiseConv2dNativeBackpropFilterConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropFilter,\n backendName: 'webgl',\n kernelFunc: depthwiseConv2dNativeBackpropFilter as {} 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, DepthwiseConv2dNativeBackpropInput, DepthwiseConv2dNativeBackpropInputAttrs, DepthwiseConv2dNativeBackpropInputInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DDerInputProgram} from '../conv_backprop_gpu_depthwise';\n\nexport function depthwiseConv2dNativeBackpropInput(args: {\n inputs: DepthwiseConv2dNativeBackpropInputInputs,\n attrs: DepthwiseConv2dNativeBackpropInputAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {dy, filter} = inputs;\n const {strides, dilations, pad, dimRoundingMode, inputShape} = attrs;\n\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n dilations, pad, dimRoundingMode, true /* depthwise */);\n\n const program = new DepthwiseConv2DDerInputProgram(convInfo);\n return backend.runWebGLProgram(program, [dy, filter], 'float32');\n}\n\nexport const depthwiseConv2dNativeBackpropInputConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNativeBackpropInput,\n backendName: 'webgl',\n kernelFunc: depthwiseConv2dNativeBackpropInput as {} 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 {GPGPUProgram} from './gpgpu_math';\n\nexport class DiagProgram implements GPGPUProgram {\n variableNames = ['X'];\n outputShape: number[];\n userCode: string;\n\n constructor(size: number) {\n this.outputShape = [size, size];\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\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 */\n\nimport {Diag, DiagInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DiagProgram} from '../diag_gpu';\nimport {reshape} from './Reshape';\n\nexport function diag(args: {inputs: DiagInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n const outShape = [...x.shape, ...x.shape];\n const xSize = util.sizeFromShape(x.shape);\n\n const flat = reshape({inputs: {x}, backend, attrs: {shape: [xSize]}});\n\n const program = new DiagProgram(xSize);\n const res = backend.runWebGLProgram(program, [flat], flat.dtype);\n\n const out = reshape({inputs: {x: res}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo(flat);\n backend.disposeIntermediateTensorInfo(res);\n\n return out;\n}\n\nexport const diagConfig: KernelConfig = {\n kernelName: Diag,\n backendName: 'webgl',\n kernelFunc: diag as {} as KernelFunc\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class Dilation2DProgram implements GPGPUProgram {\n variableNames = ['x', 'W'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.outShape;\n\n const {\n inHeight,\n inWidth,\n padInfo,\n strideHeight,\n strideWidth,\n filterHeight,\n filterWidth,\n dilationHeight,\n dilationWidth\n } = convInfo;\n\n const {top: padTop, left: padLeft} = padInfo;\n\n this.userCode = `\n const ivec2 strides = ivec2(${strideHeight}, ${strideWidth});\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n const float neg_infinity = -3.4e38;\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.w;\n ivec2 outTopLeftCorner =\n coords.yz * strides - pads;\n int hBeg = outTopLeftCorner.x;\n int wBeg = outTopLeftCorner.y;\n\n float curVal = neg_infinity;\n for (int h = 0; h < ${filterHeight}; h++) {\n int hIn = hBeg + h * ${dilationHeight};\n\n if (hIn >= 0 && hIn < ${inHeight}) {\n for (int w = 0; w < ${filterWidth}; w++) {\n int wIn = wBeg + w * ${dilationWidth};\n\n if (wIn >= 0 && wIn < ${inWidth}) {\n float xVal = getX(batch, hIn, wIn, d1);\n float wVal = getW(h, w, d1);\n\n float val = xVal + wVal;\n if (val > curVal) {\n curVal = val;\n }\n }\n }\n }\n }\n\n float result = curVal;\n setOutput(result);\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 */\n\nimport {backend_util, Dilation2D, Dilation2DAttrs, Dilation2DInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Dilation2DProgram} from '../dilation_gpu';\nimport {reshape} from './Reshape';\n\nexport function dilation2D(args: {\n inputs: Dilation2DInputs,\n attrs: Dilation2DAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter} = inputs;\n const {strides, pad, dilations} = attrs;\n\n const convInfo = backend_util.computeDilation2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number], strides, pad,\n 'NHWC' /* dataFormat */, dilations);\n let out: TensorInfo;\n\n const program = new Dilation2DProgram(convInfo);\n out = backend.runWebGLProgram(program, [x, filter], 'float32');\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: convInfo.outShape}});\n backend.disposeIntermediateTensorInfo(out);\n\n return outReshaped;\n}\n\nexport const dilation2DConfig: KernelConfig = {\n kernelName: Dilation2D,\n backendName: 'webgl',\n kernelFunc: dilation2D as {} as KernelFunc,\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 {backend_util, Einsum, EinsumAttrs, EinsumInputs, KernelConfig, KernelFunc, Tensor, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {multiply} from './Multiply';\nimport {reshape} from './Reshape';\nimport {sum} from './Sum';\nimport {transpose} from './Transpose';\n\nexport function einsum(\n args:\n {inputs: EinsumInputs, backend: MathBackendWebGL, attrs: EinsumAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {equation} = attrs;\n const tensors = inputs as Tensor[];\n\n const {allDims, summedDims, idDims} =\n backend_util.decodeEinsumEquation(equation, tensors.length);\n backend_util.checkEinsumDimSizes(allDims.length, idDims, tensors);\n const {path, steps} = backend_util.getEinsumComputePath(summedDims, idDims);\n\n const nSteps = steps.length;\n let out: TensorInfo|null = null;\n let numDimsRemaining = allDims.length;\n const tensorsToDispose: TensorInfo[] = [];\n for (let i = 0; i < nSteps; ++i) {\n for (const idTerm of steps[i]) {\n const {permutationIndices: perm, expandDims: dimsToExpand} =\n backend_util.getEinsumPermutation(numDimsRemaining, idDims[idTerm]);\n let x: TensorInfo;\n if (backend_util.isIdentityPermutation(perm)) {\n x = tensors[idTerm];\n } else {\n x = transpose({inputs: {x: tensors[idTerm]}, backend, attrs: {perm}});\n tensorsToDispose.push(x);\n }\n const targetShape: number[] = x.shape.slice();\n for (let k = 0; k < dimsToExpand.length; ++k) {\n targetShape.splice(dimsToExpand[k], 0, 1);\n }\n\n if (!util.arraysEqual(x.shape, targetShape)) {\n x = reshape({inputs: {x}, backend, attrs: {shape: targetShape}});\n tensorsToDispose.push(x);\n }\n if (out === null) {\n out = x;\n } else {\n // tslint:disable-next-line: no-unnecessary-type-assertion\n out = multiply({inputs: {a: x, b: out}, backend}) as TensorInfo;\n tensorsToDispose.push(out);\n }\n }\n if (i < nSteps - 1) {\n if (path[i] >= 0) {\n out = sum({\n inputs: {x: out},\n backend,\n attrs: {\n axis: path[i] - (allDims.length - numDimsRemaining),\n keepDims: false\n }\n });\n tensorsToDispose.push(out);\n }\n numDimsRemaining--;\n }\n }\n\n // Clean up intermediate tensors.\n for (const tensorInfo of tensorsToDispose) {\n if (tensorInfo === out) {\n continue;\n }\n backend.disposeIntermediateTensorInfo(tensorInfo);\n }\n\n return out;\n}\n\nexport const einsumConfig: KernelConfig = {\n kernelName: Einsum,\n backendName: 'webgl',\n kernelFunc: einsum as {} 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 {Elu, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst ELU = `return (x >= 0.0) ? x : (exp(x) - 1.0);`;\n\nconst ELU_PACKED = `\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n`;\n\nconst elu = unaryKernelFunc({opSnippet: ELU, packedOpSnippet: ELU_PACKED});\n\nexport const eluConfig: KernelConfig = {\n kernelName: Elu,\n backendName: 'webgl',\n kernelFunc: elu as {} 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 {EluGrad, EluGradInputs, env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {BinaryOpProgram} from '../binaryop_gpu';\nimport {BinaryOpPackedProgram} from '../binaryop_packed_gpu';\n\nconst ELU_DER = `return (b >= 1.0) ? a : a * (b + 1.0);`;\nconst ELU_DER_PACKED = `\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n`;\n\nexport const eluGrad =\n (args: {inputs: EluGradInputs, backend: MathBackendWebGL}): TensorInfo => {\n const {inputs, backend} = args;\n const {dy, y} = inputs;\n\n const program = env().getBool('WEBGL_PACK_BINARY_OPERATIONS') ?\n new BinaryOpPackedProgram(ELU_DER_PACKED, dy.shape, y.shape) :\n new BinaryOpProgram(ELU_DER, dy.shape, y.shape);\n return backend.runWebGLProgram(program, [dy, y], dy.dtype);\n };\n\nexport const eluGradConfig: KernelConfig = {\n kernelName: EluGrad,\n backendName: 'webgl',\n kernelFunc: eluGrad as {} 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 {Equal, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {equalImplCPU} from '../kernel_utils/shared';\nconst PACKED_EQUAL = `\n return vec4(equal(a, b));\n`;\n\nconst EQUAL = `return float(a == b);`;\n\nexport const equal = binaryKernelFunc({\n opSnippet: EQUAL,\n packedOpSnippet: PACKED_EQUAL,\n dtype: 'bool',\n cpuKernelImpl: equalImplCPU,\n});\n\nexport const equalConfig: KernelConfig = {\n kernelName: Equal,\n backendName: 'webgl',\n kernelFunc: equal as {} 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 '../kernel_utils/kernel_funcs_utils';\n\nconst ERF = `\n // Error function is calculated approximately with elementary function.\n // See \"Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables\", Abramowitz and Stegun.\n float p = ${backend_util.ERF_P};\n float a1 = ${backend_util.ERF_A1};\n float a2 = ${backend_util.ERF_A2};\n float a3 = ${backend_util.ERF_A3};\n float a4 = ${backend_util.ERF_A4};\n float a5 = ${backend_util.ERF_A5};\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n`;\n\nexport const erf = unaryKernelFunc({opSnippet: ERF});\n\nexport const erfConfig: KernelConfig = {\n kernelName: Erf,\n backendName: 'webgl',\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 {Exp, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {expImplCPU} from '../kernel_utils/shared';\n\nexport const EXP = `return exp(x);`;\nexport const exp = unaryKernelFunc(\n {opSnippet: EXP, packedOpSnippet: EXP, cpuKernelImpl: expImplCPU});\n\nexport const expConfig: KernelConfig = {\n kernelName: Exp,\n backendName: 'webgl',\n kernelFunc: exp as {} 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 {MathBackendWebGL} from '../backend_webgl';\nimport {reshape} from './Reshape';\n\nexport function expandDims(args: {\n inputs: ExpandDimsInputs,\n attrs: ExpandDimsAttrs,\n backend: MathBackendWebGL\n}): TensorInfo {\n const {inputs, attrs, backend} = args;\n const {dim} = attrs;\n const {input} = inputs;\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: 'webgl',\n kernelFunc: expandDims as {} 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 {Expm1, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {expm1ImplCPU} from '../kernel_utils/shared';\n\nconst EXPM1 = `return exp(x) - 1.0;`;\n\nexport const expm1 = unaryKernelFunc(\n {opSnippet: EXPM1, packedOpSnippet: EXPM1, cpuKernelImpl: expm1ImplCPU});\n\nexport const expm1Config: KernelConfig = {\n kernelName: Expm1,\n backendName: 'webgl',\n kernelFunc: expm1 as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class FFTProgram implements GPGPUProgram {\n variableNames = ['real', 'imag'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n component: 'real'|'imag', inputShape: [number, number],\n inverse: boolean) {\n const innerDim = inputShape[1];\n this.outputShape = inputShape;\n\n const exponentMultiplierSnippet =\n inverse ? `2.0 * ${Math.PI}` : `-2.0 * ${Math.PI}`;\n const resultDenominator = inverse ? `${innerDim}.0` : '1.0';\n\n let opString: string;\n if (component === 'real') {\n opString = 'return real * expR - imag * expI;';\n } else if (component === 'imag') {\n opString = 'return real * expI + imag * expR;';\n } else {\n throw new Error(\n `FFT component must be either \"real\" or \"imag\", got ${component}.`);\n }\n\n this.userCode = `\n const float exponentMultiplier = ${exponentMultiplierSnippet};\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n ${opString}\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float(${innerDim});\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < ${innerDim}; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / ${resultDenominator};\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\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 */\n\nimport {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FFTProgram} from '../fft_gpu';\n\nimport {complex} from './Complex';\nimport {reshape} from './Reshape';\n\nexport function fftImpl(\n x: TensorInfo, inverse: boolean, backend: MathBackendWebGL): TensorInfo {\n const xData = backend.texData.get(x.dataId);\n\n const inputSize = util.sizeFromShape(x.shape);\n // Collapse all outer dimensions to a single batch dimension.\n const innerDimensionSize = x.shape[x.shape.length - 1];\n const batch = inputSize / innerDimensionSize;\n\n const input2D = reshape(\n {inputs: {x}, backend, attrs: {shape: [batch, innerDimensionSize]}});\n\n const xShape = input2D.shape as [number, number];\n const realProgram = new FFTProgram('real', xShape, inverse);\n const imagProgram = new FFTProgram('imag', xShape, inverse);\n\n const inputs = [\n {\n dataId: xData.complexTensorInfos.real.dataId,\n dtype: xData.complexTensorInfos.real.dtype,\n shape: xShape\n },\n {\n dataId: xData.complexTensorInfos.imag.dataId,\n dtype: xData.complexTensorInfos.imag.dtype,\n shape: xShape\n }\n ];\n\n const realPart = backend.runWebGLProgram(realProgram, inputs, 'float32');\n const imagPart = backend.runWebGLProgram(imagProgram, inputs, 'float32');\n\n const complexOutput =\n complex({inputs: {real: realPart, imag: imagPart}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(imagPart);\n\n const complexOutputReshaped =\n reshape({inputs: {x: complexOutput}, backend, attrs: {shape: x.shape}});\n\n backend.disposeIntermediateTensorInfo(input2D);\n backend.disposeIntermediateTensorInfo(complexOutput);\n return complexOutputReshaped;\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 {FFT, FFTInputs, KernelConfig, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {fftImpl} from './FFT_impl';\n\nexport function fft(args: {inputs: FFTInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n return fftImpl(input, false /* inverse */, backend);\n}\n\nexport const fftConfig: KernelConfig = {\n kernelName: FFT,\n backendName: 'webgl',\n kernelFunc: fft\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 {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class FillProgram implements GPGPUProgram {\n variableNames: string[];\n outputShape: number[] = [];\n userCode: string;\n customUniforms = [{name: 'value', type: 'float' as UniformType}];\n\n constructor(shape: number[], value: number) {\n this.variableNames = ['x'];\n this.outputShape = shape;\n\n this.userCode = `\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\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 */\n\nimport {Fill, FillAttrs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FillProgram} from '../fill_gpu';\n\nexport function fill(args: {backend: MathBackendWebGL, attrs: FillAttrs}):\n TensorInfo {\n const {backend, attrs} = args;\n const {shape, value} = attrs;\n let {dtype} = attrs;\n\n dtype = dtype || util.inferDtype(value);\n\n if (dtype === 'string') {\n // String type should be handled in CPU memory.\n const values = util.getArrayFromDType(dtype, util.sizeFromShape(shape));\n values.fill(value as string);\n return backend.makeTensorInfo(shape, dtype, values);\n } else {\n const program = new FillProgram(shape, value as number);\n const customValues = [[value as number]];\n return backend.runWebGLProgram(program, [], dtype, customValues);\n }\n}\n\nexport const fillConfig: KernelConfig = {\n kernelName: Fill,\n backendName: 'webgl',\n kernelFunc: fill as {} 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 {GPGPUProgram} from './gpgpu_math';\n\nexport class FlipLeftRightProgram implements GPGPUProgram {\n variableNames = ['Image'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(imageShape: [number, number, number, number]) {\n const imageWidth = imageShape[2];\n this.outputShape = imageShape;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n\n int coordX = ${imageWidth} - x - 1;\n float outputValue;\n if(coordX >= 0 && coordX < ${imageWidth}) {\n outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n } else {\n outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n }\n setOutput(outputValue);\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 */\n\nimport {KernelConfig, Tensor4D} from '@tensorflow/tfjs-core';\nimport {FlipLeftRight, FlipLeftRightInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {FlipLeftRightProgram} from '../flip_left_right_gpu';\n\nexport const flipLeftRightConfig: KernelConfig = {\n kernelName: FlipLeftRight,\n backendName: 'webgl',\n kernelFunc: ({inputs, backend}) => {\n const {image} = inputs as FlipLeftRightInputs;\n const webglBackend = backend as MathBackendWebGL;\n\n const program = new FlipLeftRightProgram((image as Tensor4D).shape);\n const output = webglBackend.runWebGLProgram(program, [image], image.dtype);\n return output;\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 {Floor, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {floorImplCPU} from '../kernel_utils/shared';\n\nconst FLOOR = `return floor(x);`;\n\nexport const floor = unaryKernelFunc(\n {opSnippet: FLOOR, packedOpSnippet: FLOOR, cpuKernelImpl: floorImplCPU});\n\nexport const floorConfig: KernelConfig = {\n kernelName: Floor,\n backendName: 'webgl',\n kernelFunc: floor,\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 {FloorDiv, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// We use native integer division to deal with floating point imprecision. Since\n// we implement floor division and glsl implements truncated division, we\n// correct for this by subtracting 1 from result when the result is negative and\n// there is a remainder.\nconst INT_DIV = `\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n`;\n\nconst INT_DIV_PACKED = `\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n`;\n\nexport const floorDiv = binaryKernelFunc(\n {opSnippet: INT_DIV, packedOpSnippet: INT_DIV_PACKED, dtype: 'int32'});\n\nexport const floorDivConfig: KernelConfig = {\n kernelName: FloorDiv,\n backendName: 'webgl',\n kernelFunc: floorDiv as {} as KernelFunc\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 {getGlslDifferences} from '../../glsl_version';\nimport {GPGPUProgram} from '../../gpgpu_math';\n\nexport class FromPixelsProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n\n constructor(outputShape: number[]) {\n const glsl = getGlslDifferences();\n const [height, width, ] = outputShape;\n this.outputShape = outputShape;\n this.userCode = `\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${width}.0, ${height}.0);\n\n vec4 values = ${glsl.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\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 {getGlslDifferences} from '../../glsl_version';\nimport {GPGPUProgram} from '../../gpgpu_math';\n\nexport class FromPixelsPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n userCode: string;\n outputShape: number[];\n packedInputs = false;\n packedOutput = true;\n\n constructor(outputShape: number[]) {\n const glsl = getGlslDifferences();\n const [height, width, ] = outputShape;\n this.outputShape = outputShape;\n this.userCode = `\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${width}.0, ${height}.0);\n vec4 values = ${glsl.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${glsl.output} = result;\n }\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 {env, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\nimport {FromPixels, FromPixelsAttrs, FromPixelsInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {TextureUsage} from '../tex_util';\n\nimport {FromPixelsProgram} from './FromPixels_utils/from_pixels_gpu';\nimport {FromPixelsPackedProgram} from './FromPixels_utils/from_pixels_packed_gpu';\n\nexport const fromPixelsConfig: KernelConfig = {\n kernelName: FromPixels,\n backendName: 'webgl',\n kernelFunc: fromPixels as {} as KernelFunc,\n};\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\n\nfunction fromPixels(args: {\n inputs: FromPixelsInputs,\n backend: MathBackendWebGL,\n attrs: FromPixelsAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n let {pixels} = inputs;\n const {numChannels} = attrs;\n\n const isVideo = typeof (HTMLVideoElement) !== 'undefined' &&\n pixels instanceof HTMLVideoElement;\n const isImage = typeof (HTMLImageElement) !== 'undefined' &&\n pixels instanceof HTMLImageElement;\n const [width, height] = isVideo ?\n [\n (pixels as HTMLVideoElement).videoWidth,\n (pixels as HTMLVideoElement).videoHeight\n ] :\n [pixels.width, pixels.height];\n\n const texShape: [number, number] = [height, width];\n const outShape = [height, width, numChannels];\n\n if (isImage || isVideo) {\n if (fromPixels2DContext == null) {\n fromPixels2DContext = document.createElement('canvas').getContext('2d');\n }\n\n fromPixels2DContext.canvas.width = width;\n fromPixels2DContext.canvas.height = height;\n fromPixels2DContext.drawImage(\n pixels as HTMLVideoElement | HTMLImageElement | ImageBitmap,\n 0, 0, width, height);\n pixels = fromPixels2DContext.canvas;\n }\n\n const tempPixelHandle = backend.makeTensorInfo(texShape, 'int32');\n // This is a byte texture with pixels.\n backend.texData.get(tempPixelHandle.dataId).usage = TextureUsage.PIXELS;\n backend.gpgpu.uploadPixelDataToTexture(\n backend.getTexture(tempPixelHandle.dataId), pixels as ImageData);\n const program = env().getBool('WEBGL_PACK') ?\n new FromPixelsPackedProgram(outShape) :\n new FromPixelsProgram(outShape);\n const res = backend.runWebGLProgram(program, [tempPixelHandle], 'int32');\n backend.disposeData(tempPixelHandle.dataId);\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 {backend_util, env, FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Conv2DProgram} from '../conv_gpu';\nimport {mapActivationToShaderProgram} from '../kernel_utils/kernel_funcs_utils';\n\nimport {conv2dByMatMul, conv2dWithIm2Row} from './Conv2D_impl';\nimport {reshape} from './Reshape';\n\nexport function fusedConv2d(args: {\n inputs: FusedConv2DInputs,\n attrs: FusedConv2DAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {\n strides,\n pad,\n dataFormat,\n dilations,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n } = attrs;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, dilations, pad,\n dimRoundingMode, false /* depthwise */, $dataFormat);\n let out: TensorInfo;\n const intermediates: TensorInfo[] = [];\n\n if (convInfo.filterHeight === 1 && convInfo.filterWidth === 1 &&\n convInfo.dilationHeight === 1 && convInfo.dilationWidth === 1 &&\n convInfo.strideHeight === 1 && convInfo.strideWidth === 1 &&\n (convInfo.padInfo.type === 'SAME' || convInfo.padInfo.type === 'VALID')) {\n out = conv2dByMatMul({\n x,\n filter,\n convInfo,\n backend,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n } else if (env().getBool('WEBGL_CONV_IM2COL') && x.shape[0] === 1) {\n out = conv2dWithIm2Row({\n x,\n filter,\n convInfo,\n backend,\n bias,\n activation,\n preluActivationWeights,\n leakyreluAlpha\n });\n } else {\n const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n const fusedActivation =\n activation ? mapActivationToShaderProgram(activation, false) : null;\n const program = new Conv2DProgram(\n convInfo, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n const inputs: TensorInfo[] = [x, filter];\n if (bias) {\n inputs.push(bias);\n }\n if (preluActivationWeights) {\n inputs.push(preluActivationWeights);\n }\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as {} as 'float32', 'float32'));\n inputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n out = backend.runWebGLProgram(program, inputs, 'float32');\n }\n\n const outReshaped =\n reshape({inputs: {x: out}, backend, attrs: {shape: convInfo.outShape}});\n\n intermediates.push(out);\n intermediates.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return outReshaped;\n}\n\nexport const fusedConv2DConfig: KernelConfig = {\n kernelName: FusedConv2D,\n backendName: 'webgl',\n kernelFunc: fusedConv2d as {} 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, env, FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {DepthwiseConv2DProgram} from '../conv_gpu_depthwise';\nimport {DepthwiseConvPacked2DProgram} from '../conv_packed_gpu_depthwise';\nimport {mapActivationToShaderProgram} from '../kernel_utils/kernel_funcs_utils';\n\nexport function fusedDepthwiseConv2D(args: {\n inputs: FusedDepthwiseConv2DInputs,\n attrs: FusedDepthwiseConv2DAttrs,\n backend: MathBackendWebGL\n}) {\n const {inputs, backend, attrs} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {strides, pad, dilations, dimRoundingMode, activation, leakyreluAlpha} =\n attrs;\n\n const intermediates: TensorInfo[] = [];\n\n let $dilations = dilations;\n if ($dilations == null) {\n $dilations = [1, 1];\n }\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, $dilations),\n () => 'Error in depthwiseConv2d: Either strides or dilations must be ' +\n `1. Got strides ${strides} and dilations '${$dilations}'`);\n\n const convInfo = backend_util.computeConv2DInfo(\n x.shape as [number, number, number, number],\n filter.shape as [number, number, number, number], strides, $dilations,\n pad, dimRoundingMode, true /* depthwise */);\n\n const shouldPackDepthwiseConv = env().getBool('WEBGL_PACK_DEPTHWISECONV') &&\n convInfo.strideWidth <= 2 &&\n convInfo.outChannels / convInfo.inChannels === 1;\n const fusedActivation = activation ?\n mapActivationToShaderProgram(activation, shouldPackDepthwiseConv) :\n null;\n const programInputs: TensorInfo[] = [x, filter];\n\n const hasBias = bias != null;\n const hasPreluActivationWeights = preluActivationWeights != null;\n const hasLeakyreluAlpha = activation === 'leakyrelu';\n\n if (hasBias) {\n programInputs.push(bias);\n }\n if (hasPreluActivationWeights) {\n programInputs.push(preluActivationWeights);\n }\n if (hasLeakyreluAlpha) {\n const $leakyreluAlpha = backend.makeTensorInfo(\n [], 'float32',\n util.createScalarValue(leakyreluAlpha as {} as 'float32', 'float32'));\n programInputs.push($leakyreluAlpha);\n intermediates.push($leakyreluAlpha);\n }\n\n let program: DepthwiseConv2DProgram|DepthwiseConvPacked2DProgram;\n if (shouldPackDepthwiseConv) {\n program = new DepthwiseConvPacked2DProgram(\n convInfo, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n } else {\n program = new DepthwiseConv2DProgram(\n convInfo, hasBias, fusedActivation, hasPreluActivationWeights,\n hasLeakyreluAlpha);\n }\n\n const result = backend.runWebGLProgram(program, programInputs, 'float32');\n\n intermediates.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n}\n\nexport const fusedDepthwiseConv2DConfig: KernelConfig = {\n kernelName: FusedDepthwiseConv2D,\n backendName: 'webgl',\n kernelFunc: fusedDepthwiseConv2D as {} as KernelFunc,\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class GatherNDProgram implements GPGPUProgram {\n variableNames = ['x', 'indices'];\n outputShape: number[];\n userCode: string;\n constructor(\n private sliceDim: number, private strides: number[], shape: number[]) {\n this.outputShape = shape;\n const stridesType = getCoordsDataType(strides.length);\n const dtype = getCoordsDataType(shape.length);\n const strideString = this.sliceDim > 1 ? 'strides[j]' : 'strides';\n this.userCode = `\n ${stridesType} strides = ${stridesType}(${this.strides});\n void main() {\n ${dtype} coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < ${this.sliceDim}; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * ${strideString};\n }\n setOutput(getX(flattenIndex, coords[1]));\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 */\n\nimport {backend_util, GatherNd, GatherNdInputs, KernelConfig, KernelFunc, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {GatherNDProgram} from '../gather_nd_gpu';\nimport {gatherNdImplCPU} from '../kernel_utils/shared';\n\nimport {reshape} from './Reshape';\n\nexport function gatherNd(\n args: {inputs: GatherNdInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {params, indices} = inputs;\n\n const indicesShape = indices.shape;\n const sliceRank = indicesShape[indicesShape.length - 1];\n const paramsSize = util.sizeFromShape(params.shape);\n\n const [resultShape, numSlices, sliceSize, strides] =\n backend_util.prepareAndValidate(params, indices);\n\n const flattenIndices = reshape(\n {inputs: {x: indices}, backend, attrs: {shape: [numSlices, sliceRank]}});\n const flattenX = reshape({\n inputs: {x: params},\n backend,\n attrs: {shape: [(util.sizeFromShape(params.shape) / sliceSize), sliceSize]}\n });\n\n if (backend.shouldExecuteOnCPU([params, indices]) ||\n params.dtype === 'string') {\n const indicesData = backend.readSync(indices.dataId) as TypedArray;\n const paramsBuf = backend.bufferSync(params);\n const outValue = gatherNdImplCPU(\n indicesData, paramsBuf, params.dtype, numSlices, sliceRank, sliceSize,\n strides, params.shape, paramsSize);\n\n return backend.makeTensorInfo(resultShape, params.dtype, outValue.values);\n }\n const program =\n new GatherNDProgram(sliceRank, strides, [numSlices, sliceSize]);\n const res = backend.runWebGLProgram(\n program, [flattenX, flattenIndices], flattenX.dtype);\n\n const reshaped =\n reshape({inputs: {x: res}, backend, attrs: {shape: resultShape}});\n\n backend.disposeIntermediateTensorInfo(flattenIndices);\n backend.disposeIntermediateTensorInfo(flattenX);\n backend.disposeIntermediateTensorInfo(res);\n\n return reshaped;\n}\n\nexport const gatherNdConfig: KernelConfig = {\n kernelName: GatherNd,\n backendName: 'webgl',\n kernelFunc: gatherNd as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class GatherProgram implements GPGPUProgram {\n variableNames = ['A', 'indices'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n constructor(aShape: number[], outputShape: number[]) {\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n const dtype = getCoordsDataType(this.rank);\n const sourceCoords = getSourceCoords(aShape, 2);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n setOutput(getA(${sourceCoords}));\n }\n `;\n }\n}\n\n// The input and output are always flattened into rank 4 tensors.\nfunction getSourceCoords(aShape: number[], axis: number): string {\n const currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];\n\n const sourceCoords = [];\n for (let i = 0; i < aShape.length; i++) {\n if (i === 2) {\n sourceCoords.push('int(getIndices(resRC.x, resRC.z))');\n } else {\n sourceCoords.push(`${currentCoords[i]}`);\n }\n }\n return sourceCoords.join();\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 {MathBackendWebGL} from '../backend_webgl';\nimport {GatherProgram} from '../gather_gpu';\nimport {gatherV2ImplCPU} from '../kernel_utils/shared';\n\nimport {reshape} from './Reshape';\n\nexport function gatherV2(args: {\n inputs: GatherV2Inputs,\n backend: MathBackendWebGL,\n attrs: GatherV2Attrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, indices} = inputs;\n const {axis, batchDims} = attrs;\n\n const parsedAxis = util.parseAxisParam(axis, x.shape)[0];\n const shapeInfo = backend_util.segment_util.collectGatherOpShapeInfo(\n x, indices, parsedAxis, batchDims);\n\n const indicesSize = util.sizeFromShape(indices.shape);\n\n const toDispose = [];\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 toDispose.push(flattenX);\n toDispose.push(flattenIndex);\n\n const flattenOutputShape = [\n shapeInfo.batchSize, shapeInfo.outerSize, indicesSize / shapeInfo.batchSize,\n shapeInfo.sliceSize\n ];\n\n if (backend.shouldExecuteOnCPU([x, indices]) || x.dtype === 'string') {\n const indicesBuf = backend.bufferSync(flattenIndex);\n const xBuf = backend.bufferSync(flattenX);\n const outBuf = gatherV2ImplCPU(xBuf, indicesBuf, flattenOutputShape);\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return backend.makeTensorInfo(\n shapeInfo.outputShape, outBuf.dtype, outBuf.values as TypedArray);\n }\n\n const program = new GatherProgram(flattenX.shape, flattenOutputShape);\n const res = backend.runWebGLProgram(\n program, [flattenX, flattenIndex], flattenX.dtype);\n toDispose.push(res);\n\n const reshaped = reshape(\n {inputs: {x: res}, backend, attrs: {shape: shapeInfo.outputShape}});\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n return reshaped;\n}\n\nexport const gatherV2Config: KernelConfig = {\n kernelName: GatherV2,\n backendName: 'webgl',\n kernelFunc: gatherV2 as {} 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 {Greater, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {greaterImplCPU} from '../kernel_utils/shared';\n\nconst GREATER = `return float(a > b);`;\nconst GREATER_PACKED = `\n return vec4(greaterThan(a, b));\n`;\n\nexport const greater = binaryKernelFunc({\n opSnippet: GREATER,\n packedOpSnippet: GREATER_PACKED,\n cpuKernelImpl: greaterImplCPU,\n dtype: 'bool'\n});\n\nexport const greaterConfig: KernelConfig = {\n kernelName: Greater,\n backendName: 'webgl',\n kernelFunc: greater as {} 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 {GreaterEqual, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {greaterEqualImplCPU} from '../kernel_utils/shared';\n\nconst GREATER_EQUAL = `return float(a >= b);`;\nconst GREATER_EQUAL_PACKED = `\n return vec4(greaterThanEqual(a, b));\n`;\n\nexport const greaterEqual = binaryKernelFunc({\n opSnippet: GREATER_EQUAL,\n packedOpSnippet: GREATER_EQUAL_PACKED,\n dtype: 'bool',\n cpuKernelImpl: greaterEqualImplCPU\n});\n\nexport const greaterEqualConfig: KernelConfig = {\n kernelName: GreaterEqual,\n backendName: 'webgl',\n kernelFunc: greaterEqual as {} 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 {IFFT, IFFTInputs, KernelConfig, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {fftImpl} from './FFT_impl';\n\nexport function ifft(args: {inputs: IFFTInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {input} = inputs;\n\n return fftImpl(input, true /* inverse */, backend);\n}\n\nexport const ifftConfig: KernelConfig = {\n kernelName: IFFT,\n backendName: 'webgl',\n kernelFunc: ifft\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 {IsFinite, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst IS_FINITE = `return float(!isnan(x) && !isinf(x));`;\n\nexport const isFinite = unaryKernelFunc({opSnippet: IS_FINITE, dtype: 'bool'});\n\nexport const isFiniteConfig: KernelConfig = {\n kernelName: IsFinite,\n backendName: 'webgl',\n kernelFunc: isFinite,\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 {IsInf, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst IS_INF = `return float(isinf(x));`;\n\nexport const isInf = unaryKernelFunc({opSnippet: IS_INF, dtype: 'bool'});\n\nexport const isInfConfig: KernelConfig = {\n kernelName: IsInf,\n backendName: 'webgl',\n kernelFunc: isInf,\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 {IsNan, KernelConfig} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst IS_NAN = `return float(isnan(x));`;\n\nexport const isNaN = unaryKernelFunc({opSnippet: IS_NAN, dtype: 'bool'});\n\nexport const isNaNConfig: KernelConfig = {\n kernelName: IsNan,\n backendName: 'webgl',\n kernelFunc: isNaN,\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, Less} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {lessImplCPU} from '../kernel_utils/shared';\n\nconst LESS = `return float(a < b);`;\nconst LESS_PACKED = `\n return vec4(lessThan(a, b));\n`;\n\nexport const less = binaryKernelFunc({\n opSnippet: LESS,\n packedOpSnippet: LESS_PACKED,\n cpuKernelImpl: lessImplCPU,\n dtype: 'bool'\n});\n\nexport const lessConfig: KernelConfig = {\n kernelName: Less,\n backendName: 'webgl',\n kernelFunc: less as {} 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, LessEqual} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {lessEqualImplCPU} from '../kernel_utils/shared';\n\nexport const LESS_EQUAL = `return float(a <= b);`;\nexport const LESS_EQUAL_PACKED = `\n return vec4(lessThanEqual(a, b));\n`;\n\nexport const lessEqual = binaryKernelFunc({\n opSnippet: LESS_EQUAL,\n packedOpSnippet: LESS_EQUAL_PACKED,\n cpuKernelImpl: lessEqualImplCPU,\n dtype: 'bool'\n});\n\nexport const lessEqualConfig: KernelConfig = {\n kernelName: LessEqual,\n backendName: 'webgl',\n kernelFunc: lessEqual as {} 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, LinSpace, LinSpaceAttrs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {linSpaceImplCPU} from '../kernel_utils/shared';\n\nexport function linSpace(\n args: {backend: MathBackendWebGL, attrs: LinSpaceAttrs}): TensorInfo {\n const {backend, attrs} = args;\n const {start, stop, num} = attrs;\n\n // TODO: Use CPU implementation due to the precision problem in Safari.\n const outVals = linSpaceImplCPU(start, stop, num);\n return backend.makeTensorInfo([outVals.length], 'float32', outVals);\n}\n\nexport const linSpaceConfig: KernelConfig = {\n kernelName: LinSpace,\n backendName: 'webgl',\n kernelFunc: linSpace as {} 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, Log} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {logImplCPU} from '../kernel_utils/shared';\n\nconst LOG = `if (x < 0.0) return NAN;\n return log(x);`;\n\nconst LOG_PACKED = `\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n`;\n\nexport const log = unaryKernelFunc(\n {opSnippet: LOG, packedOpSnippet: LOG_PACKED, cpuKernelImpl: logImplCPU});\n\nexport const logConfig: KernelConfig = {\n kernelName: Log,\n backendName: 'webgl',\n kernelFunc: log as {} 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, Log1p} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOG1P = `return log(1.0 + x);`;\n\nexport const log1p = unaryKernelFunc({opSnippet: LOG1P});\n\nexport const log1pConfig: KernelConfig = {\n kernelName: Log1p,\n backendName: 'webgl',\n kernelFunc: log1p,\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, LogicalAnd} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOGICAL_AND = `return float(a >= 1.0 && b >= 1.0);`;\nconst LOGICAL_AND_PACKED = `\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n`;\n\nexport const logicalAnd = binaryKernelFunc({\n opSnippet: LOGICAL_AND,\n packedOpSnippet: LOGICAL_AND_PACKED,\n dtype: 'bool'\n});\n\nexport const logicalAndConfig: KernelConfig = {\n kernelName: LogicalAnd,\n backendName: 'webgl',\n kernelFunc: logicalAnd as {} 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, LogicalNot} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOGICAL_NOT = `return float(!(x >= 1.0));`;\n\nexport const logicalNot = unaryKernelFunc({opSnippet: LOGICAL_NOT});\n\nexport const logicalNotConfig: KernelConfig = {\n kernelName: LogicalNot,\n backendName: 'webgl',\n kernelFunc: logicalNot,\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, LogicalOr} from '@tensorflow/tfjs-core';\n\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst LOGICAL_OR = `return float(a >= 1.0 || b >= 1.0);`;\nconst LOGICAL_OR_PACKED = `\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n`;\n\nexport const logicalOr = binaryKernelFunc(\n {opSnippet: LOGICAL_OR, packedOpSnippet: LOGICAL_OR_PACKED, dtype: 'bool'});\n\nexport const logicalOrConfig: KernelConfig = {\n kernelName: LogicalOr,\n backendName: 'webgl',\n kernelFunc: logicalOr as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n xShape: number[], radius: number, bias: number, alpha: number,\n beta: number) {\n const rad = radius;\n const maxD = xShape[3] - 1;\n this.outputShape = xShape;\n\n // optimize pow(bias + alpha * sum, -beta)\n // src: https://github.com/tensorflow/tensorflow/..\n // blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..\n // tensorflow/core/kernels/mkl_lrn_op.cc#L320\n let powOperator;\n const basis = `float(${bias}) + float(${alpha}) * sum`;\n if (beta === 0.5) {\n powOperator = `inversesqrt(${basis})`;\n } else if (beta === 1.0) {\n powOperator = `1.0/(${basis})`;\n } else {\n powOperator = `exp(log(${basis}) * float(-${beta}));`;\n }\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -${rad}; j <= ${rad}; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= ${maxD}) {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * ${powOperator};\n setOutput(val);\n }\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[] = [];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(\n xShape: number[], radius: number, bias: number, alpha: number,\n beta: number) {\n const rad = radius;\n const maxD = xShape[3] - 1;\n this.outputShape = xShape;\n\n // optimize pow(bias + alpha * sum, -beta)\n // src: https://github.com/tensorflow/tensorflow/..\n // blob/26033a1644a9c4a5fbe3170ab2e864b6a4ccd4ca/..\n // tensorflow/core/kernels/mkl_lrn_op.cc#L320\n let powOperator;\n const basis = `float(${bias}) + float(${alpha}) * sum`;\n if (beta === 0.5) {\n powOperator = `inversesqrt(${basis})`;\n } else if (beta === 1.0) {\n powOperator = `1.0/(${basis})`;\n } else {\n powOperator = `exp(log(${basis}) * float(-${beta}));`;\n }\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < ${this.outputShape[3]};\n bool hasNextRow = c < ${this.outputShape[2]};\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - ${rad};\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - ${rad}; j <= ${rad}; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${maxD}));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * ${powOperator};\n setOutput(result);\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 */\n\nimport {env, KernelConfig, KernelFunc, LRN, LRNAttrs, LRNInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {LRNProgram} from '../lrn_gpu';\nimport {LRNPackedProgram} from '../lrn_packed_gpu';\n\nexport const lrn =\n (args: {inputs: LRNInputs, backend: MathBackendWebGL, attrs: LRNAttrs}):\n TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n const program = env().getBool('WEBGL_PACK_NORMALIZATION') ?\n new LRNPackedProgram(x.shape, depthRadius, bias, alpha, beta) :\n new LRNProgram(x.shape, depthRadius, bias, alpha, beta);\n return backend.runWebGLProgram(program, [x], x.dtype);\n };\n\n// tslint:disable-next-line: variable-name\nexport const LRNConfig: KernelConfig = {\n kernelName: LRN,\n backendName: 'webgl',\n kernelFunc: lrn as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class LRNGradProgram implements GPGPUProgram {\n variableNames = ['inputImage', 'outputImage', 'dy'];\n outputShape: number[] = [];\n userCode: string;\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n depth: number;\n\n constructor(\n inputShape: number[], depthRadius: number, bias: number, alpha: number,\n beta: number) {\n this.outputShape = inputShape;\n this.depth = inputShape[3];\n this.depthRadius = depthRadius;\n this.bias = bias;\n this.alpha = alpha;\n this.beta = beta;\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < ${this.depth}; ++d) {\n int depthBegin = int(max(0.0, float(d - ${depthRadius})));\n int depthEnd = int(min(float(${this.depth}),\n float(d + ${depthRadius} + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = ${this.depth};\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float(${alpha}) * norm + float(${bias});\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float(${alpha})\n * float(${beta})\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * ${beta});\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\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 */\n\nimport {KernelConfig, KernelFunc, LRNGrad, LRNGradAttrs, LRNGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {LRNGradProgram} from '../lrn_grad_gpu';\n\nexport const lrnGrad = (args: {\n inputs: LRNGradInputs,\n backend: MathBackendWebGL,\n attrs: LRNGradAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x, y, dy} = inputs;\n const {depthRadius, bias, alpha, beta} = attrs;\n\n const program = new LRNGradProgram(x.shape, depthRadius, bias, alpha, beta);\n return backend.runWebGLProgram(program, [x, y, dy], x.dtype);\n};\n\n// tslint:disable-next-line: variable-name\nexport const LRNGradConfig: KernelConfig = {\n kernelName: LRNGrad,\n backendName: 'webgl',\n kernelFunc: lrnGrad as {} 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 {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from '../kernels/Reshape';\n\nexport function maxImpl(\n x: TensorInfo, reduceShape: number[], outShape: number[],\n backend: MathBackendWebGL): TensorInfo {\n const inSize = util.sizeFromShape(reduceShape);\n const xSize = util.sizeFromShape(x.shape);\n const batchSize = xSize / inSize;\n const reshapedInput =\n reshape({inputs: {x}, attrs: {shape: [batchSize, inSize]}, backend});\n\n const reduced = reduce(reshapedInput, x.dtype, 'max', backend);\n const reshapedOutput =\n reshape({inputs: {x: reduced}, attrs: {shape: outShape}, backend});\n\n backend.disposeIntermediateTensorInfo(reshapedInput);\n backend.disposeIntermediateTensorInfo(reduced);\n\n return reshapedOutput;\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, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {maxImplCPU} from '../kernel_utils/shared';\n\nimport {maxImpl} from './Max_impl';\nimport {transposeImpl, transposeImplCPU} from './Transpose_impl';\n\nexport function max(\n args: {inputs: MaxInputs, backend: MathBackendWebGL, attrs: MaxAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {reductionIndices, keepDims} = attrs;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(reductionIndices, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n const maxInputIsTransposed = permutedAxes != null;\n const shouldExecuteOnCPU = backend.shouldExecuteOnCPU([x]);\n\n let maxInput = x;\n if (maxInputIsTransposed) {\n if (shouldExecuteOnCPU) {\n const xTexData = backend.texData.get(maxInput.dataId);\n const values = xTexData.values as TypedArray;\n\n const newShape: number[] = new Array(xRank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = x.shape[permutedAxes[i]];\n }\n const maxInputValues =\n transposeImplCPU(values, x.shape, x.dtype, permutedAxes, newShape);\n\n maxInput = backend.makeTensorInfo(newShape, x.dtype);\n const maxInputData = backend.texData.get(maxInput.dataId);\n maxInputData.values = maxInputValues;\n } else {\n maxInput = transposeImpl(x, permutedAxes, backend);\n }\n\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('max', axes, xRank);\n const [maxOutShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(maxInput.shape, axes);\n\n let outShape = maxOutShape;\n if (keepDims) {\n // rather than reshape at the end, set the target shape here.\n outShape = backend_util.expandShapeToKeepDim(maxOutShape, origAxes);\n }\n\n let out;\n if (shouldExecuteOnCPU) {\n const xTexData = backend.texData.get(maxInput.dataId);\n const values = xTexData.values as TypedArray;\n\n const outValues =\n maxImplCPU(values, util.sizeFromShape(reduceShape), outShape, x.dtype);\n\n out = backend.makeTensorInfo(outShape, x.dtype);\n const outData = backend.texData.get(out.dataId);\n outData.values = outValues;\n } else {\n out = maxImpl(maxInput, reduceShape, outShape, backend);\n }\n\n if (maxInputIsTransposed) {\n backend.disposeIntermediateTensorInfo(maxInput);\n }\n\n return out;\n}\n\nexport const maxConfig: KernelConfig = {\n kernelName: Max,\n backendName: 'webgl',\n kernelFunc: max as {} 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, Maximum} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_gpu';\nimport {CHECK_NAN_SNIPPET as CHECK_NAN_SNIPPET_PACKED} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {maximumImplCPU} from '../kernel_utils/shared';\n\nconst MAXIMUM = CHECK_NAN_SNIPPET + `\n return max(a, b);\n`;\n\nconst MAXIMUM_PACKED = `\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n ` +\n CHECK_NAN_SNIPPET_PACKED + `\n return result;\n`;\n\nexport const maximum = binaryKernelFunc({\n opSnippet: MAXIMUM,\n packedOpSnippet: MAXIMUM_PACKED,\n cpuKernelImpl: maximumImplCPU\n});\n\nexport const maximumConfig: KernelConfig = {\n kernelName: Maximum,\n backendName: 'webgl',\n kernelFunc: maximum as {} 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 */\nimport {backend_util, KernelConfig, KernelFunc, MaxPool, MaxPoolAttrs, MaxPoolInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool2DProgram} from '../pool_gpu';\nimport {assertNotComplex} from '../webgl_util';\nimport {identity} from './Identity';\n\nexport function maxPool(args: {\n inputs: MaxPoolInputs,\n backend: MathBackendWebGL,\n attrs: MaxPoolAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n assertNotComplex(x, 'maxPool');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations = 1;\n\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n if (convInfo.filterWidth === 1 && convInfo.filterHeight === 1 &&\n util.arraysEqual(convInfo.inShape, convInfo.outShape)) {\n return identity({inputs: {x}, backend});\n }\n const maxPoolProgram = new Pool2DProgram(convInfo, 'max', false);\n return backend.runWebGLProgram(maxPoolProgram, [x], x.dtype);\n}\n\nexport const maxPoolConfig: KernelConfig = {\n kernelName: MaxPool,\n backendName: 'webgl',\n kernelFunc: maxPool as {} 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 */\nimport {backend_util, KernelConfig, KernelFunc, MaxPool3D, MaxPool3DAttrs, MaxPool3DInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool3DProgram} from '../pool_gpu';\n\nexport function maxPool3d(args: {\n inputs: MaxPool3DInputs,\n backend: MathBackendWebGL,\n attrs: MaxPool3DAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {filterSize, strides, pad, dataFormat, dimRoundingMode} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode, dataFormat);\n const maxPoolProgram = new Pool3DProgram(convInfo, 'max', false);\n return backend.runWebGLProgram(maxPoolProgram, [x], x.dtype);\n}\n\nexport const maxPool3DConfig: KernelConfig = {\n kernelName: MaxPool3D,\n backendName: 'webgl',\n kernelFunc: maxPool3d as {} as KernelFunc\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class MaxPool2DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy', 'maxPos'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv2DInfo) {\n this.outputShape = convInfo.inShape;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationHeight = convInfo.dilationHeight;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const lastIndex = effectiveFilterHeight * effectiveFilterWidth - 1;\n this.userCode = `\n const ivec2 pads = ivec2(${padTop}, ${padLeft});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth}; wC++) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = ${lastIndex} - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * ${effectiveFilterWidth} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n `;\n }\n}\n\nexport class MaxPool3DBackpropProgram implements GPGPUProgram {\n variableNames = ['dy', 'maxPos'];\n outputShape: number[];\n userCode: string;\n\n constructor(convInfo: backend_util.Conv3DInfo) {\n this.outputShape = convInfo.inShape;\n const strideDepth = convInfo.strideDepth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const dilationDepth = convInfo.dilationDepth;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const effectiveFilterDepth = convInfo.effectiveFilterDepth;\n const effectiveFilterHeight = convInfo.effectiveFilterHeight;\n const effectiveFilterWidth = convInfo.effectiveFilterWidth;\n\n const padFront = effectiveFilterDepth - 1 - convInfo.padInfo.front;\n const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;\n const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;\n\n const lastIndex =\n effectiveFilterDepth * effectiveFilterHeight * effectiveFilterWidth - 1;\n this.userCode = `\n const ivec3 pads = ivec3(${padFront}, ${padTop}, ${padLeft});\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < ${effectiveFilterDepth};\n wD += ${dilationDepth}) {\n float dyD = float(dyDCorner + wD) / ${strideDepth}.0;\n\n if (dyD < 0.0 || dyD >= ${convInfo.outDepth}.0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < ${effectiveFilterHeight};\n wR += ${dilationHeight}) {\n float dyR = float(dyRCorner + wR) / ${strideHeight}.0;\n\n if (dyR < 0.0 || dyR >= ${convInfo.outHeight}.0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < ${effectiveFilterWidth};\n wC += ${dilationWidth}) {\n float dyC = float(dyCCorner + wC) / ${strideWidth}.0;\n\n if (dyC < 0.0 || dyC >= ${convInfo.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = ${lastIndex} -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * ${effectiveFilterHeight} * ${effectiveFilterWidth} +\n wR * ${effectiveFilterWidth} + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\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 {backend_util, KernelConfig, KernelFunc, MaxPool3DGrad, MaxPool3DGradAttrs, MaxPool3DGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MaxPool3DBackpropProgram} from '../max_pool_backprop_gpu';\nimport {Pool3DProgram} from '../pool_gpu';\n\nexport function maxPool3DGrad(args: {\n inputs: MaxPool3DGradInputs,\n backend: MathBackendWebGL,\n attrs: MaxPool3DGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input} = inputs;\n const x = input;\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const dilations: [number, number, number] = [1, 1, 1];\n\n const convInfo = backend_util.computePool3DInfo(\n x.shape as [number, number, number, number, number], filterSize, strides,\n dilations, pad, dimRoundingMode);\n\n const maxPool3dPositionsProgram =\n new Pool3DProgram(convInfo, 'max', true /* get positions */);\n const maxPool3dPositions =\n backend.runWebGLProgram(maxPool3dPositionsProgram, [x], x.dtype);\n const maxPoolBackpropProgram = new MaxPool3DBackpropProgram(convInfo);\n const result = backend.runWebGLProgram(\n maxPoolBackpropProgram, [dy, maxPool3dPositions], x.dtype);\n backend.disposeIntermediateTensorInfo(maxPool3dPositions);\n return result;\n}\n\nexport const maxPoolGrad3DConfig: KernelConfig = {\n kernelName: MaxPool3DGrad,\n backendName: 'webgl',\n kernelFunc: maxPool3DGrad as {} 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 */\nimport {backend_util, KernelConfig, KernelFunc, MaxPoolGrad, MaxPoolGradAttrs, MaxPoolGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MaxPool2DBackpropProgram} from '../max_pool_backprop_gpu';\nimport {Pool2DProgram} from '../pool_gpu';\nimport {assertNotComplex} from '../webgl_util';\n\nexport function maxPoolGrad(args: {\n inputs: MaxPoolGradInputs,\n backend: MathBackendWebGL,\n attrs: MaxPoolGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {dy, input, output} = inputs;\n const x = input;\n assertNotComplex([input, output], 'maxPoolGrad');\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n 1 /* dilations */, pad, dimRoundingMode);\n const getPositions = true;\n const maxPoolPositionsProgram =\n new Pool2DProgram(convInfo, 'max', getPositions);\n const maxPoolPositions: TensorInfo =\n backend.runWebGLProgram(maxPoolPositionsProgram, [x], x.dtype);\n\n const maxPoolBackPropProgram = new MaxPool2DBackpropProgram(convInfo);\n const result = backend.runWebGLProgram(\n maxPoolBackPropProgram, [dy, maxPoolPositions], x.dtype);\n backend.disposeIntermediateTensorInfo(maxPoolPositions);\n return result;\n}\n\nexport const maxPoolGradConfig: KernelConfig = {\n kernelName: MaxPoolGrad,\n backendName: 'webgl',\n kernelFunc: maxPoolGrad as {} 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, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {Pool2DProgram} from '../pool_gpu';\n\nexport function maxPoolWithArgmaxImpl(\n x: TensorInfo, includeBatchInIndex: boolean,\n convInfo: backend_util.Conv2DInfo,\n backend: MathBackendWebGL): TensorInfo[] {\n let program = new Pool2DProgram(convInfo, 'max', false);\n const poolOutput = backend.runWebGLProgram(program, [x], 'float32');\n\n program = new Pool2DProgram(convInfo, 'max', true, true, includeBatchInIndex);\n const indexOutput = backend.runWebGLProgram(program, [x], 'float32');\n return [poolOutput, indexOutput];\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 {MaxPoolWithArgmax, MaxPoolWithArgmaxAttrs, MaxPoolWithArgmaxInputs} from '@tensorflow/tfjs-core';\nimport {backend_util, KernelConfig, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {maxPoolWithArgmaxImpl} from './MaxPoolWithArgmax_impl';\n\nexport const maxPoolWithArgmaxConfig: KernelConfig = {\n kernelName: MaxPoolWithArgmax,\n backendName: 'webgl',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {x} = inputs as MaxPoolWithArgmaxInputs;\n const {filterSize, strides, pad, includeBatchInIndex} =\n attrs as {} as MaxPoolWithArgmaxAttrs;\n const webglBackend = backend as MathBackendWebGL;\n\n util.assert(\n x.shape.length === 4,\n () => `Error in maxPool: input must be rank 4 but got rank ${\n x.shape.length}.`);\n const dilations: [number, number] = [1, 1];\n util.assert(\n backend_util.eitherStridesOrDilationsAreOne(strides, dilations),\n () => 'Error in maxPool: Either strides or dilations must be 1. ' +\n `Got strides ${strides} and dilations '${dilations}'`);\n\n const convInfo = backend_util.computePool2DInfo(\n x.shape as [number, number, number, number], filterSize, strides,\n dilations, pad);\n\n const [result, indexes] =\n maxPoolWithArgmaxImpl(x, includeBatchInIndex, convInfo, webglBackend);\n return [result, indexes];\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 {TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {reshape} from '../kernels/Reshape';\n\nexport function meanImpl(\n x: TensorInfo, reduceShape: number[], outShape: number[],\n backend: MathBackendWebGL): TensorInfo {\n const inSize = util.sizeFromShape(reduceShape);\n const xSize = util.sizeFromShape(x.shape);\n const batchSize = xSize / inSize;\n const reshapedInput =\n reshape({inputs: {x}, attrs: {shape: [batchSize, inSize]}, backend});\n\n const reduced = reduce(reshapedInput, 'float32', 'mean', backend);\n const reshapedOutput =\n reshape({inputs: {x: reduced}, attrs: {shape: outShape}, backend});\n\n backend.disposeIntermediateTensorInfo(reshapedInput);\n backend.disposeIntermediateTensorInfo(reduced);\n\n return reshapedOutput;\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, Mean, MeanAttrs, MeanInputs, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {meanImpl} from './Mean_impl';\nimport {transposeImpl, transposeImplCPU} from './Transpose_impl';\n\nexport const meanConfig: KernelConfig = {\n kernelName: Mean,\n backendName: 'webgl',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {x} = inputs as MeanInputs;\n const {keepDims, axis} = attrs as {} as MeanAttrs;\n const webglBackend = backend as MathBackendWebGL;\n\n const xRank = x.shape.length;\n const origAxes = util.parseAxisParam(axis, x.shape);\n\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n const meanInputIsTransposed = permutedAxes != null;\n const shouldExecuteOnCPU = webglBackend.shouldExecuteOnCPU([x]);\n\n const intermediates: TensorInfo[] = [];\n\n let meanInput = x;\n if (meanInputIsTransposed) {\n if (shouldExecuteOnCPU) {\n const xTexData = webglBackend.texData.get(meanInput.dataId);\n const values = xTexData.values as TypedArray;\n\n const newShape: number[] = new Array(xRank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = x.shape[permutedAxes[i]];\n }\n const meanInputValues =\n transposeImplCPU(values, x.shape, x.dtype, permutedAxes, newShape);\n\n meanInput = webglBackend.makeTensorInfo(newShape, x.dtype);\n const meanInputData = webglBackend.texData.get(meanInput.dataId);\n meanInputData.values = meanInputValues;\n } else {\n meanInput = transposeImpl(x, permutedAxes, webglBackend);\n }\n\n intermediates.push(meanInput);\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n }\n\n backend_util.assertAxesAreInnerMostDims('sum', axes, xRank);\n const [meanOutShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(meanInput.shape, axes);\n\n let outShape = meanOutShape;\n if (keepDims) {\n // rather than reshape at the end, set the target shape here.\n outShape = backend_util.expandShapeToKeepDim(meanOutShape, origAxes);\n }\n\n const out = meanImpl(meanInput, reduceShape, outShape, webglBackend);\n for (const i of intermediates) {\n webglBackend.disposeIntermediateTensorInfo(i);\n }\n\n return out;\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, KernelConfig, KernelFunc, Min, MinAttrs, MinInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\n\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function min(\n args: {inputs: MinInputs, backend: MathBackendWebGL, attrs: MinAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const xRank = x.shape.length;\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let permutedX = x;\n if (permutedAxes != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, x.shape.length);\n }\n\n backend_util.assertAxesAreInnerMostDims('min', axes, xRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n const reduced = reduce(a2D, a2D.dtype, 'min', backend);\n\n let res;\n if (keepDims) {\n const newShape = backend_util.expandShapeToKeepDim(outShape, origAxes);\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: newShape}});\n } else {\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n }\n\n backend.disposeIntermediateTensorInfo(a2D);\n backend.disposeIntermediateTensorInfo(reduced);\n\n if (permutedAxes != null) {\n backend.disposeIntermediateTensorInfo(permutedX);\n }\n\n return res;\n}\n\nexport const minConfig: KernelConfig = {\n kernelName: Min,\n backendName: 'webgl',\n kernelFunc: min as {} 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, Minimum} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_gpu';\nimport {CHECK_NAN_SNIPPET as CHECK_NAN_SNIPPET_PACKED} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {minimumImplCPU} from '../kernel_utils/shared';\n\nconst MINIMUM = CHECK_NAN_SNIPPET + `\n return min(a, b);\n`;\n\nconst MINIMUM_PACKED = `\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n ` +\n CHECK_NAN_SNIPPET_PACKED + `\n return result;\n`;\n\nexport const minimum = binaryKernelFunc({\n opSnippet: MINIMUM,\n packedOpSnippet: MINIMUM_PACKED,\n cpuKernelImpl: minimumImplCPU\n});\n\nexport const minimumConfig: KernelConfig = {\n kernelName: Minimum,\n backendName: 'webgl',\n kernelFunc: minimum as {} 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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class MirrorPadProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n mode: 'reflect'|'symmetric') {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const unpackedCoords =\n ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);\n const offset = mode === 'reflect' ? 0 : 1;\n\n if (rank === 1) {\n this.userCode = `\n int start = ${start};\n int end = ${end};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start) {\n outC = start * 2 - outC - ${offset};\n } else if(outC >= end) {\n outC = (end - 1) * 2 - outC + ${offset};\n }\n setOutput(getX(outC - start));\n }\n `;\n return;\n }\n this.userCode = `\n ${dtype} start = ${dtype}(${start});\n ${dtype} end = ${dtype}(${end});\n\n void main() {\n ${dtype} outC = getOutputCoords();\n for (int i = 0; i < ${rank}; i++) {\n if (outC[i] < start[i]) {\n outC[i] = start[i] * 2 - outC[i] - ${offset};\n } else if(outC[i] >= end[i]) {\n outC[i] = (end[i] - 1) * 2 - outC[i] + ${offset};\n }\n }\n ${dtype} coords = outC - start;\n setOutput(getX(${unpackedCoords}));\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 */\n\nimport {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\n/**\n * Example shader code for\n * `mirrorPad(tf.tensor1d([1, 2, 3], 'int32'), [[2, 2]], 'reflect')`\n * ```\n * const int start = int(2);\n * const int end = int(5);\n *\n * void main() {\n * int outputLoc = getOutputCoords();\n * vec4 result = vec4(0.);\n *\n * int rc = outputLoc;\n *\n * int source = rc;\n * if (source < start) {\n * source = start * 2 - source - 0;\n * } else if (source >= end) {\n * source = (end - 1) * 2 - source + 0;\n * }\n * source -= start;\n *\n * result[0] = getChannel(getX(source), source);\n * rc += 1;\n * if(rc < 6) {\n * int source = rc;\n * if (source < start) {\n * source = start * 2 - source - 0;\n * } else if (source >= end) {\n * source = (end - 1) * 2 - source + 0;\n * }\n * source -= start;\n *\n * result[1] = getChannel(getX(source), source);\n * }\n *\n * setOutput(result);\n * }\n * ```\n */\nexport class MirrorPadPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n mode: 'reflect'|'symmetric') {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const coords = getChannels('rc', rank);\n const source = getChannels('source', rank);\n const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;\n const innerDims =\n rank === 1 ? 'source' : `vec2(${source.slice(-2).join()})`;\n const offset = mode === 'reflect' ? 0 : 1;\n\n let mainLoop = '';\n if (rank === 1) {\n const padSetup = `\n ${dtype} source = rc;\n if (source < start) {\n source = start * 2 - source - ${offset};\n } else if (source >= end) {\n source = (end - 1) * 2 - source + ${offset};\n }\n source -= start;\n `;\n mainLoop = `\n ${dtype} rc = outputLoc;\n ${padSetup}\n result[0] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[1] = getChannel(getX(${source.join()}), ${innerDims});\n }\n `;\n } else {\n const padSetup = `\n ${dtype} source = rc;\n ${dtype} lt = ${dtype}(lessThan(source, start));\n ${dtype} gte = ${dtype}(greaterThanEqual(source, end));\n ${dtype} orig = 1 - (lt + gte);\n source = orig * source +\n lt * (start * 2 - source - ${offset}) +\n gte * ((end - 1) * 2 - source + ${offset});\n source -= start;\n `;\n\n mainLoop = `\n ${dtype} rc = outputLoc;\n ${padSetup}\n result[0] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[1] = getChannel(getX(${source.join()}), ${innerDims});\n }\n rc = outputLoc;\n ${coords[rank - 2]} += 1;\n if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {\n ${padSetup}\n result[2] = getChannel(getX(${source.join()}), ${innerDims});\n ${coords[rank - 1]} += 1;\n if(${cLimit}) {\n ${padSetup}\n result[3] = getChannel(getX(${source.join()}), ${innerDims});\n }\n }\n `;\n }\n\n this.userCode = `\n const ${dtype} start = ${dtype}(${start});\n const ${dtype} end = ${dtype}(${end});\n\n void main() {\n ${dtype} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${mainLoop}\n setOutput(result);\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 */\n\nimport {env, KernelConfig, KernelFunc, MirrorPad, MirrorPadAttrs, MirrorPadInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MirrorPadProgram} from '../mirror_pad_gpu';\nimport {MirrorPadPackedProgram} from '../mirror_pad_packed_gpu';\n\nexport const mirrorPadKernelFunc: (params: {\n inputs: MirrorPadInputs,\n backend: MathBackendWebGL,\n attrs: MirrorPadAttrs\n}) => TensorInfo = ({inputs, backend, attrs}) => {\n const {x} = inputs;\n const {paddings, mode} = attrs;\n\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new MirrorPadPackedProgram(x.shape, paddings, mode) :\n new MirrorPadProgram(x.shape, paddings, mode);\n\n const output = backend.runWebGLProgram(program, [x], x.dtype);\n\n return output;\n};\n\nexport const mirrorPadConfig: KernelConfig = {\n kernelName: MirrorPad,\n backendName: 'webgl',\n kernelFunc: mirrorPadKernelFunc as {} 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, Mod} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst MOD = `if (b == 0.0) return NAN;\n return mod(a, b);`;\n\nconst MOD_PACKED = `\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n ` +\n CHECK_NAN_SNIPPET + `\n return result;\n`;\n\nexport const mod = binaryKernelFunc({\n opSnippet: MOD,\n packedOpSnippet: MOD_PACKED,\n});\n\nexport const modConfig: KernelConfig = {\n kernelName: Mod,\n backendName: 'webgl',\n kernelFunc: mod as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class MultinomialProgram implements GPGPUProgram {\n variableNames = ['probs'];\n outputShape: number[];\n userCode: string;\n customUniforms = [{name: 'seed', type: 'float' as UniformType}];\n\n constructor(batchSize: number, numOutcomes: number, numSamples: number) {\n this.outputShape = [batchSize, numSamples];\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < ${numOutcomes - 1}; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float(${numOutcomes - 1}));\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 */\n\nimport {RealDiv} from '@tensorflow/tfjs-core';\nimport {KernelConfig} from '@tensorflow/tfjs-core';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// Without the equality check div produces 0.9999 for a = b, which when\n// floored can cause errors.\nconst DIV = `\nif (a == b) {\n return 1.0;\n};\nreturn a / b;`;\n\n// We do the same as in ./binaryop_gpu, with vec4 and ivec4.\n// On Linux, the vectorized implementation produces NaNs when a and b are 0.\nconst DIV_PACKED = `\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n`;\n\nexport const realDiv = binaryKernelFunc(\n {opSnippet: DIV, packedOpSnippet: DIV_PACKED, checkOutOfBounds: true});\n\nexport const realDivConfig: KernelConfig = {\n kernelName: RealDiv,\n backendName: 'webgl',\n kernelFunc: realDiv,\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 {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {subImplCPU as cpuSub} from '../kernel_utils/shared';\n\nconst SUB = 'return a - b;';\n\nexport const sub = binaryKernelFunc({\n opSnippet: SUB,\n packedOpSnippet: SUB,\n supportsComplex: true,\n cpuKernelImpl: cpuSub\n});\n\nexport const subConfig: KernelConfig = {\n kernelName: Sub,\n backendName: 'webgl',\n kernelFunc: sub\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 {MathBackendWebGL} from '../backend_webgl';\n\nimport {exp} from './Exp';\nimport {max} from './Max';\nimport {realDiv} from './RealDiv';\nimport {reshape} from './Reshape';\nimport {sub} from './Sub';\nimport {sum} from './Sum';\n\nexport function softmax(args: {\n inputs: SoftmaxInputs,\n backend: MathBackendWebGL,\n attrs: SoftmaxAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {logits} = inputs;\n const {dim} = attrs;\n\n const axes = util.parseAxisParam([dim], logits.shape);\n\n const maxLogit = max({\n inputs: {x: logits},\n backend,\n attrs: {reductionIndices: axes, keepDims: false}\n });\n\n const expandedShape = backend_util.expandShapeToKeepDim(maxLogit.shape, axes);\n\n const maxLogitsReshaped =\n reshape({inputs: {x: maxLogit}, backend, attrs: {shape: expandedShape}});\n const a =\n sub({inputs: {a: logits, b: maxLogitsReshaped}, 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 sumExpReshaped =\n reshape({inputs: {x: sumExp}, backend, attrs: {shape: expandedShape}});\n\n const res =\n realDiv({inputs: {a: b, b: sumExpReshaped}, backend}) as TensorInfo;\n\n backend.disposeIntermediateTensorInfo(maxLogit);\n backend.disposeIntermediateTensorInfo(maxLogitsReshaped);\n backend.disposeIntermediateTensorInfo(a);\n backend.disposeIntermediateTensorInfo(b);\n backend.disposeIntermediateTensorInfo(sumExp);\n backend.disposeIntermediateTensorInfo(sumExpReshaped);\n\n return res;\n}\n\nexport const softmaxConfig: KernelConfig = {\n kernelName: Softmax,\n backendName: 'webgl',\n kernelFunc: softmax as {} 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, Multinomial, MultinomialAttrs, MultinomialInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {MultinomialProgram} from '../multinomial_gpu';\n\nimport {softmax} from './Softmax';\n\nexport function multinomial(args: {\n inputs: MultinomialInputs,\n backend: MathBackendWebGL,\n attrs: MultinomialAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {logits} = inputs;\n const {numSamples, seed, normalized} = attrs;\n\n const probs = normalized ?\n logits :\n softmax(\n {inputs: {logits}, backend, attrs: {dim: logits.shape.length - 1}});\n const batchSize = probs.shape[0];\n const numOutcomes = probs.shape[1];\n const program = new MultinomialProgram(batchSize, numOutcomes, numSamples);\n const customValues = [[seed]];\n const res = backend.runWebGLProgram(program, [probs], 'int32', customValues);\n if (!normalized) {\n backend.disposeIntermediateTensorInfo(probs);\n }\n return res;\n}\n\nexport const multinomialConfig: KernelConfig = {\n kernelName: Multinomial,\n backendName: 'webgl',\n kernelFunc: multinomial as {} 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 {env, KernelConfig, KernelFunc, Neg, NegInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {negImplCPU} from '../kernel_utils/shared';\nimport {UnaryOpProgram} from '../unaryop_gpu';\nimport {UnaryOpPackedProgram} from '../unaryop_packed_gpu';\n\nconst NEG = `return -x;`;\n\n// This doesn't use unaryKernelFunc because negImplCPU is not of type\n// SimpleUnaryKernelImplCPU.\nexport function neg(args: {inputs: NegInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (backend.shouldExecuteOnCPU([x])) {\n const xData = backend.texData.get(x.dataId);\n const [outValues, newShape] =\n negImplCPU(xData.values as TypedArray, x.shape, x.dtype);\n return backend.makeTensorInfo(newShape, x.dtype, outValues);\n }\n\n let program: UnaryOpProgram|UnaryOpPackedProgram;\n if (env().getBool('WEBGL_PACK_UNARY_OPERATIONS')) {\n program = new UnaryOpPackedProgram(x.shape, NEG);\n } else {\n program = new UnaryOpProgram(x.shape, NEG);\n }\n\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const negConfig: KernelConfig = {\n kernelName: Neg,\n backendName: 'webgl',\n kernelFunc: neg as {} 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, kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV3, NonMaxSuppressionV3Attrs, NonMaxSuppressionV3Inputs, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV3Impl = kernel_impls.nonMaxSuppressionV3Impl;\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function nonMaxSuppressionV3(args: {\n inputs: NonMaxSuppressionV3Inputs,\n backend: MathBackendWebGL,\n attrs: NonMaxSuppressionV3Attrs\n}) {\n backend_util.warn(\n 'tf.nonMaxSuppression() in webgl locks the UI thread. ' +\n 'Call tf.nonMaxSuppressionAsync() instead');\n\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold} = attrs;\n\n const boxesVals = backend.readSync(boxes.dataId) as TypedArray;\n const scoresVals = backend.readSync(scores.dataId) as TypedArray;\n\n const {selectedIndices} = nonMaxSuppressionV3Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold);\n\n return backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices));\n}\n\nexport const nonMaxSuppressionV3Config: KernelConfig = {\n kernelName: NonMaxSuppressionV3,\n backendName: 'webgl',\n kernelFunc: nonMaxSuppressionV3 as {} 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, kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\nconst nonMaxSuppressionV4Impl = kernel_impls.nonMaxSuppressionV4Impl;\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function nonMaxSuppressionV4(args: {\n inputs: NonMaxSuppressionV4Inputs,\n backend: MathBackendWebGL,\n attrs: NonMaxSuppressionV4Attrs\n}): [TensorInfo, TensorInfo] {\n backend_util.warn(\n 'tf.nonMaxSuppression() in webgl locks the UI thread. ' +\n 'Call tf.nonMaxSuppressionAsync() instead');\n\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold, padToMaxOutputSize} =\n attrs;\n\n const boxesVals = backend.readSync(boxes.dataId) as TypedArray;\n const scoresVals = backend.readSync(scores.dataId) as TypedArray;\n\n const {selectedIndices, validOutputs} = nonMaxSuppressionV4Impl(\n boxesVals, scoresVals, maxOutputSize, iouThreshold, scoreThreshold,\n padToMaxOutputSize);\n\n return [\n backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices)),\n backend.makeTensorInfo([], 'int32', new Int32Array([validOutputs]))\n ];\n}\n\nexport const nonMaxSuppressionV4Config: KernelConfig = {\n kernelName: NonMaxSuppressionV4,\n backendName: 'webgl',\n kernelFunc: nonMaxSuppressionV4 as {} 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, kernel_impls, KernelConfig, KernelFunc, NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nconst nonMaxSuppressionV5Impl = kernel_impls.nonMaxSuppressionV5Impl;\nimport {MathBackendWebGL} from '../backend_webgl';\n\nexport function nonMaxSuppressionV5(args: {\n inputs: NonMaxSuppressionV5Inputs,\n backend: MathBackendWebGL,\n attrs: NonMaxSuppressionV5Attrs\n}): [TensorInfo, TensorInfo] {\n backend_util.warn(\n 'tf.nonMaxSuppression() in webgl locks the UI thread. ' +\n 'Call tf.nonMaxSuppressionAsync() instead');\n\n const {inputs, backend, attrs} = args;\n const {boxes, scores} = inputs;\n const {maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma} = attrs;\n\n const boxesVals = backend.readSync(boxes.dataId) as TypedArray;\n const scoresVals = backend.readSync(scores.dataId) as TypedArray;\n\n const maxOutputSizeVal = maxOutputSize;\n const iouThresholdVal = iouThreshold;\n const scoreThresholdVal = scoreThreshold;\n const softNmsSigmaVal = softNmsSigma;\n\n const {selectedIndices, selectedScores} = nonMaxSuppressionV5Impl(\n boxesVals, scoresVals, maxOutputSizeVal, iouThresholdVal,\n scoreThresholdVal, softNmsSigmaVal);\n\n return [\n backend.makeTensorInfo(\n [selectedIndices.length], 'int32', new Int32Array(selectedIndices)),\n backend.makeTensorInfo(\n [selectedScores.length], 'float32', new Float32Array(selectedScores))\n ];\n}\n\nexport const nonMaxSuppressionV5Config: KernelConfig = {\n kernelName: NonMaxSuppressionV5,\n backendName: 'webgl',\n kernelFunc: nonMaxSuppressionV5 as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class OneHotProgram implements GPGPUProgram {\n variableNames = ['indices'];\n outputShape: number[];\n userCode: string;\n\n // Caching uniform location for speed.\n seedLoc: WebGLUniformLocation;\n\n constructor(\n numIndices: number, depth: number, onValue: number, offValue: number) {\n this.outputShape = [numIndices, depth];\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float(${offValue}), float(${onValue}),\n float(index == coords.y)));\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 */\n\nimport {KernelConfig, KernelFunc, OneHot, OneHotAttrs, OneHotInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {OneHotProgram} from '../onehot_gpu';\nimport {reshape} from './Reshape';\n\nexport const oneHot = (args: {\n inputs: OneHotInputs,\n backend: MathBackendWebGL,\n attrs: OneHotAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {indices} = inputs;\n const {depth, onValue, offValue} = attrs;\n\n const indicesSize = util.sizeFromShape(indices.shape);\n const program = new OneHotProgram(indicesSize, depth, onValue, offValue);\n const reshaped =\n reshape({inputs: {x: indices}, backend, attrs: {shape: [indicesSize]}});\n const result = backend.runWebGLProgram(program, [reshaped], indices.dtype);\n backend.disposeIntermediateTensorInfo(reshaped);\n\n const outShape = [...indices.shape, depth];\n const out = reshape({inputs: {x: result}, backend, attrs: {shape: outShape}});\n backend.disposeIntermediateTensorInfo(result);\n return out;\n};\n\nexport const oneHotConfig: KernelConfig = {\n kernelName: OneHot,\n backendName: 'webgl',\n kernelFunc: oneHot as {} 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, ZerosLike, ZerosLikeInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {complex} from './Complex';\nimport {fill} from './Fill';\nimport {imag} from './Imag';\nimport {real} from './Real';\n\nexport function zerosLike(\n args: {inputs: ZerosLikeInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const r = zerosLike({inputs: {x: realPart}, backend});\n const imagPart = imag({inputs: {input: x}, backend});\n const i = zerosLike({inputs: {x: imagPart}, backend});\n\n const result = complex({inputs: {real: r, imag: i}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(r);\n backend.disposeIntermediateTensorInfo(imagPart);\n backend.disposeIntermediateTensorInfo(i);\n\n return result;\n } else {\n return fill({\n attrs: {\n shape: x.shape,\n dtype: x.dtype,\n value: x.dtype === 'string' ? '' : 0\n },\n backend\n });\n }\n}\n\nexport const zerosLikeConfig: KernelConfig = {\n kernelName: ZerosLike,\n backendName: 'webgl',\n kernelFunc: zerosLike as {} 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, OnesLike, OnesLikeInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {complex} from './Complex';\nimport {fill} from './Fill';\nimport {imag} from './Imag';\nimport {real} from './Real';\nimport {zerosLike} from './ZerosLike';\n\nexport function onesLike(\n args: {inputs: OnesLikeInputs, backend: MathBackendWebGL}): TensorInfo {\n const {inputs, backend} = args;\n const {x} = inputs;\n\n if (x.dtype === 'string') {\n throw new Error('onesLike is not supported under string dtype');\n } else if (x.dtype === 'complex64') {\n const realPart = real({inputs: {input: x}, backend});\n const r = onesLike({inputs: {x: realPart}, backend});\n const imagPart = imag({inputs: {input: x}, backend});\n const i = zerosLike({inputs: {x: imagPart}, backend});\n\n const result = complex({inputs: {real: r, imag: i}, backend});\n\n backend.disposeIntermediateTensorInfo(realPart);\n backend.disposeIntermediateTensorInfo(r);\n backend.disposeIntermediateTensorInfo(imagPart);\n backend.disposeIntermediateTensorInfo(i);\n\n return result;\n } else {\n // TODO(cais, smilkov): Add WebGL shader for onesLike:\n // https://github.com/tensorflow/tfjs/issues/1293\n return fill({attrs: {shape: x.shape, dtype: x.dtype, value: 1}, backend});\n }\n}\n\nexport const onesLikeConfig: KernelConfig = {\n kernelName: OnesLike,\n backendName: 'webgl',\n kernelFunc: onesLike as {} 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 {MathBackendWebGL} from '../backend_webgl';\nimport {concat} from './Concat';\nimport {expandDims} from './ExpandDims';\n\nexport function pack(\n args: {inputs: PackInputs, backend: MathBackendWebGL, 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: 'webgl',\n kernelFunc: pack as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class PadProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n customUniforms = [{name: 'value', type: 'float' as UniformType}];\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n constantValue: number) {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const type = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const unpackedCoords =\n ['coords[0]', 'coords[1]', 'coords[2]', 'coords[3]'].slice(0, rank);\n\n if (rank === 1) {\n this.userCode = `\n int start = ${start};\n int end = ${end};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `;\n return;\n }\n this.userCode = `\n ${type} start = ${type}(${start});\n ${type} end = ${type}(${end});\n\n void main() {\n ${type} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${type} coords = outC - start;\n setOutput(getX(${unpackedCoords}));\n }\n }\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 {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType, UniformType} from './shader_compiler';\n\nexport class PadPackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[];\n userCode: string;\n customUniforms = [{name: 'value', type: 'float' as UniformType}];\n\n constructor(\n xShape: number[], paddings: Array<[number, number]>,\n constantValue: number) {\n this.outputShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + xShape[i] + p[1] /* afterPad */);\n const rank = xShape.length;\n const dtype = getCoordsDataType(rank);\n\n const start = paddings.map(p => p[0]).join(',');\n const end = paddings.map((p, i) => p[0] + xShape[i]).join(',');\n const coords = getChannels('rc', rank);\n const source = getChannels('source', rank);\n const cLimit = `${coords[rank - 1]} < ${this.outputShape[rank - 1]}`;\n const innerDims =\n rank === 1 ? 'source' : `vec2(${source.slice(-2).join()})`;\n\n const componentSetup = [\n `${dtype} rc = outputLoc;`, `${coords[rank - 1]} += 1;\n if(${cLimit}) {\n `,\n rank === 1 ? '' : `}\n rc = outputLoc;\n ${coords[rank - 2]} += 1;\n if(${coords[rank - 2]} < ${this.outputShape[rank - 2]}) {`,\n rank === 1 ? '' : ` ${coords[rank - 1]} += 1;\n if(${cLimit}) {`\n ];\n\n const paddingArea = rank === 1 ?\n 'rc < start || rc >= end' :\n 'any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))';\n let mainLoop = '';\n for (let i = 0, j = rank === 1 ? 2 : 4; i < j; i++) {\n mainLoop += `\n ${componentSetup[i]}\n if (${paddingArea}) {\n result[${i}] = float(value);\n } else {\n ${dtype} source = rc - start;\n result[${i}] = getChannel(getX(${source.join()}), ${innerDims});\n }\n `;\n }\n mainLoop += (rank === 1 ? `} ` : `}}`);\n\n this.userCode = `\n const ${dtype} start = ${dtype}(${start});\n const ${dtype} end = ${dtype}(${end});\n\n void main() {\n ${dtype} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${mainLoop}\n setOutput(result);\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 */\n\nimport {env, KernelConfig, KernelFunc, PadV2, PadV2Attrs, PadV2Inputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {PadProgram} from '../pad_gpu';\nimport {PadPackedProgram} from '../pad_packed_gpu';\n\nexport const padV2 =\n (args: {inputs: PadV2Inputs, backend: MathBackendWebGL, attrs: PadV2Attrs}):\n TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {paddings, constantValue} = attrs;\n\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new PadPackedProgram(x.shape, paddings, constantValue) :\n new PadProgram(x.shape, paddings, constantValue);\n const customValues = [[constantValue]];\n return backend.runWebGLProgram(program, [x], x.dtype, customValues);\n };\n\nexport const padV2Config: KernelConfig = {\n kernelName: PadV2,\n backendName: 'webgl',\n kernelFunc: padV2 as {} 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, Pow} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET} from '../binaryop_packed_gpu';\nimport {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst POW = `\n if(a < 0.0 && floor(b) < b){\n return NAN;\n }\n if (b == 0.0) {\n return 1.0;\n }\n return (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n`;\n\nconst POW_PACKED = `\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n ` +\n CHECK_NAN_SNIPPET + `\n return result;\n`;\n\nexport const pow =\n binaryKernelFunc({opSnippet: POW, packedOpSnippet: POW_PACKED});\n\nexport const powConfig: KernelConfig = {\n kernelName: Pow,\n backendName: 'webgl',\n kernelFunc: pow as {} 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, Prod, ProdAttrs, ProdInputs, sumOutType, TensorInfo, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {reduce} from '../kernel_utils/reduce';\nimport {prodImplCPU} from '../kernel_utils/shared';\n\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport function prod(\n args: {inputs: ProdInputs, backend: MathBackendWebGL, attrs: ProdAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, keepDims} = attrs;\n\n const xRank = x.shape.length;\n const toDispose = [];\n\n const origAxes = util.parseAxisParam(axis, x.shape);\n let axes = origAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let permutedX = x;\n if (permutedAxes != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutedAxes}});\n axes = backend_util.getInnerMostAxes(axes.length, xRank);\n toDispose.push(permutedX);\n }\n\n backend_util.assertAxesAreInnerMostDims('prod', axes, xRank);\n\n let res;\n if (backend.shouldExecuteOnCPU([permutedX])) {\n const xVals = backend.texData.get(permutedX.dataId).values as TypedArray;\n const {outVals, outShape, outDtype} =\n prodImplCPU(permutedX.shape, permutedX.dtype, xVals, axes);\n res = backend.makeTensorInfo(outShape, outDtype, outVals);\n } else {\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(permutedX.shape, axes);\n const inSize = util.sizeFromShape(reduceShape);\n const a2D = reshape(\n {inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n const outputDType = sumOutType(x.dtype);\n const reduced = reduce(a2D, outputDType, 'prod', backend);\n res = reshape({inputs: {x: reduced}, backend, attrs: {shape: outShape}});\n\n toDispose.push(a2D);\n toDispose.push(reduced);\n }\n\n if (keepDims) {\n toDispose.push(res);\n const newShape = backend_util.expandShapeToKeepDim(res.shape, origAxes);\n res = reshape({inputs: {x: res}, backend, attrs: {shape: newShape}});\n }\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return res;\n}\n\nexport const prodConfig: KernelConfig = {\n kernelName: Prod,\n backendName: 'webgl',\n kernelFunc: prod as {} 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 {MathBackendWebGL} from '../backend_webgl';\nimport {rangeImplCPU} from '../kernel_utils/shared';\n\nexport const range =\n (args: {backend: MathBackendWebGL, attrs: RangeAttrs}): TensorInfo => {\n const {backend, attrs} = args;\n const {start, stop, step, dtype} = attrs;\n const values = rangeImplCPU(start, stop, step, dtype);\n return backend.makeTensorInfo([values.length], dtype, values);\n };\n\nexport const rangeConfig: KernelConfig = {\n kernelName: Range,\n backendName: 'webgl',\n kernelFunc: range as {} 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, Reciprocal} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst RECIPROCAL = `return 1.0 / x;`;\n\nexport const reciprocal = unaryKernelFunc({opSnippet: RECIPROCAL});\n\nexport const reciprocalConfig: KernelConfig = {\n kernelName: Reciprocal,\n backendName: 'webgl',\n kernelFunc: reciprocal,\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, Relu} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst RELU = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : x;\n`;\n\nconst RELU_PACKED = `\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const relu =\n unaryKernelFunc({opSnippet: RELU, packedOpSnippet: RELU_PACKED});\n\nexport const reluConfig: KernelConfig = {\n kernelName: Relu,\n backendName: 'webgl',\n kernelFunc: relu as {} 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, Relu6} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {CHECK_NAN_SNIPPET} from '../unaryop_gpu';\n\nconst RELU6 = CHECK_NAN_SNIPPET + `\n return (x < 0.0) ? 0.0 : min(6.0, x);\n`;\n\nconst RELU6_PACKED = `\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n`;\n\nexport const relu6 =\n unaryKernelFunc({opSnippet: RELU6, packedOpSnippet: RELU6_PACKED});\n\nexport const relu6Config: KernelConfig = {\n kernelName: Relu6,\n backendName: 'webgl',\n kernelFunc: relu6 as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC =\n `(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC` +\n ` - vec2(0.5)`;\n } else {\n sourceFracIndexRC = `vec2(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${sourceFracIndexRC};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC = `(vec3(yRC) + vec3(0.5)) * ` +\n `effectiveInputOverOutputRatioRC - vec3(0.5)`;\n } else {\n sourceFracIndexRC = `vec3(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec3 inputShapeRC = vec3(${oldHeight}.0, ${oldWidth}.0,\n ${oldWidth}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${sourceFracIndexRC};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${depth - 1};\n bool hasNextRow = coords.z < ${newWidth - 1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\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 */\n\nimport {env, KernelConfig, KernelFunc, ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeBilinearProgram} from '../resize_bilinear_gpu';\nimport {ResizeBilinearPackedProgram} from '../resize_bilinear_packed_gpu';\n\nexport function resizeBilinear(args: {\n inputs: ResizeBilinearInputs,\n backend: MathBackendWebGL,\n attrs: ResizeBilinearAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n const [newHeight, newWidth] = size;\n\n const program = env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ?\n new ResizeBilinearPackedProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters) :\n new ResizeBilinearProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters);\n return backend.runWebGLProgram(program, [images], 'float32');\n}\n\nexport const resizeBilinearConfig: KernelConfig = {\n kernelName: ResizeBilinear,\n backendName: 'webgl',\n kernelFunc: resizeBilinear as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeBilinearBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n dyShape: [number, number, number, number],\n inputShape: [number, number, number, number], alignCorners: boolean) {\n this.outputShape = inputShape;\n const [, xHeight, xWidth, ] = inputShape;\n const [, yHeight, yWidth] = dyShape;\n\n // In the backwards pass, we want to find the pixels that were generated for\n // each pixel in the input image the forward pass and add the corresponding\n // coefficient from dy to the gradient (with some interpolation).\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n const invHeightScale = 1 / heightScale;\n const invWidthScale = 1 / widthScale;\n\n // This defines the size of the window of values around a particular\n // index in dy that we want to search for contributions to dx.\n const winHeight = (Math.ceil(invHeightScale) * 2) + 2;\n const winWidth = (Math.ceil(invWidthScale) * 2) + 2;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${heightScale});\n const float widthScale = float(${widthScale});\n\n const float invHeightScale = float(${invHeightScale});\n const float invWidthScale = float(${invWidthScale});\n\n const int winHeight = int(${winHeight});\n const int winWidth = int(${winWidth});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${yHeight}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${yWidth}) {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), ${xHeight - 1}.0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), ${xWidth - 1}.0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\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 */\n\nimport {KernelConfig, KernelFunc, ResizeBilinearGrad, ResizeBilinearGradAttrs, ResizeBilinearGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeBilinearBackpropProgram} from '../resize_bilinear_backprop_gpu';\n\nexport function resizeBilinearGrad(args: {\n inputs: ResizeBilinearGradInputs,\n backend: MathBackendWebGL,\n attrs: ResizeBilinearGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n const program = new ResizeBilinearBackpropProgram(\n dy.shape as [number, number, number, number],\n images.shape as [number, number, number, number], alignCorners);\n\n return backend.runWebGLProgram(program, [dy], dy.dtype);\n}\n\nexport const resizeBilinearGradConfig: KernelConfig = {\n kernelName: ResizeBilinearGrad,\n backendName: 'webgl',\n kernelFunc: resizeBilinearGrad as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeighborProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n // When align corners is false, we rounds the value with floor.\n const roundBase = alignCorners ? '0.5' : '0.0';\n\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC =\n `max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC` +\n `, vec2(0.0))`;\n } else {\n sourceFracIndexRC = `vec2(yRC) * effectiveInputOverOutputRatioRC`;\n }\n this.userCode = `\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec2 inputShapeRC = vec2(${oldHeight}.0, ${oldWidth}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${sourceFracIndexRC};\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeighborPackedProgram implements GPGPUProgram {\n variableNames = ['A'];\n packedInputs = true;\n packedOutput = true;\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n inputShape: [number, number, number, number], newHeight: number,\n newWidth: number, alignCorners: boolean, halfPixelCenters: boolean) {\n const [batch, oldHeight, oldWidth, depth] = inputShape;\n this.outputShape = [batch, newHeight, newWidth, depth];\n\n const effectiveInSize: [number, number] = [\n (alignCorners && newHeight > 1) ? oldHeight - 1 : oldHeight,\n (alignCorners && newWidth > 1) ? oldWidth - 1 : oldWidth\n ];\n\n const effectiveOutSize: [number, number] = [\n (alignCorners && newHeight > 1) ? newHeight - 1 : newHeight,\n (alignCorners && newWidth > 1) ? newWidth - 1 : newWidth\n ];\n\n // When align corners is false, we rounds the value with floor.\n const roundBase = alignCorners ? '0.5' : '0.0';\n let sourceFracIndexRC: string;\n if (halfPixelCenters) {\n sourceFracIndexRC = `max((vec3(yRC) + vec3(0.5)) * ` +\n `effectiveInputOverOutputRatioRC, vec3(0.0))`;\n } else {\n sourceFracIndexRC = `vec3(yRC) * effectiveInputOverOutputRatioRC`;\n }\n\n this.userCode = `\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${effectiveInSize[0] / effectiveOutSize[0]},\n ${effectiveInSize[1] / effectiveOutSize[1]},\n ${effectiveInSize[1] / effectiveOutSize[1]});\n const vec3 inputShapeRC = vec3(${oldHeight}.0, ${oldWidth}.0,\n ${oldWidth}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${sourceFracIndexRC};\n\n // Compute the coordinators of nearest neighbor point.\n ivec3 sourceNearestRC = ivec3(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${roundBase})));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${depth - 1};\n bool hasNextRow = coords.z < ${newWidth - 1};\n\n vec4 newValue = vec4(\n getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n setOutput(newValue);\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 */\n\nimport {env, KernelConfig, KernelFunc, ResizeNearestNeighbor, ResizeNearestNeighborAttrs, ResizeNearestNeighborInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeNearestNeighborProgram} from '../resize_nearest_neighbor_gpu';\nimport {ResizeNearestNeighborPackedProgram} from '../resize_nearest_neighbor_packed_gpu';\n\nexport function resizeNearestNeighbor(args: {\n inputs: ResizeNearestNeighborInputs,\n backend: MathBackendWebGL,\n attrs: ResizeNearestNeighborAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n\n const [newHeight, newWidth] = size;\n\n const program = env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ?\n new ResizeNearestNeighborPackedProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters) :\n new ResizeNearestNeighborProgram(\n images.shape as [number, number, number, number], newHeight, newWidth,\n alignCorners, halfPixelCenters);\n return backend.runWebGLProgram(program, [images], images.dtype);\n}\n\nexport const resizeNearestNeighborConfig: KernelConfig = {\n kernelName: ResizeNearestNeighbor,\n backendName: 'webgl',\n kernelFunc: resizeNearestNeighbor as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class ResizeNearestNeigborBackpropProgram implements GPGPUProgram {\n variableNames = ['dy'];\n outputShape: number[] = [];\n userCode: string;\n\n constructor(\n dyShape: [number, number, number, number],\n inputShape: [number, number, number, number], alignCorners: boolean) {\n this.outputShape = inputShape;\n const [, xHeight, xWidth, ] = inputShape;\n const [, yHeight, yWidth] = dyShape;\n\n // In the backwards pass, we want to find the pixels that were generated for\n // each pixel in the input image the forward pass and add the corresponding\n // coefficient from dy to the gradient (with some interpolation).\n\n const effectiveXSize: [number, number] = [\n (alignCorners && yHeight > 1) ? xHeight - 1 : xHeight,\n (alignCorners && yWidth > 1) ? xWidth - 1 : xWidth\n ];\n\n const effectiveYSize: [number, number] = [\n (alignCorners && yHeight > 1) ? yHeight - 1 : yHeight,\n (alignCorners && yWidth > 1) ? yWidth - 1 : yWidth\n ];\n\n const heightScale = effectiveXSize[0] / effectiveYSize[0];\n const widthScale = effectiveXSize[1] / effectiveYSize[1];\n\n const invHeightScale = 1 / heightScale;\n const invWidthScale = 1 / widthScale;\n\n // This defines the size of the window of values around a particular\n // index in dy that we want to search for contributions to dx.\n const winHeight = (Math.ceil(invHeightScale) * 2) + 2;\n const winWidth = (Math.ceil(invWidthScale) * 2) + 2;\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float(${heightScale});\n const float widthScale = float(${widthScale});\n\n const float invHeightScale = float(${invHeightScale});\n const float invWidthScale = float(${invWidthScale});\n\n const int winHeight = int(${winHeight});\n const int winWidth = int(${winWidth});\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= ${yHeight}) {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= ${yWidth}) {\n continue;\n }\n\n float sourceFracRow =\n float(${effectiveXSize[0]}) *\n (float(dyR) / float(${effectiveYSize[0]}));\n\n float sourceFracCol =\n float(${effectiveXSize[1]}) *\n (float(dyC) / float(${effectiveYSize[1]}));\n\n int sourceNearestRow = int(min(\n float(int(${xHeight}) - 1),\n ${alignCorners} ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int(${xWidth}) - 1),\n ${alignCorners} ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\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 */\n\nimport {KernelConfig, KernelFunc, ResizeNearestNeighborGrad, ResizeNearestNeighborGradAttrs, ResizeNearestNeighborGradInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ResizeNearestNeigborBackpropProgram} from '../resize_nearest_neighbor_backprop_gpu';\n\nexport function resizeNearestNeighborGrad(args: {\n inputs: ResizeNearestNeighborGradInputs,\n backend: MathBackendWebGL,\n attrs: ResizeNearestNeighborGradAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {images, dy} = inputs;\n const {alignCorners} = attrs;\n\n const program = new ResizeNearestNeigborBackpropProgram(\n dy.shape as [number, number, number, number],\n images.shape as [number, number, number, number], alignCorners);\n return backend.runWebGLProgram(program, [dy], dy.dtype);\n}\n\nexport const resizeNearestNeighborGradConfig: KernelConfig = {\n kernelName: ResizeNearestNeighborGrad,\n backendName: 'webgl',\n kernelFunc: resizeNearestNeighborGrad as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ReverseProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(xShape: number[], axis: number[]) {\n const rank = xShape.length;\n if (rank > 4) {\n throw new Error(\n `WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);\n }\n this.outputShape = xShape;\n\n if (rank === 1) {\n this.userCode = `\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${xShape[0]} - coord - 1));\n }\n `;\n return;\n }\n const getInCoord = (i: number) => {\n if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {\n return `${xShape[i]} - coords[${i}] - 1`;\n }\n return `coords[${i}]`;\n };\n const inCoords = xShape.map((_, i) => getInCoord(i)).join(',');\n const type = getCoordsDataType(rank);\n\n this.userCode = `\n void main() {\n ${type} coords = getOutputCoords();\n setOutput(getX(${inCoords}));\n }\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 {GPGPUProgram} from './gpgpu_math';\nimport {getChannels} from './packing_util';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ReversePackedProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n packedInputs = true;\n packedOutput = true;\n\n constructor(xShape: number[], axis: number[]) {\n const rank = xShape.length;\n if (rank > 4) {\n throw new Error(\n `WebGL backend: Reverse of rank-${rank} tensor is not yet supported`);\n }\n this.outputShape = xShape;\n const channels = getChannels('rc', rank);\n const nextColumn =\n `${channels[rank - 1]} + 1 < ${this.outputShape[rank - 1]}`;\n const nextRow = `${channels[rank - 2]} + 1 < ${this.outputShape[rank - 2]}`;\n const type = getCoordsDataType(rank);\n if (rank === 1) {\n this.userCode = `\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${xShape[0]} - rc - 1),\n ${xShape[0]} - rc - 1);\n if(${nextColumn}){\n result.g = getChannel(getX(${xShape[0]} - (rc + 1) - 1),\n ${xShape[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `;\n } else {\n this.userCode = `\n void main() {\n ${type} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${getR(channels.slice())};\n if(${nextColumn}){\n result.g = ${getG(channels.slice())};\n }\n if(${nextRow}) {\n result.b = ${getB(channels.slice())};\n if(${nextColumn}) {\n result.a = ${getA(channels.slice())};\n }\n }\n setOutput(result);\n }\n `;\n }\n\n function getR(channels: string[]): string {\n return getChannel(channels);\n }\n\n function getG(channels: string[]): string {\n channels[rank - 1] = '(' + channels[rank - 1] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getB(channels: string[]): string {\n channels[rank - 2] = '(' + channels[rank - 2] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getA(channels: string[]): string {\n channels[rank - 1] = '(' + channels[rank - 1] + ` + 1)`;\n channels[rank - 2] = '(' + channels[rank - 2] + ` + 1)`;\n return getChannel(channels);\n }\n\n function getChannel(channels: string[]): string {\n const inCoordsArray = xShape.map((_, i) => getInCoord(i, channels));\n const inCoords = inCoordsArray.join(',');\n const innerDims = inCoordsArray.slice(-2).join(',');\n return `getChannel(getX(${inCoords}), vec2(${innerDims}))`;\n }\n\n function getInCoord(i: number, channels1: string[]): string {\n if (axis.indexOf(i) !== -1 && xShape[i] !== 1) {\n return `${xShape[i]} - ${channels1[i]} - 1`;\n } else {\n return `${channels1[i]}`;\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 */\n\nimport {env, KernelConfig, KernelFunc, Reverse, ReverseAttrs, ReverseInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ReverseProgram} from '../reverse_gpu';\nimport {ReversePackedProgram} from '../reverse_packed_gpu';\n\nimport {identity} from './Identity';\n\nexport function reverse(args: {\n inputs: ReverseInputs,\n backend: MathBackendWebGL,\n attrs: ReverseAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {dims} = attrs;\n\n const xRank = x.shape.length;\n\n const $dims = util.parseAxisParam(dims, x.shape);\n if (xRank === 0) {\n return identity({inputs: {x}, backend});\n }\n\n const program = env().getBool('WEBGL_PACK_ARRAY_OPERATIONS') ?\n new ReversePackedProgram(x.shape, $dims) :\n new ReverseProgram(x.shape, $dims);\n\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const reverseConfig: KernelConfig = {\n kernelName: Reverse,\n backendName: 'webgl',\n kernelFunc: reverse as {} 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 {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\nexport class RotateProgram implements GPGPUProgram {\n variableNames = ['Image'];\n outputShape: number[] = [];\n userCode: string;\n customUniforms = [{name: 'params', type: 'vec4' as UniformType}];\n constructor(\n imageShape: [number, number, number, number],\n fillValue: number|[number, number, number]) {\n const imageHeight = imageShape[1];\n const imageWidth = imageShape[2];\n this.outputShape = imageShape;\n\n let fillSnippet = '';\n if (typeof fillValue === 'number') {\n fillSnippet = `float outputValue = ${fillValue.toFixed(2)};`;\n } else {\n fillSnippet = `\n vec3 fill = vec3(${fillValue.join(',')});\n float outputValue = fill[coords[3]];`;\n }\n\n this.userCode = `\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n float coordXFloat = (float(x) - params[0]) * params[3] -\n (float(y) - params[1]) * params[2];\n float coordYFloat = (float(x) - params[0]) * params[2] +\n (float(y) - params[1]) * params[3];\n int coordX = int(round(coordXFloat + params[0]));\n int coordY = int(round(coordYFloat + params[1]));\n ${fillSnippet}\n if(coordX >= 0 && coordX < ${imageWidth} && coordY >= 0 && coordY < ${\n imageHeight}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n setOutput(outputValue);\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 */\n\nimport {backend_util, KernelConfig, Tensor4D} from '@tensorflow/tfjs-core';\nimport {RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {RotateProgram} from '../rotate_gpu';\n\nexport const rotateWithOffsetConfig: KernelConfig = {\n kernelName: RotateWithOffset,\n backendName: 'webgl',\n kernelFunc: ({inputs, attrs, backend}) => {\n const {image} = inputs as RotateWithOffsetInputs;\n const {radians, fillValue, center} = attrs as {} as RotateWithOffsetAttrs;\n const webglBackend = backend as MathBackendWebGL;\n\n const program = new RotateProgram((image as Tensor4D).shape, fillValue);\n const [centerX, centerY] =\n backend_util.getImageCenter(center, image.shape[1], image.shape[2]);\n const customValues =\n [[centerX, centerY, Math.sin(radians), Math.cos(radians)]];\n const output = webglBackend.runWebGLProgram(\n program, [image], image.dtype, customValues);\n return output;\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 {KernelConfig, Round} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst ROUND = `\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n`;\n\nexport const round = unaryKernelFunc({opSnippet: ROUND});\n\nexport const roundConfig: KernelConfig = {\n kernelName: Round,\n backendName: 'webgl',\n kernelFunc: round,\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, Rsqrt} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\nimport {rsqrtImplCPU} from '../kernel_utils/shared';\n\nconst RSQRT = `return inversesqrt(x);`;\n\nexport const rsqrt =\n unaryKernelFunc({opSnippet: RSQRT, cpuKernelImpl: rsqrtImplCPU});\n\nexport const rsqrtConfig: KernelConfig = {\n kernelName: Rsqrt,\n backendName: 'webgl',\n kernelFunc: rsqrt as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class ScatterProgram implements GPGPUProgram {\n variableNames = ['updates', 'indices', 'defaultValue'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n updateSize: number, sliceDim: number, indicesRank: number,\n updatesRank: number, strides: number[], shape: number[],\n summingDupeIndex = true) {\n this.outputShape = shape;\n const stridesType = getCoordsDataType(strides.length);\n const dtype = getCoordsDataType(shape.length);\n let indicesString = '';\n if (indicesRank === 1) {\n indicesString = 'i';\n } else if (indicesRank === 2) {\n indicesString = 'i, j';\n }\n const indicesSnippet = `getIndices(${indicesString})`;\n\n let updatesString = '';\n if (updatesRank === 1) {\n updatesString = 'i';\n } else if (updatesRank === 2) {\n updatesString = 'i, coords[1]';\n }\n const updatesSnippet = `getUpdates(${updatesString})`;\n\n const strideString = sliceDim > 1 ? 'strides[j]' : 'strides';\n this.userCode = `\n ${stridesType} strides = ${stridesType}(${strides});\n\n void main() {\n ${dtype} coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < ${updateSize}; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < ${sliceDim}; j++) {\n int index = round(${indicesSnippet});\n flattenedIndex += index * ${strideString};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${updatesSnippet};\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\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 */\n\nimport {backend_util, KernelConfig, KernelFunc, ScatterNd, ScatterNdAttrs, ScatterNdInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ScatterProgram} from '../scatter_gpu';\nimport {reshape} from './Reshape';\n\nexport function scatterNd(args: {\n inputs: ScatterNdInputs,\n backend: MathBackendWebGL,\n attrs: ScatterNdAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {indices, updates} = inputs;\n const {shape} = attrs;\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n backend_util.calculateShapes(updates, indices, shape);\n\n const flattenShape = [outputSize / sliceSize, sliceSize];\n\n if (outputSize === 0) {\n return backend.makeTensorInfo(shape, indices.dtype);\n }\n\n const flattenIndices = reshape(\n {inputs: {x: indices}, backend, attrs: {shape: [numUpdates, sliceRank]}});\n const flattenX = reshape(\n {inputs: {x: updates}, backend, attrs: {shape: [numUpdates, sliceSize]}});\n\n const defaultValue = backend.makeTensorInfo(\n [], 'float32', new Float32Array([0])); // scalar(0)\n const program = new ScatterProgram(\n numUpdates, sliceRank, flattenIndices.shape.length, flattenX.shape.length,\n strides, flattenShape);\n const res = backend.runWebGLProgram(\n program, [flattenX, flattenIndices, defaultValue], flattenX.dtype);\n\n const reshaped = reshape({inputs: {x: res}, backend, attrs: {shape}});\n\n backend.disposeIntermediateTensorInfo(flattenIndices);\n backend.disposeIntermediateTensorInfo(flattenX);\n backend.disposeIntermediateTensorInfo(res);\n backend.disposeIntermediateTensorInfo(defaultValue);\n\n return reshaped;\n}\n\nexport const scatterNdConfig: KernelConfig = {\n kernelName: ScatterNd,\n backendName: 'webgl',\n kernelFunc: scatterNd as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class SelectProgram implements GPGPUProgram {\n variableNames = ['c', 'a', 'b'];\n outputShape: number[];\n userCode: string;\n\n constructor(cRank: number, shape: number[], rank: number) {\n this.outputShape = shape;\n\n let cCoords;\n let abCoords;\n if (rank > 4) {\n throw Error(`Where for rank ${rank} is not yet supported`);\n }\n\n if (rank === 1) {\n abCoords = `resRC`;\n cCoords = `resRC`;\n } else {\n const currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w'];\n const cCoordVars = [];\n const abCoordVars = [];\n for (let i = 0; i < shape.length; i++) {\n abCoordVars.push(`${currentCoords[i]}`);\n if (i < cRank) {\n cCoordVars.push(`${currentCoords[i]}`);\n }\n }\n cCoords = cCoordVars.join();\n abCoords = abCoordVars.join();\n }\n\n const dtype = getCoordsDataType(rank);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n float cVal = getC(${cCoords});\n if (cVal >= 1.0) {\n setOutput(getA(${abCoords}));\n } else {\n setOutput(getB(${abCoords}));\n }\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 */\n\nimport {KernelConfig, KernelFunc, Select, SelectInputs, TensorInfo, upcastType} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {SelectProgram} from '../select_gpu';\n\nexport function select(args: {inputs: SelectInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {condition, t, e} = inputs;\n\n const program =\n new SelectProgram(condition.shape.length, t.shape, t.shape.length);\n return backend.runWebGLProgram(\n program, [condition, t, e], upcastType(t.dtype, e.dtype));\n}\n\nexport const selectConfig: KernelConfig = {\n kernelName: Select,\n backendName: 'webgl',\n kernelFunc: select as {} 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, Selu} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SELU = `\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = ${backend_util.SELU_SCALEALPHA};\n float scale = ${backend_util.SELU_SCALE};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`;\n\nexport const selu = unaryKernelFunc({opSnippet: SELU});\n\nexport const seluConfig: KernelConfig = {\n kernelName: Selu,\n backendName: 'webgl',\n kernelFunc: selu,\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, Sigmoid} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * x));`;\n\nexport const sigmoid = unaryKernelFunc({opSnippet: SIGMOID});\n\nexport const sigmoidConfig: KernelConfig = {\n kernelName: Sigmoid,\n backendName: 'webgl',\n kernelFunc: sigmoid,\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, Sign} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\n// Sign does not propagate NANs.\nconst SIGN = `\n if (isnan(x)) { return 0.0; }\n return sign(x);\n`;\n\nexport const sign = unaryKernelFunc({opSnippet: SIGN});\n\nexport const signConfig: KernelConfig = {\n kernelName: Sign,\n backendName: 'webgl',\n kernelFunc: sign,\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, Sin} from '@tensorflow/tfjs-core';\n\nimport {CHECK_NAN_SNIPPET_UNARY, unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SIN = CHECK_NAN_SNIPPET_UNARY + `\n return sin(x);\n`;\n\nexport const sin = unaryKernelFunc({opSnippet: SIN});\n\nexport const sinConfig: KernelConfig = {\n kernelName: Sin,\n backendName: 'webgl',\n kernelFunc: sin,\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, Sinh} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SINH = `\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n`;\n\nexport const sinh = unaryKernelFunc({opSnippet: SINH});\n\nexport const sinhConfig: KernelConfig = {\n kernelName: Sinh,\n backendName: 'webgl',\n kernelFunc: sinh,\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, Softplus} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SOFTPLUS = `\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n`;\n\nexport const softplus = unaryKernelFunc({opSnippet: SOFTPLUS});\n\nexport const softplusConfig: KernelConfig = {\n kernelName: Softplus,\n backendName: 'webgl',\n kernelFunc: softplus,\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, SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {padV2} from './PadV2';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nexport const spaceToBatchND = (args: {\n inputs: SpaceToBatchNDInputs,\n backend: MathBackendWebGL,\n attrs: SpaceToBatchNDAttrs\n}): TensorInfo => {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, paddings} = attrs;\n\n util.assert(\n x.shape.length <= 4,\n () => 'spaceToBatchND for rank > 4 with a WebGL backend not ' +\n 'implemented yet');\n\n const prod = blockShape.reduce((a, b) => a * b);\n\n const completePaddings: Array<[number, number]> = [[0, 0]];\n completePaddings.push(...paddings as Array<[number, number]>);\n for (let i = 1 + blockShape.length; i < x.shape.length; ++i) {\n completePaddings.push([0, 0]);\n }\n\n const toDispose = [];\n\n const paddedX = padV2({\n inputs: {x},\n backend,\n attrs: {paddings: completePaddings, constantValue: 0}\n });\n\n const reshapedPaddedShape =\n backend_util.getReshaped(paddedX.shape, blockShape, prod, false);\n\n const permutedReshapedPaddedPermutation = backend_util.getPermuted(\n reshapedPaddedShape.length, blockShape.length, false);\n\n const flattenShape =\n backend_util.getReshapedPermuted(paddedX.shape, blockShape, prod, false);\n\n const reshapedPaddedX = reshape(\n {inputs: {x: paddedX}, backend, attrs: {shape: reshapedPaddedShape}});\n\n const paddedXT = transpose({\n inputs: {x: reshapedPaddedX},\n backend,\n attrs: {perm: permutedReshapedPaddedPermutation}\n });\n\n const result =\n reshape({inputs: {x: paddedXT}, backend, attrs: {shape: flattenShape}});\n\n toDispose.push(paddedX);\n toDispose.push(reshapedPaddedX);\n toDispose.push(paddedXT);\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n\n return result;\n};\n\nexport const spaceToBatchNDConfig: KernelConfig = {\n kernelName: SpaceToBatchND,\n backendName: 'webgl',\n kernelFunc: spaceToBatchND as {} as KernelFunc\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 {KernelConfig, KernelFunc, SparseFillEmptyRows, SparseFillEmptyRowsInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseFillEmptyRowsImplCPU} from '../kernel_utils/shared';\n\nexport function sparseFillEmptyRows(args: {\n inputs: SparseFillEmptyRowsInputs,\n backend: MathBackendWebGL\n}): [TensorInfo, TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {indices, values, denseShape, defaultValue} = inputs;\n if (denseShape.shape.length !== 1) {\n throw new Error(`Dense shape must be a vector, saw:\n ${denseShape.shape}`);\n }\n if (indices.shape.length !== 2) {\n throw new Error(`Indices must be a matrix, saw:\n ${indices.shape}`);\n }\n if (values.shape.length !== 1) {\n throw new Error(`Values must be a vector, saw:\n ${values.shape}`);\n }\n if (defaultValue.shape.length !== 0) {\n throw new Error(`Default value must be a scalar, saw:\n ${defaultValue.shape}`);\n }\n\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n const $values = backend.readSync(values.dataId) as TypedArray;\n const $denseShape = backend.readSync(denseShape.dataId) as TypedArray;\n const $defaultValue =\n backend.readSync(defaultValue.dataId)[0] as number;\n\n const [outputIndices, outputIndicesShape, outputValues,\n emptyRowIndicator, reverseIndexMap] =\n sparseFillEmptyRowsImplCPU(\n $indices, indices.shape, indices.dtype, $values, values.dtype,\n $denseShape, $defaultValue);\n return [\n backend.makeTensorInfo(outputIndicesShape, indices.dtype, outputIndices),\n backend.makeTensorInfo(\n [outputIndicesShape[0]], values.dtype, outputValues),\n backend.makeTensorInfo(\n [emptyRowIndicator.length], 'bool',\n new Uint8Array(\n emptyRowIndicator.map((value: boolean) => Number(value)))),\n backend.makeTensorInfo(\n [reverseIndexMap.length], indices.dtype,\n new Int32Array(reverseIndexMap)),\n ];\n}\n\nexport const sparseFillEmptyRowsConfig: KernelConfig = {\n kernelName: SparseFillEmptyRows,\n backendName: 'webgl',\n kernelFunc: sparseFillEmptyRows as {} as KernelFunc,\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 {KernelConfig, SparseReshape, SparseReshapeInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseReshapeImplCPU} from '../kernel_utils/shared';\n\nexport function sparseReshape(\n args: {inputs: SparseReshapeInputs, backend: MathBackendWebGL}):\n [TensorInfo, TensorInfo] {\n const {inputs, backend} = args;\n const {inputIndices, inputShape, newShape} = inputs;\n if (inputIndices.shape.length !== 2) {\n throw new Error(`Input indices should be a matrix but received shape ${\n inputIndices.shape}`);\n }\n if (inputShape.shape.length !== 1) {\n throw new Error(`Input shape should be a vector but received shape ${\n inputShape.shape}`);\n }\n\n if (newShape.shape.length !== 1) {\n throw new Error(\n `Target shape should be a vector but received shape ${newShape.shape}`);\n }\n\n const $inputShape =\n Array.from(backend.readSync(inputShape.dataId) as TypedArray);\n const $inputIndices = backend.readSync(inputIndices.dataId) as TypedArray;\n const targetShape =\n Array.from(backend.readSync(newShape.dataId) as TypedArray);\n\n const [newIndices, indicesShape, outputShape] = sparseReshapeImplCPU(\n $inputIndices, inputIndices.shape, inputIndices.dtype, $inputShape,\n targetShape);\n return [\n backend.makeTensorInfo(indicesShape, inputIndices.dtype, newIndices),\n backend.makeTensorInfo(\n [outputShape.length], newShape.dtype, new Int32Array(outputShape)),\n ];\n}\n\nexport const sparseReshapeConfig: KernelConfig = {\n kernelName: SparseReshape,\n backendName: 'webgl',\n kernelFunc: sparseReshape,\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 {KernelConfig, KernelFunc, SparseSegmentMean, SparseSegmentMeanInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseSegmentReductionImplCPU} from '../kernel_utils/shared';\n\nexport function sparseSegmentMean(\n args: {inputs: SparseSegmentMeanInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n\n const $data = backend.readSync(data.dataId) as TypedArray;\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n const $segmentIds = backend.readSync(segmentIds.dataId) as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImplCPU(\n $data, data.shape, data.dtype, $indices, $segmentIds, true);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentMeanConfig: KernelConfig = {\n kernelName: SparseSegmentMean,\n backendName: 'webgl',\n kernelFunc: sparseSegmentMean as {} as KernelFunc,\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 {KernelConfig, KernelFunc, SparseSegmentSum, SparseSegmentSumInputs, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {sparseSegmentReductionImplCPU} from '../kernel_utils/shared';\n\nexport function sparseSegmentSum(\n args: {inputs: SparseSegmentSumInputs, backend: MathBackendWebGL}):\n TensorInfo {\n const {inputs, backend} = args;\n const {data, indices, segmentIds} = inputs;\n if (data.shape.length < 1) {\n throw new Error(\n `Data should be at least 1 dimensional but received scalar`);\n }\n if (indices.shape.length !== 1) {\n throw new Error(`Indices should be a vector but received shape\n ${indices.shape}`);\n }\n if (segmentIds.shape.length !== 1) {\n throw new Error(`Segment ids should be a vector but received shape\n ${segmentIds.shape}`);\n }\n\n const $data = backend.readSync(data.dataId) as TypedArray;\n const $indices = backend.readSync(indices.dataId) as TypedArray;\n const $segmentIds = backend.readSync(segmentIds.dataId) as TypedArray;\n\n const [outputData, outputDataShape] = sparseSegmentReductionImplCPU(\n $data, data.shape, data.dtype, $indices, $segmentIds);\n return backend.makeTensorInfo(outputDataShape, data.dtype, outputData);\n}\n\nexport const sparseSegmentSumConfig: KernelConfig = {\n kernelName: SparseSegmentSum,\n backendName: 'webgl',\n kernelFunc: sparseSegmentSum as {} 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, SparseToDense, SparseToDenseAttrs, SparseToDenseInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {ScatterProgram} from '../scatter_gpu';\nimport {reshape} from './Reshape';\n\nexport function sparseToDense(args: {\n inputs: SparseToDenseInputs,\n backend: MathBackendWebGL,\n attrs: SparseToDenseAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {sparseIndices, sparseValues, defaultValue} = inputs;\n const {outputShape} = attrs;\n\n const {sliceRank, numUpdates, strides, outputSize} =\n backend_util.calculateShapes(sparseValues, sparseIndices, outputShape);\n\n const sumDupeIndices = false;\n const program = new ScatterProgram(\n numUpdates, sliceRank, sparseIndices.shape.length,\n sparseValues.shape.length, strides, [outputSize, 1], sumDupeIndices);\n\n const res = backend.runWebGLProgram(\n program, [sparseValues, sparseIndices, defaultValue], sparseValues.dtype);\n\n const reshaped =\n reshape({inputs: {x: res}, backend, attrs: {shape: outputShape}});\n\n backend.disposeIntermediateTensorInfo(res);\n return reshaped;\n}\n\nexport const sparseToDenseConfig: KernelConfig = {\n kernelName: SparseToDense,\n backendName: 'webgl',\n kernelFunc: sparseToDense as {} 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, SplitV, SplitVAttrs, SplitVInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {slice} from './Slice';\n\nexport function splitV(\n args:\n {inputs: SplitVInputs, backend: MathBackendWebGL, attrs: SplitVAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {numOrSizeSplits, axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, x.shape)[0];\n const splitSizes = backend_util.prepareSplitSize(x, numOrSizeSplits, $axis);\n\n const xRank = x.shape.length;\n const begin = new Array(xRank).fill(0);\n const size = x.shape.slice();\n\n return splitSizes.map(s => {\n const sliceSize = [...size];\n sliceSize[$axis] = s;\n const sliceT =\n slice({inputs: {x}, backend, attrs: {begin, size: sliceSize}});\n begin[$axis] += s;\n return sliceT;\n });\n}\n\nexport const splitVConfig: KernelConfig = {\n kernelName: SplitV,\n backendName: 'webgl',\n kernelFunc: splitV as {} 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, Sqrt} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SQRT = `return sqrt(x);`;\n\nexport const sqrt = unaryKernelFunc({opSnippet: SQRT});\n\nexport const sqrtConfig: KernelConfig = {\n kernelName: Sqrt,\n backendName: 'webgl',\n kernelFunc: sqrt as {} 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 {KernelConfig, Square} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SQUARE = `return x * x;`;\n\nexport const square = unaryKernelFunc({opSnippet: SQUARE});\n\nexport const squareConfig: KernelConfig = {\n kernelName: Square,\n backendName: 'webgl',\n kernelFunc: square,\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 {binaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst SQUARED_DIFFERENCE = 'return (a - b) * (a - b);';\n\nexport const squaredDifference = binaryKernelFunc(\n {opSnippet: SQUARED_DIFFERENCE, packedOpSnippet: SQUARED_DIFFERENCE});\n\nexport const squaredDifferenceConfig: KernelConfig = {\n kernelName: SquaredDifference,\n backendName: 'webgl',\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 {KernelConfig, KernelFunc, Step, StepAttrs, TensorInfo, UnaryInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {CHECK_NAN_SNIPPET, UnaryOpProgram} from '../unaryop_gpu';\n\nexport function step(\n {inputs, attrs, backend}:\n {inputs: UnaryInputs, attrs: StepAttrs, backend: MathBackendWebGL}):\n TensorInfo {\n const {x} = inputs;\n const opSnippet = CHECK_NAN_SNIPPET + `\n return x > 0.0 ? 1.0 : float(${attrs.alpha});\n `;\n\n const program = new UnaryOpProgram(x.shape, opSnippet);\n\n return backend.runWebGLProgram(program, [x], x.dtype);\n}\n\nexport const stepConfig: KernelConfig = {\n kernelName: Step,\n backendName: 'webgl',\n kernelFunc: step as {} as KernelFunc,\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class StridedSliceProgram implements GPGPUProgram {\n variableNames = ['x'];\n outputShape: number[];\n userCode: string;\n\n constructor(begin: number[], strides: number[], size: number[]) {\n this.outputShape = size;\n const rank = size.length;\n const inputDtype = getCoordsDataType(size.length);\n const dtype = getCoordsDataType(size.length);\n\n let newCoords = '';\n if (rank === 1) {\n newCoords = 'coords * strides + begin';\n } else {\n let outputAxis = 0;\n newCoords =\n size.map((_, i) => {\n outputAxis++;\n return size.length === 1 ?\n `coords * strides[${i}] + begin[${i}]` :\n `coords[${outputAxis - 1}] * strides[${i}] + begin[${i}]`;\n })\n .join(',');\n }\n\n this.userCode = `\n ${inputDtype} begin = ${inputDtype}(${begin});\n ${inputDtype} strides = ${inputDtype}(${strides});\n\n void main() {\n ${dtype} coords = getOutputCoords();\n setOutput(getX(${newCoords}));\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 */\n\nimport {buffer, KernelConfig, KernelFunc, Rank, slice_util, StridedSlice, StridedSliceAttrs, StridedSliceInputs, TensorBuffer, TensorInfo, TypedArray} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stridedSliceImplCPU} from '../kernel_utils/shared';\nimport {StridedSliceProgram} from '../strided_slice_gpu';\n\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nexport function stridedSlice(args: {\n inputs: StridedSliceInputs,\n backend: MathBackendWebGL,\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 const {nonStrided, $begin, $strides, size, newShape, outShape} =\n slice_util.sliceInfo(\n x.shape, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask);\n\n const $x = reshape({inputs: {x}, backend, attrs: {shape: newShape}});\n\n let result;\n if (nonStrided) {\n const sliced =\n slice({inputs: {x: $x}, backend, attrs: {begin: $begin, size}});\n result = reshape({inputs: {x: sliced}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo(sliced);\n } else if (outShape.some(axis => axis === 0)) {\n result = backend.makeTensorInfo(outShape, x.dtype, []);\n } else {\n const shouldExecuteOnCPU = backend.shouldExecuteOnCPU([$x]);\n if (shouldExecuteOnCPU) {\n const xTexData = backend.texData.get($x.dataId);\n const values = xTexData.values as TypedArray;\n const xBuf = buffer($x.shape, $x.dtype, values) as TensorBuffer<Rank>;\n const resultValues =\n stridedSliceImplCPU(outShape, xBuf, $strides, $begin);\n result = backend.makeTensorInfo(outShape, $x.dtype, resultValues.values);\n } else {\n const program = new StridedSliceProgram($begin, $strides, outShape);\n result = backend.runWebGLProgram(program, [$x], $x.dtype);\n }\n }\n\n const resultReshaped =\n reshape({inputs: {x: result}, backend, attrs: {shape: outShape}});\n\n backend.disposeIntermediateTensorInfo($x);\n backend.disposeIntermediateTensorInfo(result);\n\n return resultReshaped;\n}\n\nexport const stridedSliceConfig: KernelConfig = {\n kernelName: StridedSlice,\n backendName: 'webgl',\n kernelFunc: stridedSlice as {} as KernelFunc\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 {KernelConfig, KernelFunc, StringNGrams, StringNGramsAttrs, StringNGramsInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringNGramsImplCPU} from '../kernel_utils/shared';\n\nexport function stringNGrams(args: {\n inputs: StringNGramsInputs,\n backend: MathBackendWebGL,\n attrs: StringNGramsAttrs\n}): [TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {\n separator,\n nGramWidths,\n leftPad,\n rightPad,\n padWidth,\n preserveShortSequences\n } = attrs;\n const {data, dataSplits} = inputs;\n const $data = backend.readSync(data.dataId) as Uint8Array[];\n const $dataSplits = backend.readSync(dataSplits.dataId) as Int32Array;\n\n const [nGrams, nGramsSplits] = stringNGramsImplCPU(\n $data, $dataSplits, separator, nGramWidths, leftPad, rightPad, padWidth,\n preserveShortSequences);\n return [\n backend.makeTensorInfo([nGrams.length], 'string', nGrams),\n backend.makeTensorInfo(dataSplits.shape, 'int32', nGramsSplits),\n ];\n}\n\nexport const stringNGramsConfig: KernelConfig = {\n kernelName: StringNGrams,\n backendName: 'webgl',\n kernelFunc: stringNGrams as {} as KernelFunc,\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 {KernelConfig, KernelFunc, StringSplit, StringSplitAttrs, StringSplitInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringSplitImplCPU} from '../kernel_utils/shared';\n\nexport function stringSplit(args: {\n inputs: StringSplitInputs,\n backend: MathBackendWebGL,\n attrs: StringSplitAttrs\n}): [TensorInfo, TensorInfo, TensorInfo] {\n const {inputs, backend, attrs} = args;\n const {skipEmpty} = attrs;\n const {input, delimiter} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (input.shape.length !== 1) {\n throw new Error(`Input must be a vector, got shape: ${input.shape}`);\n }\n if (delimiter.shape.length !== 0) {\n throw new Error(\n `Delimiter must be a scalar, got shape: ${delimiter.shape}`);\n }\n\n const $input = backend.readSync(input.dataId) as Uint8Array[];\n const $delimiter = backend.readSync(delimiter.dataId)[0] as Uint8Array;\n\n const [indices, values, shape] =\n stringSplitImplCPU($input, $delimiter, skipEmpty);\n const outputSize = values.length;\n return [\n backend.makeTensorInfo([outputSize, 2], 'int32', indices),\n backend.makeTensorInfo([outputSize], 'string', values),\n backend.makeTensorInfo([2], 'int32', new Int32Array(shape))\n ];\n}\n\nexport const stringSplitConfig: KernelConfig = {\n kernelName: StringSplit,\n backendName: 'webgl',\n kernelFunc: stringSplit as {} as KernelFunc,\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 {KernelConfig, KernelFunc, StringToHashBucketFast, StringToHashBucketFastAttrs, StringToHashBucketFastInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {stringToHashBucketFastImplCPU} from '../kernel_utils/shared';\n\nexport function stringToHashBucketFast(args: {\n inputs: StringToHashBucketFastInputs,\n backend: MathBackendWebGL,\n attrs: StringToHashBucketFastAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {numBuckets} = attrs;\n const {input} = inputs;\n\n if (input.dtype !== 'string') {\n throw new Error('Input must be of datatype string');\n }\n if (numBuckets <= 0) {\n throw new Error(`Number of buckets must be at least 1`);\n }\n\n const $input = backend.readSync(input.dataId) as Uint8Array[];\n\n const output = stringToHashBucketFastImplCPU($input, numBuckets);\n return backend.makeTensorInfo(input.shape, 'int32', output);\n}\n\nexport const stringToHashBucketFastConfig: KernelConfig = {\n kernelName: StringToHashBucketFast,\n backendName: 'webgl',\n kernelFunc: stringToHashBucketFast as {} 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, Tan} from '@tensorflow/tfjs-core';\n\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst TAN = `return tan(x);`;\n\nexport const tan = unaryKernelFunc({opSnippet: TAN});\n\nexport const tanConfig: KernelConfig = {\n kernelName: Tan,\n backendName: 'webgl',\n kernelFunc: tan,\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, Tanh} from '@tensorflow/tfjs-core';\nimport {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';\n\nconst TANH = `\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n`;\n\nexport const tanh = unaryKernelFunc({opSnippet: TANH});\n\nexport const tanhConfig: KernelConfig = {\n kernelName: Tanh,\n backendName: 'webgl',\n kernelFunc: tanh,\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 {GPGPUProgram} from './gpgpu_math';\nimport {getCoordsDataType} from './shader_compiler';\n\nexport class TileProgram implements GPGPUProgram {\n variableNames = ['A'];\n outputShape: number[];\n userCode: string;\n rank: number;\n\n constructor(aShape: number[], reps: number[]) {\n const outputShape: number[] = new Array(aShape.length);\n for (let i = 0; i < outputShape.length; i++) {\n outputShape[i] = aShape[i] * reps[i];\n }\n this.outputShape = outputShape;\n this.rank = outputShape.length;\n const dtype = getCoordsDataType(this.rank);\n const sourceCoords = getSourceCoords(aShape);\n\n this.userCode = `\n void main() {\n ${dtype} resRC = getOutputCoords();\n setOutput(getA(${sourceCoords}));\n }\n `;\n }\n}\n\nfunction getSourceCoords(aShape: number[]): string {\n const rank = aShape.length;\n if (rank > 5) {\n throw Error(`Tile for rank ${rank} is not yet supported`);\n }\n if (rank === 1) {\n return `imod(resRC, ${aShape[0]})`;\n }\n\n const currentCoords = ['resRC.x', 'resRC.y', 'resRC.z', 'resRC.w', 'resRC.u'];\n\n const sourceCoords = [];\n for (let i = 0; i < aShape.length; i++) {\n sourceCoords.push(`imod(${currentCoords[i]}, ${aShape[i]})`);\n }\n return sourceCoords.join();\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, KernelConfig, KernelFunc, TensorInfo, Tile, TileAttrs, TileInputs, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {tileImplCPU} from '../kernel_utils/shared';\nimport {TileProgram} from '../tile_gpu';\n\nexport function tile(\n params: {inputs: TileInputs, backend: MathBackendWebGL, attrs: TileAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = params;\n const {x} = inputs;\n const {reps} = attrs;\n\n // tile gpu program cannot handle rank > 5 case.\n if (x.dtype === 'string' || x.shape.length > 5) {\n // Even thought string tensor is always on CPU, just to be consistent on how\n // to access tensor data.\n const data = backend.readSync(x.dataId);\n const value = x.dtype === 'string' ?\n (data as Uint8Array[]).map(d => util.decodeString(d)) :\n data as TypedArray;\n const buf = buffer(x.shape, x.dtype, value);\n const outBuf = tileImplCPU(buf, reps);\n return backend.makeTensorInfo(outBuf.shape, outBuf.dtype, outBuf.values);\n }\n\n const program = new TileProgram(x.shape, reps);\n const output = backend.runWebGLProgram(program, [x], x.dtype);\n\n return output;\n}\n\nexport const tileConfig: KernelConfig = {\n kernelName: Tile,\n backendName: 'webgl',\n kernelFunc: tile as {} as KernelFunc,\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 {GPGPUProgram} from './gpgpu_math';\nimport {UniformType} from './shader_compiler';\n\n// Based on Algorithm 2 of Bitonic Top K, ref:\n// https://anilshanbhag.in/static/papers/gputopk_sigmod18.pdf\n// The original algorithm is based on computing the top K only, however\n// since for TFJS we require the indices of the top K values as well then the\n// algorithm found here is a bit modified. Rather than producing the values\n// at each step, the indices containing the top K are generated instead.\n// The output values are not generated to reduce the number of outputs in the\n// GPU, the values can easily be retrieved from the indices using a gather\n// op.\nexport class SwapProgram implements GPGPUProgram {\n variableNames = ['x', 'indices'];\n outputShape: number[];\n userCode: string;\n // |n| Size of the original input of TopK.\n // |firstPass|indicates if this is the first time swap is being used which\n // means no indices input containing the top K is present yet.\n // |inc| Swaps pairs of indices (0, inc), (1, inc + 1), (2, inc + 2) ...\n customUniforms = [\n {name: 'n', type: 'int' as UniformType},\n {name: 'firstPass', type: 'int' as UniformType},\n {name: 'negativeInf', type: 'float' as UniformType},\n {name: 'dir', type: 'int' as UniformType},\n {name: 'inc', type: 'int' as UniformType}\n ];\n\n /**\n * @param shape desired output shape (can be larger than input shape, output\n * will be padded with -Infinity)\n */\n constructor(shape: number[]) {\n this.outputShape = shape;\n\n this.userCode = `\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // We compare elements pair-wise within a group of size 2 * inc.\n // The comparing rule for each group alternates between ascending\n // and descending. Within each group, we compare each pair at\n // positions i and i+inc. To decide whether an element at position i\n // is x0 or x1, we mod it by 2 * inc, if the result is smaller than\n // inc, it is in the first half of the group, we denote it as x0,\n // otherwise we denote it as x1.\n // For example, as shown in the Bitonic top K paper referenced above,\n // Figure5(a) shows that element[1] is in the\n // second half of the group when group size is 2, but it is in the\n // first half of the group when group size is 4.\n\n bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;\n int i = isFirstInPair ? elemIdx : elemIdx - inc;\n\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));\n float x0 = i0 < n ? getX(batch, i0) : negativeInf;\n float x1 = i1 < n ? getX(batch, i1) : negativeInf;\n\n // Denotes which direction indices are in (ascending or descending).\n bool reverse = imod(elemIdx, 2 * dir) >= dir;\n bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\n if (reverse == isGreater) { // Elements in opposite order of direction\n int iTemp = i0;\n i0 = i1;\n i1 = iTemp;\n }\n if (isFirstInPair) {\n setOutput(float(i0));\n } else {\n setOutput(float(i1));\n }\n }\n `;\n }\n}\n\nexport class MergeProgram implements GPGPUProgram {\n variableNames = ['x', 'indices'];\n outputShape: number[];\n userCode: string;\n // |n| Size of the original input of TopK\n // |firstPass| indicates if this is the first time swap is being used which\n // means no indices input containing the top K is present yet.\n // |k| Top k elements desired\n customUniforms = [\n {name: 'n', type: 'int' as UniformType},\n {name: 'firstPass', type: 'int' as UniformType},\n {name: 'k', type: 'int' as UniformType}\n ];\n\n /**\n * @param shape desired output shape (must be half of the input size)\n */\n constructor(shape: number[]) {\n this.outputShape = shape;\n\n this.userCode = `\n void main() {\n // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int elemIdx = coords[1];\n\n // The output size is half of the previous size.\n // If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),\n // we only need to output the indices at positions |, the indices at\n // positions _ can be thrown away, see Figure5(b) After Phase 2\n // (Merge phase) in the Bitonic Top K paper referenced above.\n // For example, the paper shows we only need to output the orange bars.\n // The output sequence should look like this | | | | | | | |.\n // Because the sequence is halved, to map the output index back\n // to the previous sequence to find the corresponding value,\n // we need to double the index. When we double the index,\n // we basically interpolate a position, so 2i looks like\n // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position\n // of each 2k positions by - elemIdx % k. E.g. for output at\n // index 4,5,6,7, we want to get the corresponding element at\n // original index 8,9,10,11, for output at index 8,9,10,11,\n // we want to get the corresponding element at original index\n // 16,17,18,19, so on and so forth.\n\n int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));\n int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));\n\n float x0 = getX(batch, i0);\n float x1 = i1 < n ? getX(batch, i1) : x0;\n\n setOutput(x0 >= x1 ? float(i0) : float(i1));\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 */\n\nimport {env, KernelConfig, KernelFunc, NumericDataType, TensorInfo, TopK, TopKAttrs, TopKInputs, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {topKImplCPU} from '../kernel_utils/shared';\nimport {MergeProgram, SwapProgram} from '../top_k_gpu';\nimport {fill} from './Fill';\nimport {gatherV2} from './GatherV2';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nfunction disposeIntermediateTensorInfoOrNull(\n backend: MathBackendWebGL, tensorInfo: TensorInfo) {\n if (tensorInfo !== null) {\n backend.disposeIntermediateTensorInfo(tensorInfo);\n }\n}\n\nfunction roundUpToPow2(num: number) {\n let pow2 = 1;\n while (pow2 < num) {\n pow2 *= 2;\n }\n return pow2;\n}\n\n// Based on Algorithm 2 of Bitonic Top K, ref:\n// https://anilshanbhag.in/static/papers/gputopk_sigmod18.pdf\nexport function topK(\n args: {inputs: TopKInputs, backend: MathBackendWebGL, attrs: TopKAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {k, sorted} = attrs;\n\n // Empirically determined constant used to determine last dim threshold for\n // handing off execution to the CPU.\n const TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD =\n env().getNumber('TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD');\n\n // Empirically determined constant used to determine k threshold for handing\n // off execution to the CPU.\n const TOPK_K_CPU_HANDOFF_THRESHOLD =\n env().getNumber('TOPK_K_CPU_HANDOFF_THRESHOLD');\n\n const xShape = x.shape;\n const lastDim = xShape[xShape.length - 1];\n\n if (backend.shouldExecuteOnCPU([x]) ||\n lastDim < TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD ||\n k > TOPK_K_CPU_HANDOFF_THRESHOLD) {\n const xVals = backend.readSync(x.dataId) as TypedArray;\n const [allTopKVals, allTopKIndices] =\n topKImplCPU(xVals, xShape, x.dtype as NumericDataType, k, sorted);\n\n return [\n backend.makeTensorInfo(\n allTopKVals.shape, allTopKVals.dtype, allTopKVals.values),\n backend.makeTensorInfo(\n allTopKIndices.shape, allTopKIndices.dtype, allTopKIndices.values)\n ];\n }\n\n if (k === 0) {\n xShape[xShape.length - 1] = 0;\n return [\n backend.makeTensorInfo(xShape, x.dtype, []),\n backend.makeTensorInfo(xShape, 'int32', [])\n ];\n }\n\n if (lastDim === 1 /* firstPass */) {\n return [\n x, fill({attrs: {shape: xShape, dtype: 'int32', value: 0}, backend})\n ];\n }\n\n // Eagerly unpack x input since it is passed in to all the shaders which\n // require unpacked inputs.\n const xtexData = backend.texData.get(x.dataId);\n const xIsPacked = xtexData !== null && xtexData.isPacked;\n const xUnPacked = xIsPacked ? backend.unpackTensor(x) : x;\n\n // Reshape into a 2d tensor [batch, lastDim] and compute topk along lastDim.\n const xSize = util.sizeFromShape(xShape);\n const batch = xSize / lastDim;\n const x2D = reshape(\n {inputs: {x: xUnPacked}, attrs: {shape: [batch, lastDim]}, backend});\n\n if (xIsPacked) {\n disposeIntermediateTensorInfoOrNull(backend, xUnPacked);\n }\n\n const kPow2 = roundUpToPow2(k);\n const lastDimPow2 = roundUpToPow2(lastDim);\n\n // Only the indices containing the top K are kept at every step to reduce\n // number of outputs in the GPU algorithms, so once the final set of indices\n // is computed then gather is used to grab the corresponding values\n // from the original input.\n let indices: TensorInfo = null;\n\n // GPU algorithm always takes in an indices input but this input is not used\n // on the first run of a GPU algorithm, therefore if indices is null we simply\n // pass in x2D instead of it but the value will not actually be used\n const getInputs = () => indices === null ? [x2D, x2D] : [x2D, indices];\n\n const runSwap = (dir: number, inc: number, shape: number[]) => {\n const inputs = getInputs();\n const program = new SwapProgram(shape);\n const fistPass = indices === null ? 1 : 0;\n const customValues =\n [[lastDim], [fistPass], [Number.NEGATIVE_INFINITY], [dir], [inc]];\n const prevIndices = indices;\n indices = backend.runWebGLProgram(program, inputs, 'int32', customValues);\n disposeIntermediateTensorInfoOrNull(backend, prevIndices);\n };\n\n // Step 1: local sort\n for (let len = 1; len < kPow2; len *= 2) {\n const dir = len * 2;\n for (let inc = len; inc >= 1; inc /= 2) {\n runSwap(dir, inc, [batch, lastDimPow2]);\n }\n }\n\n // Step 2: merge\n for (let indicesSize = lastDimPow2; indicesSize > kPow2; indicesSize /= 2) {\n const inputs = getInputs();\n const mergeProgram = new MergeProgram([batch, indicesSize / 2]);\n const firstPass = indices === null ? 1 : 0;\n const customValues = [[lastDim], [firstPass], [kPow2]];\n const prevIndices = indices;\n indices =\n backend.runWebGLProgram(mergeProgram, inputs, 'int32', customValues);\n disposeIntermediateTensorInfoOrNull(backend, prevIndices);\n\n // Step 3: rebuild\n const len = kPow2 / 2;\n const dir = len * 2;\n for (let inc = len; inc >= 1; inc /= 2) {\n runSwap(dir, inc, indices.shape);\n }\n }\n\n // Keep only the requested top K results instead of kPow2\n let prevIndices = indices;\n indices = slice(\n {inputs: {x: indices}, backend, attrs: {begin: 0, size: [batch, k]}});\n disposeIntermediateTensorInfoOrNull(backend, prevIndices);\n\n // Gather values on last dimension\n let values = gatherV2(\n {inputs: {x: x2D, indices}, backend, attrs: {axis: 1, batchDims: 1}});\n disposeIntermediateTensorInfoOrNull(backend, x2D);\n\n // Reshape back to the original input shape, except that the last\n // dimension is k.\n const newShape = xShape.slice(0, -1);\n newShape.push(k);\n\n prevIndices = indices;\n indices = reshape({inputs: {x: indices}, attrs: {shape: newShape}, backend});\n disposeIntermediateTensorInfoOrNull(backend, prevIndices);\n\n const prevValues = values;\n values = reshape({inputs: {x: values}, attrs: {shape: newShape}, backend});\n disposeIntermediateTensorInfoOrNull(backend, prevValues);\n\n return [values, indices];\n}\n\nexport const topKConfig: KernelConfig = {\n kernelName: TopK,\n backendName: 'webgl',\n kernelFunc: topK as {} as KernelFunc\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 {GPGPUProgram} from './gpgpu_math';\n\nexport class TransformProgram implements GPGPUProgram {\n variableNames = ['Image', 'Transforms'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n imageHeight: number, imageWidth: number,\n interpolation: 'nearest'|'bilinear',\n fillMode: 'constant'|'reflect'|'wrap'|'nearest', fillValue: number,\n outShape: [number, number, number, number]) {\n this.outputShape = outShape;\n const interpolationModeId = interpolation === 'nearest' ? 1 : 2;\n let fillModeId;\n switch (fillMode) {\n case 'constant':\n fillModeId = 1;\n break;\n case 'reflect':\n fillModeId = 2;\n break;\n case 'wrap':\n fillModeId = 3;\n break;\n case 'nearest':\n fillModeId = 4;\n break;\n default:\n fillModeId = 1;\n break;\n }\n this.userCode = `\n float mapCoord(float outCoord, float len) {\n float inCoord = outCoord;\n if(${fillModeId} == 2) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n if (inCoord < sz2) {\n inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n inCoord;\n }\n inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz2 = 2.0 * len;\n inCoord -= sz2 * float(int(float(inCoord / sz2)));\n if (inCoord >= len) {\n inCoord = sz2 - inCoord - 1.0;\n }\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${fillModeId} == 3) {\n if (inCoord < 0.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n }\n } else if (inCoord > len - 1.0) {\n if (len <= 1.0) {\n inCoord = 0.0;\n } else {\n float sz = len - 1.0;\n inCoord -= len * float(int(float(inCoord / sz)));\n }\n }\n return clamp(inCoord, 0.0, len - 1.0);\n } else if (${fillModeId} == 4) {\n return clamp(outCoord, 0.0, len - 1.0);\n } else {\n return outCoord;\n }\n }\n\n float readWithFillValue(int batch, int coordY, int coordX,\n int channel) {\n float outputValue;\n if (0 <= coordY && coordY < ${\n imageHeight} && 0 <= coordX && coordX < ${imageWidth}) {\n outputValue = getImage(batch, coordY, coordX, channel);\n } else {\n outputValue = float(${fillValue});\n }\n return outputValue;\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n float outputValue;\n int batch = coords[0];\n int x = coords[2];\n int y = coords[1];\n int channel = coords[3];\n float xf = float(x);\n float yf = float(y);\n float a1 = getTransforms(batch, 0);\n float a2 = getTransforms(batch, 1);\n float a3 = getTransforms(batch, 2);\n float b1 = getTransforms(batch, 3);\n float b2 = getTransforms(batch, 4);\n float b3 = getTransforms(batch, 5);\n float c1 = getTransforms(batch, 6);\n float c2 = getTransforms(batch, 7);\n float projection = c1 * xf + c2 * yf + 1.0;\n if (projection == 0.0) {\n outputValue = float(${fillValue});\n } else {\n float inX = (a1 * xf + a2 * yf + a3) / projection;\n float inY = (b1 * xf + b2 * yf + b3) / projection;\n float mapX = mapCoord(inX, float(${imageWidth}));\n float mapY = mapCoord(inY, float(${imageHeight}));\n\n if (${interpolationModeId} == 1) {\n int coordY = int(round(mapY));\n int coordX = int(round(mapX));\n outputValue = readWithFillValue(batch, coordY, coordX,\n channel);\n } else {\n float yFloor = floor(mapY);\n float xFloor = floor(mapX);\n float yCeil = yFloor + 1.0;\n float xCeil = xFloor + 1.0;\n float valueYFloor = (xCeil - mapX) *\n readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n float valueYCeil = (xCeil - mapX) *\n readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n (mapX - xFloor) *\n readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n outputValue = (yCeil - mapY) * valueYFloor +\n (mapY - yFloor) * valueYCeil;\n }\n }\n setOutput(outputValue);\n }\n `;\n }\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 {KernelConfig, KernelFunc, TensorInfo, Transform, TransformAttrs, TransformInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {TransformProgram} from '../transform_gpu';\n\nexport function transform(args: {\n inputs: TransformInputs,\n backend: MathBackendWebGL,\n attrs: TransformAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {image, transforms} = inputs;\n const {interpolation, fillMode, fillValue, outputShape} = attrs;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n const [outHeight, outWidth] =\n outputShape != null ? outputShape : [imageHeight, imageWidth];\n const outShape =\n [batch, outHeight, outWidth,\n numChannels] as [number, number, number, number];\n\n const program = new TransformProgram(\n imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape);\n return backend.runWebGLProgram(program, [image, transforms], 'float32');\n}\n\nexport const transformConfig: KernelConfig = {\n kernelName: Transform,\n backendName: 'webgl',\n kernelFunc: transform as {} 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, Unique, UniqueAttrs, UniqueInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {uniqueImplCPU} from '../kernel_utils/shared';\nimport {assertNotComplex} from '../webgl_util';\n\nexport function unique(\n args:\n {inputs: UniqueInputs, attrs: UniqueAttrs, backend: MathBackendWebGL}):\n TensorInfo[] {\n const {inputs, attrs, backend} = args;\n const {axis} = attrs;\n const {x} = inputs;\n assertNotComplex(x, 'unique');\n\n // For now, always forward calculation to the CPU backend.\n console.warn(\n 'WARNING: ',\n 'UI might be locked temporarily as data is being downloaded');\n const values = backend.readSync(x.dataId);\n const {outputValues, outputShape, indices} =\n uniqueImplCPU(values, axis, x.shape, x.dtype);\n return [\n backend.makeTensorInfo(outputShape, x.dtype, outputValues),\n backend.makeTensorInfo([indices.length], 'int32', indices),\n ];\n}\n\nexport const uniqueConfig: KernelConfig = {\n kernelName: Unique,\n backendName: 'webgl',\n kernelFunc: unique as {} 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, Unpack, UnpackAttrs, UnpackInputs} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\n\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nexport function unpack(\n args:\n {inputs: UnpackInputs, backend: MathBackendWebGL, attrs: UnpackAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {value} = inputs;\n let {axis} = attrs;\n\n if (axis < 0) {\n axis += value.shape.length;\n }\n\n const x = value;\n const xRank = x.shape.length;\n\n const num = value.shape[axis];\n const outShape: number[] = new Array(xRank - 1);\n let outIndex = 0;\n for (let i = 0; i < xRank; i++) {\n if (i !== axis) {\n outShape[outIndex++] = x.shape[i];\n }\n }\n\n const toDispose = [];\n\n const begin = new Array(xRank).fill(0);\n const size = x.shape.slice();\n size[axis] = 1;\n const res: TensorInfo[] = new Array(num);\n for (let i = 0; i < res.length; i++) {\n begin[axis] = i;\n const sliced = slice({inputs: {x}, backend, attrs: {begin, size}});\n const reshaped =\n reshape({inputs: {x: sliced}, backend, attrs: {shape: outShape}});\n res[i] = reshaped;\n\n toDispose.push(sliced);\n }\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n return res;\n}\n\nexport const unpackConfig: KernelConfig = {\n kernelName: Unpack,\n backendName: 'webgl',\n kernelFunc: unpack as {} as KernelFunc\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 {backend_util} from '@tensorflow/tfjs-core';\nimport {GPGPUProgram} from './gpgpu_math';\n\nexport class SegmentOpProgram implements GPGPUProgram {\n variableNames = ['x', 'segmentIds'];\n outputShape: number[];\n userCode: string;\n\n constructor(\n segOpInfo: backend_util.segment_util.SegOpInfo,\n segOpType: 'unsortedSegmentSum') {\n const windowSize = segOpInfo.windowSize;\n const batchSize = segOpInfo.batchSize;\n const inSize = segOpInfo.inSize;\n const numSegments = segOpInfo.numSegments;\n const outSize = numSegments * Math.ceil(inSize / windowSize);\n this.outputShape = [batchSize, outSize];\n\n const initializationValue = '0.0';\n const returnValue = `sumValue`;\n\n const windowSizeNearestVec4 = Math.floor(windowSize / 4) * 4;\n const windowSizeVec4Remainder = windowSize % 4;\n\n const updateSnippet = `\n sumValue += dot(values, segFilter);\n `;\n\n let checkValueOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkValueOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return initializationValue;\n }\n `;\n }\n\n let checkSegmentIdOutOfBounds = '';\n if (inSize % windowSize > 0) {\n checkSegmentIdOutOfBounds = `\n if (inIdx < 0 || inIdx >= ${inSize}) {\n return -1.0;\n }\n `;\n }\n\n this.userCode = `\n const float initializationValue = ${initializationValue};\n\n float getValue(int batch, int inIdx) {\n ${checkValueOutOfBounds}\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n ${checkSegmentIdOutOfBounds}\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n ${numSegments})) * float(${windowSize}));\n int currentSeg = int(mod(float(outIdx), float(${numSegments})));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${windowSizeNearestVec4}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n ${updateSnippet}\n }\n\n int inIdx = inOffset + ${windowSizeNearestVec4};\n if (${windowSizeVec4Remainder === 1}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 2}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n ${updateSnippet}\n } else if (${windowSizeVec4Remainder === 3}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n ${updateSnippet}\n }\n setOutput(${returnValue});\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 */\n\nimport {backend_util, DataType, KernelConfig, KernelFunc, sumOutType, TensorInfo, UnsortedSegmentSum, UnsortedSegmentSumAttrs, UnsortedSegmentSumInputs, util} from '@tensorflow/tfjs-core';\n\nimport {MathBackendWebGL} from '../backend_webgl';\nimport {SegmentOpProgram} from '../segment_gpu';\n\nimport {range} from './Range';\nimport {reshape} from './Reshape';\nimport {tile} from './Tile';\nimport {transpose} from './Transpose';\n\nexport function unsortedSegmentSum(args: {\n inputs: UnsortedSegmentSumInputs,\n backend: MathBackendWebGL,\n attrs: UnsortedSegmentSumAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x, segmentIds} = inputs;\n const {numSegments} = attrs;\n\n const xRank = x.shape.length;\n\n const toDispose = [];\n\n let axis = 0;\n const permutation = backend_util.getAxesPermutation([axis], xRank);\n let permutedX = x;\n if (permutation != null) {\n permutedX = transpose({inputs: {x}, backend, attrs: {perm: permutation}});\n toDispose.push(permutedX);\n axis = backend_util.getInnerMostAxes(1, xRank)[0];\n }\n\n const outShape = backend_util.segment_util.computeOutShape(\n permutedX.shape, axis, numSegments);\n const inSize = util.sizeFromShape([permutedX.shape[axis]]);\n const a2D =\n reshape({inputs: {x: permutedX}, backend, attrs: {shape: [-1, inSize]}});\n toDispose.push(a2D);\n\n const outputDType = sumOutType(x.dtype);\n\n const segOpCompute =\n (x: TensorInfo, segOpType: 'unsortedSegmentSum', segmentIds: TensorInfo,\n dtype: DataType, numSegments: number): TensorInfo => {\n const batchSize = x.shape[0];\n const inSize = x.shape[1];\n const windowSize =\n backend_util.segment_util.segOpComputeOptimalWindowSize(\n inSize, numSegments);\n const segOpInfo = {windowSize, inSize, batchSize, numSegments};\n const program = new SegmentOpProgram(segOpInfo, segOpType);\n const output = backend.compileAndRun(program, [x, segmentIds], dtype);\n toDispose.push(output);\n // No need to run another GPGPU program.\n if (output.shape[1] === numSegments) {\n return output;\n }\n const rangeInfo = range({\n backend,\n attrs: {start: 0, stop: numSegments, step: 1, dtype: 'float32'}\n });\n const tileInfo = tile({\n inputs: {x: rangeInfo},\n backend,\n attrs: {reps: [inSize / windowSize]}\n });\n\n toDispose.push(rangeInfo);\n toDispose.push(tileInfo);\n\n const result =\n segOpCompute(output, segOpType, tileInfo, dtype, numSegments);\n return result;\n };\n\n const segOpResult = segOpCompute(\n a2D, 'unsortedSegmentSum', segmentIds, outputDType, numSegments);\n\n const reshaped =\n reshape({inputs: {x: segOpResult}, backend, attrs: {shape: outShape}});\n\n let result = reshaped;\n if (permutation != null) {\n toDispose.push(reshaped);\n const perm = backend_util.getUndoAxesPermutation(permutation);\n result = transpose({inputs: {x: result}, backend, attrs: {perm}});\n }\n\n toDispose.forEach(t => backend.disposeIntermediateTensorInfo(t));\n return result;\n}\n\nexport const unsortedSegmentSumConfig: KernelConfig = {\n kernelName: UnsortedSegmentSum,\n backendName: 'webgl',\n kernelFunc: unsortedSegmentSum as {} 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 */\nimport {KernelConfig, registerKernel} from '@tensorflow/tfjs-core';\n\nimport {_fusedMatMulConfig} from './kernels/_FusedMatMul';\nimport {absConfig} from './kernels/Abs';\nimport {acosConfig} from './kernels/Acos';\nimport {acoshConfig} from './kernels/Acosh';\nimport {addConfig} from './kernels/Add';\nimport {addNConfig} from './kernels/AddN';\nimport {allConfig} from './kernels/All';\nimport {anyConfig} from './kernels/Any';\nimport {argMaxConfig} from './kernels/ArgMax';\nimport {argMinConfig} from './kernels/ArgMin';\nimport {asinConfig} from './kernels/Asin';\nimport {asinhConfig} from './kernels/Asinh';\nimport {atanConfig} from './kernels/Atan';\nimport {atan2Config} from './kernels/Atan2';\nimport {atanhConfig} from './kernels/Atanh';\nimport {avgPoolConfig} from './kernels/AvgPool';\nimport {avgPool3DConfig} from './kernels/AvgPool3D';\nimport {avgPoolGrad3DConfig} from './kernels/AvgPool3DGrad';\nimport {avgPoolGradConfig} from './kernels/AvgPoolGrad';\nimport {batchMatMulConfig} from './kernels/BatchMatMul';\nimport {batchNormConfig} from './kernels/BatchNorm';\nimport {batchToSpaceNDConfig} from './kernels/BatchToSpaceND';\nimport {bincountConfig} from './kernels/Bincount';\nimport {castConfig} from './kernels/Cast';\nimport {ceilConfig} from './kernels/Ceil';\nimport {clipByValueConfig} from './kernels/ClipByValue';\nimport {complexConfig} from './kernels/Complex';\nimport {complexAbsConfig} from './kernels/ComplexAbs';\nimport {concatConfig} from './kernels/Concat';\nimport {conv2DConfig} from './kernels/Conv2D';\nimport {conv2DBackpropFilterConfig} from './kernels/Conv2DBackpropFilter';\nimport {conv2DBackpropInputConfig} from './kernels/Conv2DBackpropInput';\nimport {conv3DConfig} from './kernels/Conv3D';\nimport {conv3DBackpropFilterV2Config} from './kernels/Conv3DBackpropFilterV2';\nimport {conv3DBackpropInputConfig} from './kernels/Conv3DBackpropInputV2';\nimport {cosConfig} from './kernels/Cos';\nimport {coshConfig} from './kernels/Cosh';\nimport {cropAndResizeConfig} from './kernels/CropAndResize';\nimport {cumsumConfig} from './kernels/Cumsum';\nimport {denseBincountConfig} from './kernels/DenseBincount';\nimport {depthToSpaceConfig} from './kernels/DepthToSpace';\nimport {depthwiseConv2dNativeConfig} from './kernels/DepthwiseConv2dNative';\nimport {depthwiseConv2dNativeBackpropFilterConfig} from './kernels/DepthwiseConv2dNativeBackpropFilter';\nimport {depthwiseConv2dNativeBackpropInputConfig} from './kernels/DepthwiseConv2dNativeBackpropInput';\nimport {diagConfig} from './kernels/Diag';\nimport {dilation2DConfig} from './kernels/Dilation2D';\nimport {einsumConfig} from './kernels/Einsum';\nimport {eluConfig} from './kernels/Elu';\nimport {eluGradConfig} from './kernels/EluGrad';\nimport {equalConfig} from './kernels/Equal';\nimport {erfConfig} from './kernels/Erf';\nimport {expConfig} from './kernels/Exp';\nimport {expandDimsConfig} from './kernels/ExpandDims';\nimport {expm1Config} from './kernels/Expm1';\nimport {fftConfig} from './kernels/FFT';\nimport {fillConfig} from './kernels/Fill';\nimport {flipLeftRightConfig} from './kernels/FlipLeftRight';\nimport {floorConfig} from './kernels/Floor';\nimport {floorDivConfig} from './kernels/FloorDiv';\nimport {fromPixelsConfig} from './kernels/FromPixels';\nimport {fusedConv2DConfig} from './kernels/FusedConv2D';\nimport {fusedDepthwiseConv2DConfig} from './kernels/FusedDepthwiseConv2D';\nimport {gatherNdConfig} from './kernels/GatherNd';\nimport {gatherV2Config} from './kernels/GatherV2';\nimport {greaterConfig} from './kernels/Greater';\nimport {greaterEqualConfig} from './kernels/GreaterEqual';\nimport {identityConfig} from './kernels/Identity';\nimport {ifftConfig} from './kernels/IFFT';\nimport {imagConfig} from './kernels/Imag';\nimport {isFiniteConfig} from './kernels/IsFinite';\nimport {isInfConfig} from './kernels/IsInf';\nimport {isNaNConfig} from './kernels/IsNaN';\nimport {leakyReluConfig} from './kernels/LeakyRelu';\nimport {lessConfig} from './kernels/Less';\nimport {lessEqualConfig} from './kernels/LessEqual';\nimport {linSpaceConfig} from './kernels/LinSpace';\nimport {logConfig} from './kernels/Log';\nimport {log1pConfig} from './kernels/Log1p';\nimport {logicalAndConfig} from './kernels/LogicalAnd';\nimport {logicalNotConfig} from './kernels/LogicalNot';\nimport {logicalOrConfig} from './kernels/LogicalOr';\nimport {LRNConfig} from './kernels/LRN';\nimport {LRNGradConfig} from './kernels/LRNGrad';\nimport {maxConfig} from './kernels/Max';\nimport {maximumConfig} from './kernels/Maximum';\nimport {maxPoolConfig} from './kernels/MaxPool';\nimport {maxPool3DConfig} from './kernels/MaxPool3D';\nimport {maxPoolGrad3DConfig} from './kernels/MaxPool3DGrad';\nimport {maxPoolGradConfig} from './kernels/MaxPoolGrad';\nimport {maxPoolWithArgmaxConfig} from './kernels/MaxPoolWithArgmax';\nimport {meanConfig} from './kernels/Mean';\nimport {minConfig} from './kernels/Min';\nimport {minimumConfig} from './kernels/Minimum';\nimport {mirrorPadConfig} from './kernels/MirrorPad';\nimport {modConfig} from './kernels/Mod';\nimport {multinomialConfig} from './kernels/Multinomial';\nimport {multiplyConfig} from './kernels/Multiply';\nimport {negConfig} from './kernels/Neg';\nimport {nonMaxSuppressionV3Config} from './kernels/NonMaxSuppressionV3';\nimport {nonMaxSuppressionV4Config} from './kernels/NonMaxSuppressionV4';\nimport {nonMaxSuppressionV5Config} from './kernels/NonMaxSuppressionV5';\nimport {notEqualConfig} from './kernels/NotEqual';\nimport {oneHotConfig} from './kernels/OneHot';\nimport {onesLikeConfig} from './kernels/OnesLike';\nimport {packConfig} from './kernels/Pack';\nimport {padV2Config} from './kernels/PadV2';\nimport {powConfig} from './kernels/Pow';\nimport {preluConfig} from './kernels/Prelu';\nimport {prodConfig} from './kernels/Prod';\nimport {rangeConfig} from './kernels/Range';\nimport {realConfig} from './kernels/Real';\nimport {realDivConfig} from './kernels/RealDiv';\nimport {reciprocalConfig} from './kernels/Reciprocal';\nimport {reluConfig} from './kernels/Relu';\nimport {relu6Config} from './kernels/Relu6';\nimport {reshapeConfig} from './kernels/Reshape';\nimport {resizeBilinearConfig} from './kernels/ResizeBilinear';\nimport {resizeBilinearGradConfig} from './kernels/ResizeBilinearGrad';\nimport {resizeNearestNeighborConfig} from './kernels/ResizeNearestNeighbor';\nimport {resizeNearestNeighborGradConfig} from './kernels/ResizeNearestNeighborGrad';\nimport {reverseConfig} from './kernels/Reverse';\nimport {rotateWithOffsetConfig} from './kernels/RotateWithOffset';\nimport {roundConfig} from './kernels/Round';\nimport {rsqrtConfig} from './kernels/Rsqrt';\nimport {scatterNdConfig} from './kernels/ScatterNd';\nimport {selectConfig} from './kernels/Select';\nimport {seluConfig} from './kernels/Selu';\nimport {sigmoidConfig} from './kernels/Sigmoid';\nimport {signConfig} from './kernels/Sign';\nimport {sinConfig} from './kernels/Sin';\nimport {sinhConfig} from './kernels/Sinh';\nimport {sliceConfig} from './kernels/Slice';\nimport {softmaxConfig} from './kernels/Softmax';\nimport {softplusConfig} from './kernels/Softplus';\nimport {spaceToBatchNDConfig} from './kernels/SpaceToBatchND';\nimport {sparseFillEmptyRowsConfig} from './kernels/SparseFillEmptyRows';\nimport {sparseReshapeConfig} from './kernels/SparseReshape';\nimport {sparseSegmentMeanConfig} from './kernels/SparseSegmentMean';\nimport {sparseSegmentSumConfig} from './kernels/SparseSegmentSum';\nimport {sparseToDenseConfig} from './kernels/SparseToDense';\nimport {splitVConfig} from './kernels/SplitV';\nimport {sqrtConfig} from './kernels/Sqrt';\nimport {squareConfig} from './kernels/Square';\nimport {squaredDifferenceConfig} from './kernels/SquaredDifference';\nimport {stepConfig} from './kernels/Step';\nimport {stridedSliceConfig} from './kernels/StridedSlice';\nimport {stringNGramsConfig} from './kernels/StringNGrams';\nimport {stringSplitConfig} from './kernels/StringSplit';\nimport {stringToHashBucketFastConfig} from './kernels/StringToHashBucketFast';\nimport {subConfig} from './kernels/Sub';\nimport {sumConfig} from './kernels/Sum';\nimport {tanConfig} from './kernels/Tan';\nimport {tanhConfig} from './kernels/Tanh';\nimport {tileConfig} from './kernels/Tile';\nimport {topKConfig} from './kernels/TopK';\nimport {transformConfig} from './kernels/Transform';\nimport {transposeConfig} from './kernels/Transpose';\nimport {uniqueConfig} from './kernels/Unique';\nimport {unpackConfig} from './kernels/Unpack';\nimport {unsortedSegmentSumConfig} from './kernels/UnsortedSegmentSum';\nimport {zerosLikeConfig} from './kernels/ZerosLike';\n\n// List all kernel configs here\nconst kernelConfigs: KernelConfig[] = [\n LRNConfig,\n LRNGradConfig,\n _fusedMatMulConfig,\n absConfig,\n acosConfig,\n acoshConfig,\n addConfig,\n addNConfig,\n allConfig,\n anyConfig,\n argMaxConfig,\n argMinConfig,\n asinConfig,\n asinhConfig,\n atan2Config,\n atanConfig,\n atanhConfig,\n avgPool3DConfig,\n avgPoolConfig,\n avgPoolGrad3DConfig,\n avgPoolGradConfig,\n batchMatMulConfig,\n batchNormConfig,\n batchToSpaceNDConfig,\n bincountConfig,\n castConfig,\n ceilConfig,\n clipByValueConfig,\n complexAbsConfig,\n complexConfig,\n concatConfig,\n conv2DBackpropFilterConfig,\n conv2DBackpropInputConfig,\n conv2DConfig,\n conv3DBackpropFilterV2Config,\n conv3DBackpropInputConfig,\n conv3DConfig,\n cosConfig,\n coshConfig,\n cropAndResizeConfig,\n cumsumConfig,\n denseBincountConfig,\n depthToSpaceConfig,\n depthwiseConv2dNativeBackpropFilterConfig,\n depthwiseConv2dNativeBackpropInputConfig,\n depthwiseConv2dNativeConfig,\n diagConfig,\n dilation2DConfig,\n einsumConfig,\n eluConfig,\n eluGradConfig,\n equalConfig,\n erfConfig,\n expConfig,\n expandDimsConfig,\n expm1Config,\n fftConfig,\n fillConfig,\n flipLeftRightConfig,\n floorConfig,\n floorDivConfig,\n fromPixelsConfig,\n fusedConv2DConfig,\n fusedDepthwiseConv2DConfig,\n gatherNdConfig,\n gatherV2Config,\n greaterConfig,\n greaterEqualConfig,\n identityConfig,\n ifftConfig,\n imagConfig,\n isFiniteConfig,\n isInfConfig,\n isNaNConfig,\n leakyReluConfig,\n lessConfig,\n lessEqualConfig,\n linSpaceConfig,\n log1pConfig,\n logConfig,\n logicalAndConfig,\n logicalNotConfig,\n logicalOrConfig,\n maxConfig,\n maxPool3DConfig,\n maxPoolConfig,\n maxPoolGrad3DConfig,\n maxPoolGradConfig,\n maxPoolWithArgmaxConfig,\n maximumConfig,\n meanConfig,\n minConfig,\n minimumConfig,\n mirrorPadConfig,\n modConfig,\n multinomialConfig,\n multiplyConfig,\n negConfig,\n nonMaxSuppressionV3Config,\n nonMaxSuppressionV4Config,\n nonMaxSuppressionV5Config,\n notEqualConfig,\n oneHotConfig,\n onesLikeConfig,\n packConfig,\n padV2Config,\n powConfig,\n preluConfig,\n prodConfig,\n rangeConfig,\n realConfig,\n realDivConfig,\n reciprocalConfig,\n relu6Config,\n reluConfig,\n reshapeConfig,\n resizeBilinearConfig,\n resizeBilinearGradConfig,\n resizeNearestNeighborConfig,\n resizeNearestNeighborGradConfig,\n reverseConfig,\n rotateWithOffsetConfig,\n roundConfig,\n rsqrtConfig,\n scatterNdConfig,\n selectConfig,\n seluConfig,\n sigmoidConfig,\n signConfig,\n sinConfig,\n sinhConfig,\n sliceConfig,\n softmaxConfig,\n softplusConfig,\n spaceToBatchNDConfig,\n sparseFillEmptyRowsConfig,\n sparseReshapeConfig,\n sparseSegmentMeanConfig,\n sparseSegmentSumConfig,\n sparseToDenseConfig,\n splitVConfig,\n sqrtConfig,\n squareConfig,\n squaredDifferenceConfig,\n stepConfig,\n stridedSliceConfig,\n stringNGramsConfig,\n stringSplitConfig,\n stringToHashBucketFastConfig,\n subConfig,\n sumConfig,\n tanConfig,\n tanhConfig,\n tileConfig,\n topKConfig,\n transformConfig,\n transposeConfig,\n uniqueConfig,\n unpackConfig,\n unsortedSegmentSumConfig,\n zerosLikeConfig\n];\n\nfor (const kernelConfig of kernelConfigs) {\n registerKernel(kernelConfig);\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// All exports from this package should be in base.\nexport * from './base';\nimport './register_all_kernels';\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// This enum must align with the enum defined in cc/backend.h.\nexport enum CppDType {\n float32 = 0,\n int32 = 1,\n bool = 2,\n string = 3,\n complex64 = 4\n}\n\n// Must match enum in cc/fusable_activations.h.\nexport enum FusableActivation {\n linear = 0,\n relu = 1,\n relu6 = 2,\n prelu = 3,\n leakyrelu = 4,\n sigmoid = 5\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 {_FusedMatMul, _FusedMatMulAttrs, _FusedMatMulInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {FusableActivation} from './types';\n\nlet wasmFusedMatMul:\n (aId: number, aShape: Uint8Array, aShapeSize: number, bId: number,\n bShape: Uint8Array, bShapeSize: number, transposeA: boolean,\n transposeB: boolean, activation: number, biasId: number,\n preluActivationWeightsId: number, leakyreluAlpha: number, outId: number) =>\n void;\n\nfunction setup(backend: BackendWasm) {\n wasmFusedMatMul = backend.wasm.cwrap(_FusedMatMul, null /* void */, [\n 'number', // a_id\n 'array', // a_shape\n 'number', // a_shape.length\n 'number', // b_id\n 'array', // b_shape\n 'number', // b_shape.length\n 'number', // transpose_a\n 'number', // transpose_b\n 'number', // activation\n 'number', // biasId\n 'number', // preluActivationWeightsId\n 'number', // leakyreluAlpha\n 'number' // out_id\n ]);\n}\n\nfunction fusedBatchMatMul(args: {\n inputs: _FusedMatMulInputs,\n backend: BackendWasm,\n attrs: _FusedMatMulAttrs\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b, bias, preluActivationWeights} = inputs;\n\n if (a.dtype !== 'float32' || b.dtype !== 'float32') {\n throw new Error(\n `_FusedMatMul for non non-float32 tensors not yet supported.`);\n }\n\n const {transposeA, transposeB, activation, leakyreluAlpha} = attrs;\n const aId = backend.dataIdMap.get(a.dataId).id;\n const bId = backend.dataIdMap.get(b.dataId).id;\n\n let biasId = 0;\n if (bias != null) {\n const biasData = backend.dataIdMap.get(bias.dataId);\n if (biasData.shape.length !== 1) {\n throw new Error(\n `_FusedMatMul only supports rank-1 bias but got ` +\n `rank ${biasData.shape.length}.`);\n }\n biasId = biasData.id;\n }\n const preluActivationWeightsId = preluActivationWeights == null ?\n 0 :\n backend.dataIdMap.get(preluActivationWeights.dataId).id;\n const fusedActivation =\n FusableActivation[activation as {} as keyof typeof FusableActivation];\n if (fusedActivation == null) {\n throw new Error(\n `${activation} activation not yet supported for FusedConv2D ` +\n `in the wasm backend.`);\n }\n\n const leftDim = transposeA ? a.shape[2] : a.shape[1];\n const rightDim = transposeB ? b.shape[1] : b.shape[2];\n const batchDim = a.shape[0];\n\n const out = backend.makeOutput([batchDim, leftDim, rightDim], a.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const aShapeBytes = new Uint8Array(new Int32Array(a.shape).buffer);\n const bShapeBytes = new Uint8Array(new Int32Array(b.shape).buffer);\n\n wasmFusedMatMul(\n aId, aShapeBytes, a.shape.length, bId, bShapeBytes, b.shape.length,\n transposeA, transposeB, fusedActivation, biasId, preluActivationWeightsId,\n leakyreluAlpha || 0, outId);\n\n return out;\n}\n\nexport const fusedMatMulConfig: KernelConfig = {\n kernelName: _FusedMatMul,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: fusedBatchMatMul as {} 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 {KernelConfig, TensorInfo, UnaryInputs, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nexport function createUnaryKernelConfig(kernelName: string): KernelConfig {\n let wasmFunc: (xId: number, outId: number) => void;\n\n function setupFunc(backend: BackendWasm): void {\n wasmFunc =\n backend.wasm.cwrap(kernelName, null /* void */, ['number', 'number']);\n }\n\n function kernelFunc(args: {backend: BackendWasm, inputs: UnaryInputs}):\n TensorInfo {\n const {backend, inputs: {x}} = args;\n const xId = backend.dataIdMap.get(x.dataId).id;\n const out = backend.makeOutput(x.shape, x.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n // Short-circuit zero-sized tensors.\n if (util.sizeFromShape(out.shape) === 0) {\n return out;\n }\n\n wasmFunc(xId, outId);\n return out;\n }\n\n return {kernelName, backendName: 'wasm', setupFunc, 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 */\nimport {Abs, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\n\nexport const absConfig: KernelConfig = createUnaryKernelConfig(Abs);\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 {backend_util, BinaryInputs, DataType, KernelConfig, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {CppDType} from './types';\n\nexport function createBinaryKernelConfig(\n kernelName: string, supportsFullBroadcast: boolean,\n dtype?: DataType): KernelConfig {\n let wasmFunc:\n (aId: number, aShape: Uint8Array, aShapeLen: number, bId: number,\n bShape: Uint8Array, bShapeLen: number, dtype: number, outId: number) =>\n void;\n\n function setupFunc(backend: BackendWasm): void {\n wasmFunc = backend.wasm.cwrap(kernelName, null /* void */, [\n 'number', // a_id,\n 'array', // a_shape\n 'number', // a_shape.length\n 'number', // b_id\n 'array', // b_shape\n 'number', // b_shape.length\n 'number', // dtype\n 'number' // out_id\n ]);\n }\n\n function kernelFunc(args: {backend: BackendWasm, inputs: BinaryInputs}):\n TensorInfo {\n const {backend, inputs} = args;\n const {a, b} = inputs;\n const aId = backend.dataIdMap.get(a.dataId).id;\n const bId = backend.dataIdMap.get(b.dataId).id;\n\n const outputType = dtype != null ? dtype : a.dtype;\n const newShape = backend_util.assertAndGetBroadcastShape(a.shape, b.shape);\n const out = backend.makeOutput(newShape, outputType);\n\n // Short-circuit zero-sized tensors.\n if (util.sizeFromShape(newShape) === 0) {\n return out;\n }\n\n const aShapeBytes = new Uint8Array(new Int32Array(a.shape).buffer);\n const bShapeBytes = new Uint8Array(new Int32Array(b.shape).buffer);\n const outId = backend.dataIdMap.get(out.dataId).id;\n const kernelFunc = () => wasmFunc(\n aId, aShapeBytes, a.shape.length, bId, bShapeBytes, b.shape.length,\n CppDType[a.dtype], outId);\n\n // Currently only some float operations support full broadcast.\n if (supportsFullBroadcast && a.dtype === 'float32') {\n kernelFunc();\n return out;\n }\n\n const aBroadcastDims = backend_util.getBroadcastDims(a.shape, newShape);\n const bBroadcastDims = backend_util.getBroadcastDims(b.shape, newShape);\n const loopsOverAllOfA = aBroadcastDims.every((v, i) => v === i);\n const loopsOverAllOfB = bBroadcastDims.every((v, i) => v === i);\n if (loopsOverAllOfA && loopsOverAllOfB) {\n kernelFunc();\n return out;\n } else {\n throw new Error(\n `Broadcasting along outer dims is not yet ` +\n `supported for ${a.dtype} ${kernelName}.`);\n }\n }\n\n return {kernelName, backendName: 'wasm', setupFunc, 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 {Add, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\n\nconst supportsFullBroadcast = true;\n\nexport const addConfig: KernelConfig =\n createBinaryKernelConfig(Add, supportsFullBroadcast);\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 {AddN, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {CppDType} from './types';\n\nlet wasmFunc:\n (inputIds: Uint8Array, inputIdsLen: number, dtype: number, outId: number) =>\n void;\n\nfunction setupFunc(backend: BackendWasm): void {\n wasmFunc = backend.wasm.cwrap(AddN, null /* void */, [\n 'array', // input_ids\n 'number', // input_ids.length\n 'number', // dtype\n 'number', // out_id\n ]);\n}\n\nfunction addn(args: {inputs: TensorInfo[], backend: BackendWasm}) {\n const {inputs, backend} = args;\n const out = backend.makeOutput(inputs[0].shape, inputs[0].dtype);\n\n // Short-circuit zero-sized tensors.\n if (util.sizeFromShape(out.shape) === 0) {\n return out;\n }\n\n const inputIds = inputs.map(x => backend.dataIdMap.get(x.dataId).id);\n const inputIdsBytes = new Uint8Array(new Int32Array(inputIds).buffer);\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmFunc(inputIdsBytes, inputIds.length, CppDType[out.dtype], outId);\n\n return out;\n}\n\nexport const addNConfig: KernelConfig = {\n kernelName: AddN,\n backendName: 'wasm',\n setupFunc,\n kernelFunc: addn as {} 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} from '@tensorflow/tfjs-core';\nimport {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nexport function identity(args: {inputs: IdentityInputs, backend: BackendWasm}):\n TensorInfo {\n const {inputs: {x}, backend} = args;\n const out = backend.makeOutput(x.shape, x.dtype);\n const inVals = backend.typedArrayFromHeap(x);\n const outVals = backend.typedArrayFromHeap(out);\n outVals.set(inVals);\n return out;\n}\n\nexport const identityConfig: KernelConfig = {\n kernelName: Identity,\n backendName: 'wasm',\n kernelFunc: identity as {} 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 {KernelConfig, KernelFunc, TensorInfo, Transpose, TransposeAttrs, TransposeInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {identity} from './Identity';\nimport {CppDType} from './types';\n\nlet wasmTranspose: (\n xId: number, xShape: Uint8Array, xShapeLength: number, dtype: CppDType,\n outId: number, perm: Uint8Array, permLength: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmTranspose = backend.wasm.cwrap(Transpose, null /* void */, [\n 'number', // xId\n 'array', // x.shape\n 'number', // x.shape.length\n 'number', // dtype\n 'number', // outId\n 'array', // perm\n 'number', // perm.length\n ]);\n}\n\nexport function transpose(\n args:\n {inputs: TransposeInputs, backend: BackendWasm, attrs: TransposeAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n // Reduce any dimensions with size one. Lower-rank transpose kernel performs\n // better due to simpler memory access pattern.\n const [reducedShape, perm] = removeOneSizeDims(inputs.x.shape, attrs.perm);\n\n let permIsNoOp = true;\n for (let i = 0; i < perm.length; i++) {\n if (perm[i] !== i) {\n permIsNoOp = false;\n }\n }\n const outShape = computeOutShape(inputs.x.shape, attrs.perm);\n const x = {\n dataId: inputs.x.dataId,\n shape: reducedShape,\n dtype: inputs.x.dtype\n };\n\n if (permIsNoOp) {\n const cloned = identity({inputs, backend});\n cloned.shape = outShape;\n return cloned;\n }\n\n const out = backend.makeOutput(outShape, x.dtype);\n const xId = backend.dataIdMap.get(x.dataId).id;\n const outId = backend.dataIdMap.get(out.dataId).id;\n const permBytes = new Uint8Array(new Int32Array(perm).buffer);\n const xShapeBytes = new Uint8Array(new Int32Array(x.shape).buffer);\n\n wasmTranspose(\n xId, xShapeBytes, x.shape.length, CppDType[x.dtype], outId, permBytes,\n perm.length);\n return out;\n}\n\nfunction computeOutShape(inShape: number[], perm: number[]): number[] {\n const outShape = new Array(inShape.length);\n for (let i = 0; i < outShape.length; i++) {\n outShape[i] = inShape[perm[i]];\n }\n return outShape;\n}\n\nfunction removeOneSizeDims(\n shape: number[], perm: number[]): [number[], number[]] {\n const newShape: number[] = [];\n const newPerm: number[] = [];\n for (let i = 0; i < shape.length; ++i) {\n if (shape[i] !== 1) {\n newShape.push(shape[i]);\n }\n if (shape[perm[i]] !== 1) {\n newPerm.push(perm[i]);\n }\n }\n for (let i = 0; i < newPerm.length; ++i) {\n let minValIdx = -1;\n for (let j = 0; j < newPerm.length; ++j) {\n if (newPerm[j] >= i &&\n (minValIdx === -1 || newPerm[minValIdx] > newPerm[j])) {\n minValIdx = j;\n }\n }\n newPerm[minValIdx] = i;\n }\n return [newShape, newPerm];\n}\n\nexport const transposeConfig: KernelConfig = {\n kernelName: Transpose,\n backendName: 'wasm',\n kernelFunc: transpose as {} as KernelFunc,\n setupFunc: setup,\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 {backend_util, TensorInfo, util} from '@tensorflow/tfjs-core';\nimport {BackendWasm} from '../backend_wasm';\nimport {transpose} from './Transpose';\n\n/**\n * Compute permutation axes and do a transpose if necessary.\n *\n * Used by reduction ops.\n * @param x input TensorInfo\n * @param axis reduction axes\n * @param backend wasm backend instance\n */\nexport function permuteAxesAndTranspose(\n x: TensorInfo, axis: number|number[], backend: BackendWasm): {\n transposed: TensorInfo|null,\n axes: number[],\n originalAxes: number[],\n inputWasTransposed: boolean\n} {\n const xShape = x.shape;\n const xRank = x.shape.length;\n\n const originalAxes = util.parseAxisParam(axis, xShape);\n let axes = originalAxes;\n const permutedAxes = backend_util.getAxesPermutation(axes, xRank);\n let xTransposed = null;\n let inputWasTransposed = false;\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 axes = backend_util.getInnerMostAxes(axes.length, xRank);\n xTransposed =\n transpose({inputs: {x}, attrs: {perm: permutedAxes}, backend});\n\n const xId = backend.dataIdMap.get(x.dataId).id;\n const transposedId = backend.dataIdMap.get(xTransposed.dataId).id;\n if (transposedId !== xId) {\n inputWasTransposed = true;\n }\n }\n\n return {transposed: xTransposed, originalAxes, axes, inputWasTransposed};\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 {All, AllAttrs, AllInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {permuteAxesAndTranspose} from './kernel_utils';\n\nlet wasmAll: (xId: number, reduceSize: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmAll = backend.wasm.cwrap(All, null /*void*/, ['number, number, number']);\n}\n\nfunction all(args: {backend: BackendWasm, inputs: AllInputs, attrs: AllAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {axis, keepDims} = attrs;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n let inputId = xId;\n let input = x;\n\n const {transposed, axes, originalAxes, inputWasTransposed} =\n permuteAxesAndTranspose(x, axis, backend);\n\n if (inputWasTransposed) {\n const transposedId = backend.dataIdMap.get(transposed.dataId).id;\n input = transposed;\n inputId = transposedId;\n }\n\n const inputRank = input.shape.length;\n backend_util.assertAxesAreInnerMostDims('all', axes, inputRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(input.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const out = backend.makeOutput(outShape, x.dtype);\n if (util.sizeFromShape(input.shape) !== 0) {\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmAll(inputId, reduceSize, outId);\n }\n\n if (inputWasTransposed) {\n // dispose of the transposed tensor.\n backend.disposeData(transposed.dataId);\n }\n\n if (keepDims) {\n // reshape\n const newShape = backend_util.expandShapeToKeepDim(out.shape, originalAxes);\n out.shape = newShape;\n }\n\n return out;\n}\n\nexport const allConfig: KernelConfig = {\n kernelName: All,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: all as {} as KernelFunc\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 {Any, AnyAttrs, AnyInputs, backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {permuteAxesAndTranspose} from './kernel_utils';\n\nlet wasmAny: (xId: number, reduceSize: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmAny = backend.wasm.cwrap(Any, null /*void*/, ['number, number, number']);\n}\n\nfunction any(args: {backend: BackendWasm, inputs: AnyInputs, attrs: AnyAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {axis, keepDims} = attrs;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n let inputId = xId;\n let input = x;\n\n const {transposed, axes, originalAxes, inputWasTransposed} =\n permuteAxesAndTranspose(x, axis, backend);\n\n if (inputWasTransposed) {\n const transposedId = backend.dataIdMap.get(transposed.dataId).id;\n input = transposed;\n inputId = transposedId;\n }\n\n const inputRank = input.shape.length;\n backend_util.assertAxesAreInnerMostDims('any', axes, inputRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(input.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const out = backend.makeOutput(outShape, x.dtype);\n if (util.sizeFromShape(input.shape) !== 0) {\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmAny(inputId, reduceSize, outId);\n }\n\n if (inputWasTransposed) {\n // dispose of the transposed tensor.\n backend.disposeData(transposed.dataId);\n }\n\n if (keepDims) {\n // reshape\n const newShape = backend_util.expandShapeToKeepDim(out.shape, originalAxes);\n out.shape = newShape;\n }\n\n return out;\n}\n\nexport const anyConfig: KernelConfig = {\n kernelName: Any,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: any as {} 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 {ArgMax, ArgMaxAttrs, ArgMaxInputs, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {permuteAxesAndTranspose} from './kernel_utils';\nimport {CppDType} from './types';\n\nlet wasmFunc: (\n xId: number, dtype: number, outerSize: number, innerSize: number,\n outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmFunc = backend.wasm.cwrap(ArgMax, null /* void */, [\n 'number', // x_id\n 'number', // dtype\n 'number', // outer_size\n 'number', // inner_size\n 'number' // out_id\n ]);\n}\n\nfunction argmax(\n args: {inputs: ArgMaxInputs, backend: BackendWasm, attrs: ArgMaxAttrs}) {\n const {backend, inputs, attrs} = args;\n const {axis} = attrs as {} as ArgMaxAttrs;\n const {x} = inputs as {} as ArgMaxInputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n let inputId = xId;\n let input = x;\n\n const {transposed, axes, inputWasTransposed} =\n permuteAxesAndTranspose(x, axis, backend);\n\n if (inputWasTransposed) {\n const transposedId = backend.dataIdMap.get(transposed.dataId).id;\n if (transposedId !== xId) {\n // transpose was not a no-op. We will need to dispose of this\n // once we are done.\n input = transposed;\n inputId = transposedId;\n }\n }\n\n const outShape = input.shape.slice(0, -1);\n const out = backend.makeOutput(outShape, 'int32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n const outerSize = util.sizeFromShape(out.shape);\n const innerSize = input.shape[axes[0]];\n wasmFunc(inputId, CppDType[input.dtype], outerSize, innerSize, outId);\n\n if (inputWasTransposed) {\n // dispose of the transposed tensor.\n backend.disposeData(transposed.dataId);\n }\n\n return out;\n}\n\nexport const argMaxConfig: KernelConfig = {\n kernelName: ArgMax,\n backendName: 'wasm',\n kernelFunc: argmax as {} as KernelFunc,\n setupFunc: setup\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 {AvgPool, AvgPoolAttrs, AvgPoolInputs, backend_util, KernelConfig, KernelFunc, Tensor4D} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmAvgPool: (\n xId: number, batchSize: number, inputHeight: number, inputWidth: number,\n filterHeight: number, filterWidth: number, padTop: number, padRight: number,\n padBottom: number, padLeft: number, strideHeight: number,\n strideWidth: number, channels: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmAvgPool = backend.wasm.cwrap(AvgPool, null /* void */, [\n 'number', // xId\n 'number', // batchSize\n 'number', // inputHeight\n 'number', // inputWidth\n 'number', // filterHeight\n 'number', // filterWidth\n 'number', // padTop\n 'number', // padRight\n 'number', // padBottom\n 'number', // padLeft\n 'number', // strideHeight\n 'number', // strideWidth\n 'number', // channels\n 'number', // outId\n ]);\n}\n\nfunction avgPool(\n args: {inputs: AvgPoolInputs, backend: BackendWasm, attrs: AvgPoolAttrs}) {\n const {inputs, attrs, backend} = args;\n\n const x = inputs.x as Tensor4D;\n const xId = backend.dataIdMap.get(x.dataId).id;\n\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const convInfo = backend_util.computePool2DInfo(\n x.shape, filterSize, strides, 1 /* dilations */, pad, dimRoundingMode);\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const padTop = convInfo.padInfo.top;\n const padRight = convInfo.padInfo.right;\n const padBottom = convInfo.padInfo.bottom;\n const padLeft = convInfo.padInfo.left;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const channels = convInfo.inChannels;\n\n if (convInfo.dataFormat !== 'channelsLast') {\n throw new Error(\n `wasm backend does not support dataFormat:'` +\n `${convInfo.dataFormat}'. Please use 'channelsLast'.`);\n }\n\n if (convInfo.dilationWidth !== 1 || convInfo.dilationHeight !== 1) {\n throw new Error(\n `was backend only supports average pooling with dilation = [1, 1], ` +\n `got [${convInfo.dilationHeight}, ${convInfo.dilationWidth}].`);\n }\n\n const out = backend.makeOutput(convInfo.outShape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n wasmAvgPool(\n xId, x.shape[0], x.shape[1], x.shape[2], filterHeight, filterWidth,\n padTop, padRight, padBottom, padLeft, strideHeight, strideWidth, channels,\n outId);\n return out;\n}\n\nexport const avgPoolConfig: KernelConfig = {\n kernelName: AvgPool,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: avgPool as {} 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 {KernelConfig, KernelFunc, Reshape, ReshapeAttrs, ReshapeInputs, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nexport function reshape(\n args: {inputs: ReshapeInputs, attrs: ReshapeAttrs, backend: BackendWasm}) {\n const {inputs, 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\n util.assert(\n xSize === util.sizeFromShape($shape),\n () => `new shape: ${$shape}, old shape: ${x.shape}. New shape and old ` +\n `shape must have the same number of elements.`);\n\n // Backend needs to track refCount for the dataId for reshape op\n args.backend.incRef(x.dataId);\n return {dataId: x.dataId, shape: $shape, dtype: x.dtype};\n}\n\nexport const reshapeConfig: KernelConfig = {\n kernelName: Reshape,\n backendName: 'wasm',\n kernelFunc: reshape as {} 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 {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {reshape} from './Reshape';\n\nlet wasmBatchMatMul: (\n aId: number, aShape: Uint8Array, aShapeSize: number, bId: number,\n bShape: Uint8Array, bShapeSize: number, transposeA: boolean,\n transposeB: boolean, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmBatchMatMul = backend.wasm.cwrap(BatchMatMul, null /* void */, [\n 'number', // a_id\n 'array', // a_shape\n 'number', // a_shape.length\n 'number', // b_id\n 'array', // b_shape\n 'number', // b_shape.length\n 'number', // transpose_a\n 'number', // transpose_b\n 'number' // out_id\n ]);\n}\n\nfunction batchMatMul(args: {\n inputs: BatchMatMulInputs,\n backend: BackendWasm,\n attrs: BatchMatMulAttrs\n}) {\n const {inputs, backend, attrs} = args;\n const {a, b} = inputs;\n const {transposeA, transposeB} = attrs;\n\n if (a.dtype !== 'float32' || b.dtype !== 'float32') {\n throw new Error(\n `BatchMatMul for non non-float32 tensors not yet supported.`);\n }\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 batchDimsCompatible =\n batchDimA === batchDimB || batchDimA === 1 || batchDimB === 1;\n\n util.assert(\n aRank >= 2 && bRank >= 2 && batchDimsCompatible,\n () => `Error in matMul: the input batch dimensions must either be the ` +\n `same or at least one input batch dimension must be 1. Got input ` +\n `batch dimensions of (${outerDimsA}) and (${outerDimsB}).`);\n\n const outShapeOuterDims =\n batchDimA > batchDimB ? 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 a3dId = backend.dataIdMap.get(a3d.dataId).id;\n const b3dId = backend.dataIdMap.get(b3d.dataId).id;\n\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 out = backend.makeOutput([batchDim, leftDim, rightDim], a3d.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const aShapeBytes = new Uint8Array(new Int32Array(a3d.shape).buffer);\n const bShapeBytes = new Uint8Array(new Int32Array(b3d.shape).buffer);\n\n wasmBatchMatMul(\n a3dId, aShapeBytes, a3d.shape.length, b3dId, bShapeBytes,\n b3d.shape.length, transposeA, transposeB, outId);\n\n backend.disposeData(a3d.dataId);\n backend.disposeData(b3d.dataId);\n\n out.shape = outShape;\n return out;\n}\n\nexport const batchMatMulConfig: KernelConfig = {\n kernelName: BatchMatMul,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: batchMatMul as {} 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\n// Import shared functionality from tfjs-backend-cpu without triggering\n// side effects.\n// tslint:disable-next-line: no-imports-from-dist\nimport {concatImpl as concatImplCPU} from '@tensorflow/tfjs-backend-cpu/dist/shared';\n// tslint:disable-next-line: no-imports-from-dist\nimport {sliceImpl as sliceImplCPU} from '@tensorflow/tfjs-backend-cpu/dist/shared';\n// tslint:disable-next-line: no-imports-from-dist\nimport {rangeImpl as rangeImplCPU} from '@tensorflow/tfjs-backend-cpu/dist/shared';\n\nexport {concatImplCPU, rangeImplCPU, sliceImplCPU};\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 {backend_util, KernelConfig, KernelFunc, Slice, slice_util, SliceAttrs, SliceInputs, TypedArray, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\nimport {sliceImplCPU} from '../kernel_utils/shared';\n\nexport function slice(\n args: {inputs: SliceInputs, attrs: SliceAttrs, backend: BackendWasm}) {\n const {inputs: {x}, attrs: {begin, size}, backend} = args;\n\n const [begin_, size_] = slice_util.parseSliceParams(x, begin, size);\n\n const isContinous = slice_util.isSliceContinous(x.shape, begin_, size_);\n const xVals = backend.readSync(x.dataId);\n const out = backend.makeOutput(size_, x.dtype);\n const xStrides = util.computeStrides(x.shape);\n const outData = backend.dataIdMap.get(out.dataId);\n\n if (isContinous) {\n const flatOffset = slice_util.computeFlatOffset(begin_, xStrides);\n\n if (x.dtype === 'string') {\n outData.stringBytes =\n (xVals as Uint8Array[])\n .slice(flatOffset, flatOffset + util.sizeFromShape(size_));\n } else {\n const outVals = backend.typedArrayFromHeap(out);\n outVals.set(\n (xVals as TypedArray)\n .subarray(flatOffset, flatOffset + util.sizeFromShape(size_)));\n }\n\n return out;\n }\n\n if (x.dtype === 'string') {\n const res = sliceImplCPU(xVals, begin_, size_, x.shape, x.dtype);\n outData.stringBytes = res as Uint8Array[];\n return out;\n }\n\n const outVals = backend.typedArrayFromHeap(out);\n const rank = x.shape.length;\n if (rank === 2) {\n slice2d(\n xVals as TypedArray, xStrides[0], outVals, begin_ as [number, number],\n size_ as [number, number]);\n } else if (rank === 3) {\n slice3d(\n xVals as TypedArray, xStrides[0], xStrides[1], outVals,\n begin_ as [number, number, number], size_ as [number, number, number]);\n } else if (rank === 4) {\n slice4d(\n xVals as TypedArray, xStrides[0], xStrides[1], xStrides[2], outVals,\n begin_ as [number, number, number, number],\n size_ as [number, number, number, number]);\n } else {\n const res =\n sliceImplCPU(xVals, begin_, size_, x.shape, x.dtype) as TypedArray;\n outVals.set(res);\n }\n\n return out;\n}\n\nfunction slice2d(\n xVals: backend_util.TypedArray, xStride: number,\n outVals: backend_util.TypedArray, begin: [number, number],\n size: [number, number]): void {\n let outOffset = 0;\n const beginI = begin[0];\n const beginJ = begin[1];\n const endI = beginI + size[0];\n for (let i = beginI; i < endI; i++) {\n const xOffset = i * xStride + beginJ;\n outVals.set(xVals.subarray(xOffset, xOffset + size[1]), outOffset);\n outOffset += size[1];\n }\n}\n\nfunction slice3d(\n xVals: backend_util.TypedArray, xStride1: number, xStride2: number,\n outVals: backend_util.TypedArray, begin: [number, number, number],\n size: [number, number, number]): void {\n let outOffset = 0;\n const beginI = begin[0];\n const beginJ = begin[1];\n const beginK = begin[2];\n const endI = beginI + size[0];\n const endJ = beginJ + size[1];\n for (let i = beginI; i < endI; i++) {\n for (let j = beginJ; j < endJ; j++) {\n const xOffset = i * xStride1 + j * xStride2 + beginK;\n outVals.set(xVals.subarray(xOffset, xOffset + size[2]), outOffset);\n outOffset += size[2];\n }\n }\n}\n\nfunction slice4d(\n xVals: backend_util.TypedArray, xStride1: number, xStride2: number,\n xStride3: number, outVals: backend_util.TypedArray,\n begin: [number, number, number, number],\n size: [number, number, number, number]): void {\n let outOffset = 0;\n const beginI = begin[0];\n const beginJ = begin[1];\n const beginK = begin[2];\n const endI = beginI + size[0];\n const endJ = beginJ + size[1];\n const endK = beginK + size[2];\n const beginL = begin[3];\n\n for (let i = beginI; i < endI; i++) {\n for (let j = beginJ; j < endJ; j++) {\n for (let k = beginK; k < endK; k++) {\n const xOffset = i * xStride1 + j * xStride2 + k * xStride3 + beginL;\n outVals.set(xVals.subarray(xOffset, xOffset + size[3]), outOffset);\n outOffset += size[3];\n }\n }\n }\n}\n\nexport const sliceConfig: KernelConfig = {\n kernelName: Slice,\n backendName: 'wasm',\n kernelFunc: slice as {} as KernelFunc,\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 {backend_util, BatchToSpaceND, BatchToSpaceNDAttrs, BatchToSpaceNDInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\nimport {transpose} from './Transpose';\n\nfunction batchToSpaceND(args: {\n inputs: BatchToSpaceNDInputs,\n backend: BackendWasm,\n attrs: BatchToSpaceNDAttrs\n}) {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, crops} = attrs;\n\n const prod = blockShape.reduce((a, b) => a * b);\n\n const reshaped = backend_util.getReshaped(x.shape, blockShape, prod);\n const permuted = backend_util.getPermuted(reshaped.length, blockShape.length);\n const reshapedPermuted =\n backend_util.getReshapedPermuted(x.shape, blockShape, prod);\n const sliceBeginCoords =\n backend_util.getSliceBeginCoords(crops, blockShape.length);\n const sliceSize =\n backend_util.getSliceSize(reshapedPermuted, crops, blockShape.length);\n\n const xReshaped = reshape({inputs: {x}, backend, attrs: {shape: reshaped}});\n const xTransposed =\n transpose({inputs: {x: xReshaped}, backend, attrs: {perm: permuted}});\n const xTransposedReshaped = reshape(\n {inputs: {x: xTransposed}, backend, attrs: {shape: reshapedPermuted}});\n const result = slice({\n inputs: {x: xTransposedReshaped},\n backend,\n attrs: {begin: sliceBeginCoords, size: sliceSize}\n });\n\n backend.disposeData(xReshaped.dataId);\n backend.disposeData(xTransposed.dataId);\n backend.disposeData(xReshaped.dataId);\n\n return result;\n}\n\nexport const batchToSpaceNDConfig: KernelConfig = {\n kernelName: BatchToSpaceND,\n backendName: 'wasm',\n kernelFunc: batchToSpaceND as {} 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 {Cast, CastAttrs, CastInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\nimport {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nexport function cast(\n args: {inputs: CastInputs, attrs: CastAttrs, backend: BackendWasm}):\n TensorInfo {\n const {inputs: {x}, attrs: {dtype}, backend} = args;\n const out = backend.makeOutput(x.shape, dtype);\n const inVals = backend.typedArrayFromHeap(x);\n const outVals = backend.typedArrayFromHeap(out);\n outVals.set(inVals);\n return out;\n}\n\nexport const castConfig: KernelConfig = {\n kernelName: Cast,\n backendName: 'wasm',\n kernelFunc: cast as {} as KernelFunc,\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 {KernelConfig, Ceil} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\n\nexport const ceilConfig: KernelConfig = createUnaryKernelConfig(Ceil);\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 {ClipByValue, ClipByValueAttrs, ClipByValueInputs, KernelConfig, KernelFunc} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmClip: (xId: number, min: number, max: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmClip = backend.wasm.cwrap(ClipByValue, null /* void */, [\n 'number', // x_id\n 'number', // min\n 'number', // max\n 'number' // out_id\n ]);\n}\n\nfunction clip(args: {\n inputs: ClipByValueInputs,\n backend: BackendWasm,\n attrs: ClipByValueAttrs\n}) {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {clipValueMin, clipValueMax} = attrs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n const out = backend.makeOutput(x.shape, x.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmClip(xId, clipValueMin, clipValueMax, outId);\n return out;\n}\n\nexport const clipByValueConfig: KernelConfig = {\n kernelName: ClipByValue,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: clip as {} 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 {backend_util, Concat, ConcatAttrs, ConcatInputs, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\nimport {concatImplCPU} from '../kernel_utils/shared';\nimport {identity} from './Identity';\nimport {reshape} from './Reshape';\n\nexport function concat(\n args: {inputs: ConcatInputs, backend: BackendWasm, attrs: ConcatAttrs}) {\n const {inputs, backend} = args;\n\n const axis = util.parseAxisParam(args.attrs.axis, inputs[0].shape)[0];\n\n let outShape = backend_util.computeOutShape(inputs.map(t => t.shape), axis);\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 const out = backend.makeOutput(outShape, inputs[0].dtype);\n\n if (util.sizeFromShape(outShape) === 0) {\n return out;\n }\n\n const shapes = $inputs.map(t => t.shape);\n backend_util.assertParamsConsistent(shapes, axis);\n\n if ($inputs[0].dtype === 'string') {\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.readSync(t.dataId), 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 = concatImplCPU(\n inputsValShapes, outShape, inputs[0].dtype,\n simplyConcat) as string[];\n\n const finalOutShape =\n backend_util.computeOutShape($inputs.map(t => t.shape), axis);\n\n out.shape = finalOutShape;\n const outData = backend.dataIdMap.get(out.dataId);\n outData.stringBytes = backend_util.fromStringArrayToUint8(outVals);\n\n inputs2D.forEach(t => backend.disposeData(t.dataId));\n\n return out;\n }\n\n const batchDim = util.sizeFromShape($inputs[0].shape.slice(0, axis));\n let sumInnerDims = 0;\n const innerDims = $inputs.map(input => {\n const innerDim = util.sizeFromShape(input.shape.slice(axis));\n sumInnerDims += innerDim;\n return innerDim;\n });\n const inVals = $inputs.map(input => backend.typedArrayFromHeap(input));\n const outVals = backend.typedArrayFromHeap(out);\n for (let b = 0; b < batchDim; b++) {\n let outOffset = b * sumInnerDims;\n for (let i = 0; i < inVals.length; i++) {\n const innerDim = innerDims[i];\n const inOffset = b * innerDim;\n const vals = inVals[i].subarray(inOffset, inOffset + innerDim);\n outVals.set(vals, outOffset);\n outOffset += innerDim;\n }\n }\n return out;\n}\n\nexport const concatConfig: KernelConfig = {\n kernelName: Concat,\n backendName: 'wasm',\n kernelFunc: concat as {} 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 {backend_util, Conv2D, Conv2DAttrs, Conv2DInputs, KernelConfig, KernelFunc, Tensor4D} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmConv2d: (\n xId: number, batchSize: number, inputHeight: number, inputWidth: number,\n filterId: number, filterHeight: number, filterWidth: number, padTop: number,\n padRight: number, padBottom: number, padLeft: number, isSamePad: number,\n dilationHeight: number, dilationWidth: number, strideHeight: number,\n strideWidth: number, inputChannels: number, outputChannels: number,\n outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmConv2d = backend.wasm.cwrap(Conv2D, null /* void */, [\n 'number', // xId\n 'number', // batchSize\n 'number', // inputHeight\n 'number', // inputWidth\n 'number', // filterId\n 'number', // filterHeight\n 'number', // filterWidth\n 'number', // padTop\n 'number', // padRight\n 'number', // padBottom\n 'number', // padLeft\n 'number', // isSamePad\n 'number', // dilationHeight\n 'number', // dilationWidth\n 'number', // strideHeight\n 'number', // strideWidth\n 'number', // inputChannels\n 'number', // outputChannels\n 'number', // outId\n ]);\n}\n\nfunction conv2d(\n args: {inputs: Conv2DInputs, backend: BackendWasm, attrs: Conv2DAttrs}) {\n const {inputs, attrs, backend} = args;\n\n const {x, filter} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n const filterId = backend.dataIdMap.get(filter.dataId).id;\n\n const {strides, dilations, pad, dimRoundingMode, dataFormat} = attrs;\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n (x as Tensor4D).shape, (filter as Tensor4D).shape, strides, dilations,\n pad, dimRoundingMode, false, $dataFormat);\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const padTop = convInfo.padInfo.top;\n const padRight = convInfo.padInfo.right;\n const padBottom = convInfo.padInfo.bottom;\n const padLeft = convInfo.padInfo.left;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const inputChannels = convInfo.inChannels;\n const outputChannels = convInfo.outChannels;\n const isSamePad = convInfo.padInfo.type === 'SAME' ? 1 : 0;\n\n if (convInfo.dataFormat !== 'channelsLast') {\n throw new Error(\n `wasm backend Conv2D does not support dataFormat:'` +\n `${convInfo.dataFormat}'. Please use 'channelsLast'.`);\n }\n\n const out = backend.makeOutput(convInfo.outShape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmConv2d(\n xId, x.shape[0], x.shape[1], x.shape[2], filterId, filterHeight,\n filterWidth, padTop, padRight, padBottom, padLeft, isSamePad,\n dilationHeight, dilationWidth, strideHeight, strideWidth, inputChannels,\n outputChannels, outId);\n return out;\n}\n\nexport const conv2DConfig: KernelConfig = {\n kernelName: Conv2D,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: conv2d as {} 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, Conv2DBackpropInput, Conv2DBackpropInputAttrs, Conv2DBackpropInputInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmConv2DBackpropInput: (\n dyId: number, filterId: number, batchSize: number, filterHeight: number,\n filterWidth: number, inHeight: number, inWidth: number, inChannels: number,\n outHeight: number, outWidth: number, outChannels: number,\n strideHeight: number, strideWidth: number, topPad: number, leftPad: number,\n fltS0: number, fltS1: number, fltS2: number, xBatchStride: number,\n xRowStride: number, xColStride: number, xChannelStride: number,\n yBatchStride: number, yRowStride: number, yColStride: number,\n yChannelStride: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmConv2DBackpropInput = backend.wasm.cwrap(Conv2DBackpropInput, null, [\n 'number', // dyId\n 'number', // filterId\n 'number', // batchSize\n 'number', // filterHeight\n 'number', // filterWidth\n 'number', // inHeight\n 'number', // inWidth\n 'number', // inChannels\n 'number', // outHeight\n 'number', // outWidth\n 'number', // outChannels\n 'number', // strideHeight\n 'number', // strideWidth\n 'number', // topPad\n 'number', // leftPad\n 'number', // fltS0\n 'number', // fltS1\n 'number', // fltS2\n 'number', // xBatchStride\n 'number', // xRowStride\n 'number', // xColStride\n 'number', // xChannelStride\n 'number', // yBatchStride\n 'number', // yRowStride\n 'number', // yColStride\n 'number', // yChannelStride\n 'number', // outId\n ]);\n}\n\nfunction conv2DBackpropInput(args: {\n backend: BackendWasm,\n inputs: Conv2DBackpropInputInputs,\n attrs: Conv2DBackpropInputAttrs\n}): TensorInfo {\n const {backend, inputs, attrs} = args;\n const {dy, filter} = inputs;\n const {strides, pad, dataFormat, dimRoundingMode, inputShape} = attrs;\n\n const dilations = 1;\n\n const $dataFormat = backend_util.convertConv2DDataFormat(dataFormat);\n const convInfo = backend_util.computeConv2DInfo(\n inputShape, filter.shape as [number, number, number, number], strides,\n dilations, pad, dimRoundingMode, false /* depthwise */, $dataFormat);\n const {\n batchSize,\n filterHeight,\n filterWidth,\n inChannels,\n inHeight,\n inWidth,\n outChannels,\n outHeight,\n outWidth,\n strideHeight,\n strideWidth\n } = convInfo;\n\n const topPad = filterHeight - 1 - convInfo.padInfo.top;\n const leftPad = filterWidth - 1 - convInfo.padInfo.left;\n\n const isChannelsLast = convInfo.dataFormat === 'channelsLast';\n const dxStrides = util.computeStrides(convInfo.inShape);\n const dyStrides = util.computeStrides(dy.shape);\n const [fltS0, fltS1, fltS2] = util.computeStrides(filter.shape);\n const xBatchStride = dxStrides[0];\n const xRowStride = isChannelsLast ? dxStrides[1] : dxStrides[2];\n const xColStride = isChannelsLast ? dxStrides[2] : 1;\n const xChannelStride = isChannelsLast ? 1 : dxStrides[1];\n const yBatchStride = dyStrides[0];\n const yRowStride = isChannelsLast ? dyStrides[1] : dyStrides[2];\n const yColStride = isChannelsLast ? dyStrides[2] : 1;\n const yChannelStride = isChannelsLast ? 1 : dyStrides[1];\n\n const out = backend.makeOutput(convInfo.inShape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n const dyId = backend.dataIdMap.get(dy.dataId).id;\n const filterId = backend.dataIdMap.get(filter.dataId).id;\n\n wasmConv2DBackpropInput(\n dyId, filterId, batchSize, filterHeight, filterWidth, inHeight, inWidth,\n inChannels, outHeight, outWidth, outChannels, strideHeight, strideWidth,\n topPad, leftPad, fltS0, fltS1, fltS2, xBatchStride, xRowStride,\n xColStride, xChannelStride, yBatchStride, yRowStride, yColStride,\n yChannelStride, outId);\n return out;\n}\n\nexport const conv2DBackpropInputConfig: KernelConfig = {\n kernelName: Conv2DBackpropInput,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: conv2DBackpropInput as {} 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 {Cos, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\n\nexport const cosConfig: KernelConfig = createUnaryKernelConfig(Cos);\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 {Cosh, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\n\nexport const coshConfig: KernelConfig = createUnaryKernelConfig(Cosh);\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 {CropAndResize, CropAndResizeAttrs, CropAndResizeInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {cast} from './Cast';\n\n// Must match enum in CropAndResize.cc\nenum InterpolationMethod {\n bilinear = 0,\n nearest = 1\n}\n\nlet wasmCropAndResize: (\n imagesId: number, boxesId: number, boxIndId: number, numBoxes: number,\n imagesShape: Uint8Array, cropHeight: number, cropWidth: number,\n method: number, extrapolationValue: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmCropAndResize = backend.wasm.cwrap(CropAndResize, null /*void*/, [\n 'number', // imagesId\n 'number', // boxesId\n 'number', // boxIndId\n 'number', // numBoxes\n 'array', // images shape\n 'number', // cropHeight\n 'number', // cropWidth\n 'number', // method\n 'number', // extrapolation value\n 'number' // out id\n ]);\n}\n\nfunction cropAndResize(args: {\n backend: BackendWasm,\n inputs: CropAndResizeInputs,\n attrs: CropAndResizeAttrs\n}): TensorInfo {\n const {backend, inputs, attrs} = args;\n const {method, extrapolationValue, cropSize} = attrs;\n const {image, boxes, boxInd} = inputs;\n\n const numBoxes = boxes.shape[0];\n\n const [cropHeight, cropWidth] = cropSize as [number, number];\n const outShape = [numBoxes, cropHeight, cropWidth, image.shape[3]];\n\n let imagesData = backend.dataIdMap.get(image.dataId);\n let castedData;\n if (image.dtype !== 'float32') {\n castedData = cast({backend, inputs: {x: image}, attrs: {dtype: 'float32'}});\n imagesData = backend.dataIdMap.get(castedData.dataId);\n }\n\n const imagesId = imagesData.id;\n const boxesId = backend.dataIdMap.get(boxes.dataId).id;\n const boxIndId = backend.dataIdMap.get(boxInd.dataId).id;\n\n const out = backend.makeOutput(outShape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const imagesShapeBytes = new Uint8Array(new Int32Array(image.shape).buffer);\n\n wasmCropAndResize(\n imagesId, boxesId, boxIndId, numBoxes, imagesShapeBytes, cropHeight,\n cropWidth,\n InterpolationMethod[method as {} as keyof typeof InterpolationMethod],\n extrapolationValue, outId);\n\n if (castedData != null) {\n backend.disposeData(castedData.dataId);\n }\n\n return out;\n}\n\nexport const cropAndResizeConfig: KernelConfig = {\n kernelName: CropAndResize,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: cropAndResize as {} 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, Cumsum, CumsumAttrs, CumsumInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {CppDType} from './types';\n\nimport {transpose} from './Transpose';\n\nlet wasmCumsum: (xId: number, exclusive: number, reverse: number,\n finalDim: number, outId: number, dtype: CppDType) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmCumsum = backend.wasm.cwrap(Cumsum, null /* void */, [\n 'number', // x_id\n 'number', // exclusive\n 'number', // reverse\n 'number', // final_dim\n 'number', // out_id\n 'number' // dtype\n ]);\n}\n\nexport function cumsum(\n args: {inputs: CumsumInputs, backend: BackendWasm, attrs: CumsumAttrs}):\nTensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {axis, exclusive, reverse} = attrs;\n const xRank = x.shape.length;\n\n util.assert(x.dtype === 'float32' || x.dtype === 'int32',\n () => `cumsum does not support ${x.dtype} tensors in the WASM backend`);\n // permute required axis to inner most axis\n const permutation = backend_util.getAxesPermutation([axis], xRank);\n let permutedX = x;\n if (permutation !== null) {\n permutedX = transpose({inputs: {x}, attrs: {perm: permutation}, backend});\n }\n const permutedAxis = backend_util.getInnerMostAxes(1, xRank)[0];\n backend_util.assertAxesAreInnerMostDims('cumsum', [permutedAxis], xRank);\n\n const permutedOut = backend.makeOutput(permutedX.shape, permutedX.dtype);\n const finalDim = permutedX.shape[permutedAxis];\n const permutedXId = backend.dataIdMap.get(permutedX.dataId).id;\n const permutedOutId = backend.dataIdMap.get(permutedOut.dataId).id;\n wasmCumsum(permutedXId, exclusive ? 1 : 0, reverse ? 1 : 0, finalDim,\n permutedOutId, CppDType[x.dtype]);\n\n // transpose data back if permuted\n let out = permutedOut;\n if (permutation !== null) {\n const undoPermutation = backend_util.getUndoAxesPermutation(permutation);\n out = transpose(\n {inputs: {x: permutedOut}, attrs: {perm: undoPermutation}, backend});\n backend.disposeData(permutedX.dataId);\n backend.disposeData(permutedOut.dataId);\n }\n return out;\n}\n\nexport const cumsumConfig: KernelConfig = {\n kernelName: Cumsum,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: cumsum as {} 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 {DepthToSpace, DepthToSpaceAttrs, DepthToSpaceInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmDepthToSpace: (\n xId: number, blockSize: number, channelsLast: number, xStrides: Uint8Array,\n xStridesLength: number, outputShape: Uint8Array, outputStrides: Uint8Array,\n outSize: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmDepthToSpace = backend.wasm.cwrap(DepthToSpace, null /*void*/, [\n 'number', // xId\n 'number', // blockSize\n 'number', // channelsLast\n 'array', // xStrides\n 'number', // xStridesLength\n 'array', // outputShape\n 'array', // outputStrides\n 'number', // outSize\n 'number', // outId\n ]);\n}\n\nexport function depthToSpace(args: {\n backend: BackendWasm,\n inputs: DepthToSpaceInputs,\n attrs: DepthToSpaceAttrs\n}): TensorInfo {\n const {backend, inputs, attrs} = args;\n const {x} = inputs;\n const {blockSize, dataFormat} = attrs;\n\n util.assert(\n blockSize > 1,\n () => `blockSize should be > 1 for depthToSpace, but was: ${blockSize}`);\n\n const batchSize = x.shape[0];\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 const outputHeight = inputHeight * blockSize;\n const outputWidth = inputWidth * blockSize;\n const outputDepth = inputDepth / (blockSize * blockSize);\n\n const outputShape = (dataFormat === 'NHWC') ?\n [batchSize, outputHeight, outputWidth, outputDepth] :\n [batchSize, outputDepth, outputHeight, outputWidth];\n\n const out = backend.makeOutput(outputShape, 'float32');\n\n const xData = backend.dataIdMap.get(x.dataId);\n const xId = xData.id;\n const xStridesBytes =\n new Uint8Array(new Int32Array(util.computeStrides(x.shape)).buffer);\n\n const outputShapeBytes = new Uint8Array(new Int32Array(outputShape).buffer);\n const outStridesBytes =\n new Uint8Array(new Int32Array(util.computeStrides(outputShape)).buffer);\n\n const outId = backend.dataIdMap.get(out.dataId).id;\n const channelsLast = dataFormat === 'NHWC' ? 1 : 0;\n wasmDepthToSpace(\n xId, blockSize, channelsLast, xStridesBytes, x.shape.length - 1,\n outputShapeBytes, outStridesBytes, outputShape.length, outId);\n\n return out;\n}\n\nexport const depthToSpaceConfig: KernelConfig = {\n kernelName: DepthToSpace,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: depthToSpace as {} 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 {backend_util, DepthwiseConv2dNative, DepthwiseConv2dNativeAttrs, DepthwiseConv2dNativeInputs, KernelConfig, KernelFunc, Tensor4D} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmDepthwiseConv2d: (\n xId: number, batchSize: number, inputHeight: number, inputWidth: number,\n filterId: number, filterHeight: number, filterWidth: number, padTop: number,\n padRight: number, padBottom: number, padLeft: number, isSamePad: number,\n dilationHeight: number, dilationWidth: number, strideHeight: number,\n strideWidth: number, inputChannels: number, outputChannels: number,\n outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmDepthwiseConv2d =\n backend.wasm.cwrap(DepthwiseConv2dNative, null /* void */, [\n 'number', // xId\n 'number', // batchSize\n 'number', // inputHeight\n 'number', // inputWidth\n 'number', // filterId\n 'number', // filterHeight\n 'number', // filterWidth\n 'number', // padTop\n 'number', // padRight\n 'number', // padBottom\n 'number', // padLeft\n 'number', // isSamePad\n 'number', // dilationHeight\n 'number', // dilationWidth\n 'number', // strideHeight\n 'number', // strideWidth\n 'number', // inputChannels\n 'number', // outputChannels\n 'number', // outId\n ]);\n}\n\nfunction depthwiseConv2d(args: {\n inputs: DepthwiseConv2dNativeInputs,\n backend: BackendWasm,\n attrs: DepthwiseConv2dNativeAttrs\n}) {\n const {inputs, attrs, backend} = args;\n\n const {x, filter} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n const filterId = backend.dataIdMap.get(filter.dataId).id;\n\n const {strides, dilations, pad, dimRoundingMode} = attrs;\n\n const $dilations = dilations == null ? [1, 1] : dilations;\n\n const convInfo = backend_util.computeConv2DInfo(\n (x as Tensor4D).shape, (filter as Tensor4D).shape, strides,\n ($dilations as number | [number, number]), pad, dimRoundingMode,\n true /* depthwise */);\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const padTop = convInfo.padInfo.top;\n const padRight = convInfo.padInfo.right;\n const padBottom = convInfo.padInfo.bottom;\n const padLeft = convInfo.padInfo.left;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const inputChannels = convInfo.inChannels;\n const outputChannels = convInfo.outChannels;\n const isSamePad = convInfo.padInfo.type === 'SAME' ? 1 : 0;\n\n if (convInfo.dataFormat !== 'channelsLast') {\n throw new Error(\n `wasm backend DepthwiseConv2dNative does not support dataFormat:'` +\n `${convInfo.dataFormat}'. Please use 'channelsLast'.`);\n }\n\n const out = backend.makeOutput(convInfo.outShape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmDepthwiseConv2d(\n xId, x.shape[0], x.shape[1], x.shape[2], filterId, filterHeight,\n filterWidth, padTop, padRight, padBottom, padLeft, isSamePad,\n dilationHeight, dilationWidth, strideHeight, strideWidth, inputChannels,\n outputChannels, outId);\n return out;\n}\n\nexport const depthwiseConv2dNativeConfig: KernelConfig = {\n kernelName: DepthwiseConv2dNative,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: depthwiseConv2d as {} 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 */\nimport {Equal, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\n\nconst supportsFullBroadcast = false;\nexport const equalConfig: KernelConfig =\n createBinaryKernelConfig(Equal, supportsFullBroadcast, 'bool');\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 {Exp, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\n\nexport const expConfig: KernelConfig = createUnaryKernelConfig(Exp);\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 {ExpandDims, ExpandDimsAttrs, ExpandDimsInputs, KernelConfig, KernelFunc, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\nimport {reshape} from './Reshape';\n\nexport function expandDims(args: {\n inputs: ExpandDimsInputs,\n attrs: ExpandDimsAttrs,\n backend: BackendWasm\n}) {\n const {inputs, attrs, backend} = 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: 'wasm',\n kernelFunc: expandDims as {} 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} from '@tensorflow/tfjs-core';\nimport {Fill, FillAttrs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nfunction fill(args: {attrs: FillAttrs, backend: BackendWasm}) {\n const {attrs: {shape, value, dtype}, backend} = args;\n const out = backend.makeOutput(shape, dtype);\n const outVals = backend.typedArrayFromHeap(out);\n outVals.fill(value as number);\n return out;\n}\n\nexport const fillConfig: KernelConfig = {\n kernelName: Fill,\n backendName: 'wasm',\n kernelFunc: fill as {} 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 {FlipLeftRight, FlipLeftRightInputs, KernelConfig, KernelFunc, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmFlipLeftRight: (\n xId: number, batch: number, imageHeight: number, imageWidth: number,\n numChannels: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmFlipLeftRight = backend.wasm.cwrap(FlipLeftRight, null /* void */, [\n 'number', // xId\n 'number', // batch\n 'number', // imageHeight\n 'number', // imageWidth\n 'number', // numChannels\n 'number', // outId\n ]);\n}\n\nexport function flipLeftRight(\n args: {inputs: FlipLeftRightInputs, backend: BackendWasm}): TensorInfo {\n const {inputs, backend} = args;\n const {image} = inputs;\n\n const out = backend.makeOutput(image.shape, image.dtype);\n const imageId = backend.dataIdMap.get(image.dataId).id;\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n\n wasmFlipLeftRight(\n imageId, batch, imageHeight, imageWidth, numChannels, outId);\n return out;\n}\n\nexport const flipLeftRightConfig: KernelConfig = {\n kernelName: FlipLeftRight,\n backendName: 'wasm',\n kernelFunc: flipLeftRight as {} as KernelFunc,\n setupFunc: setup\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 {Floor, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const floorConfig: KernelConfig = createUnaryKernelConfig(Floor);\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 {FloorDiv, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\n\nconst supportsFullBroadcast = false;\nexport const floorDivConfig: KernelConfig =\n createBinaryKernelConfig(FloorDiv, supportsFullBroadcast);\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 {FusedBatchNorm, FusedBatchNormAttrs, FusedBatchNormInputs, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmBatchNorm: (\n xId: number, meanId: number, varianceId: number, offsetId: number,\n scaleId: number, varianceEpsilon: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmBatchNorm = backend.wasm.cwrap(\n FusedBatchNorm, null /* void */,\n ['number', 'number', 'number', 'number', 'number', 'number', 'number']);\n}\n\nfunction fusedBatchNorm(args: {\n backend: BackendWasm,\n inputs: FusedBatchNormInputs,\n attrs: FusedBatchNormAttrs\n}): TensorInfo {\n const {backend, inputs, attrs} = args;\n const {varianceEpsilon} = attrs;\n const {x, mean, variance, offset, scale} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n const meanId = backend.dataIdMap.get(mean.dataId).id;\n const varianceId = backend.dataIdMap.get(variance.dataId).id;\n const offsetId = offset != null ? backend.dataIdMap.get(offset.dataId).id : 0;\n const scaleId = scale != null ? backend.dataIdMap.get(scale.dataId).id : 0;\n\n const out = backend.makeOutput(x.shape, x.dtype);\n // Short-circuit zero-sized tensors.\n if (util.sizeFromShape(x.shape) === 0) {\n return out;\n }\n\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n wasmBatchNorm(\n xId, meanId, varianceId, offsetId, scaleId, varianceEpsilon, outId);\n return out;\n}\n\nexport const fusedBatchNormConfig: KernelConfig = {\n kernelName: FusedBatchNorm,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: fusedBatchNorm as {} 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 {backend_util, FusedConv2D, FusedConv2DAttrs, FusedConv2DInputs, KernelConfig, KernelFunc, Tensor4D} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {FusableActivation} from './types';\n\nlet wasmFusedConv2d:\n (xId: number, batchSize: number, inputHeight: number, inputWidth: number,\n filterId: number, filterHeight: number, filterWidth: number,\n biasId: number, padTop: number, padRight: number, padBottom: number,\n padLeft: number, isSamePad: number, dilationHeight: number,\n dilationWidth: number, strideHeight: number, strideWidth: number,\n inputChannels: number, outputChannels: number, activation: number,\n preluActivationWeightsId: number, leakyreluAlpha: number, outId: number) =>\n void;\n\nfunction setup(backend: BackendWasm) {\n wasmFusedConv2d = backend.wasm.cwrap(FusedConv2D, null /* void */, [\n 'number', // xId\n 'number', // batchSize\n 'number', // inputHeight\n 'number', // inputWidth\n 'number', // filterId\n 'number', // filterHeight\n 'number', // filterWidth\n 'number', // biasId\n 'number', // padTop\n 'number', // padRight\n 'number', // padBottom\n 'number', // padLeft\n 'number', // isSamePad\n 'number', // dilationHeight\n 'number', // dilationWidth\n 'number', // strideHeight\n 'number', // strideWidth\n 'number', // inputChannels\n 'number', // outputChannels\n 'number', // activation\n 'number', // preluActivationWeightsId\n 'number', // leakyreluAlpha\n 'number', // outId\n ]);\n}\n\nfunction fusedConv2d(args: {\n inputs: FusedConv2DInputs,\n backend: BackendWasm,\n attrs: FusedConv2DAttrs\n}) {\n const {inputs, attrs, backend} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {\n strides,\n pad,\n dilations,\n dataFormat,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n } = attrs;\n\n const convInfo = backend_util.computeConv2DInfo(\n (x as Tensor4D).shape, (filter as Tensor4D).shape, strides, dilations,\n pad, dimRoundingMode);\n\n const fusedActivation =\n FusableActivation[activation as {} as keyof typeof FusableActivation];\n if (fusedActivation == null) {\n throw new Error(\n `${activation} activation not yet supported for FusedConv2D ` +\n `in the wasm backend.`);\n }\n\n const xId = backend.dataIdMap.get(x.dataId).id;\n const filterId = backend.dataIdMap.get(filter.dataId).id;\n\n const outputChannels = convInfo.outChannels;\n\n let biasId = 0;\n if (bias != null) {\n const biasData = backend.dataIdMap.get(bias.dataId);\n if (biasData.shape.length !== 1) {\n throw new Error(\n `FusedConv2D only supports rank-1 bias but got ` +\n `rank ${biasData.shape.length}.`);\n }\n if (biasData.shape[0] !== outputChannels) {\n throw new Error(\n `FusedConv2D bias shape (${biasData.shape}) does not ` +\n `match the number of output channels (${outputChannels})`);\n }\n biasId = biasData.id;\n }\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const padTop = convInfo.padInfo.top;\n const padRight = convInfo.padInfo.right;\n const padBottom = convInfo.padInfo.bottom;\n const padLeft = convInfo.padInfo.left;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const inputChannels = convInfo.inChannels;\n const isSamePad = convInfo.padInfo.type === 'SAME' ? 1 : 0;\n const batchSize = convInfo.batchSize;\n const inHeight = convInfo.inHeight;\n const inWidth = convInfo.inWidth;\n\n if (dataFormat !== 'NHWC') {\n throw new Error(\n `wasm backend FusedConv2D does not support dataFormat:'` +\n `${dataFormat}'. Please use 'NHWC'.`);\n }\n\n const out = backend.makeOutput(convInfo.outShape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n const preluActivationWeightsId = preluActivationWeights == null ?\n 0 :\n backend.dataIdMap.get(preluActivationWeights.dataId).id;\n\n wasmFusedConv2d(\n xId, batchSize, inHeight, inWidth, filterId, filterHeight, filterWidth,\n biasId, padTop, padRight, padBottom, padLeft, isSamePad, dilationHeight,\n dilationWidth, strideHeight, strideWidth, inputChannels, outputChannels,\n fusedActivation, preluActivationWeightsId, leakyreluAlpha || 0, outId);\n\n return out;\n}\n\nexport const fusedConv2DConfig: KernelConfig = {\n kernelName: FusedConv2D,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: fusedConv2d as {} 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 {backend_util, FusedDepthwiseConv2D, FusedDepthwiseConv2DAttrs, FusedDepthwiseConv2DInputs, KernelConfig, KernelFunc, Tensor4D} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {FusableActivation} from './types';\n\nlet wasmFusedDepthwiseConv2d:\n (xId: number, batchSize: number, inputHeight: number, inputWidth: number,\n filterId: number, filterHeight: number, filterWidth: number,\n biasId: number, padTop: number, padRight: number, padBottom: number,\n padLeft: number, isSamePad: number, dilationHeight: number,\n dilationWidth: number, strideHeight: number, strideWidth: number,\n inputChannels: number, outputChannels: number, activation: number,\n preluActivationWeightsId: number, leakyreluAlpha: number, outId: number) =>\n void;\n\nfunction setup(backend: BackendWasm) {\n wasmFusedDepthwiseConv2d =\n backend.wasm.cwrap(FusedDepthwiseConv2D, null /* void */, [\n 'number', // xId\n 'number', // batchSize\n 'number', // inputHeight\n 'number', // inputWidth\n 'number', // filterId\n 'number', // filterHeight\n 'number', // filterWidth\n 'number', // biasId\n 'number', // padTop\n 'number', // padRight\n 'number', // padBottom\n 'number', // padLeft\n 'number', // isSamePad\n 'number', // dilationHeight\n 'number', // dilationWidth\n 'number', // strideHeight\n 'number', // strideWidth\n 'number', // inputChannels\n 'number', // outputChannels\n 'number', // activation\n 'number', // preluActivationWeightsId\n 'number', // leakyreluAlpha\n 'number', // outId\n ]);\n}\n\nfunction fusedDepthwiseConv2d(args: {\n inputs: FusedDepthwiseConv2DInputs,\n backend: BackendWasm,\n attrs: FusedDepthwiseConv2DAttrs\n}) {\n const {inputs, attrs, backend} = args;\n const {x, filter, bias, preluActivationWeights} = inputs;\n const {\n strides,\n pad,\n dilations,\n dataFormat,\n dimRoundingMode,\n activation,\n leakyreluAlpha\n } = attrs;\n\n const convInfo = backend_util.computeConv2DInfo(\n (x as Tensor4D).shape, (filter as Tensor4D).shape, strides, dilations,\n pad, dimRoundingMode, true /* depthwise */);\n\n const fusedActivation =\n FusableActivation[activation as {} as keyof typeof FusableActivation];\n if (fusedActivation == null) {\n throw new Error(\n `${activation} activation not yet supported for FusedDepthwiseConv2D ` +\n `in the wasm backend.`);\n }\n\n const xId = backend.dataIdMap.get(x.dataId).id;\n const filterId = backend.dataIdMap.get(filter.dataId).id;\n\n const outputChannels = convInfo.outChannels;\n\n let biasId = 0;\n if (bias != null) {\n const biasData = backend.dataIdMap.get(bias.dataId);\n if (biasData.shape.length !== 1) {\n throw new Error(\n `FusedDepthwiseConv2D only supports rank-1 bias but got ` +\n `rank ${biasData.shape.length}.`);\n }\n if (biasData.shape[0] !== outputChannels) {\n throw new Error(\n `FusedDepthwiseConv2D bias shape (${biasData.shape}) does not ` +\n `match the number of output channels (${outputChannels})`);\n }\n biasId = biasData.id;\n }\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const padTop = convInfo.padInfo.top;\n const padRight = convInfo.padInfo.right;\n const padBottom = convInfo.padInfo.bottom;\n const padLeft = convInfo.padInfo.left;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const inputChannels = convInfo.inChannels;\n const isSamePad = convInfo.padInfo.type === 'SAME' ? 1 : 0;\n const batchSize = convInfo.batchSize;\n const inHeight = convInfo.inHeight;\n const inWidth = convInfo.inWidth;\n\n if (dataFormat !== 'NHWC') {\n throw new Error(\n `wasm backend FusedDepthwiseConv2D does not support dataFormat:'` +\n `${dataFormat}'. Please use 'NHWC'.`);\n }\n\n const out = backend.makeOutput(convInfo.outShape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n const preluActivationWeightsId = preluActivationWeights == null ?\n 0 :\n backend.dataIdMap.get(preluActivationWeights.dataId).id;\n\n wasmFusedDepthwiseConv2d(\n xId, batchSize, inHeight, inWidth, filterId, filterHeight, filterWidth,\n biasId, padTop, padRight, padBottom, padLeft, isSamePad, dilationHeight,\n dilationWidth, strideHeight, strideWidth, inputChannels, outputChannels,\n fusedActivation, preluActivationWeightsId, leakyreluAlpha || 0, outId);\n\n return out;\n}\n\nexport const fusedDepthwiseConv2DConfig: KernelConfig = {\n kernelName: FusedDepthwiseConv2D,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: fusedDepthwiseConv2d as {} 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 {gather_util, GatherNd, GatherNdInputs, KernelConfig, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {CppDType} from './types';\n\nlet wasmGatherNd: (\n xId: number, dtype: CppDType, indicesId: number, numSlices: number,\n sliceRank: number, sliceSize: number, strides: Uint8Array, outId: number) =>\n void;\n\nfunction setup(backend: BackendWasm): void {\n wasmGatherNd = backend.wasm.cwrap(GatherNd, null /*void*/, [\n 'number', // xId\n 'number', // dtype\n 'number', // indicesId\n 'number', // numSlices\n 'number', // sliceRank\n 'number', // sliceSize\n 'array', // strides\n 'number' // outId\n ]);\n}\n\nfunction gatherNd(args: {backend: BackendWasm, inputs: GatherNdInputs}):\n TensorInfo {\n const {backend, inputs} = args;\n const {params, indices} = inputs;\n\n const [resultShape, numSlices, sliceSize, strides] =\n gather_util.prepareAndValidate(params, indices);\n\n const out = backend.makeOutput(resultShape, params.dtype);\n if (numSlices === 0) {\n return out;\n }\n\n const indicesShape = indices.shape;\n const sliceRank = indicesShape[indicesShape.length - 1];\n\n const xData = backend.dataIdMap.get(params.dataId);\n const xId = xData.id;\n const indicesData = backend.dataIdMap.get(indices.dataId);\n const indicesId = indicesData.id;\n\n const stridesBytes = new Uint8Array(new Int32Array(strides).buffer);\n\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmGatherNd(\n xId, CppDType[params.dtype], indicesId, numSlices, sliceRank, sliceSize,\n stridesBytes, outId);\n\n return out;\n}\n\nexport const gatherNdConfig: KernelConfig = {\n kernelName: GatherNd,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: gatherNd\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 {backend_util, GatherV2, GatherV2Attrs, GatherV2Inputs, KernelConfig, KernelFunc, Tensor, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {reshape} from './Reshape';\nimport {CppDType} from './types';\n\nlet wasmGather: (\n xId: number, dtype: CppDType, xStrides: Uint8Array, stridesSize: number,\n indicesId: number, batchSize: number, outStrides: Uint8Array,\n outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmGather = backend.wasm.cwrap('Gather', null /*void*/, [\n 'number', // xId\n 'number', // dtype\n 'array', // xStrides\n 'number', // stridesSize\n 'number', // indicesId\n 'number', // batchSize\n 'array', // outStrides\n 'number' // outId\n ]);\n}\n\nfunction gatherV2(\n args: {backend: BackendWasm, inputs: GatherV2Inputs, attrs: GatherV2Attrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {x, indices} = inputs;\n const {axis, batchDims} = attrs;\n\n const parsedAxis = util.parseAxisParam(axis, x.shape)[0];\n const shapeInfo = backend_util.segment_util.collectGatherOpShapeInfo(\n x as Tensor, indices as Tensor, parsedAxis, batchDims);\n\n const flattenX = reshape({\n inputs: {x},\n attrs: {\n shape: [\n shapeInfo.batchSize, shapeInfo.outerSize, shapeInfo.dimSize,\n shapeInfo.sliceSize\n ]\n },\n backend\n });\n const indicesSize = util.sizeFromShape(indices.shape);\n const flattenIndex = reshape({\n inputs: {x: indices},\n attrs: {shape: [shapeInfo.batchSize, indicesSize / shapeInfo.batchSize]},\n backend\n });\n const flattenOutputShape = [\n shapeInfo.batchSize, shapeInfo.outerSize, indicesSize / shapeInfo.batchSize,\n shapeInfo.sliceSize\n ];\n\n const out = backend.makeOutput(flattenOutputShape, x.dtype);\n if (util.sizeFromShape(x.shape) === 0) {\n return out;\n }\n const stridesSize = flattenX.shape.length - 1;\n\n const xData = backend.dataIdMap.get(flattenX.dataId);\n const xId = xData.id;\n\n const indicesData = backend.dataIdMap.get(flattenIndex.dataId);\n const indicesId = indicesData.id;\n\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const xStridesBytes = new Uint8Array(\n new Int32Array(util.computeStrides(flattenX.shape)).buffer);\n const outStridesBytes = new Uint8Array(\n new Int32Array(util.computeStrides(flattenOutputShape)).buffer);\n\n wasmGather(\n xId, CppDType[x.dtype], xStridesBytes, stridesSize, indicesId,\n shapeInfo.batchSize, outStridesBytes, outId);\n\n backend.disposeData(flattenX.dataId);\n backend.disposeData(flattenIndex.dataId);\n\n // reshape\n out.shape = shapeInfo.outputShape;\n return out;\n}\n\nexport const gatherV2Config: KernelConfig = {\n kernelName: GatherV2,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: gatherV2 as {} 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 */\nimport {Greater, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\n\nconst supportsFullBroadcast = false;\nexport const greaterConfig: KernelConfig =\n createBinaryKernelConfig(Greater, supportsFullBroadcast, 'bool');\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 {GreaterEqual, KernelConfig} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\n\nconst supportsFullBroadcast = false;\nexport const greaterEqualConfig: KernelConfig =\n createBinaryKernelConfig(GreaterEqual, supportsFullBroadcast, 'bool');\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 {KernelConfig, KernelFunc, LeakyRelu, LeakyReluAttrs, LeakyReluInputs, util} from '@tensorflow/tfjs-core';\nimport {TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmFunc: (xId: number, leakyreluAlpha: number, outId: number) => void;\n\nfunction setupFunc(backend: BackendWasm): void {\n wasmFunc = backend.wasm.cwrap(LeakyRelu, null /* void */, [\n 'number', // x_id,\n 'number', // leakyrelu_alpha\n 'number' // out_id\n ]);\n}\n\nexport function leakyRelu(\n args:\n {inputs: LeakyReluInputs, attrs: LeakyReluAttrs, backend: BackendWasm}):\n TensorInfo {\n const {inputs: {x}, attrs: {alpha}, backend} = args;\n\n const xId = backend.dataIdMap.get(x.dataId).id;\n const out = backend.makeOutput(x.shape, x.dtype);\n\n if (util.sizeFromShape(x.shape) !== 0) {\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmFunc(xId, alpha, outId);\n }\n\n return out;\n}\n\nexport const leakyReluConfig: KernelConfig = {\n kernelName: LeakyRelu,\n backendName: 'wasm',\n setupFunc,\n kernelFunc: leakyRelu as {} 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 */\nimport {KernelConfig, Less} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = false;\nexport const lessConfig: KernelConfig =\n createBinaryKernelConfig(Less, supportsFullBroadcast, 'bool');\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 {KernelConfig, LessEqual} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = false;\nexport const lessEqualConfig: KernelConfig =\n createBinaryKernelConfig(LessEqual, supportsFullBroadcast, 'bool');\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 {KernelConfig, Log} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const logConfig: KernelConfig = createUnaryKernelConfig(Log);\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 {KernelConfig, LogicalAnd} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = false;\nexport const logicalAndConfig: KernelConfig =\n createBinaryKernelConfig(LogicalAnd, supportsFullBroadcast, 'bool');\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 {backend_util, KernelConfig, KernelFunc, TensorInfo, util} from '@tensorflow/tfjs-core';\nimport {Max, MaxAttrs, MaxInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {permuteAxesAndTranspose} from './kernel_utils';\n\nlet wasmMax: (xId: number, reduceSize: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmMax = backend.wasm.cwrap(Max, null /*void*/, ['number, number, number']);\n}\n\nfunction max(args: {backend: BackendWasm, inputs: MaxInputs, attrs: MaxAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {reductionIndices: axis, keepDims} = attrs;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n let inputId = xId;\n let input = x;\n\n const {transposed, axes, originalAxes, inputWasTransposed} =\n permuteAxesAndTranspose(x, axis, backend);\n\n if (inputWasTransposed) {\n const transposedId = backend.dataIdMap.get(transposed.dataId).id;\n input = transposed;\n inputId = transposedId;\n }\n\n const inputRank = input.shape.length;\n backend_util.assertAxesAreInnerMostDims('max', axes, inputRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(input.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const out = backend.makeOutput(outShape, x.dtype);\n if (util.sizeFromShape(input.shape) !== 0) {\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmMax(inputId, reduceSize, outId);\n }\n\n if (inputWasTransposed) {\n // dispose of the transposed tensor.\n backend.disposeData(transposed.dataId);\n }\n\n if (keepDims) {\n // reshape\n const newShape = backend_util.expandShapeToKeepDim(out.shape, originalAxes);\n out.shape = newShape;\n }\n\n return out;\n}\n\nexport const maxConfig: KernelConfig = {\n kernelName: Max,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: max as {} 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 */\nimport {KernelConfig, Maximum} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = false;\nexport const maximumConfig: KernelConfig =\n createBinaryKernelConfig(Maximum, supportsFullBroadcast);\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 {backend_util, KernelConfig, KernelFunc, MaxPool, MaxPoolAttrs, MaxPoolInputs, Tensor4D} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmMaxPool: (\n xId: number, batchSize: number, inputHeight: number, inputWidth: number,\n filterHeight: number, filterWidth: number, padTop: number, padRight: number,\n padBottom: number, padLeft: number, dilationHeight: number,\n dilationWidth: number, strideHeight: number, strideWidth: number,\n inputChannels: number, outputChannels: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmMaxPool = backend.wasm.cwrap(MaxPool, null /* void */, [\n 'number', // xId\n 'number', // batchSize\n 'number', // inputHeight\n 'number', // inputWidth\n 'number', // filterHeight\n 'number', // filterWidth\n 'number', // padTop\n 'number', // padRight\n 'number', // padBottom\n 'number', // padLeft\n 'number', // dilationHeight\n 'number', // dilationWidth\n 'number', // strideHeight\n 'number', // strideWidth\n 'number', // inputChannels\n 'number', // outputChannels\n 'number', // outId\n ]);\n}\n\nfunction maxPool(\n args: {inputs: MaxPoolInputs, backend: BackendWasm, attrs: MaxPoolAttrs}) {\n const {inputs, attrs, backend} = args;\n\n const x = inputs.x as Tensor4D;\n const xId = backend.dataIdMap.get(x.dataId).id;\n\n const {filterSize, strides, pad, dimRoundingMode} = attrs;\n const convInfo = backend_util.computePool2DInfo(\n x.shape, filterSize, strides, 1 /* dilations */, pad, dimRoundingMode);\n\n const filterHeight = convInfo.filterHeight;\n const filterWidth = convInfo.filterWidth;\n const padTop = convInfo.padInfo.top;\n const padRight = convInfo.padInfo.right;\n const padBottom = convInfo.padInfo.bottom;\n const padLeft = convInfo.padInfo.left;\n const dilationHeight = convInfo.dilationHeight;\n const dilationWidth = convInfo.dilationWidth;\n const strideHeight = convInfo.strideHeight;\n const strideWidth = convInfo.strideWidth;\n const inputChannels = convInfo.inChannels;\n const outputChannels = convInfo.outChannels;\n\n if (convInfo.dataFormat !== 'channelsLast') {\n throw new Error(\n `wasm backend does not support dataFormat:'` +\n `${convInfo.dataFormat}'. Please use 'channelsLast'.`);\n }\n\n const out = backend.makeOutput(convInfo.outShape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n wasmMaxPool(\n xId, x.shape[0], x.shape[1], x.shape[2], filterHeight, filterWidth,\n padTop, padRight, padBottom, padLeft, dilationHeight, dilationWidth,\n strideHeight, strideWidth, inputChannels, outputChannels, outId);\n return out;\n}\n\nexport const maxPoolConfig: KernelConfig = {\n kernelName: MaxPool,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: maxPool as {} 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 {BackendWasm} from '../backend_wasm';\nimport {cast} from './Cast';\n\nimport {permuteAxesAndTranspose} from './kernel_utils';\n\nlet wasmMean: (xId: number, reduceSize: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmMean =\n backend.wasm.cwrap(Mean, null /*void*/, ['number, number, number']);\n}\n\nexport function mean(\n args: {backend: BackendWasm, inputs: MeanInputs, attrs: MeanAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {axis, keepDims} = attrs;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n let inputId = xId;\n let input = x;\n\n const {transposed, axes, originalAxes, inputWasTransposed} =\n permuteAxesAndTranspose(x, axis, backend);\n\n let reductionAxes = axes;\n if (inputWasTransposed) {\n const transposedId = backend.dataIdMap.get(transposed.dataId).id;\n if (transposedId !== xId) {\n // transpose was not a no-op. We will need to dispose of this\n // once we are done.\n input = transposed;\n inputId = transposedId;\n reductionAxes = backend_util.getInnerMostAxes(\n reductionAxes.length, input.shape.length);\n }\n }\n\n backend_util.assertAxesAreInnerMostDims(\n 'mean', reductionAxes, input.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(input.shape, reductionAxes);\n const reduceSize = util.sizeFromShape(reduceShape);\n let castedInput = input;\n if (input.dtype !== 'float32') {\n castedInput =\n cast({backend, inputs: {x: input}, attrs: {dtype: 'float32'}});\n inputId = backend.dataIdMap.get(castedInput.dataId).id;\n }\n\n const out = backend.makeOutput(outShape, 'float32');\n if (util.sizeFromShape(input.shape) !== 0) {\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmMean(inputId, reduceSize, outId);\n }\n\n if (inputWasTransposed) {\n // dispose of the transposed tensor.\n backend.disposeData(transposed.dataId);\n }\n\n if (keepDims) {\n // reshape\n const newShape = backend_util.expandShapeToKeepDim(out.shape, originalAxes);\n out.shape = newShape;\n }\n\n if (input.dtype !== 'float32') {\n backend.disposeData(castedInput.dataId);\n }\n\n return out;\n}\n\nexport const meanConfig: KernelConfig = {\n kernelName: Mean,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: mean as {} 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 {backend_util, KernelConfig, KernelFunc, Min, MinAttrs, MinInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {permuteAxesAndTranspose} from './kernel_utils';\n\nlet wasmMin: (xId: number, reduceSize: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmMin = backend.wasm.cwrap(Min, null /*void*/, ['number, number, number']);\n}\n\nfunction min(args: {backend: BackendWasm, inputs: MinInputs, attrs: MinAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {axis, keepDims} = attrs;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n let inputId = xId;\n let input = x;\n\n const {transposed, axes, originalAxes, inputWasTransposed} =\n permuteAxesAndTranspose(x, axis, backend);\n\n if (inputWasTransposed) {\n const transposedId = backend.dataIdMap.get(transposed.dataId).id;\n if (transposedId !== xId) {\n // transpose was not a no-op. We will need to dispose of this\n // once we are done.\n input = transposed;\n inputId = transposedId;\n }\n }\n\n const inputRank = input.shape.length;\n\n backend_util.assertAxesAreInnerMostDims('min', axes, inputRank);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(input.shape, axes);\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const out = backend.makeOutput(outShape, input.dtype);\n if (util.sizeFromShape(input.shape) !== 0) {\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmMin(inputId, reduceSize, outId);\n }\n\n if (inputWasTransposed) {\n // dispose of the transposed tensor.\n backend.disposeData(transposed.dataId);\n }\n\n if (keepDims) {\n // reshape\n const newShape = backend_util.expandShapeToKeepDim(out.shape, originalAxes);\n out.shape = newShape;\n }\n\n return out;\n}\n\nexport const minConfig: KernelConfig = {\n kernelName: Min,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: min as {} 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 */\nimport {KernelConfig, Minimum} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = false;\nexport const minimumConfig: KernelConfig =\n createBinaryKernelConfig(Minimum, supportsFullBroadcast);\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 {KernelConfig, KernelFunc, MirrorPad, MirrorPadAttrs, MirrorPadInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {CppDType} from './types';\n\n// Must match enum in MirrorPad.cc\nenum MirrorPaddingMode {\n reflect = 0,\n symmetric = 1\n}\n\nlet wasmMirrorPad: (\n xId: number, xShapeBytes: Uint8Array, xShapeLength: number, xDtype: number,\n prePaddingsBytes: Uint8Array, postPaddingsBytes: Uint8Array, mode: number,\n outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmMirrorPad = backend.wasm.cwrap(MirrorPad, null /* void */, [\n 'number', // xId\n 'array', // x.shape\n 'number', // x.shape.length\n 'number', // x.dtype\n 'array', // pre-paddings\n 'array', // post-paddings\n 'number', // mode\n 'number', // outId\n ]);\n}\n\nfunction mirrorPad(args: {\n inputs: MirrorPadInputs,\n backend: BackendWasm,\n attrs: MirrorPadAttrs\n}) {\n const {inputs: {x}, backend, attrs: {paddings, mode}} = args;\n\n const outShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + x.shape[i] + p[1] /* afterPad */);\n const xId = backend.dataIdMap.get(x.dataId).id;\n const out = backend.makeOutput(outShape, x.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n const xShapeBytes = new Uint8Array(new Int32Array(x.shape).buffer);\n\n const prePaddingsFlat = paddings.map(padTuple => padTuple[0]);\n const postPaddingsFlat = paddings.map(padTuple => padTuple[1]);\n const prePaddingsBytes =\n new Uint8Array(new Int32Array(prePaddingsFlat).buffer);\n const postPaddingsBytes =\n new Uint8Array(new Int32Array(postPaddingsFlat).buffer);\n\n wasmMirrorPad(\n xId, xShapeBytes, x.shape.length, CppDType[x.dtype], prePaddingsBytes,\n postPaddingsBytes, MirrorPaddingMode[mode], outId);\n return out;\n}\n\nexport const mirrorPadConfig: KernelConfig = {\n kernelName: MirrorPad,\n backendName: 'wasm',\n kernelFunc: mirrorPad as {} as KernelFunc,\n setupFunc: setup\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 {KernelConfig, Multiply} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\n\nconst supportsFullBroadcast = true;\nexport const multiplyConfig: KernelConfig =\n createBinaryKernelConfig(Multiply, supportsFullBroadcast);\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 {KernelConfig, Neg} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const negConfig: KernelConfig = createUnaryKernelConfig(Neg);\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 {BackendWasm} from '../backend_wasm';\n\n// Analogous to `struct Result` in `non_max_suppression_impl.h`.\ninterface Result {\n pSelectedIndices: number;\n selectedSize: number;\n pSelectedScores: number;\n pValidOutputs: number;\n}\n/**\n * Parse the result of the c++ method, which has the shape equivalent to\n * `Result`.\n */\nexport function parseResultStruct(\n backend: BackendWasm, resOffset: number): Result {\n const result = new Int32Array(backend.wasm.HEAPU8.buffer, resOffset, 4);\n const pSelectedIndices = result[0];\n const selectedSize = result[1];\n const pSelectedScores = result[2];\n const pValidOutputs = result[3];\n // Since the result was allocated on the heap, we have to delete it.\n backend.wasm._free(resOffset);\n return {pSelectedIndices, selectedSize, pSelectedScores, pValidOutputs};\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 {KernelConfig, KernelFunc, NonMaxSuppressionV3, NonMaxSuppressionV3Attrs, NonMaxSuppressionV3Inputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {parseResultStruct} from './NonMaxSuppression_util';\n\nlet wasmFunc: (\n boxesId: number, scoresId: number, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number) => number;\n\nfunction setup(backend: BackendWasm): void {\n wasmFunc = backend.wasm.cwrap(\n NonMaxSuppressionV3,\n 'number', // Result*\n [\n 'number', // boxesId\n 'number', // scoresId\n 'number', // maxOutputSize\n 'number', // iouThreshold\n 'number', // scoreThreshold\n ]);\n}\n\nfunction kernelFunc(args: {\n backend: BackendWasm,\n inputs: NonMaxSuppressionV3Inputs,\n attrs: NonMaxSuppressionV3Attrs\n}): TensorInfo {\n const {backend, inputs, attrs} = args;\n const {iouThreshold, maxOutputSize, scoreThreshold} = attrs;\n const {boxes, scores} = inputs;\n\n const boxesId = backend.dataIdMap.get(boxes.dataId).id;\n const scoresId = backend.dataIdMap.get(scores.dataId).id;\n\n const resOffset =\n wasmFunc(boxesId, scoresId, maxOutputSize, iouThreshold, scoreThreshold);\n\n const {pSelectedIndices, selectedSize, pSelectedScores, pValidOutputs} =\n parseResultStruct(backend, resOffset);\n\n // Since we are not using scores for V3, we have to delete it from the heap.\n backend.wasm._free(pSelectedScores);\n backend.wasm._free(pValidOutputs);\n\n const selectedIndicesTensor =\n backend.makeOutput([selectedSize], 'int32', pSelectedIndices);\n\n return selectedIndicesTensor;\n}\n\nexport const nonMaxSuppressionV3Config: KernelConfig = {\n kernelName: NonMaxSuppressionV3,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: kernelFunc as {} 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, NonMaxSuppressionV4, NonMaxSuppressionV4Attrs, NonMaxSuppressionV4Inputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {parseResultStruct} from './NonMaxSuppression_util';\n\nlet wasmFunc: (\n boxesId: number, scoresId: number, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number,\n padToMaxOutputSize: boolean) => number;\n\nfunction setup(backend: BackendWasm): void {\n wasmFunc = backend.wasm.cwrap(\n NonMaxSuppressionV4,\n 'number', // Result*\n [\n 'number', // boxesId\n 'number', // scoresId\n 'number', // maxOutputSize\n 'number', // iouThreshold\n 'number', // scoreThreshold\n 'bool', // padToMaxOutputSize\n ]);\n}\n\nfunction nonMaxSuppressionV4(args: {\n backend: BackendWasm,\n inputs: NonMaxSuppressionV4Inputs,\n attrs: NonMaxSuppressionV4Attrs\n}): TensorInfo[] {\n const {backend, inputs, attrs} = args;\n const {iouThreshold, maxOutputSize, scoreThreshold, padToMaxOutputSize} =\n attrs;\n const {boxes, scores} = inputs;\n\n const boxesId = backend.dataIdMap.get(boxes.dataId).id;\n const scoresId = backend.dataIdMap.get(scores.dataId).id;\n\n const resOffset = wasmFunc(\n boxesId, scoresId, maxOutputSize, iouThreshold, scoreThreshold,\n padToMaxOutputSize);\n\n const {pSelectedIndices, selectedSize, pSelectedScores, pValidOutputs} =\n parseResultStruct(backend, resOffset);\n\n // Since we are not using scores for V4, we have to delete it from the heap.\n backend.wasm._free(pSelectedScores);\n\n const selectedIndicesTensor =\n backend.makeOutput([selectedSize], 'int32', pSelectedIndices);\n\n const validOutputsTensor = backend.makeOutput([], 'int32', pValidOutputs);\n\n return [selectedIndicesTensor, validOutputsTensor];\n}\n\nexport const nonMaxSuppressionV4Config: KernelConfig = {\n kernelName: NonMaxSuppressionV4,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: nonMaxSuppressionV4 as {} 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 {KernelConfig, KernelFunc, NonMaxSuppressionV5, NonMaxSuppressionV5Attrs, NonMaxSuppressionV5Inputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {parseResultStruct} from './NonMaxSuppression_util';\n\nlet wasmFunc:\n (boxesId: number, scoresId: number, maxOutputSize: number,\n iouThreshold: number, scoreThreshold: number, softNmsSigma: number) =>\n number;\n\nfunction setup(backend: BackendWasm): void {\n wasmFunc = backend.wasm.cwrap(\n NonMaxSuppressionV5,\n 'number', // Result*\n [\n 'number', // boxesId\n 'number', // scoresId\n 'number', // maxOutputSize\n 'number', // iouThreshold\n 'number', // scoreThreshold\n 'number', // softNmsSigma\n ]);\n}\n\nfunction kernelFunc(args: {\n backend: BackendWasm,\n inputs: NonMaxSuppressionV5Inputs,\n attrs: NonMaxSuppressionV5Attrs\n}): TensorInfo[] {\n const {backend, inputs, attrs} = args;\n const {iouThreshold, maxOutputSize, scoreThreshold, softNmsSigma} = attrs;\n const {boxes, scores} = inputs;\n\n const boxesId = backend.dataIdMap.get(boxes.dataId).id;\n const scoresId = backend.dataIdMap.get(scores.dataId).id;\n\n const resOffset = wasmFunc(\n boxesId, scoresId, maxOutputSize, iouThreshold, scoreThreshold,\n softNmsSigma);\n\n const {pSelectedIndices, selectedSize, pSelectedScores, pValidOutputs} =\n parseResultStruct(backend, resOffset);\n\n // Since we are not using validOutputs for V5, we have to delete it from the\n // heap.\n backend.wasm._free(pValidOutputs);\n\n const selectedIndicesTensor =\n backend.makeOutput([selectedSize], 'int32', pSelectedIndices);\n const selectedScoresTensor =\n backend.makeOutput([selectedSize], 'float32', pSelectedScores);\n\n return [selectedIndicesTensor, selectedScoresTensor];\n}\n\nexport const nonMaxSuppressionV5Config: KernelConfig = {\n kernelName: NonMaxSuppressionV5,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: kernelFunc as {} 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 */\nimport {KernelConfig, NotEqual} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = false;\nexport const notEqualConfig: KernelConfig =\n createBinaryKernelConfig(NotEqual, supportsFullBroadcast, 'bool');\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, OneHot, OneHotAttrs, OneHotInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmOneHot: (\n indicesId: number, depth: number, onValue: number, offValue: number,\n outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmOneHot = backend.wasm.cwrap(OneHot, null /* void */, [\n 'number', // indices_id\n 'number', // depth,\n 'number', // onValue\n 'number', // offValue\n 'number' // out_id\n ]);\n}\n\nfunction oneHot(\n args: {inputs: OneHotInputs, attrs: OneHotAttrs, backend: BackendWasm}) {\n const {inputs, backend, attrs} = args;\n const {indices} = inputs;\n const {depth, onValue, offValue} = attrs;\n\n const out = backend.makeOutput([...indices.shape, depth], 'int32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const indicesData = backend.dataIdMap.get(indices.dataId);\n const indicesId = indicesData.id;\n\n wasmOneHot(indicesId, depth, onValue, offValue, outId);\n\n return out;\n}\n\nexport const oneHotConfig: KernelConfig = {\n kernelName: OneHot,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: oneHot as {} 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, OnesLike, OnesLikeInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nfunction onesLike(args: {inputs: OnesLikeInputs, backend: BackendWasm}) {\n const {inputs: {x}, backend} = args;\n const out = backend.makeOutput(x.shape, x.dtype);\n const outVals = backend.typedArrayFromHeap(out);\n outVals.fill(1);\n return out;\n}\n\nexport const onesLikeConfig: KernelConfig = {\n kernelName: OnesLike,\n backendName: 'wasm',\n kernelFunc: onesLike as {} 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';\nimport {BackendWasm} from '../backend_wasm';\n\nimport {concat} from './Concat';\nimport {expandDims} from './ExpandDims';\n\nexport function pack(\n args: {inputs: PackInputs, backend: BackendWasm, 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(t => backend.disposeData(t.dataId));\n\n return result;\n}\n\nexport const packConfig: KernelConfig = {\n kernelName: Pack,\n backendName: 'wasm',\n kernelFunc: pack as {} 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 {KernelConfig, KernelFunc, PadV2, PadV2Attrs, PadV2Inputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {CppDType} from './types';\n\nlet wasmPadV2: (\n xId: number, xShapeBytes: Uint8Array, xShapeLength: number, xDtype: number,\n prePaddingsBytes: Uint8Array, postPaddingsBytes: Uint8Array,\n constantValue: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmPadV2 = backend.wasm.cwrap(PadV2, null /* void */, [\n 'number', // xId\n 'array', // x.shape\n 'number', // x.shape.length\n 'number', // x.dtype\n 'array', // pre-paddings\n 'array', // post-paddings\n 'number', // constantValue\n 'number', // outId\n ]);\n}\n\nfunction pad(\n args: {inputs: PadV2Inputs, backend: BackendWasm, attrs: PadV2Attrs}) {\n const {inputs: {x}, backend, attrs: {paddings, constantValue}} = args;\n\n const outShape = paddings.map(\n (p, i) => p[0] /* beforePad */ + x.shape[i] + p[1] /* afterPad */);\n const xId = backend.dataIdMap.get(x.dataId).id;\n const out = backend.makeOutput(outShape, x.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n const xShapeBytes = new Uint8Array(new Int32Array(x.shape).buffer);\n\n const prePaddingsFlat = paddings.map(padTuple => padTuple[0]);\n const postPaddingsFlat = paddings.map(padTuple => padTuple[1]);\n const prePaddingsBytes =\n new Uint8Array(new Int32Array(prePaddingsFlat).buffer);\n const postPaddingsBytes =\n new Uint8Array(new Int32Array(postPaddingsFlat).buffer);\n\n wasmPadV2(\n xId, xShapeBytes, x.shape.length, CppDType[x.dtype], prePaddingsBytes,\n postPaddingsBytes, constantValue, outId);\n return out;\n}\n\nexport const padV2Config: KernelConfig = {\n kernelName: PadV2,\n backendName: 'wasm',\n kernelFunc: pad as {} as KernelFunc,\n setupFunc: setup\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 {KernelConfig, Pow} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = false;\nexport const powConfig: KernelConfig =\n createBinaryKernelConfig(Pow, supportsFullBroadcast);\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 {KernelConfig, KernelFunc, Prelu, PreluInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmPrelu: (xId: number, weightsId: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmPrelu = backend.wasm.cwrap(Prelu, null /* void */, [\n 'number', // x_id\n 'number', // weights_id\n 'number' // out_id\n ]);\n}\n\nfunction prelu(args: {inputs: PreluInputs, backend: BackendWasm}) {\n const {inputs, backend} = args;\n const {x, alpha} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n const weightsId = backend.dataIdMap.get(alpha.dataId).id;\n\n const out = backend.makeOutput(x.shape, 'float32');\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmPrelu(xId, weightsId, outId);\n return out;\n}\n\nexport const preluConfig: KernelConfig = {\n kernelName: Prelu,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: prelu as {} 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, Prod, ProdAttrs, ProdInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {permuteAxesAndTranspose} from './kernel_utils';\n\nimport {CppDType} from './types';\n\nlet wasmProd: (\n xId: number, reduceSize: number,\n dtype: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmProd = backend.wasm.cwrap(Prod, null /*void*/, [\n 'number',\n 'number',\n 'number',\n 'number'\n ]);\n}\n\nfunction prod(args: {\n backend: BackendWasm,\n inputs: ProdInputs,\n attrs: ProdAttrs\n}): TensorInfo {\n const {backend, inputs, attrs} = args;\n const {axis, keepDims} = attrs;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n let inputId = xId;\n let input = x;\n\n const {transposed, axes, originalAxes, inputWasTransposed} =\n permuteAxesAndTranspose(x, axis, backend);\n\n let reductionAxes = axes;\n if (inputWasTransposed) {\n const transposedId = backend.dataIdMap.get(transposed.dataId).id;\n if (transposedId !== xId) {\n // transpose was not a no-op. We will need to dispose of this\n // once we are done.\n input = transposed;\n inputId = transposedId;\n reductionAxes = backend_util.getInnerMostAxes(\n reductionAxes.length, input.shape.length);\n }\n }\n\n backend_util.assertAxesAreInnerMostDims(\n 'prod', reductionAxes, input.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(input.shape, reductionAxes);\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const out = backend.makeOutput(outShape, input.dtype);\n if (util.sizeFromShape(input.shape) !== 0) {\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmProd(inputId, reduceSize, CppDType[out.dtype], outId);\n }\n\n if (inputWasTransposed) {\n // dispose of the transposed tensor.\n backend.disposeData(transposed.dataId);\n }\n\n if (keepDims) {\n // reshape\n const newShape = backend_util.expandShapeToKeepDim(out.shape, originalAxes);\n out.shape = newShape;\n }\n\n return out;\n}\n\nexport const prodConfig: KernelConfig = {\n kernelName: Prod,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: prod as {} 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 {BackendWasm} from '../backend_wasm';\nimport {rangeImplCPU} from '../kernel_utils/shared';\n\nexport const range =\n (args: {backend: BackendWasm, attrs: RangeAttrs}): TensorInfo => {\n const {backend, attrs} = args;\n const {start, stop, step, dtype} = attrs;\n const values = rangeImplCPU(start, stop, step, dtype);\n\n const out = backend.makeOutput([values.length], dtype);\n const outVals = backend.typedArrayFromHeap(out);\n outVals.set(values);\n return out;\n };\n\nexport const rangeConfig: KernelConfig = {\n kernelName: Range,\n backendName: 'wasm',\n kernelFunc: range as {} 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 {KernelConfig, RealDiv} from '@tensorflow/tfjs-core';\n\nimport {createBinaryKernelConfig} from './binary_kernel';\n\nconst supportsFullBroadcast = true;\nexport const realDivConfig: KernelConfig =\n createBinaryKernelConfig(RealDiv, supportsFullBroadcast);\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 {KernelConfig, Relu} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const reluConfig: KernelConfig = createUnaryKernelConfig(Relu);\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 {KernelConfig, Relu6} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const relu6Config: KernelConfig = createUnaryKernelConfig(Relu6);\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 {KernelConfig, KernelFunc, ResizeBilinear, ResizeBilinearAttrs, ResizeBilinearInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {cast} from './Cast';\n\nlet wasmResizeBilinear: (\n xId: number, batch: number, oldHeight: number, oldWidth: number,\n numChannels: number, newHeight: number, newWidth: number,\n alignCorners: number, halfPixelCenters: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmResizeBilinear = backend.wasm.cwrap(ResizeBilinear, null /*void*/, [\n 'number', // xId\n 'number', // batch\n 'number', // oldHeight\n 'number', // oldWidth\n 'number', // numChannels\n 'number', // newHeight\n 'number', // newWidth\n 'number', // alignCorners\n 'number', // halfPixelCenters\n 'number' // outId\n ]);\n}\n\nfunction resizeBilinear(args: {\n backend: BackendWasm,\n inputs: ResizeBilinearInputs,\n attrs: ResizeBilinearAttrs\n}): TensorInfo {\n const {backend, inputs, attrs} = args;\n\n const {images} = inputs;\n const {alignCorners, halfPixelCenters, size} = attrs;\n const [newHeight, newWidth] = size;\n\n const [batch, oldHeight, oldWidth, numChannels] = images.shape;\n const outShape = [batch, newHeight, newWidth, numChannels];\n\n let xData = backend.dataIdMap.get(images.dataId);\n let castedData;\n if (xData.dtype !== 'float32') {\n castedData =\n cast({backend, inputs: {x: images}, attrs: {dtype: 'float32'}});\n xData = backend.dataIdMap.get(castedData.dataId);\n }\n const xId = xData.id;\n\n const out = backend.makeOutput(outShape, 'float32');\n if (util.sizeFromShape(images.shape) === 0) {\n return out;\n }\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n wasmResizeBilinear(\n xId, batch, oldHeight, oldWidth, numChannels, newHeight, newWidth,\n alignCorners ? 1 : 0, halfPixelCenters ? 1 : 0, outId);\n\n if (castedData != null) {\n backend.disposeData(castedData.dataId);\n }\n\n return out;\n}\n\nexport const resizeBilinearConfig: KernelConfig = {\n kernelName: ResizeBilinear,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: resizeBilinear as {} 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, Reverse, ReverseAttrs, ReverseInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {identity} from './Identity';\nimport {reshape} from './Reshape';\n\nlet wasmReverse: (\n xId: number, axes: Uint8Array, axesLength: number, outShape: Uint8Array,\n outShapeLength: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmReverse = backend.wasm.cwrap(Reverse, null, [\n 'number', // x_id\n 'array', // axes\n 'number', // axes_length\n 'array', // out_shape\n 'number', // out_shape_length\n 'number' // out_id\n ]);\n}\n\nexport function reverse(\n args: {inputs: ReverseInputs, backend: BackendWasm, attrs: ReverseAttrs}):\n TensorInfo {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {dims} = attrs;\n\n const axes = util.parseAxisParam(dims, x.shape);\n\n if (x.shape.length === 0) {\n return identity({inputs: {x}, backend});\n }\n\n const out = backend.makeOutput(x.shape, x.dtype);\n const xId = backend.dataIdMap.get(x.dataId).id;\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const axesBytes = new Uint8Array(new Int32Array(axes).buffer);\n const outShapeBytes = new Uint8Array(new Int32Array(x.shape).buffer);\n\n wasmReverse(\n xId, axesBytes, axes.length, outShapeBytes, x.shape.length, outId);\n\n const reshaped =\n reshape({inputs: {x: out}, attrs: {shape: x.shape}, backend});\n\n backend.disposeData(out.dataId);\n return reshaped;\n}\n\nexport const reverseConfig: KernelConfig = {\n kernelName: Reverse,\n backendName: 'wasm',\n kernelFunc: reverse as {} as KernelFunc,\n setupFunc: setup\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 {KernelConfig, KernelFunc, RotateWithOffset, RotateWithOffsetAttrs, RotateWithOffsetInputs, TensorInfo} from '@tensorflow/tfjs-core';\nimport {backend_util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmRotate: (\n xId: number, batch: number, imageHeight: number, imageWidth: number,\n numChannels: number, radians: number, centerX: number, centerY: number,\n fillBytes: Uint8Array, fillLength: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmRotate = backend.wasm.cwrap(RotateWithOffset, null /* void */, [\n 'number', // xId\n 'number', // batch\n 'number', // imageHeight\n 'number', // imageWidth\n 'number', // numChannels\n 'number', // radians\n 'number', // centerX\n 'number', // centerY\n 'array', // fillBytes\n 'number', // fillLength\n 'number', // outId\n ]);\n}\n\nexport function rotateWithOffset(args: {\n inputs: RotateWithOffsetInputs,\n backend: BackendWasm,\n attrs: RotateWithOffsetAttrs\n}): TensorInfo {\n const {inputs, backend, attrs} = args;\n const {image} = inputs;\n const {radians, fillValue, center} = attrs;\n\n const out = backend.makeOutput(image.shape, image.dtype);\n const imageId = backend.dataIdMap.get(image.dataId).id;\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n\n const [centerX, centerY] =\n backend_util.getImageCenter(center, imageHeight, imageWidth);\n\n const fillIsBlack = fillValue === 0;\n const fullOpacityValue = 255;\n\n const fillValues = typeof fillValue === 'number' ?\n [fillValue, fillValue, fillValue, fillIsBlack ? 0 : fullOpacityValue] :\n [...fillValue, fullOpacityValue];\n const fillBytes = new Uint8Array(new Int32Array(fillValues).buffer);\n\n wasmRotate(\n imageId, batch, imageHeight, imageWidth, numChannels, radians, centerX,\n centerY, fillBytes, fillValues.length, outId);\n return out;\n}\n\nexport const rotateWithOffsetConfig: KernelConfig = {\n kernelName: RotateWithOffset,\n backendName: 'wasm',\n kernelFunc: rotateWithOffset as {} as KernelFunc,\n setupFunc: setup\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 {KernelConfig, Round} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\n\nexport const roundConfig: KernelConfig = createUnaryKernelConfig(Round);\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 {KernelConfig, Rsqrt} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const rsqrtConfig: KernelConfig = createUnaryKernelConfig(Rsqrt);\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 {KernelConfig, KernelFunc, scatter_util, ScatterNd, ScatterNdAttrs, ScatterNdInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {CppDType} from './types';\n\nlet wasmScatterNd: (\n indicesId: number, updatesId: number, dtype: CppDType, sliceRank: number,\n numUpdates: number, sliceSize: number, strides: Uint8Array,\n outputSize: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmScatterNd = backend.wasm.cwrap(ScatterNd, null /*void*/, [\n 'number', // indicesId\n 'number', // updatesId\n 'number', // dtype\n 'number', // sliceRank\n 'number', // numUpdates\n 'number', // sliceSize\n 'array', // strides\n 'number', // outputSize\n 'number' // outId\n ]);\n}\n\nfunction scatterNd(\n args:\n {backend: BackendWasm, inputs: ScatterNdInputs, attrs: ScatterNdAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {indices, updates} = inputs;\n const {shape} = attrs;\n\n const out = backend.makeOutput(shape, updates.dtype);\n if (util.sizeFromShape(shape) === 0) {\n return out;\n }\n\n const {sliceRank, numUpdates, sliceSize, strides, outputSize} =\n scatter_util.calculateShapes(updates, indices, shape);\n\n const indicesData = backend.dataIdMap.get(indices.dataId);\n const indicesId = indicesData.id;\n\n const updatesData = backend.dataIdMap.get(updates.dataId);\n const updatesId = updatesData.id;\n\n const stridesBytes = new Uint8Array(new Int32Array(strides).buffer);\n\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmScatterNd(\n indicesId, updatesId, CppDType[updates.dtype], sliceRank, numUpdates,\n sliceSize, stridesBytes, outputSize, outId);\n\n return out;\n}\n\nexport const scatterNdConfig: KernelConfig = {\n kernelName: ScatterNd,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: scatterNd as {} 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, Select, SelectInputs, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmSelect: (\n conditionId: number, tId: number, eId: number, offset: number,\n outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmSelect = backend.wasm.cwrap('SelectV2', null, [\n 'number', // conditionId\n 'number', // tId\n 'number', // eId\n 'number', // offset\n 'number', // outId\n ]);\n}\n\nfunction select(args: {inputs: SelectInputs, backend: BackendWasm}) {\n const {inputs, backend} = args;\n const {condition, t, e} = inputs;\n\n const conditionId = backend.dataIdMap.get(condition.dataId).id;\n const tId = backend.dataIdMap.get(t.dataId).id;\n const eId = backend.dataIdMap.get(e.dataId).id;\n const out = backend.makeOutput(t.shape, t.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const cRank = condition.shape.length;\n const tRank = t.shape.length;\n\n const offset = cRank === 0 || cRank > 1 || tRank === 1 ?\n 1 :\n util.sizeFromShape(t.shape.slice(1));\n\n wasmSelect(conditionId, tId, eId, offset, outId);\n return out;\n}\n\nexport const selectConfig: KernelConfig = {\n kernelName: Select,\n backendName: 'wasm',\n kernelFunc: select as {} as KernelFunc,\n setupFunc: setup\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 {KernelConfig, KernelFunc, Sigmoid, SigmoidInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmFunc: (xId: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmFunc = backend.wasm.cwrap(Sigmoid, null /* void */, ['number', 'number']);\n}\n\nfunction sigmoid(args: {backend: BackendWasm, inputs: SigmoidInputs}):\n TensorInfo {\n const {backend, inputs: {x}} = args;\n const xId = backend.dataIdMap.get(x.dataId).id;\n const out = backend.makeOutput(x.shape, x.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n // Short-circuit zero-sized tensors.\n if (util.sizeFromShape(out.shape) === 0) {\n return out;\n }\n\n wasmFunc(xId, outId);\n return out;\n}\n\nexport const sigmoidConfig: KernelConfig = {\n kernelName: 'Sigmoid',\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: sigmoid as {} 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 */\nimport {KernelConfig, Sin} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const sinConfig: KernelConfig = createUnaryKernelConfig(Sin);\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, Softmax, SoftmaxAttrs, SoftmaxInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmFunc: (xId: number, outId: number, channels: number, batch: number) =>\n void;\n\nfunction setup(backend: BackendWasm): void {\n wasmFunc = backend.wasm.cwrap(Softmax, null /* void */, [\n 'number', // xId\n 'number', // outId\n 'number', // channels\n 'number' // batch\n ]);\n}\n\nfunction softmax(\n args: {backend: BackendWasm, inputs: SoftmaxInputs, attrs: SoftmaxAttrs}):\n TensorInfo {\n const {backend, inputs: {logits}, attrs: {dim}} = args;\n const xId = backend.dataIdMap.get(logits.dataId).id;\n const out = backend.makeOutput(logits.shape, logits.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const channels = logits.shape[dim];\n const batch = util.sizeFromShape(logits.shape) / channels;\n\n // Short-circuit zero-sized tensors.\n if (util.sizeFromShape(out.shape) === 0) {\n return out;\n }\n\n wasmFunc(xId, outId, channels, batch);\n return out;\n}\n\nexport const softmaxConfig: KernelConfig = {\n kernelName: Softmax,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: softmax as {} as KernelFunc\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 {backend_util, KernelConfig, KernelFunc, ReshapeAttrs, ReshapeInputs, SpaceToBatchND, SpaceToBatchNDAttrs, SpaceToBatchNDInputs, TensorInfo, TransposeAttrs, TransposeInputs, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {padV2Config} from './PadV2';\nimport {reshape} from './Reshape';\nimport {transpose} from './Transpose';\n\nfunction spaceToBatchND(args: {\n inputs: SpaceToBatchNDInputs,\n backend: BackendWasm,\n attrs: SpaceToBatchNDAttrs\n}) {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const {blockShape, paddings} = attrs;\n\n const prod = util.sizeFromShape(blockShape);\n\n const completePaddings: Array<[number, number]> = [[0, 0]];\n completePaddings.push(...(paddings as Array<[number, number]>));\n\n for (let i = 1 + blockShape.length; i < x.shape.length; ++i) {\n completePaddings.push([0, 0]);\n }\n\n const paddedX = padV2Config.kernelFunc({\n inputs: {x},\n backend,\n attrs: {paddings: completePaddings, constantValue: 0}\n }) as TensorInfo;\n\n const reshapedPaddedShape =\n backend_util.getReshaped(paddedX.shape, blockShape, prod, false);\n\n const permutedReshapedPaddedPermutation = backend_util.getPermuted(\n reshapedPaddedShape.length, blockShape.length, false);\n\n const flattenShape =\n backend_util.getReshapedPermuted(paddedX.shape, blockShape, prod, false);\n\n const reshapeInputs: ReshapeInputs = {x: paddedX};\n const reshapeAttrs: ReshapeAttrs = {shape: reshapedPaddedShape};\n const paddedXReshaped =\n reshape({inputs: reshapeInputs, backend, attrs: reshapeAttrs});\n\n const transposeInputs: TransposeInputs = {x: paddedXReshaped};\n const transposeAttrs:\n TransposeAttrs = {perm: permutedReshapedPaddedPermutation};\n const paddedXT =\n transpose({inputs: transposeInputs, backend, attrs: transposeAttrs});\n\n const resultReshapeInputs: ReshapeInputs = {x: paddedXT};\n const resultReshapeAttrs: ReshapeAttrs = {shape: flattenShape};\n const result = reshape(\n {inputs: resultReshapeInputs, backend, attrs: resultReshapeAttrs});\n\n backend.disposeData(paddedX.dataId);\n backend.disposeData(paddedXReshaped.dataId);\n backend.disposeData(paddedXT.dataId);\n\n return result;\n}\n\nexport const spaceToBatchNDConfig: KernelConfig = {\n kernelName: SpaceToBatchND,\n backendName: 'wasm',\n kernelFunc: spaceToBatchND as {} 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, SplitV, SplitVAttrs, SplitVInputs, util} from '@tensorflow/tfjs-core';\nimport {backend_util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {slice} from './Slice';\n\nexport function splitV(\n args: {inputs: SplitVInputs, attrs: SplitVAttrs, backend: BackendWasm}) {\n const {inputs, attrs, backend} = args;\n const {x} = inputs;\n const {numOrSizeSplits, axis} = attrs;\n\n const $axis = util.parseAxisParam(axis, x.shape)[0];\n\n const splitSizes = backend_util.prepareSplitSize(x, numOrSizeSplits, $axis);\n const begin = new Array(x.shape.length).fill(0);\n const size = x.shape.slice();\n return splitSizes.map(s => {\n const xSliceSize = [...size];\n xSliceSize[$axis] = s;\n const xSlice =\n slice({inputs: {x}, attrs: {begin, size: xSliceSize}, backend});\n begin[$axis] += s;\n return xSlice;\n });\n}\n\nexport const splitVConfig: KernelConfig = {\n kernelName: SplitV,\n backendName: 'wasm',\n kernelFunc: splitV as {} 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, Sqrt} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const sqrtConfig: KernelConfig = createUnaryKernelConfig(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 */\nimport {KernelConfig, Square} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const squareConfig: KernelConfig = createUnaryKernelConfig(Square);\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 {KernelConfig, SquaredDifference} from '@tensorflow/tfjs-core';\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = true;\nexport const squaredDifferenceConfig: KernelConfig =\n createBinaryKernelConfig(SquaredDifference, supportsFullBroadcast);\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, Step, StepAttrs, StepInputs, TensorInfo} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmStep: (xId: number, alpha: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmStep = backend.wasm.cwrap(Step, null /*void*/, [\n 'number', // x_id\n 'number', // alpha\n 'number', // out_id\n ]);\n}\n\nfunction step(\n args: {backend: BackendWasm, inputs: StepInputs, attrs: StepAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {alpha} = attrs;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n\n const out = backend.makeOutput(x.shape, x.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmStep(xId, alpha, outId);\n return out;\n}\n\nexport const stepConfig: KernelConfig = {\n kernelName: Step,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: step as {} 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, StridedSlice, StridedSliceAttrs, StridedSliceInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\nimport {reshape} from './Reshape';\nimport {slice} from './Slice';\n\nlet wasmStridedSlice: (\n xId: number, xStridesBytes: Uint8Array, xRank: number,\n beginBytes: Uint8Array, endBytes: Uint8Array, stridesBytes: Uint8Array,\n outShapeBytes: Uint8Array, outStridesBytes: Uint8Array,\n outShapeLength: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmStridedSlice = backend.wasm.cwrap(StridedSlice, null /*void*/, [\n 'number', // xId\n 'array', // xStrides\n 'number', // xRank\n 'array', // beginBytes\n 'array', // endBytes\n 'array', // stridesBytes\n 'array', // outShapeBytes\n 'array', // outStridesBytes\n 'number', // outShapeLength\n 'number', // outId\n ]);\n}\n\nexport function stridedSlice(args: {\n backend: BackendWasm,\n inputs: StridedSliceInputs,\n attrs: StridedSliceAttrs\n}): TensorInfo {\n const {backend, inputs, attrs} = args;\n const {x} = inputs;\n\n let {begin, end, strides} = attrs;\n if (strides == null) {\n strides = new Array(begin.length);\n }\n\n const {beginMask, endMask, ellipsisMask, newAxisMask, shrinkAxisMask} = attrs;\n\n const ellipsisAxes = backend_util.slice_util.maskToAxes(ellipsisMask);\n if (ellipsisAxes.length > 1) {\n throw new Error('Multiple ellipses in slice is not allowed.');\n }\n\n if (ellipsisMask !== 0 && newAxisMask !== 0) {\n throw new Error(\n 'Using both ellipsisMask and newAxisMask is not yet supported.');\n }\n\n if (ellipsisMask !== 0 && shrinkAxisMask !== 0) {\n throw new Error(\n 'Using both ellipsisMask and shrinkAxisMask is not yet supported.');\n }\n\n const numInterpolatedAxes = x.shape.length - begin.length;\n\n // Expand the dims of x based on the newAxisMask.\n const expandAxes = backend_util.slice_util.maskToAxes(newAxisMask);\n const newShape = x.shape.slice();\n expandAxes.forEach(axis => {\n begin[axis] = 0;\n end[axis] = 1;\n newShape.splice(axis, 0, 1);\n });\n\n const xReshaped = reshape({inputs: {x}, attrs: {shape: newShape}, backend});\n\n const {\n begin: normalizedBegin,\n end: normalizedEnd,\n strides: normalizedStrides\n } =\n backend_util.slice_util.getNormalizedAxes(\n xReshaped.shape, ellipsisAxes, numInterpolatedAxes, begin, end,\n strides, beginMask, endMask, ellipsisMask);\n begin = normalizedBegin;\n end = normalizedEnd;\n strides = normalizedStrides;\n\n const shrinkAxes = backend_util.slice_util.maskToAxes(shrinkAxisMask);\n // Adjust the ends based on the shrink mask.\n shrinkAxes.forEach(axis => {\n end[axis] = begin[axis] + 1;\n strides[axis] = 1;\n });\n\n // Figure out the output shape.\n const size = backend_util.slice_util.computeOutShape(begin, end, strides);\n // Remove the axes based on shrinkMask.\n const outShape = size.filter((_, axis) => shrinkAxes.indexOf(axis) === -1);\n\n const nonStrided = strides.every(v => v === 1);\n if (nonStrided) {\n const xSliced = slice(\n {inputs: {x: xReshaped}, attrs: {begin, size}, backend});\n backend.disposeData(xReshaped.dataId);\n const reshaped =\n reshape({inputs: {x: xSliced}, attrs: {shape: outShape}, backend});\n backend.disposeData(xSliced.dataId);\n return reshaped;\n }\n\n const out = backend.makeOutput(outShape, 'float32');\n if (!outShape.some(axis => axis === 0)) {\n const xId = backend.dataIdMap.get(xReshaped.dataId).id;\n const xStridesBytes = new Uint8Array(\n new Int32Array(util.computeStrides(xReshaped.shape)).buffer);\n const beginBytes = new Uint8Array(new Int32Array(begin).buffer);\n const endBytes = new Uint8Array(new Int32Array(end).buffer);\n const stridesBytes = new Uint8Array(new Int32Array(strides).buffer);\n\n const outputShapeBytes = new Uint8Array(new Int32Array(outShape).buffer);\n const outStridesBytes =\n new Uint8Array(new Int32Array(util.computeStrides(outShape)).buffer);\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n wasmStridedSlice(\n xId, xStridesBytes, xReshaped.shape.length, beginBytes, endBytes,\n stridesBytes, outputShapeBytes, outStridesBytes, outShape.length,\n outId);\n }\n backend.disposeData(xReshaped.dataId);\n\n const reshaped =\n reshape({inputs: {x: out}, attrs: {shape: outShape}, backend});\n\n backend.disposeData(out.dataId);\n return reshaped;\n}\n\nexport const stridedSliceConfig: KernelConfig = {\n kernelName: StridedSlice,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: stridedSlice as {} 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 */\nimport {KernelConfig, Sub} from '@tensorflow/tfjs-core';\nimport {createBinaryKernelConfig} from './binary_kernel';\nconst supportsFullBroadcast = true;\nexport const subConfig: KernelConfig =\n createBinaryKernelConfig(Sub, supportsFullBroadcast);\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 {backend_util, KernelConfig, KernelFunc, Sum, SumAttrs, SumInputs, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {permuteAxesAndTranspose} from './kernel_utils';\n\nlet wasmSum: (xId: number, reduceSize: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmSum = backend.wasm.cwrap(Sum, null /*void*/, ['number, number, number']);\n}\n\nfunction sum(args: {backend: BackendWasm, inputs: SumInputs, attrs: SumAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {axis, keepDims} = attrs;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n let inputId = xId;\n let input = x;\n\n const {transposed, axes, originalAxes, inputWasTransposed} =\n permuteAxesAndTranspose(x, axis, backend);\n\n let reductionAxes = axes;\n if (inputWasTransposed) {\n const transposedId = backend.dataIdMap.get(transposed.dataId).id;\n if (transposedId !== xId) {\n // transpose was not a no-op. We will need to dispose of this\n // once we are done.\n input = transposed;\n inputId = transposedId;\n reductionAxes = backend_util.getInnerMostAxes(\n reductionAxes.length, input.shape.length);\n }\n }\n\n backend_util.assertAxesAreInnerMostDims(\n 'sum', reductionAxes, input.shape.length);\n const [outShape, reduceShape] =\n backend_util.computeOutAndReduceShapes(input.shape, reductionAxes);\n const reduceSize = util.sizeFromShape(reduceShape);\n\n const out = backend.makeOutput(outShape, input.dtype);\n if (util.sizeFromShape(input.shape) !== 0) {\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmSum(inputId, reduceSize, outId);\n }\n\n if (inputWasTransposed) {\n // dispose of the transposed tensor.\n backend.disposeData(transposed.dataId);\n }\n\n if (keepDims) {\n // reshape\n const newShape = backend_util.expandShapeToKeepDim(out.shape, originalAxes);\n out.shape = newShape;\n }\n\n return out;\n}\n\nexport const sumConfig: KernelConfig = {\n kernelName: Sum,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: sum as {} as KernelFunc\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 {KernelConfig, Tan} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const tanConfig: KernelConfig = createUnaryKernelConfig(Tan);\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 {KernelConfig, Tanh} from '@tensorflow/tfjs-core';\n\nimport {createUnaryKernelConfig} from './unary_kernel';\nexport const tanhConfig: KernelConfig = createUnaryKernelConfig(Tanh);\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 {KernelConfig, KernelFunc, Tile, TileAttrs, TileInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {CppDType} from './types';\n\nlet wasmTile: (\n xId: number, xShape: Uint8Array, xShapeSize: number, newShape: Uint8Array,\n newShapeSize: number, dtype: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmTile = backend.wasm.cwrap(Tile, null /* void */, [\n 'number', // x_id\n 'array', // x_shape\n 'number', // x_shape.length\n 'array', // new_shape\n 'number', // new_shape.length\n 'number' // out_id\n ]);\n}\n\nfunction tile(\n args: {inputs: TileInputs, backend: BackendWasm, attrs: TileAttrs}) {\n const {inputs, backend, attrs} = args;\n const {x} = inputs;\n const xId = backend.dataIdMap.get(x.dataId).id;\n const {reps} = attrs;\n\n const newShape: number[] = new Array(x.shape.length);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = x.shape[i] * reps[i];\n }\n const xShapeBytes = new Uint8Array(new Int32Array(x.shape).buffer);\n const newShapeBytes = new Uint8Array(new Int32Array(newShape).buffer);\n\n const out = backend.makeOutput(newShape, x.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n wasmTile(\n xId, xShapeBytes, x.shape.length, newShapeBytes, newShape.length,\n CppDType[out.dtype], outId);\n return out;\n}\n\nexport const tileConfig: KernelConfig = {\n kernelName: Tile,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: tile as {} 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, TopK, TopKAttrs, TopKInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\nimport {CppDType} from './types';\n\nlet wasmTopK: (\n xId: number, xShapeBytes: Uint8Array, xShapeLength: number,\n xDtype: CppDType, k: number, sorted: boolean, outValuesId: number,\n outIndicesId: number) => void;\n\nfunction setup(backend: BackendWasm) {\n wasmTopK = backend.wasm.cwrap(TopK, null /* void */, [\n 'number', // xId\n 'array', // x.shape\n 'number', // x.shape.length\n 'number', // x.dtype\n 'number', // k\n 'bool', // sorted\n 'number', // outValuesId\n 'number', // outIndicesId\n ]);\n}\n\nexport const topk:\n (args: {inputs: TopKInputs, backend: BackendWasm, attrs: TopKAttrs}) =>\n TensorInfo[] | TensorInfo = ({inputs, backend, attrs}) => {\n const {x} = inputs;\n const {k, sorted} = attrs;\n\n const xId = backend.dataIdMap.get(x.dataId).id;\n const xShapeBytes = new Uint8Array(new Int32Array(x.shape).buffer);\n const outputShape = x.shape.slice();\n outputShape[outputShape.length - 1] = k;\n const outValues = backend.makeOutput(outputShape, x.dtype);\n const outValuesId = backend.dataIdMap.get(outValues.dataId).id;\n const outIndices = backend.makeOutput(outputShape, 'int32');\n const outIndicesId = backend.dataIdMap.get(outIndices.dataId).id;\n\n wasmTopK(\n xId, xShapeBytes, x.shape.length, CppDType[x.dtype], k, sorted,\n outValuesId, outIndicesId);\n\n return [outValues, outIndices];\n };\n\nexport const topKConfig: KernelConfig = {\n kernelName: TopK,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: topk as {} as KernelFunc,\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 {KernelConfig, KernelFunc, TensorInfo, Transform, TransformAttrs, TransformInputs, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nlet wasmTransform: (\n imageId: number, transformsId: number, isBatchTransform: boolean,\n batch: number, outHeight: number, outWidth: number, numChannels: number,\n imageWidth: number, imageHeight: number, strides: Uint8Array,\n stridesLength: number, interpolationModeId: number, fillModeId: number,\n fillValue: number, outId: number) => void;\n\nfunction setup(backend: BackendWasm): void {\n wasmTransform = backend.wasm.cwrap(Transform, null /*void*/, [\n 'number', // imageId\n 'number', // transformsId\n 'bool', // isBatchTransform\n 'number', // batch\n 'number', // outHeight\n 'number', // outWidth\n 'number', // numChannels\n 'number', // imageWidth\n 'number', // imageHeight\n 'array', // strides\n 'number', // stridesLength\n 'number', // interpolationModeId\n 'number', // fillModeId\n 'number', // fillValue\n 'number' // outId\n ]);\n}\n\nfunction transform(\n args:\n {backend: BackendWasm, inputs: TransformInputs, attrs: TransformAttrs}):\n TensorInfo {\n const {backend, inputs, attrs} = args;\n const {image, transforms} = inputs;\n const {interpolation, fillMode, fillValue, outputShape} = attrs;\n\n const [batch, imageHeight, imageWidth, numChannels] = image.shape;\n const [outHeight, outWidth] =\n outputShape != null ? outputShape : [imageHeight, imageWidth];\n const outShape =\n [batch, outHeight, outWidth,\n numChannels] as [number, number, number, number];\n const strides =\n new Uint8Array(new Int32Array(util.computeStrides(image.shape)).buffer);\n\n const out = backend.makeOutput(outShape, image.dtype);\n const outId = backend.dataIdMap.get(out.dataId).id;\n\n const imageData = backend.dataIdMap.get(image.dataId);\n const imageId = imageData.id;\n\n const transformsData = backend.dataIdMap.get(transforms.dataId);\n const transformsId = transformsData.id;\n\n const interpolationModeId = interpolation === 'nearest' ? 1 : 2;\n let fillModeId;\n switch (fillMode) {\n case 'constant':\n fillModeId = 1;\n break;\n case 'reflect':\n fillModeId = 2;\n break;\n case 'wrap':\n fillModeId = 3;\n break;\n case 'nearest':\n fillModeId = 4;\n break;\n default:\n fillModeId = 1;\n break;\n }\n\n wasmTransform(\n imageId, transformsId, (transforms.shape[0] > 1), batch, outHeight,\n outWidth, numChannels, imageWidth, imageHeight, strides,\n image.shape.length - 1, interpolationModeId, fillModeId, fillValue,\n outId);\n\n return out;\n}\n\nexport const transformConfig: KernelConfig = {\n kernelName: Transform,\n backendName: 'wasm',\n setupFunc: setup,\n kernelFunc: transform as {} 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 {KernelConfig, KernelFunc, TensorInfo, Unpack, UnpackAttrs, UnpackInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nimport {slice} from './Slice';\n\nfunction unpack(\n args: {inputs: UnpackInputs, backend: BackendWasm, attrs: UnpackAttrs}):\n TensorInfo[] {\n const {inputs, backend, attrs} = args;\n const {value} = inputs;\n let {axis} = attrs;\n\n if (axis < 0) {\n axis += value.shape.length;\n }\n\n const numOutputs = value.shape[axis];\n const rank = value.shape.length;\n const outShape: number[] = new Array(rank - 1);\n let outIndex = 0;\n for (let i = 0; i < rank; i++) {\n if (i !== axis) {\n outShape[outIndex++] = value.shape[i];\n }\n }\n const outs: TensorInfo[] = new Array(numOutputs);\n const begin = new Array(rank).fill(0);\n const size = value.shape.slice();\n size[axis] = 1;\n for (let i = 0; i < outs.length; i++) {\n begin[axis] = i;\n outs[i] = slice({inputs: {x: value}, attrs: {begin, size}, backend});\n }\n return outs.map(({dataId, dtype}) => ({dataId, dtype, shape: outShape}));\n}\n\nexport const unpackConfig: KernelConfig = {\n kernelName: Unpack,\n backendName: 'wasm',\n kernelFunc: unpack as {} 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, ZerosLike, ZerosLikeInputs} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm} from '../backend_wasm';\n\nfunction zerosLike(args: {inputs: ZerosLikeInputs, backend: BackendWasm}) {\n const {inputs: {x}, backend} = args;\n const out = backend.makeOutput(x.shape, x.dtype);\n const outVals = backend.typedArrayFromHeap(out);\n outVals.fill(0);\n return out;\n}\n\nexport const zerosLikeConfig: KernelConfig = {\n kernelName: ZerosLike,\n backendName: 'wasm',\n kernelFunc: zerosLike as {} 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// We explicitly import the modular kernels so they get registered in the\n// global registry when we compile the library. A modular build would replace\n// the contents of this file and import only the kernels that are needed.\nimport {KernelConfig, registerKernel} from '@tensorflow/tfjs-core';\n\nimport {fusedMatMulConfig} from './kernels/_FusedMatMul';\nimport {absConfig} from './kernels/Abs';\nimport {addConfig} from './kernels/Add';\nimport {addNConfig} from './kernels/AddN';\nimport {allConfig} from './kernels/All';\nimport {anyConfig} from './kernels/Any';\nimport {argMaxConfig} from './kernels/ArgMax';\nimport {avgPoolConfig} from './kernels/AvgPool';\nimport {batchMatMulConfig} from './kernels/BatchMatMul';\nimport {batchToSpaceNDConfig} from './kernels/BatchToSpaceND';\nimport {castConfig} from './kernels/Cast';\nimport {ceilConfig} from './kernels/Ceil';\nimport {clipByValueConfig} from './kernels/ClipByValue';\nimport {concatConfig} from './kernels/Concat';\nimport {conv2DConfig} from './kernels/Conv2D';\nimport {conv2DBackpropInputConfig} from './kernels/Conv2DBackpropInput';\nimport {cosConfig} from './kernels/Cos';\nimport {coshConfig} from './kernels/Cosh';\nimport {cropAndResizeConfig} from './kernels/CropAndResize';\nimport {cumsumConfig} from './kernels/Cumsum';\nimport {depthToSpaceConfig} from './kernels/DepthToSpace';\nimport {depthwiseConv2dNativeConfig} from './kernels/DepthwiseConv2dNative';\nimport {equalConfig} from './kernels/Equal';\nimport {expConfig} from './kernels/Exp';\nimport {expandDimsConfig} from './kernels/ExpandDims';\nimport {fillConfig} from './kernels/Fill';\nimport {flipLeftRightConfig} from './kernels/FlipLeftRight';\nimport {floorConfig} from './kernels/Floor';\nimport {floorDivConfig} from './kernels/FloorDiv';\nimport {fusedBatchNormConfig} from './kernels/FusedBatchNorm';\nimport {fusedConv2DConfig} from './kernels/FusedConv2D';\nimport {fusedDepthwiseConv2DConfig} from './kernels/FusedDepthwiseConv2D';\nimport {gatherNdConfig} from './kernels/GatherNd';\nimport {gatherV2Config} from './kernels/GatherV2';\nimport {greaterConfig} from './kernels/Greater';\nimport {greaterEqualConfig} from './kernels/GreaterEqual';\nimport {identityConfig} from './kernels/Identity';\nimport {leakyReluConfig} from './kernels/LeakyRelu';\nimport {lessConfig} from './kernels/Less';\nimport {lessEqualConfig} from './kernels/LessEqual';\nimport {logConfig} from './kernels/Log';\nimport {logicalAndConfig} from './kernels/LogicalAnd';\nimport {maxConfig} from './kernels/Max';\nimport {maximumConfig} from './kernels/Maximum';\nimport {maxPoolConfig} from './kernels/MaxPool';\nimport {meanConfig} from './kernels/Mean';\nimport {minConfig} from './kernels/Min';\nimport {minimumConfig} from './kernels/Minimum';\nimport {mirrorPadConfig} from './kernels/MirrorPad';\nimport {multiplyConfig} from './kernels/Multiply';\nimport {negConfig} from './kernels/Neg';\nimport {nonMaxSuppressionV3Config} from './kernels/NonMaxSuppressionV3';\nimport {nonMaxSuppressionV4Config} from './kernels/NonMaxSuppressionV4';\nimport {nonMaxSuppressionV5Config} from './kernels/NonMaxSuppressionV5';\nimport {notEqualConfig} from './kernels/NotEqual';\nimport {oneHotConfig} from './kernels/OneHot';\nimport {onesLikeConfig} from './kernels/OnesLike';\nimport {packConfig} from './kernels/Pack';\nimport {padV2Config} from './kernels/PadV2';\nimport {powConfig} from './kernels/Pow';\nimport {preluConfig} from './kernels/Prelu';\nimport {prodConfig} from './kernels/Prod';\nimport {rangeConfig} from './kernels/Range';\nimport {realDivConfig} from './kernels/RealDiv';\nimport {reluConfig} from './kernels/Relu';\nimport {relu6Config} from './kernels/Relu6';\nimport {reshapeConfig} from './kernels/Reshape';\nimport {resizeBilinearConfig} from './kernels/ResizeBilinear';\nimport {reverseConfig} from './kernels/Reverse';\nimport {rotateWithOffsetConfig} from './kernels/RotateWithOffset';\nimport {roundConfig} from './kernels/Round';\nimport {rsqrtConfig} from './kernels/Rsqrt';\nimport {scatterNdConfig} from './kernels/ScatterNd';\nimport {selectConfig} from './kernels/Select';\nimport {sigmoidConfig} from './kernels/Sigmoid';\nimport {sinConfig} from './kernels/Sin';\nimport {sliceConfig} from './kernels/Slice';\nimport {softmaxConfig} from './kernels/Softmax';\nimport {spaceToBatchNDConfig} from './kernels/SpaceToBatchND';\nimport {splitVConfig} from './kernels/SplitV';\nimport {sqrtConfig} from './kernels/Sqrt';\nimport {squareConfig} from './kernels/Square';\nimport {squaredDifferenceConfig} from './kernels/SquaredDifference';\nimport {stepConfig} from './kernels/Step';\nimport {stridedSliceConfig} from './kernels/StridedSlice';\nimport {subConfig} from './kernels/Sub';\nimport {sumConfig} from './kernels/Sum';\nimport {tanConfig} from './kernels/Tan';\nimport {tanhConfig} from './kernels/Tanh';\nimport {tileConfig} from './kernels/Tile';\nimport {topKConfig} from './kernels/TopK';\nimport {transformConfig} from './kernels/Transform';\nimport {transposeConfig} from './kernels/Transpose';\nimport {unpackConfig} from './kernels/Unpack';\nimport {zerosLikeConfig} from './kernels/ZerosLike';\n\n// List all kernel configs here\nconst kernelConfigs: KernelConfig[] = [\n absConfig,\n addConfig,\n addNConfig,\n allConfig,\n anyConfig,\n argMaxConfig,\n avgPoolConfig,\n batchMatMulConfig,\n batchToSpaceNDConfig,\n castConfig,\n ceilConfig,\n clipByValueConfig,\n concatConfig,\n conv2DConfig,\n conv2DBackpropInputConfig,\n cosConfig,\n coshConfig,\n cropAndResizeConfig,\n cumsumConfig,\n depthToSpaceConfig,\n depthwiseConv2dNativeConfig,\n equalConfig,\n expConfig,\n expandDimsConfig,\n fillConfig,\n flipLeftRightConfig,\n floorConfig,\n floorDivConfig,\n fusedMatMulConfig,\n fusedBatchNormConfig,\n fusedConv2DConfig,\n fusedDepthwiseConv2DConfig,\n gatherNdConfig,\n gatherV2Config,\n greaterConfig,\n greaterEqualConfig,\n identityConfig,\n leakyReluConfig,\n lessConfig,\n lessEqualConfig,\n logConfig,\n logicalAndConfig,\n maxConfig,\n maximumConfig,\n maxPoolConfig,\n meanConfig,\n minConfig,\n minimumConfig,\n mirrorPadConfig,\n multiplyConfig,\n negConfig,\n nonMaxSuppressionV3Config,\n nonMaxSuppressionV4Config,\n nonMaxSuppressionV5Config,\n notEqualConfig,\n oneHotConfig,\n onesLikeConfig,\n packConfig,\n padV2Config,\n powConfig,\n preluConfig,\n prodConfig,\n rangeConfig,\n realDivConfig,\n reluConfig,\n relu6Config,\n reshapeConfig,\n resizeBilinearConfig,\n reverseConfig,\n rotateWithOffsetConfig,\n rsqrtConfig,\n roundConfig,\n scatterNdConfig,\n selectConfig,\n sigmoidConfig,\n sinConfig,\n sliceConfig,\n softmaxConfig,\n spaceToBatchNDConfig,\n splitVConfig,\n sqrtConfig,\n squareConfig,\n squaredDifferenceConfig,\n stepConfig,\n stridedSliceConfig,\n subConfig,\n sumConfig,\n tanConfig,\n tanhConfig,\n tileConfig,\n topKConfig,\n transformConfig,\n transposeConfig,\n unpackConfig,\n zerosLikeConfig\n];\n\nfor (const kernelConfig of kernelConfigs) {\n registerKernel(kernelConfig);\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 {env} from '@tensorflow/tfjs-core';\n\nconst ENV = env();\n\n/**\n * True if SIMD is supported.\n */\n// From: https://github.com/GoogleChromeLabs/wasm-feature-detect\nENV.registerFlag(\n // This typed array passed in to WebAssembly.validate is WebAssembly binary\n // code. In this case it is a small program that contains SIMD\n // instructions.\n 'WASM_HAS_SIMD_SUPPORT', async () => WebAssembly.validate(new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3,\n 2, 1, 0, 10, 9, 1, 7, 0, 65, 0, 253, 15, 26, 11\n ])));\n\n/**\n * True if threads are supported.\n */\n// From: https://github.com/GoogleChromeLabs/wasm-feature-detect\nENV.registerFlag('WASM_HAS_MULTITHREAD_SUPPORT', async () => {\n // TODO(annxingyuan): Enable node support once this is resolved:\n // https://github.com/tensorflow/tfjs/issues/3830\n if (ENV.get('IS_NODE')) {\n return false;\n }\n\n try {\n // Test for transferability of SABs (needed for Firefox)\n // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ\n new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));\n // This typed array is a WebAssembly program containing threaded\n // instructions.\n return WebAssembly.validate(new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5,\n 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11\n ]));\n } catch (e) {\n return false;\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 './flags_wasm';\n\nimport {backend_util, BackendTimingInfo, DataStorage, DataType, deprecationWarn, engine, env, KernelBackend, TensorInfo, util} from '@tensorflow/tfjs-core';\n\nimport {BackendWasmModule, WasmFactoryConfig} from '../wasm-out/tfjs-backend-wasm';\nimport {BackendWasmThreadedSimdModule} from '../wasm-out/tfjs-backend-wasm-threaded-simd';\nimport wasmFactoryThreadedSimd from '../wasm-out/tfjs-backend-wasm-threaded-simd.js';\n// @ts-ignore\nimport {wasmWorkerContents} from '../wasm-out/tfjs-backend-wasm-threaded-simd.worker.js';\nimport wasmFactory from '../wasm-out/tfjs-backend-wasm.js';\n\ninterface TensorData {\n id: number;\n memoryOffset: number;\n shape: number[];\n dtype: DataType;\n refCount: number;\n /** Only used for string tensors, storing encoded bytes. */\n stringBytes?: Uint8Array[];\n}\n\nexport type DataId = object; // object instead of {} to force non-primitive.\n\nexport class BackendWasm extends KernelBackend {\n // 0 is reserved for null data ids.\n private dataIdNextNumber = 1;\n dataIdMap: DataStorage<TensorData>;\n\n constructor(public wasm: BackendWasmModule | BackendWasmThreadedSimdModule) {\n super();\n this.wasm.tfjs.init();\n this.dataIdMap = new DataStorage(this, engine());\n }\n\n write(values: backend_util.BackendValues, shape: number[], dtype: DataType):\n DataId {\n const dataId = {id: this.dataIdNextNumber++};\n this.move(dataId, values, shape, dtype, 1);\n return dataId;\n }\n\n numDataIds(): number {\n return this.dataIdMap.numDataIds();\n }\n\n 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 move(\n dataId: DataId, values: backend_util.BackendValues, shape: number[],\n dtype: DataType, refCount: number): void {\n const id = this.dataIdNextNumber++;\n if (dtype === 'string') {\n const stringBytes = values as Uint8Array[];\n this.dataIdMap.set(\n dataId,\n {id, stringBytes, shape, dtype, memoryOffset: null, refCount});\n return;\n }\n\n const size = util.sizeFromShape(shape);\n const numBytes = size * util.bytesPerElement(dtype);\n const memoryOffset = this.wasm._malloc(numBytes);\n\n this.dataIdMap.set(dataId, {id, memoryOffset, shape, dtype, refCount});\n\n this.wasm.tfjs.registerTensor(id, size, memoryOffset);\n\n if (values != null) {\n this.wasm.HEAPU8.set(\n new Uint8Array(\n (values as backend_util.TypedArray).buffer,\n (values as backend_util.TypedArray).byteOffset, numBytes),\n memoryOffset);\n }\n }\n\n async read(dataId: DataId): Promise<backend_util.BackendValues> {\n return this.readSync(dataId);\n }\n\n readSync(dataId: DataId): backend_util.BackendValues {\n const {memoryOffset, dtype, shape, stringBytes} =\n this.dataIdMap.get(dataId);\n if (dtype === 'string') {\n return stringBytes;\n }\n const bytes = this.wasm.HEAPU8.slice(\n memoryOffset,\n memoryOffset + util.sizeFromShape(shape) * util.bytesPerElement(dtype));\n return typedArrayFromBuffer(bytes.buffer, dtype);\n }\n\n /**\n * Dispose the memory if the dataId has 0 refCount. Return true if the memory\n * is released, false otherwise.\n * @param dataId\n * @oaram force Optional, remove the data regardless of refCount\n */\n disposeData(dataId: DataId, force = false): boolean {\n if (this.dataIdMap.has(dataId)) {\n const data = this.dataIdMap.get(dataId);\n data.refCount--;\n if (!force && data.refCount > 0) {\n return false;\n }\n\n this.wasm._free(data.memoryOffset);\n this.wasm.tfjs.disposeData(data.id);\n this.dataIdMap.delete(dataId);\n }\n return true;\n }\n\n /** Return refCount of a `TensorData`. */\n refCount(dataId: DataId): number {\n if (this.dataIdMap.has(dataId)) {\n const tensorData = this.dataIdMap.get(dataId);\n return tensorData.refCount;\n }\n return 0;\n }\n\n incRef(dataId: DataId) {\n const data = this.dataIdMap.get(dataId);\n if (data != null) {\n data.refCount++;\n }\n }\n\n floatPrecision(): 32 {\n return 32;\n }\n\n // Returns the memory offset of a tensor. Useful for debugging and unit\n // testing.\n getMemoryOffset(dataId: DataId): number {\n return this.dataIdMap.get(dataId).memoryOffset;\n }\n\n dispose() {\n this.wasm.tfjs.dispose();\n if ('PThread' in this.wasm) {\n this.wasm.PThread.terminateAllThreads();\n }\n this.wasm = null;\n }\n\n memory() {\n return {unreliable: false};\n }\n\n /**\n * Make a tensor info for the output of an op. If `memoryOffset` is not\n * present, this method allocates memory on the WASM heap. If `memoryOffset`\n * is present, the memory was allocated elsewhere (in c++) and we just record\n * the pointer where that memory lives.\n */\n makeOutput(shape: number[], dtype: DataType, memoryOffset?: number):\n TensorInfo {\n let dataId: {};\n if (memoryOffset == null) {\n dataId = this.write(null /* values */, shape, dtype);\n } else {\n const id = this.dataIdNextNumber++;\n dataId = {id};\n this.dataIdMap.set(dataId, {id, memoryOffset, shape, dtype, refCount: 1});\n const size = util.sizeFromShape(shape);\n this.wasm.tfjs.registerTensor(id, size, memoryOffset);\n }\n return {dataId, shape, dtype};\n }\n\n typedArrayFromHeap({shape, dtype, dataId}: TensorInfo):\n backend_util.TypedArray {\n const buffer = this.wasm.HEAPU8.buffer;\n const {memoryOffset} = this.dataIdMap.get(dataId);\n const size = util.sizeFromShape(shape);\n switch (dtype) {\n case 'float32':\n return new Float32Array(buffer, memoryOffset, size);\n case 'int32':\n return new Int32Array(buffer, memoryOffset, size);\n case 'bool':\n return new Uint8Array(buffer, memoryOffset, size);\n default:\n throw new Error(`Unknown dtype ${dtype}`);\n }\n }\n}\n\nfunction createInstantiateWasmFunc(path: string) {\n // this will be replace by rollup plugin patchWechatWebAssembly in \n // minprogram's output.\n // tslint:disable-next-line:no-any\n return (imports: any, callback: any) => {\n util.fetch(path, {credentials: 'same-origin'}).then((response) => {\n if (!response['ok']) {\n imports.env.a(`failed to load wasm binary file at '${path}'`);\n }\n response.arrayBuffer().then(binary => {\n WebAssembly.instantiate(binary, imports).then(output => {\n callback(output.instance, output.module);\n });\n });\n });\n return {};\n };\n}\n\n/**\n * Returns the path of the WASM binary.\n * @param simdSupported whether SIMD is supported\n * @param threadsSupported whether multithreading is supported\n * @param wasmModuleFolder the directory containing the WASM binaries.\n */\nfunction getPathToWasmBinary(\n simdSupported: boolean, threadsSupported: boolean,\n wasmModuleFolder: string) {\n if (wasmPath != null) {\n // If wasmPath is defined, the user has supplied a full path to\n // the vanilla .wasm binary.\n return wasmPath;\n }\n\n let path: WasmBinaryName = 'tfjs-backend-wasm.wasm';\n if (simdSupported && threadsSupported) {\n path = 'tfjs-backend-wasm-threaded-simd.wasm';\n } else if (simdSupported) {\n path = 'tfjs-backend-wasm-simd.wasm';\n }\n\n if (wasmFileMap != null) {\n if (wasmFileMap[path] != null) {\n return wasmFileMap[path];\n }\n }\n\n return wasmModuleFolder + path;\n}\n\n/**\n * Initializes the wasm module and creates the js <--> wasm bridge.\n *\n * NOTE: We wrap the wasm module in a object with property 'wasm' instead of\n * returning Promise<BackendWasmModule> to avoid freezing Chrome (last tested\n * in Chrome 76).\n */\nexport async function init(): Promise<{wasm: BackendWasmModule}> {\n const [simdSupported, threadsSupported] = await Promise.all([\n env().getAsync('WASM_HAS_SIMD_SUPPORT'),\n env().getAsync('WASM_HAS_MULTITHREAD_SUPPORT')\n ]);\n\n return new Promise((resolve, reject) => {\n const factoryConfig: WasmFactoryConfig = {};\n\n /**\n * This function overrides the Emscripten module locateFile utility.\n * @param path The relative path to the file that needs to be loaded.\n * @param prefix The path to the main JavaScript file's directory.\n */\n factoryConfig.locateFile = (path, prefix) => {\n if (path.endsWith('.worker.js')) {\n const response = wasmWorkerContents;\n const blob = new Blob([response], {type: 'application/javascript'});\n return URL.createObjectURL(blob);\n }\n\n if (path.endsWith('.wasm')) {\n return getPathToWasmBinary(\n simdSupported as boolean, threadsSupported as boolean,\n wasmPathPrefix != null ? wasmPathPrefix : prefix);\n }\n return prefix + path;\n };\n\n // Use the instantiateWasm override when system fetch is not available.\n // Reference:\n // https://github.com/emscripten-core/emscripten/blob/2bca083cbbd5a4133db61fbd74d04f7feecfa907/tests/manual_wasm_instantiate.html#L170\n if (customFetch) {\n factoryConfig.instantiateWasm =\n createInstantiateWasmFunc(getPathToWasmBinary(\n simdSupported as boolean, threadsSupported as boolean,\n wasmPathPrefix != null ? wasmPathPrefix : ''));\n }\n\n let initialized = false;\n factoryConfig.onAbort = () => {\n if (initialized) {\n // Emscripten already called console.warn so no need to double log.\n return;\n }\n if (initAborted) {\n // Emscripten calls `onAbort` twice, resulting in double error\n // messages.\n return;\n }\n initAborted = true;\n const rejectMsg =\n 'Make sure the server can serve the `.wasm` file relative to the ' +\n 'bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers';\n reject({message: rejectMsg});\n };\n\n let wasm: Promise<BackendWasmModule>;\n // If `wasmPath` has been defined we must initialize the vanilla module.\n if (threadsSupported && simdSupported && wasmPath == null) {\n factoryConfig.mainScriptUrlOrBlob = new Blob(\n [`var WasmBackendModuleThreadedSimd = ` +\n wasmFactoryThreadedSimd.toString()],\n {type: 'text/javascript'});\n wasm = wasmFactoryThreadedSimd(factoryConfig);\n } else {\n // The wasmFactory works for both vanilla and SIMD binaries.\n wasm = wasmFactory(factoryConfig);\n }\n\n // The WASM module has been successfully created by the factory.\n // Any error will be caught by the onAbort callback defined above.\n wasm.then((module) => {\n initialized = true;\n initAborted = false;\n\n const voidReturnType: string = null;\n // Using the tfjs namespace to avoid conflict with emscripten's API.\n module.tfjs = {\n init: module.cwrap('init', null, []),\n registerTensor: module.cwrap(\n 'register_tensor', null,\n [\n 'number', // id\n 'number', // size\n 'number', // memoryOffset\n ]),\n disposeData: module.cwrap('dispose_data', voidReturnType, ['number']),\n dispose: module.cwrap('dispose', voidReturnType, []),\n };\n\n resolve({wasm: module});\n });\n });\n}\n\nfunction typedArrayFromBuffer(\n buffer: ArrayBuffer, dtype: DataType): backend_util.TypedArray {\n switch (dtype) {\n case 'float32':\n return new Float32Array(buffer);\n case 'int32':\n return new Int32Array(buffer);\n case 'bool':\n return new Uint8Array(buffer);\n default:\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\nconst wasmBinaryNames = [\n 'tfjs-backend-wasm.wasm', 'tfjs-backend-wasm-simd.wasm',\n 'tfjs-backend-wasm-threaded-simd.wasm'\n] as const ;\ntype WasmBinaryName = typeof wasmBinaryNames[number];\n\nlet wasmPath: string = null;\nlet wasmPathPrefix: string = null;\nlet wasmFileMap: {[key in WasmBinaryName]?: string} = {};\nlet initAborted = false;\nlet customFetch = false;\n\n/**\n * @deprecated Use `setWasmPaths` instead.\n * Sets the path to the `.wasm` file which will be fetched when the wasm\n * backend is initialized. See\n * https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers\n * for more details.\n * @param path wasm file path or url\n * @param usePlatformFetch optional boolean to use platform fetch to download\n * the wasm file, default to false.\n *\n * @doc {heading: 'Environment', namespace: 'wasm'}\n */\nexport function setWasmPath(path: string, usePlatformFetch = false): void {\n deprecationWarn(\n 'setWasmPath has been deprecated in favor of setWasmPaths and' +\n ' will be removed in a future release.');\n if (initAborted) {\n throw new Error(\n 'The WASM backend was already initialized. Make sure you call ' +\n '`setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`');\n }\n wasmPath = path;\n customFetch = usePlatformFetch;\n}\n\n/**\n * Configures the locations of the WASM binaries.\n *\n * ```js\n * setWasmPaths({\n * 'tfjs-backend-wasm.wasm': 'renamed.wasm',\n * 'tfjs-backend-wasm-simd.wasm': 'renamed-simd.wasm',\n * 'tfjs-backend-wasm-threaded-simd.wasm': 'renamed-threaded-simd.wasm'\n * });\n * tf.setBackend('wasm');\n * ```\n *\n * @param prefixOrFileMap This can be either a string or object:\n * - (string) The path to the directory where the WASM binaries are located.\n * Note that this prefix will be used to load each binary (vanilla,\n * SIMD-enabled, threading-enabled, etc.).\n * - (object) Mapping from names of WASM binaries to custom\n * full paths specifying the locations of those binaries. This is useful if\n * your WASM binaries are not all located in the same directory, or if your\n * WASM binaries have been renamed.\n * @param usePlatformFetch optional boolean to use platform fetch to download\n * the wasm file, default to false.\n *\n * @doc {heading: 'Environment', namespace: 'wasm'}\n */\nexport function setWasmPaths(\n prefixOrFileMap: string|{[key in WasmBinaryName]?: string},\n usePlatformFetch = false): void {\n if (initAborted) {\n throw new Error(\n 'The WASM backend was already initialized. Make sure you call ' +\n '`setWasmPaths()` before you call `tf.setBackend()` or ' +\n '`tf.ready()`');\n }\n\n if (typeof prefixOrFileMap === 'string') {\n wasmPathPrefix = prefixOrFileMap;\n } else {\n wasmFileMap = prefixOrFileMap;\n const missingPaths =\n wasmBinaryNames.filter(name => wasmFileMap[name] == null);\n if (missingPaths.length > 0) {\n throw new Error(\n `There were no entries found for the following binaries: ` +\n `${missingPaths.join(',')}. Please either call setWasmPaths with a ` +\n `map providing a path for each binary, or with a string indicating ` +\n `the directory where all the binaries can be found.`);\n }\n }\n\n customFetch = usePlatformFetch;\n}\n\n/** Used in unit tests. */\nexport function resetWasmPath(): void {\n wasmPath = null;\n wasmPathPrefix = null;\n wasmFileMap = {};\n customFetch = false;\n initAborted = false;\n}\n", "export const wasmWorkerContents = 'var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(\" \");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(\" \");postMessage({cmd:\"alert\",text:text,threadId:Module[\"_pthread_self\"]()})}var err=threadPrintErr;this.alert=threadAlert;Module[\"instantiateWasm\"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module[\"wasmModule\"],info);Module[\"wasmModule\"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd===\"load\"){Module[\"wasmModule\"]=e.data.wasmModule;Module[\"wasmMemory\"]=e.data.wasmMemory;Module[\"buffer\"]=Module[\"wasmMemory\"].buffer;Module[\"ENVIRONMENT_IS_PTHREAD\"]=true;if(typeof e.data.urlOrBlob===\"string\"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd===\"objectTransfer\"){Module[\"PThread\"].receiveObjectTransfer(e.data)}else if(e.data.cmd===\"run\"){Module[\"__performance_now_clock_drift\"]=performance.now()-e.data.time;Module[\"__emscripten_thread_init\"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module[\"establishStackSpace\"](top,max);Module[\"_emscripten_tls_init\"]();Module[\"PThread\"].receiveObjectTransfer(e.data);Module[\"PThread\"].setThreadStatus(Module[\"_pthread_self\"](),1);try{var result=Module[\"invokeEntryPoint\"](e.data.start_routine,e.data.arg);if(!Module[\"getNoExitRuntime\"]())Module[\"PThread\"].threadExit(result)}catch(ex){if(ex===\"Canceled!\"){Module[\"PThread\"].threadCancel()}else if(ex!=\"unwind\"){if(ex instanceof Module[\"ExitStatus\"]){if(Module[\"getNoExitRuntime\"]()){}else{Module[\"PThread\"].threadExit(ex.status)}}else{Module[\"PThread\"].threadExit(-2);throw ex}}}}else if(e.data.cmd===\"cancel\"){if(Module[\"_pthread_self\"]()){Module[\"PThread\"].threadCancel()}}else if(e.data.target===\"setimmediate\"){}else if(e.data.cmd===\"processThreadQueue\"){if(Module[\"_pthread_self\"]()){Module[\"_emscripten_current_thread_process_queued_calls\"]()}}else{err(\"worker.js received unknown command \"+e.data.cmd);err(e.data)}}catch(ex){err(\"worker.js onmessage() captured an uncaught exception: \"+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process===\"object\"&&typeof process.versions===\"object\"&&typeof process.versions.node===\"string\"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require(\"worker_threads\");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on(\"message\",function(data){onmessage({data:data})});var nodeFS=require(\"fs\");var nodeRead=function(filename){return nodeFS.readFileSync(filename,\"utf8\")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance===\"undefined\"){performance={now:function(){return Date.now()}}}}';", "/** @license See the LICENSE file. */\n\n// This code is auto-generated, do not modify this file!\nconst version = '3.8.0';\nexport {version};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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_wasm';\n\nimport {registerBackend} from '@tensorflow/tfjs-core';\n\nimport {BackendWasm, init} from './backend_wasm';\n\nexport {BackendWasm, setWasmPath, setWasmPaths} from './backend_wasm';\nexport {version as version_wasm} from './version';\n\nconst WASM_PRIORITY = 2;\nregisterBackend('wasm', async () => {\n const {wasm} = await init();\n return new BackendWasm(wasm);\n}, WASM_PRIORITY);\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 './register_all_kernels';\nexport * from './base';\n", "/**\n * Creates tfjs bundle used by Human browser build target\n * @external\n */\n\n// get versions of all packages\nimport { version as tfjsVersion } from '@tensorflow/tfjs/package.json';\nimport { version as tfjsCoreVersion } from '@tensorflow/tfjs-core/package.json';\nimport { version as tfjsDataVersion } from '@tensorflow/tfjs-data/package.json';\nimport { version as tfjsLayersVersion } from '@tensorflow/tfjs-layers/package.json';\nimport { version as tfjsConverterVersion } from '@tensorflow/tfjs-converter/package.json';\nimport { version as tfjsBackendCPUVersion } from '@tensorflow/tfjs-backend-cpu/package.json';\nimport { version as tfjsBackendWebGLVersion } from '@tensorflow/tfjs-backend-webgl/package.json';\nimport { version as tfjsBackendWASMVersion } from '@tensorflow/tfjs-backend-wasm/package.json';\n\n// export all from sources\n// requires treeShaking:ignore-annotations due to tfjs misconfiguration\n/*\nexport * from '@tensorflow/tfjs-core/src/index';\nexport * from '@tensorflow/tfjs-layers/src/index';\nexport * from '@tensorflow/tfjs-converter/src/index';\nexport * as data from '@tensorflow/tfjs-data/src/index';\nexport * from '@tensorflow/tfjs-backend-cpu/src/index';\nexport * from '@tensorflow/tfjs-backend-webgl/src/index';\nexport * from '@tensorflow/tfjs-backend-wasm/src/index';\n*/\n\n// export all from build\nexport * from '@tensorflow/tfjs-core/dist/index.js';\nexport * from '@tensorflow/tfjs-layers/dist/index.js';\nexport * from '@tensorflow/tfjs-converter/dist/index.js';\nexport * as data from '@tensorflow/tfjs-data/dist/index.js';\nexport * from '@tensorflow/tfjs-backend-cpu/dist/index.js';\nexport * from '@tensorflow/tfjs-backend-webgl/dist/index.js';\nexport * from '@tensorflow/tfjs-backend-wasm/dist/index.js';\n// export * from '@tensorflow/tfjs-backend-webgpu/dist/index.js'; // experimental\n\n// export versions\nexport const version = {\n tfjs: tfjsVersion,\n 'tfjs-core': tfjsCoreVersion,\n 'tfjs-data': tfjsDataVersion,\n 'tfjs-layers': tfjsLayersVersion,\n 'tfjs-converter': tfjsConverterVersion,\n 'tfjs-backend-cpu': tfjsBackendCPUVersion,\n 'tfjs-backend-webgl': tfjsBackendWebGLVersion,\n 'tfjs-backend-wasm': tfjsBackendWASMVersion,\n};\n", "/**\n * Custom TFJS backend for Human based on WebGL\n * Not used by default\n */\n\nimport { log } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\n\nexport const config = {\n name: 'humangl',\n priority: 99,\n canvas: <null | OffscreenCanvas | HTMLCanvasElement>null,\n gl: <null | WebGL2RenderingContext>null,\n width: 1024,\n height: 1024,\n extensions: <string[]> [],\n webGLattr: { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2\n alpha: false,\n antialias: false,\n premultipliedAlpha: false,\n preserveDrawingBuffer: false,\n depth: false,\n stencil: false,\n failIfMajorPerformanceCaveat: false,\n desynchronized: true,\n },\n};\n\nfunction extensions(): void {\n /*\n https://www.khronos.org/registry/webgl/extensions/\n https://webglreport.com/?v=2\n */\n const gl = config.gl;\n if (!gl) return;\n config.extensions = gl.getSupportedExtensions() as string[];\n // gl.getExtension('KHR_parallel_shader_compile');\n}\n\n/**\n * Registers custom WebGL2 backend to be used by Human library\n *\n * @returns void\n */\nexport function register(): void {\n if (!tf.findBackend(config.name)) {\n // log('backend registration:', config.name);\n try {\n config.canvas = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(config.width, config.height) : document.createElement('canvas');\n } catch (err) {\n log('error: cannot create canvas:', err);\n return;\n }\n try {\n config.gl = config.canvas.getContext('webgl2', config.webGLattr) as WebGL2RenderingContext;\n } catch (err) {\n log('error: cannot get WebGL2 context:', err);\n return;\n }\n try {\n tf.setWebGLContext(2, config.gl);\n } catch (err) {\n log('error: cannot set WebGL2 context:', err);\n return;\n }\n try {\n const ctx = new tf.GPGPUContext(config.gl);\n tf.registerBackend(config.name, () => new tf.MathBackendWebGL(ctx), config.priority);\n } catch (err) {\n log('error: cannot register WebGL backend:', err);\n return;\n }\n try {\n const kernels = tf.getKernelsForBackend('webgl');\n kernels.forEach((kernelConfig) => {\n const newKernelConfig = { ...kernelConfig, backendName: config.name };\n tf.registerKernel(newKernelConfig);\n });\n } catch (err) {\n log('error: cannot update WebGL backend registration:', err);\n return;\n }\n try {\n tf.ENV.set('WEBGL_VERSION', 2);\n } catch (err) {\n log('error: cannot set WebGL backend flags:', err);\n return;\n }\n extensions();\n log('backend registered:', config.name);\n }\n}\n", "import * as tf from '../../dist/tfjs.esm.js';\n\nexport function scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n return { startPoint, endPoint };\n}\n\nexport function getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\n\nexport function getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\n\nexport function cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h,\n box.startPoint[0] / w,\n box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\n\nexport function enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\n\nexport function squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [Math.round(centers[0] - halfSize), Math.round(centers[1] - halfSize)];\n const endPoint = [Math.round(centers[0] + halfSize), Math.round(centers[1] + halfSize)];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\n\nexport function calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint, landmarks };\n}\n\nexport const disposeBox = (t) => {\n tf.dispose(t.startPoint);\n tf.dispose(t.endPoint);\n};\n\nexport const createBox = (startEndTensor) => ({\n startPoint: tf.slice(startEndTensor, [0, 0], [-1, 2]),\n endPoint: tf.slice(startEndTensor, [0, 2], [-1, 2]),\n});\n", "export const IDENTITY_MATRIX = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];\n/**\n * Normalizes the provided angle to the range -pi to pi.\n * @param angle The angle in radians to be normalized.\n */\nexport function normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\n\n/**\n * Computes the angle of rotation between two anchor points.\n * @param point1 First anchor point\n * @param point2 Second anchor point\n */\nexport function computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\n\nexport function radToDegrees(rad) {\n return rad * 180 / Math.PI;\n}\n\nexport function buildTranslationMatrix(x, y) {\n return [[1, 0, x], [0, 1, y], [0, 0, 1]];\n}\n\nexport function dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\n\nexport function getColumnFrom2DArr(arr, columnIndex) {\n const column: Array<number> = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\n\nexport function multiplyTransformMatrices(mat1, mat2) {\n const product: Array<number[]> = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\n\nexport function buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\n\nexport function invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\n\nexport function rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\n\nexport function xyDistanceBetweenPoints(a, b) {\n return Math.sqrt(((a[0] - b[0]) ** 2) + ((a[1] - b[1]) ** 2));\n}\n\nexport function generateAnchors(inputSize) {\n const spec = { strides: [inputSize / 16, inputSize / 8], anchors: [2, 6] };\n const anchors: Array<[number, number]> = [];\n for (let i = 0; i < spec.strides.length; i++) {\n const stride = spec.strides[i];\n const gridRows = Math.floor((inputSize + stride - 1) / stride);\n const gridCols = Math.floor((inputSize + stride - 1) / stride);\n const anchorsNum = spec.anchors[i];\n for (let gridY = 0; gridY < gridRows; gridY++) {\n const anchorY = stride * (gridY + 0.5);\n for (let gridX = 0; gridX < gridCols; gridX++) {\n const anchorX = stride * (gridX + 0.5);\n for (let n = 0; n < anchorsNum; n++) {\n anchors.push([anchorX, anchorY]);\n }\n }\n }\n }\n return anchors;\n}\n", "import { log, join, mergeDeep } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport * as box from './box';\nimport * as util from './util';\nimport { Config } from '../config';\nimport { Tensor, GraphModel } from '../tfjs/types';\n\nconst keypointsCount = 6;\n\nfunction decodeBounds(boxOutputs, anchors, inputSize) {\n const boxStarts = tf.slice(boxOutputs, [0, 1], [-1, 2]);\n const centers = tf.add(boxStarts, anchors);\n const boxSizes = tf.slice(boxOutputs, [0, 3], [-1, 2]);\n const boxSizesNormalized = tf.div(boxSizes, inputSize);\n const centersNormalized = tf.div(centers, inputSize);\n const halfBoxSize = tf.div(boxSizesNormalized, 2);\n const starts = tf.sub(centersNormalized, halfBoxSize);\n const ends = tf.add(centersNormalized, halfBoxSize);\n const startNormalized = tf.mul(starts, inputSize);\n const endNormalized = tf.mul(ends, inputSize);\n const concatAxis = 1;\n return tf.concat2d([startNormalized, endNormalized], concatAxis);\n}\n\nexport class BlazeFaceModel {\n model: GraphModel;\n anchorsData: [number, number][];\n anchors: Tensor;\n inputSize: number;\n config: Config;\n\n constructor(model, config: Config) {\n this.model = model;\n this.anchorsData = util.generateAnchors(model.inputs[0].shape[1]);\n this.anchors = tf.tensor2d(this.anchorsData);\n this.inputSize = model.inputs[0].shape[2];\n this.config = config;\n }\n\n async getBoundingBoxes(inputImage: Tensor, userConfig: Config) {\n // sanity check on input\n // @ts-ignore isDisposed is internal property\n if ((!inputImage) || (inputImage.isDisposedInternal) || (inputImage.shape.length !== 4) || (inputImage.shape[1] < 1) || (inputImage.shape[2] < 1)) return null;\n const [batch, boxes, scores] = tf.tidy(() => {\n const resizedImage = tf.image.resizeBilinear(inputImage, [this.inputSize, this.inputSize]);\n const normalizedImage = tf.sub(tf.div(resizedImage, 127.5), 0.5);\n const res = this.model.execute(normalizedImage);\n let batchOut;\n if (Array.isArray(res)) { // are we using tfhub or pinto converted model?\n const sorted = res.sort((a, b) => a.size - b.size);\n const concat384 = tf.concat([sorted[0], sorted[2]], 2); // dim: 384, 1 + 16\n const concat512 = tf.concat([sorted[1], sorted[3]], 2); // dim: 512, 1 + 16\n const concat = tf.concat([concat512, concat384], 1);\n batchOut = tf.squeeze(concat, 0);\n } else {\n batchOut = tf.squeeze(res); // when using tfhub model\n }\n const boxesOut = decodeBounds(batchOut, this.anchors, [this.inputSize, this.inputSize]);\n const logits = tf.slice(batchOut, [0, 0], [-1, 1]);\n const scoresOut = tf.squeeze(tf.sigmoid(logits)).dataSync(); // inside tf.tidy\n return [batchOut, boxesOut, scoresOut];\n });\n\n this.config = mergeDeep(this.config, userConfig) as Config;\n\n const nmsTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.config.face.detector.maxDetected, this.config.face.detector.iouThreshold, this.config.face.detector.minConfidence);\n const nms = await nmsTensor.array();\n tf.dispose(nmsTensor);\n const annotatedBoxes: Array<{ box: { startPoint: Tensor, endPoint: Tensor }, landmarks: Tensor, anchor: number[], confidence: number }> = [];\n for (let i = 0; i < nms.length; i++) {\n const confidence = scores[nms[i]];\n if (confidence > this.config.face.detector.minConfidence) {\n const boundingBox = tf.slice(boxes, [nms[i], 0], [1, -1]);\n const localBox = box.createBox(boundingBox);\n tf.dispose(boundingBox);\n const anchor = this.anchorsData[nms[i]];\n const landmarks = tf.tidy(() => tf.reshape(tf.squeeze(tf.slice(batch, [nms[i], keypointsCount - 1], [1, -1])), [keypointsCount, -1]));\n annotatedBoxes.push({ box: localBox, landmarks, anchor, confidence });\n }\n }\n tf.dispose(batch);\n tf.dispose(boxes);\n return {\n boxes: annotatedBoxes,\n scaleFactor: [inputImage.shape[2] / this.inputSize, inputImage.shape[1] / this.inputSize],\n };\n }\n}\n\nexport async function load(config: Config) {\n const model = await tf.loadGraphModel(join(config.modelBasePath, config.face.detector.modelPath), { fromTFHub: config.face.detector.modelPath.includes('tfhub.dev') });\n const blazeFace = new BlazeFaceModel(model, config);\n if (!model || !model.modelUrl) log('load model failed:', config.face.detector.modelPath);\n else if (config.debug) log('load model:', model.modelUrl);\n return blazeFace;\n}\n", "export const MESH_ANNOTATIONS = {\n silhouette: [\n 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,\n 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,\n 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,\n ],\n lipsUpperOuter: [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291],\n lipsLowerOuter: [146, 91, 181, 84, 17, 314, 405, 321, 375, 291],\n lipsUpperInner: [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308],\n lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],\n rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],\n rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],\n rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],\n rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],\n rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],\n rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],\n rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],\n rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],\n rightEyebrowLower: [35, 124, 46, 53, 52, 65],\n rightEyeIris: [473, 474, 475, 476, 477],\n leftEyeUpper0: [466, 388, 387, 386, 385, 384, 398],\n leftEyeLower0: [263, 249, 390, 373, 374, 380, 381, 382, 362],\n leftEyeUpper1: [467, 260, 259, 257, 258, 286, 414],\n leftEyeLower1: [359, 255, 339, 254, 253, 252, 256, 341, 463],\n leftEyeUpper2: [342, 445, 444, 443, 442, 441, 413],\n leftEyeLower2: [446, 261, 448, 449, 450, 451, 452, 453, 464],\n leftEyeLower3: [372, 340, 346, 347, 348, 349, 350, 357, 465],\n leftEyebrowUpper: [383, 300, 293, 334, 296, 336, 285, 417],\n leftEyebrowLower: [265, 353, 276, 283, 282, 295],\n leftEyeIris: [468, 469, 470, 471, 472],\n midwayBetweenEyes: [168],\n noseTip: [1],\n noseBottom: [2],\n noseRightCorner: [98],\n noseLeftCorner: [327],\n rightCheek: [205],\n leftCheek: [425],\n};\n\nexport const MESH_TO_IRIS_INDICES_MAP = [ // A mapping from facemesh model keypoints to iris model keypoints.\n { key: 'EyeUpper0', indices: [9, 10, 11, 12, 13, 14, 15] },\n { key: 'EyeUpper1', indices: [25, 26, 27, 28, 29, 30, 31] },\n { key: 'EyeUpper2', indices: [41, 42, 43, 44, 45, 46, 47] },\n { key: 'EyeLower0', indices: [0, 1, 2, 3, 4, 5, 6, 7, 8] },\n { key: 'EyeLower1', indices: [16, 17, 18, 19, 20, 21, 22, 23, 24] },\n { key: 'EyeLower2', indices: [32, 33, 34, 35, 36, 37, 38, 39, 40] },\n { key: 'EyeLower3', indices: [54, 55, 56, 57, 58, 59, 60, 61, 62] },\n // { key: 'EyebrowUpper', indices: [63, 64, 65, 66, 67, 68, 69, 70] },\n // { key: 'EyebrowLower', indices: [48, 49, 50, 51, 52, 53] },\n];\n\nexport const UV468 = [\n [0.499976992607117, 0.652534008026123],\n [0.500025987625122, 0.547487020492554],\n [0.499974012374878, 0.602371990680695],\n [0.482113003730774, 0.471979022026062],\n [0.500150978565216, 0.527155995368958],\n [0.499909996986389, 0.498252987861633],\n [0.499523013830185, 0.40106201171875],\n [0.289712011814117, 0.380764007568359],\n [0.499954998493195, 0.312398016452789],\n [0.499987006187439, 0.269918978214264],\n [0.500023007392883, 0.107050001621246],\n [0.500023007392883, 0.666234016418457],\n [0.5000159740448, 0.679224014282227],\n [0.500023007392883, 0.692348003387451],\n [0.499976992607117, 0.695277988910675],\n [0.499976992607117, 0.70593398809433],\n [0.499976992607117, 0.719385027885437],\n [0.499976992607117, 0.737019002437592],\n [0.499967992305756, 0.781370997428894],\n [0.499816000461578, 0.562981009483337],\n [0.473773002624512, 0.573909997940063],\n [0.104906998574734, 0.254140973091125],\n [0.365929991006851, 0.409575998783112],\n [0.338757991790771, 0.41302502155304],\n [0.311120003461838, 0.409460008144379],\n [0.274657994508743, 0.389131009578705],\n [0.393361985683441, 0.403706014156342],\n [0.345234006643295, 0.344011008739471],\n [0.370094001293182, 0.346076011657715],\n [0.319321990013123, 0.347265005111694],\n [0.297903001308441, 0.353591024875641],\n [0.24779200553894, 0.410809993743896],\n [0.396889001131058, 0.842755019664764],\n [0.280097991228104, 0.375599980354309],\n [0.106310002505779, 0.399955987930298],\n [0.2099249958992, 0.391353011131287],\n [0.355807989835739, 0.534406006336212],\n [0.471751004457474, 0.65040397644043],\n [0.474155008792877, 0.680191993713379],\n [0.439785003662109, 0.657229006290436],\n [0.414617002010345, 0.66654098033905],\n [0.450374007225037, 0.680860996246338],\n [0.428770989179611, 0.682690978050232],\n [0.374971002340317, 0.727805018424988],\n [0.486716985702515, 0.547628998756409],\n [0.485300987958908, 0.527395009994507],\n [0.257764995098114, 0.314490020275116],\n [0.401223003864288, 0.455172002315521],\n [0.429818987846375, 0.548614978790283],\n [0.421351999044418, 0.533740997314453],\n [0.276895999908447, 0.532056987285614],\n [0.483370006084442, 0.499586999416351],\n [0.33721199631691, 0.282882988452911],\n [0.296391993761063, 0.293242990970612],\n [0.169294998049736, 0.193813979625702],\n [0.447580009698868, 0.302609980106354],\n [0.392390012741089, 0.353887975215912],\n [0.354490011930466, 0.696784019470215],\n [0.067304998636246, 0.730105042457581],\n [0.442739009857178, 0.572826027870178],\n [0.457098007202148, 0.584792017936707],\n [0.381974011659622, 0.694710969924927],\n [0.392388999462128, 0.694203019142151],\n [0.277076005935669, 0.271932005882263],\n [0.422551989555359, 0.563233017921448],\n [0.385919004678726, 0.281364023685455],\n [0.383103013038635, 0.255840003490448],\n [0.331431001424789, 0.119714021682739],\n [0.229923993349075, 0.232002973556519],\n [0.364500999450684, 0.189113974571228],\n [0.229622006416321, 0.299540996551514],\n [0.173287004232407, 0.278747975826263],\n [0.472878992557526, 0.666198015213013],\n [0.446828007698059, 0.668527007102966],\n [0.422762006521225, 0.673889994621277],\n [0.445307999849319, 0.580065965652466],\n [0.388103008270264, 0.693961024284363],\n [0.403039008378983, 0.706539988517761],\n [0.403629004955292, 0.693953037261963],\n [0.460041999816895, 0.557139039039612],\n [0.431158006191254, 0.692366003990173],\n [0.452181994915009, 0.692366003990173],\n [0.475387006998062, 0.692366003990173],\n [0.465828001499176, 0.779190003871918],\n [0.472328990697861, 0.736225962638855],\n [0.473087012767792, 0.717857003211975],\n [0.473122000694275, 0.704625964164734],\n [0.473033010959625, 0.695277988910675],\n [0.427942007780075, 0.695277988910675],\n [0.426479011774063, 0.703539967536926],\n [0.423162013292313, 0.711845993995667],\n [0.4183090031147, 0.720062971115112],\n [0.390094995498657, 0.639572978019714],\n [0.013953999616206, 0.560034036636353],\n [0.499913990497589, 0.58014702796936],\n [0.413199990987778, 0.69539999961853],\n [0.409626007080078, 0.701822996139526],\n [0.468080013990402, 0.601534962654114],\n [0.422728985548019, 0.585985004901886],\n [0.463079988956451, 0.593783974647522],\n [0.37211999297142, 0.47341400384903],\n [0.334562003612518, 0.496073007583618],\n [0.411671012639999, 0.546965003013611],\n [0.242175996303558, 0.14767599105835],\n [0.290776997804642, 0.201445996761322],\n [0.327338010072708, 0.256527006626129],\n [0.399509996175766, 0.748921036720276],\n [0.441727995872498, 0.261676013469696],\n [0.429764986038208, 0.187834024429321],\n [0.412198007106781, 0.108901023864746],\n [0.288955003023148, 0.398952007293701],\n [0.218936994671822, 0.435410976409912],\n [0.41278201341629, 0.398970007896423],\n [0.257135003805161, 0.355440020561218],\n [0.427684992551804, 0.437960982322693],\n [0.448339998722076, 0.536936044692993],\n [0.178560003638268, 0.45755398273468],\n [0.247308000922203, 0.457193970680237],\n [0.286267012357712, 0.467674970626831],\n [0.332827985286713, 0.460712015628815],\n [0.368755996227264, 0.447206974029541],\n [0.398963987827301, 0.432654976844788],\n [0.476410001516342, 0.405806005001068],\n [0.189241006970406, 0.523923993110657],\n [0.228962004184723, 0.348950982093811],\n [0.490725994110107, 0.562400996685028],\n [0.404670000076294, 0.485132992267609],\n [0.019469000399113, 0.401564002037048],\n [0.426243007183075, 0.420431017875671],\n [0.396993011236191, 0.548797011375427],\n [0.266469985246658, 0.376977026462555],\n [0.439121007919312, 0.51895797252655],\n [0.032313998788595, 0.644356966018677],\n [0.419054001569748, 0.387154996395111],\n [0.462783008813858, 0.505746960639954],\n [0.238978996872902, 0.779744982719421],\n [0.198220998048782, 0.831938028335571],\n [0.107550002634525, 0.540755033493042],\n [0.183610007166862, 0.740257024765015],\n [0.134409993886948, 0.333683013916016],\n [0.385764002799988, 0.883153975009918],\n [0.490967005491257, 0.579378008842468],\n [0.382384985685349, 0.508572995662689],\n [0.174399003386497, 0.397670984268188],\n [0.318785011768341, 0.39623498916626],\n [0.343364000320435, 0.400596976280212],\n [0.396100014448166, 0.710216999053955],\n [0.187885001301765, 0.588537991046906],\n [0.430987000465393, 0.944064974784851],\n [0.318993002176285, 0.898285031318665],\n [0.266247987747192, 0.869701027870178],\n [0.500023007392883, 0.190576016902924],\n [0.499976992607117, 0.954452991485596],\n [0.366169989109039, 0.398822009563446],\n [0.393207013607025, 0.39553701877594],\n [0.410373002290726, 0.391080021858215],\n [0.194993004202843, 0.342101991176605],\n [0.388664990663528, 0.362284004688263],\n [0.365961998701096, 0.355970978736877],\n [0.343364000320435, 0.355356991291046],\n [0.318785011768341, 0.35834002494812],\n [0.301414996385574, 0.363156020641327],\n [0.058132998645306, 0.319076001644135],\n [0.301414996385574, 0.387449026107788],\n [0.499987989664078, 0.618434011936188],\n [0.415838003158569, 0.624195992946625],\n [0.445681989192963, 0.566076993942261],\n [0.465844005346298, 0.620640993118286],\n [0.49992299079895, 0.351523995399475],\n [0.288718998432159, 0.819945991039276],\n [0.335278987884521, 0.852819979190826],\n [0.440512001514435, 0.902418971061707],\n [0.128294005990028, 0.791940987110138],\n [0.408771991729736, 0.373893976211548],\n [0.455606997013092, 0.451801002025604],\n [0.499877005815506, 0.908990025520325],\n [0.375436991453171, 0.924192011356354],\n [0.11421000212431, 0.615022003650665],\n [0.448662012815475, 0.695277988910675],\n [0.4480200111866, 0.704632043838501],\n [0.447111994028091, 0.715808033943176],\n [0.444831997156143, 0.730794012546539],\n [0.430011987686157, 0.766808986663818],\n [0.406787008047104, 0.685672998428345],\n [0.400738000869751, 0.681069016456604],\n [0.392399996519089, 0.677703022956848],\n [0.367855995893478, 0.663918972015381],\n [0.247923001646996, 0.601333022117615],\n [0.452769994735718, 0.420849978923798],\n [0.43639200925827, 0.359887003898621],\n [0.416164010763168, 0.368713974952698],\n [0.413385987281799, 0.692366003990173],\n [0.228018000721931, 0.683571994304657],\n [0.468268007040024, 0.352671027183533],\n [0.411361992359161, 0.804327011108398],\n [0.499989002943039, 0.469825029373169],\n [0.479153990745544, 0.442654013633728],\n [0.499974012374878, 0.439637005329132],\n [0.432112008333206, 0.493588984012604],\n [0.499886006116867, 0.866917014122009],\n [0.49991300702095, 0.821729004383087],\n [0.456548988819122, 0.819200992584229],\n [0.344549000263214, 0.745438992977142],\n [0.37890899181366, 0.574010014533997],\n [0.374292999505997, 0.780184984207153],\n [0.319687992334366, 0.570737957954407],\n [0.357154995203018, 0.604269981384277],\n [0.295284003019333, 0.621580958366394],\n [0.447750002145767, 0.862477004528046],\n [0.410986006259918, 0.508723020553589],\n [0.31395098567009, 0.775308012962341],\n [0.354128003120422, 0.812552988529205],\n [0.324548006057739, 0.703992962837219],\n [0.189096003770828, 0.646299958229065],\n [0.279776990413666, 0.71465802192688],\n [0.1338230073452, 0.682700991630554],\n [0.336768001317978, 0.644733011722565],\n [0.429883986711502, 0.466521978378296],\n [0.455527991056442, 0.548622965812683],\n [0.437114000320435, 0.558896005153656],\n [0.467287987470627, 0.529924988746643],\n [0.414712011814117, 0.335219979286194],\n [0.37704598903656, 0.322777986526489],\n [0.344107985496521, 0.320150971412659],\n [0.312875986099243, 0.32233202457428],\n [0.283526003360748, 0.333190023899078],\n [0.241245999932289, 0.382785975933075],\n [0.102986000478268, 0.468762993812561],\n [0.267612010240555, 0.424560010433197],\n [0.297879010438919, 0.433175981044769],\n [0.333433985710144, 0.433878004550934],\n [0.366427004337311, 0.426115989685059],\n [0.396012008190155, 0.416696012020111],\n [0.420121014118195, 0.41022801399231],\n [0.007561000064015, 0.480777025222778],\n [0.432949006557465, 0.569517970085144],\n [0.458638995885849, 0.479089021682739],\n [0.473466008901596, 0.545744001865387],\n [0.476087987422943, 0.563830018043518],\n [0.468472003936768, 0.555056989192963],\n [0.433990985155106, 0.582361996173859],\n [0.483518004417419, 0.562983989715576],\n [0.482482999563217, 0.57784903049469],\n [0.42645001411438, 0.389798998832703],\n [0.438998997211456, 0.39649498462677],\n [0.450067013502121, 0.400434017181396],\n [0.289712011814117, 0.368252992630005],\n [0.276670008897781, 0.363372981548309],\n [0.517862021923065, 0.471948027610779],\n [0.710287988185883, 0.380764007568359],\n [0.526226997375488, 0.573909997940063],\n [0.895093023777008, 0.254140973091125],\n [0.634069979190826, 0.409575998783112],\n [0.661242008209229, 0.41302502155304],\n [0.688880026340485, 0.409460008144379],\n [0.725341975688934, 0.389131009578705],\n [0.606630027294159, 0.40370500087738],\n [0.654766023159027, 0.344011008739471],\n [0.629905998706818, 0.346076011657715],\n [0.680678009986877, 0.347265005111694],\n [0.702096998691559, 0.353591024875641],\n [0.75221198797226, 0.410804986953735],\n [0.602918028831482, 0.842862963676453],\n [0.719901978969574, 0.375599980354309],\n [0.893692970275879, 0.399959981441498],\n [0.790081977844238, 0.391354024410248],\n [0.643998026847839, 0.534487962722778],\n [0.528249025344849, 0.65040397644043],\n [0.525849997997284, 0.680191040039062],\n [0.560214996337891, 0.657229006290436],\n [0.585384011268616, 0.66654098033905],\n [0.549625992774963, 0.680860996246338],\n [0.57122802734375, 0.682691991329193],\n [0.624852001667023, 0.72809898853302],\n [0.513050019741058, 0.547281980514526],\n [0.51509702205658, 0.527251958847046],\n [0.742246985435486, 0.314507007598877],\n [0.598631024360657, 0.454979002475739],\n [0.570338010787964, 0.548575043678284],\n [0.578631997108459, 0.533622980117798],\n [0.723087012767792, 0.532054007053375],\n [0.516445994377136, 0.499638974666595],\n [0.662801027297974, 0.282917976379395],\n [0.70362401008606, 0.293271005153656],\n [0.830704987049103, 0.193813979625702],\n [0.552385985851288, 0.302568018436432],\n [0.607609987258911, 0.353887975215912],\n [0.645429015159607, 0.696707010269165],\n [0.932694971561432, 0.730105042457581],\n [0.557260990142822, 0.572826027870178],\n [0.542901992797852, 0.584792017936707],\n [0.6180260181427, 0.694710969924927],\n [0.607590973377228, 0.694203019142151],\n [0.722943007946014, 0.271963000297546],\n [0.577413976192474, 0.563166975975037],\n [0.614082992076874, 0.281386971473694],\n [0.616907000541687, 0.255886018276215],\n [0.668509006500244, 0.119913995265961],\n [0.770092010498047, 0.232020974159241],\n [0.635536015033722, 0.189248979091644],\n [0.77039098739624, 0.299556016921997],\n [0.826722025871277, 0.278755009174347],\n [0.527121007442474, 0.666198015213013],\n [0.553171992301941, 0.668527007102966],\n [0.577238023281097, 0.673889994621277],\n [0.554691970348358, 0.580065965652466],\n [0.611896991729736, 0.693961024284363],\n [0.59696102142334, 0.706539988517761],\n [0.596370995044708, 0.693953037261963],\n [0.539958000183105, 0.557139039039612],\n [0.568841993808746, 0.692366003990173],\n [0.547818005084991, 0.692366003990173],\n [0.52461302280426, 0.692366003990173],\n [0.534089982509613, 0.779141008853912],\n [0.527670979499817, 0.736225962638855],\n [0.526912987232208, 0.717857003211975],\n [0.526877999305725, 0.704625964164734],\n [0.526966989040375, 0.695277988910675],\n [0.572058022022247, 0.695277988910675],\n [0.573521018028259, 0.703539967536926],\n [0.57683801651001, 0.711845993995667],\n [0.581691026687622, 0.720062971115112],\n [0.609944999217987, 0.639909982681274],\n [0.986046016216278, 0.560034036636353],\n [0.5867999792099, 0.69539999961853],\n [0.590372025966644, 0.701822996139526],\n [0.531915009021759, 0.601536989212036],\n [0.577268004417419, 0.585934996604919],\n [0.536915004253387, 0.593786001205444],\n [0.627542972564697, 0.473352015018463],\n [0.665585994720459, 0.495950996875763],\n [0.588353991508484, 0.546862006187439],\n [0.757824003696442, 0.14767599105835],\n [0.709249973297119, 0.201507985591888],\n [0.672684013843536, 0.256581008434296],\n [0.600408971309662, 0.74900496006012],\n [0.55826598405838, 0.261672019958496],\n [0.570303976535797, 0.187870979309082],\n [0.588165998458862, 0.109044015407562],\n [0.711045026779175, 0.398952007293701],\n [0.781069993972778, 0.435405015945435],\n [0.587247014045715, 0.398931980133057],\n [0.742869973182678, 0.355445981025696],\n [0.572156012058258, 0.437651991844177],\n [0.55186802148819, 0.536570012569427],\n [0.821442008018494, 0.457556009292603],\n [0.752701997756958, 0.457181990146637],\n [0.71375697851181, 0.467626988887787],\n [0.66711300611496, 0.460672974586487],\n [0.631101012229919, 0.447153985500336],\n [0.6008620262146, 0.432473003864288],\n [0.523481011390686, 0.405627012252808],\n [0.810747981071472, 0.523926019668579],\n [0.771045982837677, 0.348959028720856],\n [0.509127020835876, 0.562718033790588],\n [0.595292985439301, 0.485023975372314],\n [0.980530977249146, 0.401564002037048],\n [0.573499977588654, 0.420000016689301],\n [0.602994978427887, 0.548687994480133],\n [0.733529984951019, 0.376977026462555],\n [0.560611009597778, 0.519016981124878],\n [0.967685997486115, 0.644356966018677],\n [0.580985009670258, 0.387160003185272],\n [0.537728011608124, 0.505385041236877],\n [0.760966002941132, 0.779752969741821],\n [0.801778972148895, 0.831938028335571],\n [0.892440974712372, 0.54076099395752],\n [0.816350996494293, 0.740260004997253],\n [0.865594983100891, 0.333687007427216],\n [0.614073991775513, 0.883246004581451],\n [0.508952975273132, 0.579437971115112],\n [0.617941975593567, 0.508316040039062],\n [0.825608015060425, 0.397674977779388],\n [0.681214988231659, 0.39623498916626],\n [0.656635999679565, 0.400596976280212],\n [0.603900015354156, 0.710216999053955],\n [0.81208598613739, 0.588539004325867],\n [0.56801301240921, 0.944564998149872],\n [0.681007981300354, 0.898285031318665],\n [0.733752012252808, 0.869701027870178],\n [0.633830010890961, 0.398822009563446],\n [0.606792986392975, 0.39553701877594],\n [0.589659988880157, 0.391062021255493],\n [0.805015981197357, 0.342108011245728],\n [0.611334979534149, 0.362284004688263],\n [0.634037971496582, 0.355970978736877],\n [0.656635999679565, 0.355356991291046],\n [0.681214988231659, 0.35834002494812],\n [0.698584973812103, 0.363156020641327],\n [0.941866993904114, 0.319076001644135],\n [0.698584973812103, 0.387449026107788],\n [0.584177017211914, 0.624107003211975],\n [0.554318010807037, 0.566076993942261],\n [0.534153997898102, 0.62064003944397],\n [0.711217999458313, 0.819975018501282],\n [0.664629995822906, 0.852871000766754],\n [0.559099972248077, 0.902631998062134],\n [0.871706008911133, 0.791940987110138],\n [0.591234028339386, 0.373893976211548],\n [0.544341027736664, 0.451583981513977],\n [0.624562978744507, 0.924192011356354],\n [0.88577002286911, 0.615028977394104],\n [0.551338016986847, 0.695277988910675],\n [0.551980018615723, 0.704632043838501],\n [0.552887976169586, 0.715808033943176],\n [0.555167973041534, 0.730794012546539],\n [0.569944024085999, 0.767035007476807],\n [0.593203008174896, 0.685675978660583],\n [0.599261999130249, 0.681069016456604],\n [0.607599973678589, 0.677703022956848],\n [0.631937980651855, 0.663500010967255],\n [0.752032995223999, 0.601315021514893],\n [0.547226011753082, 0.420395016670227],\n [0.563543975353241, 0.359827995300293],\n [0.583841025829315, 0.368713974952698],\n [0.586614012718201, 0.692366003990173],\n [0.771915018558502, 0.683578014373779],\n [0.531597018241882, 0.352482974529266],\n [0.588370978832245, 0.804440975189209],\n [0.52079701423645, 0.442565023899078],\n [0.567984998226166, 0.493479013442993],\n [0.543282985687256, 0.819254994392395],\n [0.655317008495331, 0.745514988899231],\n [0.621008992195129, 0.574018001556396],\n [0.625559985637665, 0.78031200170517],\n [0.680198013782501, 0.570719003677368],\n [0.64276397228241, 0.604337990283966],\n [0.704662978649139, 0.621529996395111],\n [0.552012026309967, 0.862591981887817],\n [0.589071989059448, 0.508637011051178],\n [0.685944974422455, 0.775357007980347],\n [0.645735025405884, 0.812640011310577],\n [0.675342977046967, 0.703978002071381],\n [0.810858011245728, 0.646304965019226],\n [0.72012197971344, 0.714666962623596],\n [0.866151988506317, 0.682704985141754],\n [0.663187026977539, 0.644596993923187],\n [0.570082008838654, 0.466325998306274],\n [0.544561982154846, 0.548375964164734],\n [0.562758982181549, 0.558784961700439],\n [0.531987011432648, 0.530140042304993],\n [0.585271000862122, 0.335177004337311],\n [0.622952997684479, 0.32277899980545],\n [0.655896008014679, 0.320163011550903],\n [0.687132000923157, 0.322345972061157],\n [0.716481983661652, 0.333200991153717],\n [0.758756995201111, 0.382786989212036],\n [0.897013008594513, 0.468769013881683],\n [0.732392013072968, 0.424547016620636],\n [0.70211398601532, 0.433162987232208],\n [0.66652500629425, 0.433866024017334],\n [0.633504986763, 0.426087975502014],\n [0.603875994682312, 0.416586995124817],\n [0.579657971858978, 0.409945011138916],\n [0.992439985275269, 0.480777025222778],\n [0.567192018032074, 0.569419980049133],\n [0.54136598110199, 0.478899002075195],\n [0.526564002037048, 0.546118021011353],\n [0.523913025856018, 0.563830018043518],\n [0.531529009342194, 0.555056989192963],\n [0.566035985946655, 0.582329034805298],\n [0.51631098985672, 0.563053965568542],\n [0.5174720287323, 0.577877044677734],\n [0.573594987392426, 0.389806985855103],\n [0.560697972774506, 0.395331978797913],\n [0.549755990505219, 0.399751007556915],\n [0.710287988185883, 0.368252992630005],\n [0.723330020904541, 0.363372981548309],\n];\n\nexport const TRI468 = [\n 127, 34, 139, 11, 0, 37, 232, 231, 120, 72, 37, 39, 128, 121, 47, 232, 121, 128, 104, 69, 67, 175, 171, 148, 157, 154, 155, 118, 50, 101, 73, 39, 40, 9,\n 151, 108, 48, 115, 131, 194, 204, 211, 74, 40, 185, 80, 42, 183, 40, 92, 186, 230, 229, 118, 202, 212, 214, 83, 18, 17, 76, 61, 146, 160, 29, 30, 56,\n 157, 173, 106, 204, 194, 135, 214, 192, 203, 165, 98, 21, 71, 68, 51, 45, 4, 144, 24, 23, 77, 146, 91, 205, 50, 187, 201, 200, 18, 91, 106, 182, 90, 91,\n 181, 85, 84, 17, 206, 203, 36, 148, 171, 140, 92, 40, 39, 193, 189, 244, 159, 158, 28, 247, 246, 161, 236, 3, 196, 54, 68, 104, 193, 168, 8, 117,\n 228, 31, 189, 193, 55, 98, 97, 99, 126, 47, 100, 166, 79, 218, 155, 154, 26, 209, 49, 131, 135, 136, 150, 47, 126, 217, 223, 52, 53, 45, 51, 134, 211,\n 170, 140, 67, 69, 108, 43, 106, 91, 230, 119, 120, 226, 130, 247, 63, 53, 52, 238, 20, 242, 46, 70, 156, 78, 62, 96, 46, 53, 63, 143, 34, 227, 173,\n 155, 133, 123, 117, 111, 44, 125, 19, 236, 134, 51, 216, 206, 205, 154, 153, 22, 39, 37, 167, 200, 201, 208, 36, 142, 100, 57, 212, 202, 20, 60, 99, 28,\n 158, 157, 35, 226, 113, 160, 159, 27, 204, 202, 210, 113, 225, 46, 43, 202, 204, 62, 76, 77, 137, 123, 116, 41, 38, 72, 203, 129, 142, 64, 98, 240, 49,\n 102, 64, 41, 73, 74, 212, 216, 207, 42, 74, 184, 169, 170, 211, 170, 149, 176, 105, 66, 69, 122, 6, 168, 123, 147, 187, 96, 77, 90, 65, 55, 107, 89,\n 90, 180, 101, 100, 120, 63, 105, 104, 93, 137, 227, 15, 86, 85, 129, 102, 49, 14, 87, 86, 55, 8, 9, 100, 47, 121, 145, 23, 22, 88, 89, 179, 6, 122,\n 196, 88, 95, 96, 138, 172, 136, 215, 58, 172, 115, 48, 219, 42, 80, 81, 195, 3, 51, 43, 146, 61, 171, 175, 199, 81, 82, 38, 53, 46, 225, 144, 163, 110,\n 246, 33, 7, 52, 65, 66, 229, 228, 117, 34, 127, 234, 107, 108, 69, 109, 108, 151, 48, 64, 235, 62, 78, 191, 129, 209, 126, 111, 35, 143, 163, 161, 246,\n 117, 123, 50, 222, 65, 52, 19, 125, 141, 221, 55, 65, 3, 195, 197, 25, 7, 33, 220, 237, 44, 70, 71, 139, 122, 193, 245, 247, 130, 33, 71, 21, 162,\n 153, 158, 159, 170, 169, 150, 188, 174, 196, 216, 186, 92, 144, 160, 161, 2, 97, 167, 141, 125, 241, 164, 167, 37, 72, 38, 12, 145, 159, 160, 38, 82, 13,\n 63, 68, 71, 226, 35, 111, 158, 153, 154, 101, 50, 205, 206, 92, 165, 209, 198, 217, 165, 167, 97, 220, 115, 218, 133, 112, 243, 239, 238, 241, 214,\n 135, 169, 190, 173, 133, 171, 208, 32, 125, 44, 237, 86, 87, 178, 85, 86, 179, 84, 85, 180, 83, 84, 181, 201, 83, 182, 137, 93, 132, 76, 62, 183, 61,\n 76, 184, 57, 61, 185, 212, 57, 186, 214, 207, 187, 34, 143, 156, 79, 239, 237, 123, 137, 177, 44, 1, 4, 201, 194, 32, 64, 102, 129, 213, 215, 138, 59,\n 166, 219, 242, 99, 97, 2, 94, 141, 75, 59, 235, 24, 110, 228, 25, 130, 226, 23, 24, 229, 22, 23, 230, 26, 22, 231, 112, 26, 232, 189, 190, 243, 221, 56,\n 190, 28, 56, 221, 27, 28, 222, 29, 27, 223, 30, 29, 224, 247, 30, 225, 238, 79, 20, 166, 59, 75, 60, 75, 240, 147, 177, 215, 20, 79, 166, 187, 147, 213,\n 112, 233, 244, 233, 128, 245, 128, 114, 188, 114, 217, 174, 131, 115, 220, 217, 198, 236, 198, 131, 134, 177, 132, 58, 143, 35, 124, 110, 163, 7, 228,\n 110, 25, 356, 389, 368, 11, 302, 267, 452, 350, 349, 302, 303, 269, 357, 343, 277, 452, 453, 357, 333, 332, 297, 175, 152, 377, 384, 398, 382, 347,\n 348, 330, 303, 304, 270, 9, 336, 337, 278, 279, 360, 418, 262, 431, 304, 408, 409, 310, 415, 407, 270, 409, 410, 450, 348, 347, 422, 430, 434, 313,\n 314, 17, 306, 307, 375, 387, 388, 260, 286, 414, 398, 335, 406, 418, 364, 367, 416, 423, 358, 327, 251, 284, 298, 281, 5, 4, 373, 374, 253, 307, 320,\n 321, 425, 427, 411, 421, 313, 18, 321, 405, 406, 320, 404, 405, 315, 16, 17, 426, 425, 266, 377, 400, 369, 322, 391, 269, 417, 465, 464, 386, 257, 258,\n 466, 260, 388, 456, 399, 419, 284, 332, 333, 417, 285, 8, 346, 340, 261, 413, 441, 285, 327, 460, 328, 355, 371, 329, 392, 439, 438, 382, 341, 256,\n 429, 420, 360, 364, 394, 379, 277, 343, 437, 443, 444, 283, 275, 440, 363, 431, 262, 369, 297, 338, 337, 273, 375, 321, 450, 451, 349, 446, 342, 467,\n 293, 334, 282, 458, 461, 462, 276, 353, 383, 308, 324, 325, 276, 300, 293, 372, 345, 447, 382, 398, 362, 352, 345, 340, 274, 1, 19, 456, 248, 281, 436,\n 427, 425, 381, 256, 252, 269, 391, 393, 200, 199, 428, 266, 330, 329, 287, 273, 422, 250, 462, 328, 258, 286, 384, 265, 353, 342, 387, 259, 257, 424,\n 431, 430, 342, 353, 276, 273, 335, 424, 292, 325, 307, 366, 447, 345, 271, 303, 302, 423, 266, 371, 294, 455, 460, 279, 278, 294, 271, 272, 304, 432,\n 434, 427, 272, 407, 408, 394, 430, 431, 395, 369, 400, 334, 333, 299, 351, 417, 168, 352, 280, 411, 325, 319, 320, 295, 296, 336, 319, 403, 404, 330,\n 348, 349, 293, 298, 333, 323, 454, 447, 15, 16, 315, 358, 429, 279, 14, 15, 316, 285, 336, 9, 329, 349, 350, 374, 380, 252, 318, 402, 403, 6, 197, 419,\n 318, 319, 325, 367, 364, 365, 435, 367, 397, 344, 438, 439, 272, 271, 311, 195, 5, 281, 273, 287, 291, 396, 428, 199, 311, 271, 268, 283, 444, 445,\n 373, 254, 339, 263, 466, 249, 282, 334, 296, 449, 347, 346, 264, 447, 454, 336, 296, 299, 338, 10, 151, 278, 439, 455, 292, 407, 415, 358, 371, 355,\n 340, 345, 372, 390, 249, 466, 346, 347, 280, 442, 443, 282, 19, 94, 370, 441, 442, 295, 248, 419, 197, 263, 255, 359, 440, 275, 274, 300, 383, 368,\n 351, 412, 465, 263, 467, 466, 301, 368, 389, 380, 374, 386, 395, 378, 379, 412, 351, 419, 436, 426, 322, 373, 390, 388, 2, 164, 393, 370, 462, 461,\n 164, 0, 267, 302, 11, 12, 374, 373, 387, 268, 12, 13, 293, 300, 301, 446, 261, 340, 385, 384, 381, 330, 266, 425, 426, 423, 391, 429, 355, 437, 391,\n 327, 326, 440, 457, 438, 341, 382, 362, 459, 457, 461, 434, 430, 394, 414, 463, 362, 396, 369, 262, 354, 461, 457, 316, 403, 402, 315, 404, 403, 314,\n 405, 404, 313, 406, 405, 421, 418, 406, 366, 401, 361, 306, 408, 407, 291, 409, 408, 287, 410, 409, 432, 436, 410, 434, 416, 411, 264, 368, 383, 309,\n 438, 457, 352, 376, 401, 274, 275, 4, 421, 428, 262, 294, 327, 358, 433, 416, 367, 289, 455, 439, 462, 370, 326, 2, 326, 370, 305, 460, 455, 254,\n 449, 448, 255, 261, 446, 253, 450, 449, 252, 451, 450, 256, 452, 451, 341, 453, 452, 413, 464, 463, 441, 413, 414, 258, 442, 441, 257, 443, 442, 259,\n 444, 443, 260, 445, 444, 467, 342, 445, 459, 458, 250, 289, 392, 290, 290, 328, 460, 376, 433, 435, 250, 290, 392, 411, 416, 433, 341, 463, 464, 453,\n 464, 465, 357, 465, 412, 343, 412, 399, 360, 363, 440, 437, 399, 456, 420, 456, 363, 401, 435, 288, 372, 383, 353, 339, 255, 249, 448, 261, 255, 133,\n 243, 190, 133, 155, 112, 33, 246, 247, 33, 130, 25, 398, 384, 286, 362, 398, 414, 362, 463, 341, 263, 359, 467, 263, 249, 255, 466, 467, 260, 75, 60,\n 166, 238, 239, 79, 162, 127, 139, 72, 11, 37, 121, 232, 120, 73, 72, 39, 114, 128, 47, 233, 232, 128, 103, 104, 67, 152, 175, 148, 173, 157, 155,\n 119, 118, 101, 74, 73, 40, 107, 9, 108, 49, 48, 131, 32, 194, 211, 184, 74, 185, 191, 80, 183, 185, 40, 186, 119, 230, 118, 210, 202, 214, 84, 83, 17,\n 77, 76, 146, 161, 160, 30, 190, 56, 173, 182, 106, 194, 138, 135, 192, 129, 203, 98, 54, 21, 68, 5, 51, 4, 145, 144, 23, 90, 77, 91, 207, 205, 187, 83,\n 201, 18, 181, 91, 182, 180, 90, 181, 16, 85, 17, 205, 206, 36, 176, 148, 140, 165, 92, 39, 245, 193, 244, 27, 159, 28, 30, 247, 161, 174, 236, 196,\n 103, 54, 104, 55, 193, 8, 111, 117, 31, 221, 189, 55, 240, 98, 99, 142, 126, 100, 219, 166, 218, 112, 155, 26, 198, 209, 131, 169, 135, 150, 114, 47,\n 217, 224, 223, 53, 220, 45, 134, 32, 211, 140, 109, 67, 108, 146, 43, 91, 231, 230, 120, 113, 226, 247, 105, 63, 52, 241, 238, 242, 124, 46, 156, 95,\n 78, 96, 70, 46, 63, 116, 143, 227, 116, 123, 111, 1, 44, 19, 3, 236, 51, 207, 216, 205, 26, 154, 22, 165, 39, 167, 199, 200, 208, 101, 36, 100, 43,\n 57, 202, 242, 20, 99, 56, 28, 157, 124, 35, 113, 29, 160, 27, 211, 204, 210, 124, 113, 46, 106, 43, 204, 96, 62, 77, 227, 137, 116, 73, 41, 72, 36, 203,\n 142, 235, 64, 240, 48, 49, 64, 42, 41, 74, 214, 212, 207, 183, 42, 184, 210, 169, 211, 140, 170, 176, 104, 105, 69, 193, 122, 168, 50, 123, 187, 89, 96,\n 90, 66, 65, 107, 179, 89, 180, 119, 101, 120, 68, 63, 104, 234, 93, 227, 16, 15, 85, 209, 129, 49, 15, 14, 86, 107, 55, 9, 120, 100, 121, 153, 145, 22,\n 178, 88, 179, 197, 6, 196, 89, 88, 96, 135, 138, 136, 138, 215, 172, 218, 115, 219, 41, 42, 81, 5, 195, 51, 57, 43, 61, 208, 171, 199, 41, 81, 38,\n 224, 53, 225, 24, 144, 110, 105, 52, 66, 118, 229, 117, 227, 34, 234, 66, 107, 69, 10, 109, 151, 219, 48, 235, 183, 62, 191, 142, 129, 126, 116, 111,\n 143, 7, 163, 246, 118, 117, 50, 223, 222, 52, 94, 19, 141, 222, 221, 65, 196, 3, 197, 45, 220, 44, 156, 70, 139, 188, 122, 245, 139, 71, 162, 145,\n 153, 159, 149, 170, 150, 122, 188, 196, 206, 216, 92, 163, 144, 161, 164, 2, 167, 242, 141, 241, 0, 164, 37, 11, 72, 12, 144, 145, 160, 12, 38, 13, 70,\n 63, 71, 31, 226, 111, 157, 158, 154, 36, 101, 205, 203, 206, 165, 126, 209, 217, 98, 165, 97, 237, 220, 218, 237, 239, 241, 210, 214, 169, 140, 171, 32,\n 241, 125, 237, 179, 86, 178, 180, 85, 179, 181, 84, 180, 182, 83, 181, 194, 201, 182, 177, 137, 132, 184, 76, 183, 185, 61, 184, 186, 57, 185, 216, 212,\n 186, 192, 214, 187, 139, 34, 156, 218, 79, 237, 147, 123, 177, 45, 44, 4, 208, 201, 32, 98, 64, 129, 192, 213, 138, 235, 59, 219, 141, 242, 97, 97, 2,\n 141, 240, 75, 235, 229, 24, 228, 31, 25, 226, 230, 23, 229, 231, 22, 230, 232, 26, 231, 233, 112, 232, 244, 189, 243, 189, 221, 190, 222, 28, 221,\n 223, 27, 222, 224, 29, 223, 225, 30, 224, 113, 247, 225, 99, 60, 240, 213, 147, 215, 60, 20, 166, 192, 187, 213, 243, 112, 244, 244, 233, 245, 245,\n 128, 188, 188, 114, 174, 134, 131, 220, 174, 217, 236, 236, 198, 134, 215, 177, 58, 156, 143, 124, 25, 110, 7, 31, 228, 25, 264, 356, 368, 0, 11, 267,\n 451, 452, 349, 267, 302, 269, 350, 357, 277, 350, 452, 357, 299, 333, 297, 396, 175, 377, 381, 384, 382, 280, 347, 330, 269, 303, 270, 151, 9, 337,\n 344, 278, 360, 424, 418, 431, 270, 304, 409, 272, 310, 407, 322, 270, 410, 449, 450, 347, 432, 422, 434, 18, 313, 17, 291, 306, 375, 259, 387, 260,\n 424, 335, 418, 434, 364, 416, 391, 423, 327, 301, 251, 298, 275, 281, 4, 254, 373, 253, 375, 307, 321, 280, 425, 411, 200, 421, 18, 335, 321, 406,\n 321, 320, 405, 314, 315, 17, 423, 426, 266, 396, 377, 369, 270, 322, 269, 413, 417, 464, 385, 386, 258, 248, 456, 419, 298, 284, 333, 168, 417, 8,\n 448, 346, 261, 417, 413, 285, 326, 327, 328, 277, 355, 329, 309, 392, 438, 381, 382, 256, 279, 429, 360, 365, 364, 379, 355, 277, 437, 282, 443, 283,\n 281, 275, 363, 395, 431, 369, 299, 297, 337, 335, 273, 321, 348, 450, 349, 359, 446, 467, 283, 293, 282, 250, 458, 462, 300, 276, 383, 292, 308, 325,\n 283, 276, 293, 264, 372, 447, 346, 352, 340, 354, 274, 19, 363, 456, 281, 426, 436, 425, 380, 381, 252, 267, 269, 393, 421, 200, 428, 371, 266, 329,\n 432, 287, 422, 290, 250, 328, 385, 258, 384, 446, 265, 342, 386, 387, 257, 422, 424, 430, 445, 342, 276, 422, 273, 424, 306, 292, 307, 352, 366, 345,\n 268, 271, 302, 358, 423, 371, 327, 294, 460, 331, 279, 294, 303, 271, 304, 436, 432, 427, 304, 272, 408, 395, 394, 431, 378, 395, 400, 296, 334, 299,\n 6, 351, 168, 376, 352, 411, 307, 325, 320, 285, 295, 336, 320, 319, 404, 329, 330, 349, 334, 293, 333, 366, 323, 447, 316, 15, 315, 331, 358, 279,\n 317, 14, 316, 8, 285, 9, 277, 329, 350, 253, 374, 252, 319, 318, 403, 351, 6, 419, 324, 318, 325, 397, 367, 365, 288, 435, 397, 278, 344, 439, 310,\n 272, 311, 248, 195, 281, 375, 273, 291, 175, 396, 199, 312, 311, 268, 276, 283, 445, 390, 373, 339, 295, 282, 296, 448, 449, 346, 356, 264, 454, 337,\n 336, 299, 337, 338, 151, 294, 278, 455, 308, 292, 415, 429, 358, 355, 265, 340, 372, 388, 390, 466, 352, 346, 280, 295, 442, 282, 354, 19, 370, 285,\n 441, 295, 195, 248, 197, 457, 440, 274, 301, 300, 368, 417, 351, 465, 251, 301, 389, 385, 380, 386, 394, 395, 379, 399, 412, 419, 410, 436, 322, 387,\n 373, 388, 326, 2, 393, 354, 370, 461, 393, 164, 267, 268, 302, 12, 386, 374, 387, 312, 268, 13, 298, 293, 301, 265, 446, 340, 380, 385, 381, 280, 330,\n 425, 322, 426, 391, 420, 429, 437, 393, 391, 326, 344, 440, 438, 458, 459, 461, 364, 434, 394, 428, 396, 262, 274, 354, 457, 317, 316, 402, 316, 315,\n 403, 315, 314, 404, 314, 313, 405, 313, 421, 406, 323, 366, 361, 292, 306, 407, 306, 291, 408, 291, 287, 409, 287, 432, 410, 427, 434, 411, 372, 264,\n 383, 459, 309, 457, 366, 352, 401, 1, 274, 4, 418, 421, 262, 331, 294, 358, 435, 433, 367, 392, 289, 439, 328, 462, 326, 94, 2, 370, 289, 305, 455, 339,\n 254, 448, 359, 255, 446, 254, 253, 449, 253, 252, 450, 252, 256, 451, 256, 341, 452, 414, 413, 463, 286, 441, 414, 286, 258, 441, 258, 257, 442, 257,\n 259, 443, 259, 260, 444, 260, 467, 445, 309, 459, 250, 305, 289, 290, 305, 290, 460, 401, 376, 435, 309, 250, 392, 376, 411, 433, 453, 341, 464, 357,\n 453, 465, 343, 357, 412, 437, 343, 399, 344, 360, 440, 420, 437, 456, 360, 420, 363, 361, 401, 288, 265, 372, 353, 390, 339, 249, 339, 448, 255];\n\nexport const TRI68 = [0, 1, 36, 0, 36, 17, 1, 2, 41, 1, 41, 36, 2, 3, 31, 2, 31, 41, 3, 4, 48, 3, 48, 31, 4, 5, 48, 5, 6, 48, 6, 7, 59, 6, 59, 48, 7, 8, 58, 7, 58, 59,\n 8, 9, 56, 8, 56, 57, 8, 57, 58, 9, 10, 55, 9, 55, 56, 10, 11, 54, 10, 54, 55, 11, 12, 54, 12, 13, 54, 13, 14, 35, 13, 35, 54, 14, 15, 46, 14, 46, 35, 15, 16,\n 45, 15, 45, 46, 16, 26, 45, 17, 36, 18, 18, 37, 19, 18, 36, 37, 19, 38, 20, 19, 37, 38, 20, 39, 21, 20, 38, 39, 21, 39, 27, 22, 42, 23, 22, 27, 42, 23, 43, 24,\n 23, 42, 43, 24, 44, 25, 24, 43, 44, 25, 45, 26, 25, 44, 45, 27, 39, 28, 27, 28, 42, 28, 39, 29, 28, 29, 42, 29, 31, 30, 29, 30, 35, 29, 40, 31, 29, 35, 47, 29,\n 39, 40, 29, 47, 42, 30, 31, 32, 30, 32, 33, 30, 33, 34, 30, 34, 35, 31, 50, 32, 31, 40, 41, 31, 48, 49, 31, 49, 50, 32, 51, 33, 32, 50, 51, 33, 51, 34, 34, 52,\n 35, 34, 51, 52, 35, 46, 47, 35, 52, 53, 35, 53, 54, 36, 41, 37, 37, 40, 38, 37, 41, 40, 38, 40, 39, 42, 47, 43, 43, 47, 44, 44, 46, 45, 44, 47, 46, 48, 60, 49,\n 48, 59, 60, 49, 61, 50, 49, 60, 61, 50, 62, 51, 50, 61, 62, 51, 62, 52, 52, 63, 53, 52, 62, 63, 53, 64, 54, 53, 63, 64, 54, 64, 55, 55, 65, 56, 55, 64, 65, 56,\n 66, 57, 56, 65, 66, 57, 66, 58, 58, 67, 59, 58, 66, 67, 59, 67, 60, 60, 67, 61, 61, 66, 62, 61, 67, 66, 62, 66, 63, 63, 65, 64, 63, 66, 65, 21, 27, 22];\n\nexport const TRI33 = [\n /* eyes */ 0, 8, 7, 7, 8, 1, 2, 10, 9, 9, 10, 3,\n /* brows */ 17, 0, 18, 18, 0, 7, 18, 7, 19, 19, 7, 1, 19, 1, 11, 19, 11, 20, 21, 3, 22, 21, 9, 3, 20, 9, 21, 20, 2, 9, 20, 11, 2,\n /* 4head */ 23, 17, 18, 25, 21, 22, 24, 19, 20, 24, 18, 19, 24, 20, 21, 24, 23, 18, 24, 21, 25,\n /* nose */ 11, 12, 4, 11, 4, 13, 1, 12, 11, 11, 13, 2, 12, 14, 4, 4, 14, 13,\n /* up-lip */ 14, 5, 15, 14, 15, 6, 12, 5, 14, 14, 6, 13,\n /* cheeks */ 8, 12, 1, 2, 13, 10, 8, 26, 12, 10, 13, 27, 26, 5, 12, 13, 6, 27, 0, 26, 8, 10, 27, 3,\n /* chin */ 5, 32, 16, 16, 32, 6, 5, 30, 32, 6, 32, 31,\n /* cont */ 26, 30, 5, 27, 6, 31, 0, 28, 26, 3, 27, 29, 17, 28, 0, 3, 29, 22, 23, 28, 17, 22, 29, 25, 28, 30, 26, 27, 31, 29,\n];\n\nexport const TRI7 = [0, 4, 1, 2, 4, 3, 4, 5, 6];\n\nexport const VTX68 = [\n /* cont */ 127, 234, 132, 58, 172, 150, 149, 148, 152, 377, 378, 379, 397, 288, 361, 454, 356,\n /* brows */ 70, 63, 105, 66, 107, 336, 296, 334, 293, 300,\n /* nose */ 168, 6, 195, 4, 98, 97, 2, 326, 327,\n /* eyes */ 33, 160, 158, 133, 153, 144, 362, 385, 387, 263, 373, 380,\n /* lip */ 57, 40, 37, 0, 267, 270, 287, 321, 314, 17, 84, 91,\n /* mouth */ 78, 81, 13, 311, 308, 402, 14, 178,\n];\n\nexport const VTX33 = [33, 133, 362, 263, 1, 62, 308, 159, 145, 386, 374, 6, 102, 331, 2, 13, 14, 70, 105, 107, 336, 334, 300, 54, 10, 284, 50, 280, 234, 454, 58, 288, 152];\n\nexport const VTX7 = [33, 133, 362, 263, 1, 78, 308];\n\nexport const UV68 = VTX68.map((x) => UV468[x]);\n\nexport const UV33 = VTX33.map((x) => UV468[x]);\n\nexport const UV7 = VTX7.map((x) => UV468[x]);\n", "import * as tf from '../../dist/tfjs.esm.js';\nimport * as bounding from './box';\nimport * as util from './util';\nimport * as coords from './coords';\nimport { Tensor, GraphModel } from '../tfjs/types';\nimport { BlazeFaceModel } from './blazeface';\n\nconst leftOutline = coords.MESH_ANNOTATIONS['leftEyeLower0'];\nconst rightOutline = coords.MESH_ANNOTATIONS['rightEyeLower0'];\n\nconst eyeLandmarks = {\n leftBounds: [leftOutline[0], leftOutline[leftOutline.length - 1]],\n rightBounds: [rightOutline[0], rightOutline[rightOutline.length - 1]],\n};\n\nconst meshLandmarks = {\n count: 468,\n mouth: 13,\n symmetryLine: [13, coords.MESH_ANNOTATIONS['midwayBetweenEyes'][0]],\n};\n\nconst blazeFaceLandmarks = {\n leftEye: 0,\n rightEye: 1,\n nose: 2,\n mouth: 3,\n leftEar: 4,\n rightEar: 5,\n symmetryLine: [3, 2],\n};\n\nconst irisLandmarks = {\n upperCenter: 3,\n lowerCenter: 4,\n index: 71,\n numCoordinates: 76,\n};\n\n// Replace the raw coordinates returned by facemesh with refined iris model coordinates\n// Update the z coordinate to be an average of the original and the new.\nfunction replaceRawCoordinates(rawCoords, newCoords, prefix, keys) {\n for (let i = 0; i < coords.MESH_TO_IRIS_INDICES_MAP.length; i++) {\n const { key, indices } = coords.MESH_TO_IRIS_INDICES_MAP[i];\n const originalIndices = coords.MESH_ANNOTATIONS[`${prefix}${key}`];\n if (!keys || keys.includes(key)) {\n for (let j = 0; j < indices.length; j++) {\n const index = indices[j];\n rawCoords[originalIndices[j]] = [\n newCoords[index][0], newCoords[index][1],\n (newCoords[index][2] + rawCoords[originalIndices[j]][2]) / 2,\n ];\n }\n }\n }\n}\n// The Pipeline coordinates between the bounding box and skeleton models.\nexport class Pipeline {\n storedBoxes: Array<{ startPoint: number[], endPoint: number[], landmarks: Array<number>, confidence: number, faceConfidence?: number }>;\n boundingBoxDetector: BlazeFaceModel; // tf.GraphModel\n meshDetector: GraphModel; // tf.GraphModel\n irisModel: GraphModel; // tf.GraphModel\n boxSize: number;\n meshSize: number;\n irisSize: number;\n irisEnlarge: number;\n skipped: number;\n detectedFaces: number;\n\n constructor(boundingBoxDetector, meshDetector, irisModel) {\n // An array of facial bounding boxes.\n this.storedBoxes = [];\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.irisModel = irisModel;\n this.boxSize = boundingBoxDetector?.model?.inputs[0].shape[2] || 0;\n this.meshSize = meshDetector?.inputs[0].shape[2] || boundingBoxDetector?.model?.inputs[0].shape[2];\n this.irisSize = irisModel?.inputs[0].shape[1] || 0;\n this.irisEnlarge = 2.3;\n this.skipped = 0;\n this.detectedFaces = 0;\n }\n\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize({ startPoint: box.startPoint, endPoint: box.endPoint });\n const coordsScaled = rawCoords.map((coord) => ([\n boxSize[0] / this.meshSize * (coord[0] - this.meshSize / 2),\n boxSize[1] / this.meshSize * (coord[1] - this.meshSize / 2),\n coord[2],\n ]));\n const coordsRotationMatrix = (angle !== 0) ? util.buildRotationMatrix(angle, [0, 0]) : util.IDENTITY_MATRIX;\n const coordsRotated = (angle !== 0) ? coordsScaled.map((coord) => ([...util.rotatePoint(coord, coordsRotationMatrix), coord[2]])) : coordsScaled;\n const inverseRotationMatrix = (angle !== 0) ? util.invertTransformMatrix(rotationMatrix) : util.IDENTITY_MATRIX;\n const boxCenter = [...bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint }), 1];\n return coordsRotated.map((coord) => ([\n Math.round(coord[0] + util.dot(boxCenter, inverseRotationMatrix[0])),\n Math.round(coord[1] + util.dot(boxCenter, inverseRotationMatrix[1])),\n Math.round(coord[2]),\n ]));\n }\n\n // eslint-disable-next-line class-methods-use-this\n getLeftToRightEyeDepthDifference(rawCoords) {\n const leftEyeZ = rawCoords[eyeLandmarks.leftBounds[0]][2];\n const rightEyeZ = rawCoords[eyeLandmarks.rightBounds[0]][2];\n return leftEyeZ - rightEyeZ;\n }\n\n // Returns a box describing a cropped region around the eye fit for passing to the iris model.\n getEyeBox(rawCoords, face, eyeInnerCornerIndex, eyeOuterCornerIndex, flip = false) {\n const box = bounding.squarifyBox(bounding.enlargeBox(bounding.calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex], rawCoords[eyeOuterCornerIndex]]), this.irisEnlarge));\n const boxSize = bounding.getBoxSize(box);\n let crop = tf.image.cropAndResize(face, [[\n box.startPoint[1] / this.meshSize,\n box.startPoint[0] / this.meshSize, box.endPoint[1] / this.meshSize,\n box.endPoint[0] / this.meshSize,\n ]], [0], [this.irisSize, this.irisSize]);\n if (flip && tf.ENV.flags.IS_BROWSER) {\n crop = tf.image.flipLeftRight(crop); // flipLeftRight is not defined for tfjs-node\n }\n return { box, boxSize, crop };\n }\n\n // Given a cropped image of an eye, returns the coordinates of the contours surrounding the eye and the iris.\n getEyeCoords(eyeData, eyeBox, eyeBoxSize, flip = false) {\n const eyeRawCoords: Array<[number, number, number]> = [];\n for (let i = 0; i < irisLandmarks.numCoordinates; i++) {\n const x = eyeData[i * 3];\n const y = eyeData[i * 3 + 1];\n const z = eyeData[i * 3 + 2];\n eyeRawCoords.push([\n (flip ? (1 - (x / this.irisSize)) : (x / this.irisSize)) * eyeBoxSize[0] + eyeBox.startPoint[0],\n (y / this.irisSize) * eyeBoxSize[1] + eyeBox.startPoint[1], z,\n ]);\n }\n return { rawCoords: eyeRawCoords, iris: eyeRawCoords.slice(irisLandmarks.index) };\n }\n\n // The z-coordinates returned for the iris are unreliable, so we take the z values from the surrounding keypoints.\n // eslint-disable-next-line class-methods-use-this\n getAdjustedIrisCoords(rawCoords, irisCoords, direction) {\n const upperCenterZ = rawCoords[coords.MESH_ANNOTATIONS[`${direction}EyeUpper0`][irisLandmarks.upperCenter]][2];\n const lowerCenterZ = rawCoords[coords.MESH_ANNOTATIONS[`${direction}EyeLower0`][irisLandmarks.lowerCenter]][2];\n const averageZ = (upperCenterZ + lowerCenterZ) / 2;\n // Iris indices: 0: center | 1: right | 2: above | 3: left | 4: below\n return irisCoords.map((coord, i) => {\n let z = averageZ;\n if (i === 2) {\n z = upperCenterZ;\n } else if (i === 4) {\n z = lowerCenterZ;\n }\n return [coord[0], coord[1], z];\n });\n }\n\n async predict(input, config) {\n let useFreshBox = false;\n // run new detector every skipFrames unless we only want box to start with\n let detector;\n if ((this.skipped === 0) || (this.skipped > config.face.detector.skipFrames) || !config.face.mesh.enabled || !config.skipFrame) {\n detector = await this.boundingBoxDetector.getBoundingBoxes(input, config);\n this.skipped = 0;\n }\n if (config.skipFrame) this.skipped++;\n\n // if detector result count doesn't match current working set, use it to reset current working set\n if (!config.skipFrame || (detector && detector.boxes && (!config.face.mesh.enabled || (detector.boxes.length !== this.detectedFaces) && (this.detectedFaces !== config.face.detector.maxDetected)))) {\n this.storedBoxes = [];\n this.detectedFaces = 0;\n for (const possible of detector.boxes) {\n const startPoint = await possible.box.startPoint.data();\n const endPoint = await possible.box.endPoint.data();\n const landmarks = await possible.landmarks.array();\n this.storedBoxes.push({ startPoint, endPoint, landmarks, confidence: possible.confidence });\n }\n if (this.storedBoxes.length > 0) useFreshBox = true;\n }\n\n if (useFreshBox) {\n if (!detector || !detector.boxes || (detector.boxes.length === 0)) {\n this.storedBoxes = [];\n this.detectedFaces = 0;\n return null;\n }\n for (let i = 0; i < this.storedBoxes.length; i++) {\n const scaledBox = bounding.scaleBoxCoordinates({ startPoint: this.storedBoxes[i].startPoint, endPoint: this.storedBoxes[i].endPoint }, detector.scaleFactor);\n const enlargedBox = bounding.enlargeBox(scaledBox);\n const squarifiedBox = bounding.squarifyBox(enlargedBox);\n const landmarks = this.storedBoxes[i].landmarks;\n const confidence = this.storedBoxes[i].confidence;\n this.storedBoxes[i] = { ...squarifiedBox, confidence, landmarks };\n }\n }\n if (detector && detector.boxes) {\n detector.boxes.forEach((prediction) => {\n tf.dispose(prediction.box.startPoint);\n tf.dispose(prediction.box.endPoint);\n tf.dispose(prediction.landmarks);\n });\n }\n const results = tf.tidy(() => this.storedBoxes.map((box, i) => {\n // The facial bounding box landmarks could come either from blazeface (if we are using a fresh box), or from the mesh model (if we are reusing an old box).\n let face;\n let angle = 0;\n let rotationMatrix;\n\n if (config.face.detector.rotation && config.face.mesh.enabled && tf.ENV.flags.IS_BROWSER) {\n const [indexOfMouth, indexOfForehead] = (box.landmarks.length >= meshLandmarks.count) ? meshLandmarks.symmetryLine : blazeFaceLandmarks.symmetryLine;\n angle = util.computeRotation(box.landmarks[indexOfMouth], box.landmarks[indexOfForehead]);\n const faceCenter = bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint });\n const faceCenterNormalized = [faceCenter[0] / input.shape[2], faceCenter[1] / input.shape[1]];\n const rotatedImage = tf.image.rotateWithOffset(input, angle, 0, faceCenterNormalized); // rotateWithOffset is not defined for tfjs-node\n rotationMatrix = util.buildRotationMatrix(-angle, faceCenter);\n if (config.face.mesh.enabled) face = tf.div(bounding.cutBoxFromImageAndResize({ startPoint: box.startPoint, endPoint: box.endPoint }, rotatedImage, [this.meshSize, this.meshSize]), 255);\n else face = tf.div(bounding.cutBoxFromImageAndResize({ startPoint: box.startPoint, endPoint: box.endPoint }, rotatedImage, [this.boxSize, this.boxSize]), 255);\n } else {\n rotationMatrix = util.IDENTITY_MATRIX;\n const clonedImage = input.clone();\n if (config.face.mesh.enabled) face = tf.div(bounding.cutBoxFromImageAndResize({ startPoint: box.startPoint, endPoint: box.endPoint }, clonedImage, [this.meshSize, this.meshSize]), 255);\n else face = tf.div(bounding.cutBoxFromImageAndResize({ startPoint: box.startPoint, endPoint: box.endPoint }, clonedImage, [this.boxSize, this.boxSize]), 255);\n }\n\n // if we're not going to produce mesh, don't spend time with further processing\n if (!config.face.mesh.enabled) {\n const prediction = {\n mesh: [],\n box,\n faceConfidence: null,\n boxConfidence: box.confidence,\n confidence: box.confidence,\n image: face,\n };\n return prediction;\n }\n\n const [, confidence, contourCoords] = this.meshDetector.execute(face) as Array<Tensor>; // The first returned tensor represents facial contours which are already included in the coordinates.\n const faceConfidence = confidence.dataSync()[0] as number; // inside tf.tidy\n if (faceConfidence < config.face.detector.minConfidence) {\n this.storedBoxes[i].confidence = faceConfidence; // reset confidence of cached box\n return null; // if below confidence just exit\n }\n const coordsReshaped = tf.reshape(contourCoords, [-1, 3]);\n let rawCoords = coordsReshaped.arraySync();\n\n if (config.face.iris.enabled) {\n const { box: leftEyeBox, boxSize: leftEyeBoxSize, crop: leftEyeCrop } = this.getEyeBox(rawCoords, face, eyeLandmarks.leftBounds[0], eyeLandmarks.leftBounds[1], true);\n const { box: rightEyeBox, boxSize: rightEyeBoxSize, crop: rightEyeCrop } = this.getEyeBox(rawCoords, face, eyeLandmarks.rightBounds[0], eyeLandmarks.rightBounds[1]);\n const eyePredictions = this.irisModel.predict(tf.concat([leftEyeCrop, rightEyeCrop])) as Tensor;\n const eyePredictionsData = eyePredictions.dataSync(); // inside tf.tidy\n const leftEyeData = eyePredictionsData.slice(0, irisLandmarks.numCoordinates * 3);\n const { rawCoords: leftEyeRawCoords, iris: leftIrisRawCoords } = this.getEyeCoords(leftEyeData, leftEyeBox, leftEyeBoxSize, true);\n const rightEyeData = eyePredictionsData.slice(irisLandmarks.numCoordinates * 3);\n const { rawCoords: rightEyeRawCoords, iris: rightIrisRawCoords } = this.getEyeCoords(rightEyeData, rightEyeBox, rightEyeBoxSize);\n const leftToRightEyeDepthDifference = this.getLeftToRightEyeDepthDifference(rawCoords);\n if (Math.abs(leftToRightEyeDepthDifference) < 30) { // User is looking straight ahead.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left', null);\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right', null);\n // If the user is looking to the left or to the right, the iris coordinates tend to diverge too much from the mesh coordinates for them to be merged\n // So we only update a single contour line above and below the eye.\n } else if (leftToRightEyeDepthDifference < 1) { // User is looking towards the right.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left', ['EyeUpper0', 'EyeLower0']);\n } else { // User is looking towards the left.\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right', ['EyeUpper0', 'EyeLower0']);\n }\n const adjustedLeftIrisCoords = this.getAdjustedIrisCoords(rawCoords, leftIrisRawCoords, 'left');\n const adjustedRightIrisCoords = this.getAdjustedIrisCoords(rawCoords, rightIrisRawCoords, 'right');\n rawCoords = rawCoords.concat(adjustedLeftIrisCoords).concat(adjustedRightIrisCoords);\n }\n\n // override box from detection with one calculated from mesh\n const mesh = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n const storeConfidence = box.confidence;\n // @ts-ignore enlargeBox does not include confidence so we append it manually\n box = bounding.enlargeBox(bounding.calculateLandmarksBoundingBox(mesh), 1.5); // redefine box with mesh calculated one\n box.confidence = storeConfidence;\n\n // do rotation one more time with mesh keypoints if we want to return perfect image\n if (config.face.detector.rotation && config.face.mesh.enabled && config.face.description.enabled && tf.ENV.flags.IS_BROWSER) {\n const [indexOfMouth, indexOfForehead] = (box.landmarks.length >= meshLandmarks.count) ? meshLandmarks.symmetryLine : blazeFaceLandmarks.symmetryLine;\n angle = util.computeRotation(box.landmarks[indexOfMouth], box.landmarks[indexOfForehead]);\n const faceCenter = bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint });\n const faceCenterNormalized = [faceCenter[0] / input.shape[2], faceCenter[1] / input.shape[1]];\n const rotatedImage = tf.image.rotateWithOffset(tf.cast(input, 'float32'), angle, 0, faceCenterNormalized); // rotateWithOffset is not defined for tfjs-node\n rotationMatrix = util.buildRotationMatrix(-angle, faceCenter);\n face = tf.div(bounding.cutBoxFromImageAndResize({ startPoint: box.startPoint, endPoint: box.endPoint }, rotatedImage, [this.meshSize, this.meshSize]), 255);\n }\n\n const prediction = {\n mesh,\n box,\n faceConfidence,\n boxConfidence: box.confidence,\n image: face,\n };\n\n // updated stored cache values\n this.storedBoxes[i] = { ...bounding.squarifyBox(box), confidence: box.confidence, faceConfidence };\n\n return prediction;\n }));\n\n // results = results.filter((a) => a !== null);\n // remove cache entries for detected boxes on low confidence\n if (config.face.mesh.enabled) this.storedBoxes = this.storedBoxes.filter((a) => a.confidence > config.face.detector.minConfidence);\n this.detectedFaces = results.length;\n\n return results;\n }\n}\n", "/**\n * FaceMesh & BlazeFace Module entry point\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport * as blazeface from './blazeface';\nimport * as facepipeline from './facepipeline';\nimport * as coords from './coords';\nimport { GraphModel, Tensor } from '../tfjs/types';\nimport { Face } from '../result';\nimport { Config } from '../config';\n\nlet faceModels: [blazeface.BlazeFaceModel | null, GraphModel | null, GraphModel | null] = [null, null, null];\nlet facePipeline;\n\nexport async function predict(input: Tensor, config: Config): Promise<Face[]> {\n const predictions = await facePipeline.predict(input, config);\n const results: Array<Face> = [];\n let id = 0;\n for (const prediction of (predictions || [])) {\n if (!prediction || prediction.isDisposedInternal) continue; // guard against disposed tensors on long running operations such as pause in middle of processing\n const meshRaw = prediction.mesh.map((pt) => [\n pt[0] / (input.shape[2] || 0),\n pt[1] / (input.shape[1] || 0),\n pt[2] / facePipeline.meshSize,\n ]);\n const annotations = {};\n if (prediction.mesh && prediction.mesh.length > 0) {\n for (const key of Object.keys(coords.MESH_ANNOTATIONS)) annotations[key] = coords.MESH_ANNOTATIONS[key].map((index) => prediction.mesh[index]);\n }\n const clampedBox: [number, number, number, number] = prediction.box ? [\n Math.trunc(Math.max(0, prediction.box.startPoint[0])),\n Math.trunc(Math.max(0, prediction.box.startPoint[1])),\n Math.trunc(Math.min((input.shape[2] || 0), prediction.box.endPoint[0]) - Math.max(0, prediction.box.startPoint[0])),\n Math.trunc(Math.min((input.shape[1] || 0), prediction.box.endPoint[1]) - Math.max(0, prediction.box.startPoint[1])),\n ] : [0, 0, 0, 0];\n const boxRaw: [number, number, number, number] = prediction.box ? [\n prediction.box.startPoint[0] / (input.shape[2] || 0),\n prediction.box.startPoint[1] / (input.shape[1] || 0),\n (prediction.box.endPoint[0] - prediction.box.startPoint[0]) / (input.shape[2] || 0),\n (prediction.box.endPoint[1] - prediction.box.startPoint[1]) / (input.shape[1] || 0),\n ] : [0, 0, 0, 0];\n results.push({\n id: id++,\n score: Math.round(100 * prediction.faceConfidence || 100 * prediction.boxConfidence || 0) / 100,\n boxScore: Math.round(100 * prediction.boxConfidence) / 100,\n faceScore: Math.round(100 * prediction.faceConfidence) / 100,\n box: clampedBox,\n boxRaw,\n mesh: prediction.mesh,\n meshRaw,\n annotations,\n tensor: prediction.image,\n });\n if (prediction.coords) tf.dispose(prediction.coords);\n }\n return results;\n}\n\nexport async function load(config): Promise<[unknown, GraphModel | null, GraphModel | null]> {\n if ((!faceModels[0] && config.face.enabled) || (!faceModels[1] && config.face.mesh.enabled) || (!faceModels[2] && config.face.iris.enabled)) {\n // @ts-ignore type mismatch for GraphModel\n faceModels = await Promise.all([\n (!faceModels[0] && config.face.enabled) ? blazeface.load(config) : null,\n (!faceModels[1] && config.face.mesh.enabled) ? tf.loadGraphModel(join(config.modelBasePath, config.face.mesh.modelPath), { fromTFHub: config.face.mesh.modelPath.includes('tfhub.dev') }) : null,\n (!faceModels[2] && config.face.iris.enabled) ? tf.loadGraphModel(join(config.modelBasePath, config.face.iris.modelPath), { fromTFHub: config.face.iris.modelPath.includes('tfhub.dev') }) : null,\n ]);\n if (config.face.mesh.enabled) {\n if (!faceModels[1] || !faceModels[1]['modelUrl']) log('load model failed:', config.face.mesh.modelPath);\n else if (config.debug) log('load model:', faceModels[1]['modelUrl']);\n }\n if (config.face.iris.enabled) {\n if (!faceModels[2] || !faceModels[2]['modelUrl']) log('load model failed:', config.face.iris.modelPath);\n else if (config.debug) log('load model:', faceModels[2]['modelUrl']);\n }\n } else if (config.debug) {\n if (faceModels[0]) log('cached model:', faceModels[0].model['modelUrl']);\n if (faceModels[1]) log('cached model:', faceModels[1]['modelUrl']);\n if (faceModels[2]) log('cached model:', faceModels[2]['modelUrl']);\n }\n facePipeline = new facepipeline.Pipeline(faceModels[0], faceModels[1], faceModels[2]);\n return faceModels;\n}\n\nexport const triangulation = coords.TRI468;\nexport const uvmap = coords.UV468;\n", "/**\n * HSE-FaceRes Module\n * Returns Age, Gender, Descriptor\n * Implements Face simmilarity function\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport { Tensor, GraphModel } from '../tfjs/types';\nimport { Config } from '../config';\n\nlet model: GraphModel;\nconst last: Array<{\n age: number,\n gender: string,\n genderScore: number,\n descriptor: number[],\n}> = [];\n\nlet lastCount = 0;\nlet skipped = Number.MAX_SAFE_INTEGER;\n\ntype DB = Array<{ name: string, source: string, embedding: number[] }>;\n\nexport async function load(config: Config): Promise<GraphModel> {\n const modelUrl = join(config.modelBasePath, config.face.description.modelPath);\n if (!model) {\n // @ts-ignore type mismatch for GraphModel\n model = await tf.loadGraphModel(modelUrl);\n if (!model) log('load model failed:', config.face.description.modelPath);\n else if (config.debug) log('load model:', modelUrl);\n } else if (config.debug) log('cached model:', modelUrl);\n return model;\n}\n\nexport function similarity(embedding1: Array<number>, embedding2: Array<number>, order = 2): number {\n if (!embedding1 || !embedding2) return 0;\n if (embedding1?.length === 0 || embedding2?.length === 0) return 0;\n if (embedding1?.length !== embedding2?.length) return 0;\n // general minkowski distance, euclidean distance is limited case where order is 2\n const distance = 5.0 * embedding1\n .map((_val, i) => (Math.abs(embedding1[i] - embedding2[i]) ** order)) // distance squared\n .reduce((sum, now) => (sum + now), 0) // sum all distances\n ** (1 / order); // get root of\n const res = Math.max(0, 100 - distance) / 100.0;\n return res;\n}\n\nexport function match(embedding: Array<number>, db: DB, threshold = 0) {\n let best = { similarity: 0, name: '', source: '', embedding: [] as number[] };\n if (!embedding || !db || !Array.isArray(embedding) || !Array.isArray(db)) return best;\n for (const f of db) {\n if (f.embedding && f.name) {\n const perc = similarity(embedding, f.embedding);\n if (perc > threshold && perc > best.similarity) best = { ...f, similarity: perc };\n }\n }\n return best;\n}\n\nexport function enhance(input): Tensor {\n const image = tf.tidy(() => {\n // input received from detector is already normalized to 0..1\n // input is also assumed to be straightened\n const tensor = input.image || input.tensor || input;\n if (!(tensor instanceof tf.Tensor)) return null;\n // do a tight crop of image and resize it to fit the model\n const box = [[0.05, 0.15, 0.85, 0.85]]; // empyrical values for top, left, bottom, right\n // const box = [[0.0, 0.0, 1.0, 1.0]]; // basically no crop for test\n if (!model.inputs[0].shape) return null; // model has no shape so no point continuing\n const crop = (tensor.shape.length === 3)\n ? tf.image.cropAndResize(tf.expandDims(tensor, 0), box, [0], [model.inputs[0].shape[2], model.inputs[0].shape[1]]) // add batch dimension if missing\n : tf.image.cropAndResize(tensor, box, [0], [model.inputs[0].shape[2], model.inputs[0].shape[1]]);\n\n /*\n // just resize to fit the embedding model instead of cropping\n const crop = tf.image.resizeBilinear(tensor, [model.inputs[0].shape[2], model.inputs[0].shape[1]], false);\n */\n\n /*\n // convert to black&white to avoid colorization impact\n const rgb = [0.2989, 0.5870, 0.1140]; // factors for red/green/blue colors when converting to grayscale: https://www.mathworks.com/help/matlab/ref/rgb2gray.html\n const [red, green, blue] = tf.split(crop, 3, 3);\n const redNorm = tf.mul(red, rgb[0]);\n const greenNorm = tf.mul(green, rgb[1]);\n const blueNorm = tf.mul(blue, rgb[2]);\n const grayscale = tf.addN([redNorm, greenNorm, blueNorm]);\n const merge = tf.stack([grayscale, grayscale, grayscale], 3).squeeze(4);\n */\n\n /*\n // increase image pseudo-contrast 100%\n // (or do it per-channel so mean is done on each channel)\n // (or calculate histogram and do it based on histogram)\n const mean = merge.mean();\n const factor = 2;\n const contrast = merge.sub(mean).mul(factor).add(mean);\n */\n\n /*\n // normalize brightness from 0..1\n // silly way of creating pseudo-hdr of image\n const darken = crop.sub(crop.min());\n const lighten = darken.div(darken.max());\n */\n\n const norm = tf.mul(crop, 255);\n\n return norm;\n });\n return image;\n}\n\nexport async function predict(image: Tensor, config: Config, idx, count) {\n if (!model) return null;\n if ((skipped < config.face.description.skipFrames) && config.skipFrame && (lastCount === count) && last[idx]?.age && (last[idx]?.age > 0)) {\n skipped++;\n return last[idx];\n }\n skipped = 0;\n return new Promise(async (resolve) => {\n const enhanced = enhance(image);\n\n let resT;\n const obj = {\n age: <number>0,\n gender: <string>'unknown',\n genderScore: <number>0,\n descriptor: <number[]>[],\n };\n\n if (config.face.description.enabled) resT = await model.predict(enhanced);\n tf.dispose(enhanced);\n\n if (resT) {\n tf.tidy(() => {\n const gender = resT.find((t) => t.shape[1] === 1).dataSync(); // inside tf.tidy\n const confidence = Math.trunc(200 * Math.abs((gender[0] - 0.5))) / 100;\n if (confidence > config.face.description.minConfidence) {\n obj.gender = gender[0] <= 0.5 ? 'female' : 'male';\n obj.genderScore = Math.min(0.99, confidence);\n }\n const age = tf.argMax(resT.find((t) => t.shape[1] === 100), 1).dataSync()[0]; // inside tf.tidy\n const all = resT.find((t) => t.shape[1] === 100).dataSync(); // inside tf.tidy\n obj.age = Math.round(all[age - 1] > all[age + 1] ? 10 * age - 100 * all[age - 1] : 10 * age + 100 * all[age + 1]) / 10;\n\n const desc = resT.find((t) => t.shape[1] === 1024);\n // const reshape = desc.reshape([128, 8]); // reshape large 1024-element descriptor to 128 x 8\n // const reduce = reshape.logSumExp(1); // reduce 2nd dimension by calculating logSumExp on it which leaves us with 128-element descriptor\n\n obj.descriptor = [...desc.dataSync()]; // inside tf.tidy\n });\n resT.forEach((t) => tf.dispose(t));\n }\n\n last[idx] = obj;\n lastCount = count;\n resolve(obj);\n });\n}\n", "/**\n * Emotion Module\n */\n\nimport { log, join } from '../helpers';\nimport { Config } from '../config';\nimport { Tensor, GraphModel } from '../tfjs/types';\nimport * as tf from '../../dist/tfjs.esm.js';\n\nconst annotations = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral'];\nlet model;\n// let last: Array<{ score: number, emotion: string }> = [];\nconst last: Array<Array<{ score: number, emotion: string }>> = [];\nlet lastCount = 0;\nlet skipped = Number.MAX_SAFE_INTEGER;\n\n// tuning values\nconst rgb = [0.2989, 0.5870, 0.1140]; // factors for red/green/blue colors when converting to grayscale\n\nexport async function load(config: Config): Promise<GraphModel> {\n if (!model) {\n model = await tf.loadGraphModel(join(config.modelBasePath, config.face.emotion.modelPath));\n if (!model || !model.modelUrl) log('load model failed:', config.face.emotion.modelPath);\n else if (config.debug) log('load model:', model.modelUrl);\n } else if (config.debug) log('cached model:', model.modelUrl);\n return model;\n}\n\nexport async function predict(image: Tensor, config: Config, idx, count) {\n if (!model) return null;\n if ((skipped < config.face.emotion.skipFrames) && config.skipFrame && (lastCount === count) && last[idx] && (last[idx].length > 0)) {\n skipped++;\n return last[idx];\n }\n skipped = 0;\n return new Promise(async (resolve) => {\n const resize = tf.image.resizeBilinear(image, [model.inputs[0].shape[2], model.inputs[0].shape[1]], false);\n const [red, green, blue] = tf.split(resize, 3, 3);\n tf.dispose(resize);\n // weighted rgb to grayscale: https://www.mathworks.com/help/matlab/ref/rgb2gray.html\n const redNorm = tf.mul(red, rgb[0]);\n const greenNorm = tf.mul(green, rgb[1]);\n const blueNorm = tf.mul(blue, rgb[2]);\n tf.dispose(red);\n tf.dispose(green);\n tf.dispose(blue);\n const grayscale = tf.addN([redNorm, greenNorm, blueNorm]);\n tf.dispose(redNorm);\n tf.dispose(greenNorm);\n tf.dispose(blueNorm);\n const normalize = tf.tidy(() => tf.mul(tf.sub(grayscale, 0.5), 2));\n tf.dispose(grayscale);\n const obj: Array<{ score: number, emotion: string }> = [];\n if (config.face.emotion.enabled) {\n const emotionT = await model.predict(normalize); // result is already in range 0..1, no need for additional activation\n const data = await emotionT.data();\n tf.dispose(emotionT);\n for (let i = 0; i < data.length; i++) {\n if (data[i] > config.face.emotion.minConfidence) obj.push({ score: Math.min(0.99, Math.trunc(100 * data[i]) / 100), emotion: annotations[i] });\n }\n obj.sort((a, b) => b.score - a.score);\n }\n tf.dispose(normalize);\n last[idx] = obj;\n lastCount = count;\n resolve(obj);\n });\n}\n", "export const partNames = [\n 'nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder',\n 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist',\n 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle',\n];\n\nexport const count = partNames.length; // 17 keypoints\n\nexport const partIds = partNames.reduce((result, jointName, i) => {\n result[jointName] = i;\n return result;\n}, {});\n\nconst connectedPartNames = [\n ['leftHip', 'leftShoulder'], ['leftElbow', 'leftShoulder'],\n ['leftElbow', 'leftWrist'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['rightHip', 'rightShoulder'],\n ['rightElbow', 'rightShoulder'], ['rightElbow', 'rightWrist'],\n ['rightHip', 'rightKnee'], ['rightKnee', 'rightAnkle'],\n ['leftShoulder', 'rightShoulder'], ['leftHip', 'rightHip'],\n];\nexport const connectedPartIndices = connectedPartNames.map(([jointNameA, jointNameB]) => ([partIds[jointNameA], partIds[jointNameB]]));\n\nexport const poseChain = [\n ['nose', 'leftEye'], ['leftEye', 'leftEar'], ['nose', 'rightEye'],\n ['rightEye', 'rightEar'], ['nose', 'leftShoulder'],\n ['leftShoulder', 'leftElbow'], ['leftElbow', 'leftWrist'],\n ['leftShoulder', 'leftHip'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['nose', 'rightShoulder'],\n ['rightShoulder', 'rightElbow'], ['rightElbow', 'rightWrist'],\n ['rightShoulder', 'rightHip'], ['rightHip', 'rightKnee'],\n ['rightKnee', 'rightAnkle'],\n];\n", "import * as kpt from './keypoints';\nimport { Body } from '../result';\n\nexport function eitherPointDoesntMeetConfidence(a, b, minConfidence) {\n return (a < minConfidence || b < minConfidence);\n}\n\nexport function getAdjacentKeyPoints(keypoints, minConfidence) {\n return kpt.connectedPartIndices.reduce((result, [leftJoint, rightJoint]) => {\n if (eitherPointDoesntMeetConfidence(keypoints[leftJoint].score, keypoints[rightJoint].score, minConfidence)) {\n return result;\n }\n result.push([keypoints[leftJoint], keypoints[rightJoint]]);\n return result;\n }, []);\n}\n\nexport function getBoundingBox(keypoints): [number, number, number, number] {\n const coord = keypoints.reduce(({ maxX, maxY, minX, minY }, { position: { x, y } }) => ({\n maxX: Math.max(maxX, x),\n maxY: Math.max(maxY, y),\n minX: Math.min(minX, x),\n minY: Math.min(minY, y),\n }), {\n maxX: Number.NEGATIVE_INFINITY,\n maxY: Number.NEGATIVE_INFINITY,\n minX: Number.POSITIVE_INFINITY,\n minY: Number.POSITIVE_INFINITY,\n });\n return [coord.minX, coord.minY, coord.maxX - coord.minX, coord.maxY - coord.minY];\n}\n\nexport function scalePoses(poses, [height, width], [inputResolutionHeight, inputResolutionWidth]): Array<Body> {\n const scaleY = height / inputResolutionHeight;\n const scaleX = width / inputResolutionWidth;\n const scalePose = (pose, i) => ({\n id: i,\n score: pose.score,\n boxRaw: [pose.box[0] / inputResolutionWidth, pose.box[1] / inputResolutionHeight, pose.box[2] / inputResolutionWidth, pose.box[3] / inputResolutionHeight],\n box: [Math.trunc(pose.box[0] * scaleX), Math.trunc(pose.box[1] * scaleY), Math.trunc(pose.box[2] * scaleX), Math.trunc(pose.box[3] * scaleY)],\n keypoints: pose.keypoints.map(({ score, part, position }) => ({\n score,\n part,\n position: [Math.trunc(position.x * scaleX), Math.trunc(position.y * scaleY)],\n positionRaw: [position.x / inputResolutionHeight, position.y / inputResolutionHeight],\n })),\n });\n const scaledPoses = poses.map((pose, i) => scalePose(pose, i));\n return scaledPoses;\n}\n\n// algorithm based on Coursera Lecture from Algorithms, Part 1: https://www.coursera.org/learn/algorithms-part1/lecture/ZjoSM/heapsort\nexport class MaxHeap {\n priorityQueue: Array<unknown>; // don't touch\n numberOfElements: number;\n getElementValue: unknown; // function call\n\n constructor(maxSize, getElementValue) {\n this.priorityQueue = new Array(maxSize);\n this.numberOfElements = -1;\n this.getElementValue = getElementValue;\n }\n\n enqueue(x) {\n this.priorityQueue[++this.numberOfElements] = x;\n this.swim(this.numberOfElements);\n }\n\n dequeue() {\n const max = this.priorityQueue[0];\n this.exchange(0, this.numberOfElements--);\n this.sink(0);\n this.priorityQueue[this.numberOfElements + 1] = null;\n return max;\n }\n\n empty() { return this.numberOfElements === -1; }\n\n size() { return this.numberOfElements + 1; }\n\n all() { return this.priorityQueue.slice(0, this.numberOfElements + 1); }\n\n max() { return this.priorityQueue[0]; }\n\n swim(k) {\n while (k > 0 && this.less(Math.floor(k / 2), k)) {\n this.exchange(k, Math.floor(k / 2));\n k = Math.floor(k / 2);\n }\n }\n\n sink(k) {\n while (2 * k <= this.numberOfElements) {\n let j = 2 * k;\n if (j < this.numberOfElements && this.less(j, j + 1)) j++;\n if (!this.less(k, j)) break;\n this.exchange(k, j);\n k = j;\n }\n }\n\n getValueAt(i) {\n // @ts-ignore getter is of unknown type\n return this.getElementValue(this.priorityQueue[i]);\n }\n\n less(i, j) {\n return this.getValueAt(i) < this.getValueAt(j);\n }\n\n exchange(i, j) {\n const t = this.priorityQueue[i];\n this.priorityQueue[i] = this.priorityQueue[j];\n this.priorityQueue[j] = t;\n }\n}\n\nexport function getOffsetPoint(y, x, keypoint, offsets) {\n return {\n y: offsets.get(y, x, keypoint),\n x: offsets.get(y, x, keypoint + kpt.count),\n };\n}\n\nexport function getImageCoords(part, outputStride, offsets) {\n const { heatmapY, heatmapX, id: keypoint } = part;\n const { y, x } = getOffsetPoint(heatmapY, heatmapX, keypoint, offsets);\n return {\n x: part.heatmapX * outputStride + x,\n y: part.heatmapY * outputStride + y,\n };\n}\n\nexport function fillArray(element, size) {\n const result = new Array(size);\n for (let i = 0; i < size; i++) {\n result[i] = element;\n }\n return result;\n}\n\nexport function clamp(a, min, max) {\n if (a < min) return min;\n if (a > max) return max;\n return a;\n}\n\nexport function squaredDistance(y1, x1, y2, x2) {\n const dy = y2 - y1;\n const dx = x2 - x1;\n return dy * dy + dx * dx;\n}\n\nexport function addVectors(a, b) {\n return { x: a.x + b.x, y: a.y + b.y };\n}\n\nexport function clampVector(a, min, max) {\n return { y: clamp(a.y, min, max), x: clamp(a.x, min, max) };\n}\n", "import * as utils from './utils';\nimport * as kpt from './keypoints';\n\nconst localMaximumRadius = 1;\nconst outputStride = 16;\nconst squaredNmsRadius = 50 ** 2;\n\nfunction traverse(edgeId, sourceKeypoint, targetId, scores, offsets, displacements, offsetRefineStep = 2) {\n const getDisplacement = (point) => ({\n y: displacements.get(point.y, point.x, edgeId),\n x: displacements.get(point.y, point.x, (displacements.shape[2] / 2) + edgeId),\n });\n const getStridedIndexNearPoint = (point, height, width) => ({\n y: utils.clamp(Math.round(point.y / outputStride), 0, height - 1),\n x: utils.clamp(Math.round(point.x / outputStride), 0, width - 1),\n });\n\n const [height, width] = scores.shape;\n // Nearest neighbor interpolation for the source->target displacements.\n const sourceKeypointIndices = getStridedIndexNearPoint(sourceKeypoint.position, height, width);\n const displacement = getDisplacement(sourceKeypointIndices);\n const displacedPoint = utils.addVectors(sourceKeypoint.position, displacement);\n let targetKeypoint = displacedPoint;\n for (let i = 0; i < offsetRefineStep; i++) {\n const targetKeypointIndices = getStridedIndexNearPoint(targetKeypoint, height, width);\n const offsetPoint = utils.getOffsetPoint(targetKeypointIndices.y, targetKeypointIndices.x, targetId, offsets);\n targetKeypoint = utils.addVectors(\n { x: targetKeypointIndices.x * outputStride, y: targetKeypointIndices.y * outputStride },\n { x: offsetPoint.x, y: offsetPoint.y },\n );\n }\n const targetKeyPointIndices = getStridedIndexNearPoint(targetKeypoint, height, width);\n const score = scores.get(targetKeyPointIndices.y, targetKeyPointIndices.x, targetId);\n return { position: targetKeypoint, part: kpt.partNames[targetId], score };\n}\n\nexport function decodePose(root, scores, offsets, displacementsFwd, displacementsBwd) {\n const tuples = kpt.poseChain.map(([parentJoinName, childJoinName]) => ([kpt.partIds[parentJoinName], kpt.partIds[childJoinName]]));\n const edgesFwd = tuples.map(([, childJointId]) => childJointId);\n const edgesBwd = tuples.map(([parentJointId]) => parentJointId);\n const numParts = scores.shape[2]; // [21,21,17]\n const numEdges = edgesFwd.length;\n const keypoints = new Array(numParts);\n // Start a new detection instance at the position of the root.\n const rootPoint = utils.getImageCoords(root.part, outputStride, offsets);\n keypoints[root.part.id] = {\n score: root.score,\n part: kpt.partNames[root.part.id],\n position: rootPoint,\n };\n // Decode the part positions upwards in the tree, following the backward displacements.\n for (let edge = numEdges - 1; edge >= 0; --edge) {\n const sourceId = edgesFwd[edge];\n const targetId = edgesBwd[edge];\n if (keypoints[sourceId] && !keypoints[targetId]) {\n keypoints[targetId] = traverse(edge, keypoints[sourceId], targetId, scores, offsets, displacementsBwd);\n }\n }\n // Decode the part positions downwards in the tree, following the forward displacements.\n for (let edge = 0; edge < numEdges; ++edge) {\n const sourceId = edgesBwd[edge];\n const targetId = edgesFwd[edge];\n if (keypoints[sourceId] && !keypoints[targetId]) {\n keypoints[targetId] = traverse(edge, keypoints[sourceId], targetId, scores, offsets, displacementsFwd);\n }\n }\n return keypoints;\n}\n\nfunction scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, scores) {\n const [height, width] = scores.shape;\n let localMaximum = true;\n const yStart = Math.max(heatmapY - localMaximumRadius, 0);\n const yEnd = Math.min(heatmapY + localMaximumRadius + 1, height);\n for (let yCurrent = yStart; yCurrent < yEnd; ++yCurrent) {\n const xStart = Math.max(heatmapX - localMaximumRadius, 0);\n const xEnd = Math.min(heatmapX + localMaximumRadius + 1, width);\n for (let xCurrent = xStart; xCurrent < xEnd; ++xCurrent) {\n if (scores.get(yCurrent, xCurrent, keypointId) > score) {\n localMaximum = false;\n break;\n }\n }\n if (!localMaximum) break;\n }\n return localMaximum;\n}\n\nexport function buildPartWithScoreQueue(minConfidence, scores) {\n const [height, width, numKeypoints] = scores.shape;\n const queue = new utils.MaxHeap(height * width * numKeypoints, ({ score }) => score);\n for (let heatmapY = 0; heatmapY < height; ++heatmapY) {\n for (let heatmapX = 0; heatmapX < width; ++heatmapX) {\n for (let keypointId = 0; keypointId < numKeypoints; ++keypointId) {\n const score = scores.get(heatmapY, heatmapX, keypointId);\n // Only consider parts with score greater or equal to threshold as root candidates.\n if (score < minConfidence) continue;\n // Only consider keypoints whose score is maximum in a local window.\n if (scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, scores)) queue.enqueue({ score, part: { heatmapY, heatmapX, id: keypointId } });\n }\n }\n }\n return queue;\n}\n\nfunction withinRadius(poses, { x, y }, keypointId) {\n return poses.some(({ keypoints }) => {\n const correspondingKeypoint = keypoints[keypointId]?.position;\n if (!correspondingKeypoint) return false;\n return utils.squaredDistance(y, x, correspondingKeypoint.y, correspondingKeypoint.x) <= squaredNmsRadius;\n });\n}\n\nfunction getInstanceScore(existingPoses, keypoints) {\n const notOverlappedKeypointScores = keypoints.reduce((result, { position, score }, keypointId) => {\n if (!withinRadius(existingPoses, position, keypointId)) result += score;\n return result;\n }, 0.0);\n return notOverlappedKeypointScores / keypoints.length;\n}\n\nexport function decode(offsets, scores, displacementsFwd, displacementsBwd, maxDetected, minConfidence) {\n const poses: Array<{ keypoints, box: [number, number, number, number], score: number }> = [];\n const queue = buildPartWithScoreQueue(minConfidence, scores);\n // Generate at most maxDetected object instances per image in decreasing root part score order.\n while (poses.length < maxDetected && !queue.empty()) {\n // The top element in the queue is the next root candidate.\n const root = queue.dequeue();\n // Part-based non-maximum suppression: We reject a root candidate if it is within a disk of `nmsRadius` pixels from the corresponding part of a previously detected instance.\n // @ts-ignore this one is tree walk\n const rootImageCoords = utils.getImageCoords(root.part, outputStride, offsets);\n // @ts-ignore this one is tree walk\n if (withinRadius(poses, rootImageCoords, root.part.id)) continue;\n // Else start a new detection instance at the position of the root.\n let keypoints = decodePose(root, scores, offsets, displacementsFwd, displacementsBwd);\n keypoints = keypoints.filter((a) => a.score > minConfidence);\n const score = getInstanceScore(poses, keypoints);\n const box = utils.getBoundingBox(keypoints);\n if (score > minConfidence) poses.push({ keypoints, box, score: Math.round(100 * score) / 100 });\n }\n return poses;\n}\n", "/**\n * PoseNet module entry point\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport * as poses from './poses';\nimport * as util from './utils';\nimport { Body } from '../result';\nimport { Tensor, GraphModel } from '../tfjs/types';\nimport { Config } from '../config';\n\nlet model: GraphModel;\nconst poseNetOutputs = ['MobilenetV1/offset_2/BiasAdd'/* offsets */, 'MobilenetV1/heatmap_2/BiasAdd'/* heatmapScores */, 'MobilenetV1/displacement_fwd_2/BiasAdd'/* displacementFwd */, 'MobilenetV1/displacement_bwd_2/BiasAdd'/* displacementBwd */];\n\nexport async function predict(input: Tensor, config: Config): Promise<Body[]> {\n const res = tf.tidy(() => {\n if (!model.inputs[0].shape) return [];\n const resized = tf.image.resizeBilinear(input, [model.inputs[0].shape[2], model.inputs[0].shape[1]]);\n const normalized = tf.sub(tf.div(tf.cast(resized, 'float32'), 127.5), 1.0);\n const results: Array<Tensor> = model.execute(normalized, poseNetOutputs) as Array<Tensor>;\n const results3d = results.map((y) => tf.squeeze(y, [0]));\n results3d[1] = results3d[1].sigmoid(); // apply sigmoid on scores\n return results3d;\n });\n\n const buffers = await Promise.all(res.map((tensor) => tensor.buffer()));\n for (const t of res) tf.dispose(t);\n\n const decoded = await poses.decode(buffers[0], buffers[1], buffers[2], buffers[3], config.body.maxDetected, config.body.minConfidence);\n if (!model.inputs[0].shape) return [];\n const scaled = util.scalePoses(decoded, [input.shape[1], input.shape[2]], [model.inputs[0].shape[2], model.inputs[0].shape[1]]) as Body[];\n return scaled;\n}\n\nexport async function load(config: Config): Promise<GraphModel> {\n if (!model) {\n // @ts-ignore type mismatch for GraphModel\n model = await tf.loadGraphModel(join(config.modelBasePath, config.body.modelPath));\n if (!model || !model['modelUrl']) log('load model failed:', config.body.modelPath);\n else if (config.debug) log('load model:', model['modelUrl']);\n } else if (config.debug) log('cached model:', model['modelUrl']);\n return model;\n}\n", "import * as tf from '../../dist/tfjs.esm.js';\n\nexport function getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\n\nexport function getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\n\nexport function cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h,\n box.startPoint[0] / w,\n box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\n\nexport function scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n const palmLandmarks = box.palmLandmarks.map((coord) => {\n const scaledCoord = [coord[0] * factor[0], coord[1] * factor[1]];\n return scaledCoord;\n });\n return { startPoint, endPoint, palmLandmarks, confidence: box.confidence };\n}\n\nexport function enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\n\nexport function squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\n\nexport function shiftBox(box, shiftFactor) {\n const boxSize = [\n box.endPoint[0] - box.startPoint[0],\n box.endPoint[1] - box.startPoint[1],\n ];\n const shiftVector = [boxSize[0] * shiftFactor[0], boxSize[1] * shiftFactor[1]];\n const startPoint = [box.startPoint[0] + shiftVector[0], box.startPoint[1] + shiftVector[1]];\n const endPoint = [box.endPoint[0] + shiftVector[0], box.endPoint[1] + shiftVector[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\n", "export const anchors = [\n { x: 0.015625, y: 0.015625 },\n { x: 0.015625, y: 0.015625 },\n { x: 0.046875, y: 0.015625 },\n { x: 0.046875, y: 0.015625 },\n { x: 0.078125, y: 0.015625 },\n { x: 0.078125, y: 0.015625 },\n { x: 0.109375, y: 0.015625 },\n { x: 0.109375, y: 0.015625 },\n { x: 0.140625, y: 0.015625 },\n { x: 0.140625, y: 0.015625 },\n { x: 0.171875, y: 0.015625 },\n { x: 0.171875, y: 0.015625 },\n { x: 0.203125, y: 0.015625 },\n { x: 0.203125, y: 0.015625 },\n { x: 0.234375, y: 0.015625 },\n { x: 0.234375, y: 0.015625 },\n { x: 0.265625, y: 0.015625 },\n { x: 0.265625, y: 0.015625 },\n { x: 0.296875, y: 0.015625 },\n { x: 0.296875, y: 0.015625 },\n { x: 0.328125, y: 0.015625 },\n { x: 0.328125, y: 0.015625 },\n { x: 0.359375, y: 0.015625 },\n { x: 0.359375, y: 0.015625 },\n { x: 0.390625, y: 0.015625 },\n { x: 0.390625, y: 0.015625 },\n { x: 0.421875, y: 0.015625 },\n { x: 0.421875, y: 0.015625 },\n { x: 0.453125, y: 0.015625 },\n { x: 0.453125, y: 0.015625 },\n { x: 0.484375, y: 0.015625 },\n { x: 0.484375, y: 0.015625 },\n { x: 0.515625, y: 0.015625 },\n { x: 0.515625, y: 0.015625 },\n { x: 0.546875, y: 0.015625 },\n { x: 0.546875, y: 0.015625 },\n { x: 0.578125, y: 0.015625 },\n { x: 0.578125, y: 0.015625 },\n { x: 0.609375, y: 0.015625 },\n { x: 0.609375, y: 0.015625 },\n { x: 0.640625, y: 0.015625 },\n { x: 0.640625, y: 0.015625 },\n { x: 0.671875, y: 0.015625 },\n { x: 0.671875, y: 0.015625 },\n { x: 0.703125, y: 0.015625 },\n { x: 0.703125, y: 0.015625 },\n { x: 0.734375, y: 0.015625 },\n { x: 0.734375, y: 0.015625 },\n { x: 0.765625, y: 0.015625 },\n { x: 0.765625, y: 0.015625 },\n { x: 0.796875, y: 0.015625 },\n { x: 0.796875, y: 0.015625 },\n { x: 0.828125, y: 0.015625 },\n { x: 0.828125, y: 0.015625 },\n { x: 0.859375, y: 0.015625 },\n { x: 0.859375, y: 0.015625 },\n { x: 0.890625, y: 0.015625 },\n { x: 0.890625, y: 0.015625 },\n { x: 0.921875, y: 0.015625 },\n { x: 0.921875, y: 0.015625 },\n { x: 0.953125, y: 0.015625 },\n { x: 0.953125, y: 0.015625 },\n { x: 0.984375, y: 0.015625 },\n { x: 0.984375, y: 0.015625 },\n { x: 0.015625, y: 0.046875 },\n { x: 0.015625, y: 0.046875 },\n { x: 0.046875, y: 0.046875 },\n { x: 0.046875, y: 0.046875 },\n { x: 0.078125, y: 0.046875 },\n { x: 0.078125, y: 0.046875 },\n { x: 0.109375, y: 0.046875 },\n { x: 0.109375, y: 0.046875 },\n { x: 0.140625, y: 0.046875 },\n { x: 0.140625, y: 0.046875 },\n { x: 0.171875, y: 0.046875 },\n { x: 0.171875, y: 0.046875 },\n { x: 0.203125, y: 0.046875 },\n { x: 0.203125, y: 0.046875 },\n { x: 0.234375, y: 0.046875 },\n { x: 0.234375, y: 0.046875 },\n { x: 0.265625, y: 0.046875 },\n { x: 0.265625, y: 0.046875 },\n { x: 0.296875, y: 0.046875 },\n { x: 0.296875, y: 0.046875 },\n { x: 0.328125, y: 0.046875 },\n { x: 0.328125, y: 0.046875 },\n { x: 0.359375, y: 0.046875 },\n { x: 0.359375, y: 0.046875 },\n { x: 0.390625, y: 0.046875 },\n { x: 0.390625, y: 0.046875 },\n { x: 0.421875, y: 0.046875 },\n { x: 0.421875, y: 0.046875 },\n { x: 0.453125, y: 0.046875 },\n { x: 0.453125, y: 0.046875 },\n { x: 0.484375, y: 0.046875 },\n { x: 0.484375, y: 0.046875 },\n { x: 0.515625, y: 0.046875 },\n { x: 0.515625, y: 0.046875 },\n { x: 0.546875, y: 0.046875 },\n { x: 0.546875, y: 0.046875 },\n { x: 0.578125, y: 0.046875 },\n { x: 0.578125, y: 0.046875 },\n { x: 0.609375, y: 0.046875 },\n { x: 0.609375, y: 0.046875 },\n { x: 0.640625, y: 0.046875 },\n { x: 0.640625, y: 0.046875 },\n { x: 0.671875, y: 0.046875 },\n { x: 0.671875, y: 0.046875 },\n { x: 0.703125, y: 0.046875 },\n { x: 0.703125, y: 0.046875 },\n { x: 0.734375, y: 0.046875 },\n { x: 0.734375, y: 0.046875 },\n { x: 0.765625, y: 0.046875 },\n { x: 0.765625, y: 0.046875 },\n { x: 0.796875, y: 0.046875 },\n { x: 0.796875, y: 0.046875 },\n { x: 0.828125, y: 0.046875 },\n { x: 0.828125, y: 0.046875 },\n { x: 0.859375, y: 0.046875 },\n { x: 0.859375, y: 0.046875 },\n { x: 0.890625, y: 0.046875 },\n { x: 0.890625, y: 0.046875 },\n { x: 0.921875, y: 0.046875 },\n { x: 0.921875, y: 0.046875 },\n { x: 0.953125, y: 0.046875 },\n { x: 0.953125, y: 0.046875 },\n { x: 0.984375, y: 0.046875 },\n { x: 0.984375, y: 0.046875 },\n { x: 0.015625, y: 0.078125 },\n { x: 0.015625, y: 0.078125 },\n { x: 0.046875, y: 0.078125 },\n { x: 0.046875, y: 0.078125 },\n { x: 0.078125, y: 0.078125 },\n { x: 0.078125, y: 0.078125 },\n { x: 0.109375, y: 0.078125 },\n { x: 0.109375, y: 0.078125 },\n { x: 0.140625, y: 0.078125 },\n { x: 0.140625, y: 0.078125 },\n { x: 0.171875, y: 0.078125 },\n { x: 0.171875, y: 0.078125 },\n { x: 0.203125, y: 0.078125 },\n { x: 0.203125, y: 0.078125 },\n { x: 0.234375, y: 0.078125 },\n { x: 0.234375, y: 0.078125 },\n { x: 0.265625, y: 0.078125 },\n { x: 0.265625, y: 0.078125 },\n { x: 0.296875, y: 0.078125 },\n { x: 0.296875, y: 0.078125 },\n { x: 0.328125, y: 0.078125 },\n { x: 0.328125, y: 0.078125 },\n { x: 0.359375, y: 0.078125 },\n { x: 0.359375, y: 0.078125 },\n { x: 0.390625, y: 0.078125 },\n { x: 0.390625, y: 0.078125 },\n { x: 0.421875, y: 0.078125 },\n { x: 0.421875, y: 0.078125 },\n { x: 0.453125, y: 0.078125 },\n { x: 0.453125, y: 0.078125 },\n { x: 0.484375, y: 0.078125 },\n { x: 0.484375, y: 0.078125 },\n { x: 0.515625, y: 0.078125 },\n { x: 0.515625, y: 0.078125 },\n { x: 0.546875, y: 0.078125 },\n { x: 0.546875, y: 0.078125 },\n { x: 0.578125, y: 0.078125 },\n { x: 0.578125, y: 0.078125 },\n { x: 0.609375, y: 0.078125 },\n { x: 0.609375, y: 0.078125 },\n { x: 0.640625, y: 0.078125 },\n { x: 0.640625, y: 0.078125 },\n { x: 0.671875, y: 0.078125 },\n { x: 0.671875, y: 0.078125 },\n { x: 0.703125, y: 0.078125 },\n { x: 0.703125, y: 0.078125 },\n { x: 0.734375, y: 0.078125 },\n { x: 0.734375, y: 0.078125 },\n { x: 0.765625, y: 0.078125 },\n { x: 0.765625, y: 0.078125 },\n { x: 0.796875, y: 0.078125 },\n { x: 0.796875, y: 0.078125 },\n { x: 0.828125, y: 0.078125 },\n { x: 0.828125, y: 0.078125 },\n { x: 0.859375, y: 0.078125 },\n { x: 0.859375, y: 0.078125 },\n { x: 0.890625, y: 0.078125 },\n { x: 0.890625, y: 0.078125 },\n { x: 0.921875, y: 0.078125 },\n { x: 0.921875, y: 0.078125 },\n { x: 0.953125, y: 0.078125 },\n { x: 0.953125, y: 0.078125 },\n { x: 0.984375, y: 0.078125 },\n { x: 0.984375, y: 0.078125 },\n { x: 0.015625, y: 0.109375 },\n { x: 0.015625, y: 0.109375 },\n { x: 0.046875, y: 0.109375 },\n { x: 0.046875, y: 0.109375 },\n { x: 0.078125, y: 0.109375 },\n { x: 0.078125, y: 0.109375 },\n { x: 0.109375, y: 0.109375 },\n { x: 0.109375, y: 0.109375 },\n { x: 0.140625, y: 0.109375 },\n { x: 0.140625, y: 0.109375 },\n { x: 0.171875, y: 0.109375 },\n { x: 0.171875, y: 0.109375 },\n { x: 0.203125, y: 0.109375 },\n { x: 0.203125, y: 0.109375 },\n { x: 0.234375, y: 0.109375 },\n { x: 0.234375, y: 0.109375 },\n { x: 0.265625, y: 0.109375 },\n { x: 0.265625, y: 0.109375 },\n { x: 0.296875, y: 0.109375 },\n { x: 0.296875, y: 0.109375 },\n { x: 0.328125, y: 0.109375 },\n { x: 0.328125, y: 0.109375 },\n { x: 0.359375, y: 0.109375 },\n { x: 0.359375, y: 0.109375 },\n { x: 0.390625, y: 0.109375 },\n { x: 0.390625, y: 0.109375 },\n { x: 0.421875, y: 0.109375 },\n { x: 0.421875, y: 0.109375 },\n { x: 0.453125, y: 0.109375 },\n { x: 0.453125, y: 0.109375 },\n { x: 0.484375, y: 0.109375 },\n { x: 0.484375, y: 0.109375 },\n { x: 0.515625, y: 0.109375 },\n { x: 0.515625, y: 0.109375 },\n { x: 0.546875, y: 0.109375 },\n { x: 0.546875, y: 0.109375 },\n { x: 0.578125, y: 0.109375 },\n { x: 0.578125, y: 0.109375 },\n { x: 0.609375, y: 0.109375 },\n { x: 0.609375, y: 0.109375 },\n { x: 0.640625, y: 0.109375 },\n { x: 0.640625, y: 0.109375 },\n { x: 0.671875, y: 0.109375 },\n { x: 0.671875, y: 0.109375 },\n { x: 0.703125, y: 0.109375 },\n { x: 0.703125, y: 0.109375 },\n { x: 0.734375, y: 0.109375 },\n { x: 0.734375, y: 0.109375 },\n { x: 0.765625, y: 0.109375 },\n { x: 0.765625, y: 0.109375 },\n { x: 0.796875, y: 0.109375 },\n { x: 0.796875, y: 0.109375 },\n { x: 0.828125, y: 0.109375 },\n { x: 0.828125, y: 0.109375 },\n { x: 0.859375, y: 0.109375 },\n { x: 0.859375, y: 0.109375 },\n { x: 0.890625, y: 0.109375 },\n { x: 0.890625, y: 0.109375 },\n { x: 0.921875, y: 0.109375 },\n { x: 0.921875, y: 0.109375 },\n { x: 0.953125, y: 0.109375 },\n { x: 0.953125, y: 0.109375 },\n { x: 0.984375, y: 0.109375 },\n { x: 0.984375, y: 0.109375 },\n { x: 0.015625, y: 0.140625 },\n { x: 0.015625, y: 0.140625 },\n { x: 0.046875, y: 0.140625 },\n { x: 0.046875, y: 0.140625 },\n { x: 0.078125, y: 0.140625 },\n { x: 0.078125, y: 0.140625 },\n { x: 0.109375, y: 0.140625 },\n { x: 0.109375, y: 0.140625 },\n { x: 0.140625, y: 0.140625 },\n { x: 0.140625, y: 0.140625 },\n { x: 0.171875, y: 0.140625 },\n { x: 0.171875, y: 0.140625 },\n { x: 0.203125, y: 0.140625 },\n { x: 0.203125, y: 0.140625 },\n { x: 0.234375, y: 0.140625 },\n { x: 0.234375, y: 0.140625 },\n { x: 0.265625, y: 0.140625 },\n { x: 0.265625, y: 0.140625 },\n { x: 0.296875, y: 0.140625 },\n { x: 0.296875, y: 0.140625 },\n { x: 0.328125, y: 0.140625 },\n { x: 0.328125, y: 0.140625 },\n { x: 0.359375, y: 0.140625 },\n { x: 0.359375, y: 0.140625 },\n { x: 0.390625, y: 0.140625 },\n { x: 0.390625, y: 0.140625 },\n { x: 0.421875, y: 0.140625 },\n { x: 0.421875, y: 0.140625 },\n { x: 0.453125, y: 0.140625 },\n { x: 0.453125, y: 0.140625 },\n { x: 0.484375, y: 0.140625 },\n { x: 0.484375, y: 0.140625 },\n { x: 0.515625, y: 0.140625 },\n { x: 0.515625, y: 0.140625 },\n { x: 0.546875, y: 0.140625 },\n { x: 0.546875, y: 0.140625 },\n { x: 0.578125, y: 0.140625 },\n { x: 0.578125, y: 0.140625 },\n { x: 0.609375, y: 0.140625 },\n { x: 0.609375, y: 0.140625 },\n { x: 0.640625, y: 0.140625 },\n { x: 0.640625, y: 0.140625 },\n { x: 0.671875, y: 0.140625 },\n { x: 0.671875, y: 0.140625 },\n { x: 0.703125, y: 0.140625 },\n { x: 0.703125, y: 0.140625 },\n { x: 0.734375, y: 0.140625 },\n { x: 0.734375, y: 0.140625 },\n { x: 0.765625, y: 0.140625 },\n { x: 0.765625, y: 0.140625 },\n { x: 0.796875, y: 0.140625 },\n { x: 0.796875, y: 0.140625 },\n { x: 0.828125, y: 0.140625 },\n { x: 0.828125, y: 0.140625 },\n { x: 0.859375, y: 0.140625 },\n { x: 0.859375, y: 0.140625 },\n { x: 0.890625, y: 0.140625 },\n { x: 0.890625, y: 0.140625 },\n { x: 0.921875, y: 0.140625 },\n { x: 0.921875, y: 0.140625 },\n { x: 0.953125, y: 0.140625 },\n { x: 0.953125, y: 0.140625 },\n { x: 0.984375, y: 0.140625 },\n { x: 0.984375, y: 0.140625 },\n { x: 0.015625, y: 0.171875 },\n { x: 0.015625, y: 0.171875 },\n { x: 0.046875, y: 0.171875 },\n { x: 0.046875, y: 0.171875 },\n { x: 0.078125, y: 0.171875 },\n { x: 0.078125, y: 0.171875 },\n { x: 0.109375, y: 0.171875 },\n { x: 0.109375, y: 0.171875 },\n { x: 0.140625, y: 0.171875 },\n { x: 0.140625, y: 0.171875 },\n { x: 0.171875, y: 0.171875 },\n { x: 0.171875, y: 0.171875 },\n { x: 0.203125, y: 0.171875 },\n { x: 0.203125, y: 0.171875 },\n { x: 0.234375, y: 0.171875 },\n { x: 0.234375, y: 0.171875 },\n { x: 0.265625, y: 0.171875 },\n { x: 0.265625, y: 0.171875 },\n { x: 0.296875, y: 0.171875 },\n { x: 0.296875, y: 0.171875 },\n { x: 0.328125, y: 0.171875 },\n { x: 0.328125, y: 0.171875 },\n { x: 0.359375, y: 0.171875 },\n { x: 0.359375, y: 0.171875 },\n { x: 0.390625, y: 0.171875 },\n { x: 0.390625, y: 0.171875 },\n { x: 0.421875, y: 0.171875 },\n { x: 0.421875, y: 0.171875 },\n { x: 0.453125, y: 0.171875 },\n { x: 0.453125, y: 0.171875 },\n { x: 0.484375, y: 0.171875 },\n { x: 0.484375, y: 0.171875 },\n { x: 0.515625, y: 0.171875 },\n { x: 0.515625, y: 0.171875 },\n { x: 0.546875, y: 0.171875 },\n { x: 0.546875, y: 0.171875 },\n { x: 0.578125, y: 0.171875 },\n { x: 0.578125, y: 0.171875 },\n { x: 0.609375, y: 0.171875 },\n { x: 0.609375, y: 0.171875 },\n { x: 0.640625, y: 0.171875 },\n { x: 0.640625, y: 0.171875 },\n { x: 0.671875, y: 0.171875 },\n { x: 0.671875, y: 0.171875 },\n { x: 0.703125, y: 0.171875 },\n { x: 0.703125, y: 0.171875 },\n { x: 0.734375, y: 0.171875 },\n { x: 0.734375, y: 0.171875 },\n { x: 0.765625, y: 0.171875 },\n { x: 0.765625, y: 0.171875 },\n { x: 0.796875, y: 0.171875 },\n { x: 0.796875, y: 0.171875 },\n { x: 0.828125, y: 0.171875 },\n { x: 0.828125, y: 0.171875 },\n { x: 0.859375, y: 0.171875 },\n { x: 0.859375, y: 0.171875 },\n { x: 0.890625, y: 0.171875 },\n { x: 0.890625, y: 0.171875 },\n { x: 0.921875, y: 0.171875 },\n { x: 0.921875, y: 0.171875 },\n { x: 0.953125, y: 0.171875 },\n { x: 0.953125, y: 0.171875 },\n { x: 0.984375, y: 0.171875 },\n { x: 0.984375, y: 0.171875 },\n { x: 0.015625, y: 0.203125 },\n { x: 0.015625, y: 0.203125 },\n { x: 0.046875, y: 0.203125 },\n { x: 0.046875, y: 0.203125 },\n { x: 0.078125, y: 0.203125 },\n { x: 0.078125, y: 0.203125 },\n { x: 0.109375, y: 0.203125 },\n { x: 0.109375, y: 0.203125 },\n { x: 0.140625, y: 0.203125 },\n { x: 0.140625, y: 0.203125 },\n { x: 0.171875, y: 0.203125 },\n { x: 0.171875, y: 0.203125 },\n { x: 0.203125, y: 0.203125 },\n { x: 0.203125, y: 0.203125 },\n { x: 0.234375, y: 0.203125 },\n { x: 0.234375, y: 0.203125 },\n { x: 0.265625, y: 0.203125 },\n { x: 0.265625, y: 0.203125 },\n { x: 0.296875, y: 0.203125 },\n { x: 0.296875, y: 0.203125 },\n { x: 0.328125, y: 0.203125 },\n { x: 0.328125, y: 0.203125 },\n { x: 0.359375, y: 0.203125 },\n { x: 0.359375, y: 0.203125 },\n { x: 0.390625, y: 0.203125 },\n { x: 0.390625, y: 0.203125 },\n { x: 0.421875, y: 0.203125 },\n { x: 0.421875, y: 0.203125 },\n { x: 0.453125, y: 0.203125 },\n { x: 0.453125, y: 0.203125 },\n { x: 0.484375, y: 0.203125 },\n { x: 0.484375, y: 0.203125 },\n { x: 0.515625, y: 0.203125 },\n { x: 0.515625, y: 0.203125 },\n { x: 0.546875, y: 0.203125 },\n { x: 0.546875, y: 0.203125 },\n { x: 0.578125, y: 0.203125 },\n { x: 0.578125, y: 0.203125 },\n { x: 0.609375, y: 0.203125 },\n { x: 0.609375, y: 0.203125 },\n { x: 0.640625, y: 0.203125 },\n { x: 0.640625, y: 0.203125 },\n { x: 0.671875, y: 0.203125 },\n { x: 0.671875, y: 0.203125 },\n { x: 0.703125, y: 0.203125 },\n { x: 0.703125, y: 0.203125 },\n { x: 0.734375, y: 0.203125 },\n { x: 0.734375, y: 0.203125 },\n { x: 0.765625, y: 0.203125 },\n { x: 0.765625, y: 0.203125 },\n { x: 0.796875, y: 0.203125 },\n { x: 0.796875, y: 0.203125 },\n { x: 0.828125, y: 0.203125 },\n { x: 0.828125, y: 0.203125 },\n { x: 0.859375, y: 0.203125 },\n { x: 0.859375, y: 0.203125 },\n { x: 0.890625, y: 0.203125 },\n { x: 0.890625, y: 0.203125 },\n { x: 0.921875, y: 0.203125 },\n { x: 0.921875, y: 0.203125 },\n { x: 0.953125, y: 0.203125 },\n { x: 0.953125, y: 0.203125 },\n { x: 0.984375, y: 0.203125 },\n { x: 0.984375, y: 0.203125 },\n { x: 0.015625, y: 0.234375 },\n { x: 0.015625, y: 0.234375 },\n { x: 0.046875, y: 0.234375 },\n { x: 0.046875, y: 0.234375 },\n { x: 0.078125, y: 0.234375 },\n { x: 0.078125, y: 0.234375 },\n { x: 0.109375, y: 0.234375 },\n { x: 0.109375, y: 0.234375 },\n { x: 0.140625, y: 0.234375 },\n { x: 0.140625, y: 0.234375 },\n { x: 0.171875, y: 0.234375 },\n { x: 0.171875, y: 0.234375 },\n { x: 0.203125, y: 0.234375 },\n { x: 0.203125, y: 0.234375 },\n { x: 0.234375, y: 0.234375 },\n { x: 0.234375, y: 0.234375 },\n { x: 0.265625, y: 0.234375 },\n { x: 0.265625, y: 0.234375 },\n { x: 0.296875, y: 0.234375 },\n { x: 0.296875, y: 0.234375 },\n { x: 0.328125, y: 0.234375 },\n { x: 0.328125, y: 0.234375 },\n { x: 0.359375, y: 0.234375 },\n { x: 0.359375, y: 0.234375 },\n { x: 0.390625, y: 0.234375 },\n { x: 0.390625, y: 0.234375 },\n { x: 0.421875, y: 0.234375 },\n { x: 0.421875, y: 0.234375 },\n { x: 0.453125, y: 0.234375 },\n { x: 0.453125, y: 0.234375 },\n { x: 0.484375, y: 0.234375 },\n { x: 0.484375, y: 0.234375 },\n { x: 0.515625, y: 0.234375 },\n { x: 0.515625, y: 0.234375 },\n { x: 0.546875, y: 0.234375 },\n { x: 0.546875, y: 0.234375 },\n { x: 0.578125, y: 0.234375 },\n { x: 0.578125, y: 0.234375 },\n { x: 0.609375, y: 0.234375 },\n { x: 0.609375, y: 0.234375 },\n { x: 0.640625, y: 0.234375 },\n { x: 0.640625, y: 0.234375 },\n { x: 0.671875, y: 0.234375 },\n { x: 0.671875, y: 0.234375 },\n { x: 0.703125, y: 0.234375 },\n { x: 0.703125, y: 0.234375 },\n { x: 0.734375, y: 0.234375 },\n { x: 0.734375, y: 0.234375 },\n { x: 0.765625, y: 0.234375 },\n { x: 0.765625, y: 0.234375 },\n { x: 0.796875, y: 0.234375 },\n { x: 0.796875, y: 0.234375 },\n { x: 0.828125, y: 0.234375 },\n { x: 0.828125, y: 0.234375 },\n { x: 0.859375, y: 0.234375 },\n { x: 0.859375, y: 0.234375 },\n { x: 0.890625, y: 0.234375 },\n { x: 0.890625, y: 0.234375 },\n { x: 0.921875, y: 0.234375 },\n { x: 0.921875, y: 0.234375 },\n { x: 0.953125, y: 0.234375 },\n { x: 0.953125, y: 0.234375 },\n { x: 0.984375, y: 0.234375 },\n { x: 0.984375, y: 0.234375 },\n { x: 0.015625, y: 0.265625 },\n { x: 0.015625, y: 0.265625 },\n { x: 0.046875, y: 0.265625 },\n { x: 0.046875, y: 0.265625 },\n { x: 0.078125, y: 0.265625 },\n { x: 0.078125, y: 0.265625 },\n { x: 0.109375, y: 0.265625 },\n { x: 0.109375, y: 0.265625 },\n { x: 0.140625, y: 0.265625 },\n { x: 0.140625, y: 0.265625 },\n { x: 0.171875, y: 0.265625 },\n { x: 0.171875, y: 0.265625 },\n { x: 0.203125, y: 0.265625 },\n { x: 0.203125, y: 0.265625 },\n { x: 0.234375, y: 0.265625 },\n { x: 0.234375, y: 0.265625 },\n { x: 0.265625, y: 0.265625 },\n { x: 0.265625, y: 0.265625 },\n { x: 0.296875, y: 0.265625 },\n { x: 0.296875, y: 0.265625 },\n { x: 0.328125, y: 0.265625 },\n { x: 0.328125, y: 0.265625 },\n { x: 0.359375, y: 0.265625 },\n { x: 0.359375, y: 0.265625 },\n { x: 0.390625, y: 0.265625 },\n { x: 0.390625, y: 0.265625 },\n { x: 0.421875, y: 0.265625 },\n { x: 0.421875, y: 0.265625 },\n { x: 0.453125, y: 0.265625 },\n { x: 0.453125, y: 0.265625 },\n { x: 0.484375, y: 0.265625 },\n { x: 0.484375, y: 0.265625 },\n { x: 0.515625, y: 0.265625 },\n { x: 0.515625, y: 0.265625 },\n { x: 0.546875, y: 0.265625 },\n { x: 0.546875, y: 0.265625 },\n { x: 0.578125, y: 0.265625 },\n { x: 0.578125, y: 0.265625 },\n { x: 0.609375, y: 0.265625 },\n { x: 0.609375, y: 0.265625 },\n { x: 0.640625, y: 0.265625 },\n { x: 0.640625, y: 0.265625 },\n { x: 0.671875, y: 0.265625 },\n { x: 0.671875, y: 0.265625 },\n { x: 0.703125, y: 0.265625 },\n { x: 0.703125, y: 0.265625 },\n { x: 0.734375, y: 0.265625 },\n { x: 0.734375, y: 0.265625 },\n { x: 0.765625, y: 0.265625 },\n { x: 0.765625, y: 0.265625 },\n { x: 0.796875, y: 0.265625 },\n { x: 0.796875, y: 0.265625 },\n { x: 0.828125, y: 0.265625 },\n { x: 0.828125, y: 0.265625 },\n { x: 0.859375, y: 0.265625 },\n { x: 0.859375, y: 0.265625 },\n { x: 0.890625, y: 0.265625 },\n { x: 0.890625, y: 0.265625 },\n { x: 0.921875, y: 0.265625 },\n { x: 0.921875, y: 0.265625 },\n { x: 0.953125, y: 0.265625 },\n { x: 0.953125, y: 0.265625 },\n { x: 0.984375, y: 0.265625 },\n { x: 0.984375, y: 0.265625 },\n { x: 0.015625, y: 0.296875 },\n { x: 0.015625, y: 0.296875 },\n { x: 0.046875, y: 0.296875 },\n { x: 0.046875, y: 0.296875 },\n { x: 0.078125, y: 0.296875 },\n { x: 0.078125, y: 0.296875 },\n { x: 0.109375, y: 0.296875 },\n { x: 0.109375, y: 0.296875 },\n { x: 0.140625, y: 0.296875 },\n { x: 0.140625, y: 0.296875 },\n { x: 0.171875, y: 0.296875 },\n { x: 0.171875, y: 0.296875 },\n { x: 0.203125, y: 0.296875 },\n { x: 0.203125, y: 0.296875 },\n { x: 0.234375, y: 0.296875 },\n { x: 0.234375, y: 0.296875 },\n { x: 0.265625, y: 0.296875 },\n { x: 0.265625, y: 0.296875 },\n { x: 0.296875, y: 0.296875 },\n { x: 0.296875, y: 0.296875 },\n { x: 0.328125, y: 0.296875 },\n { x: 0.328125, y: 0.296875 },\n { x: 0.359375, y: 0.296875 },\n { x: 0.359375, y: 0.296875 },\n { x: 0.390625, y: 0.296875 },\n { x: 0.390625, y: 0.296875 },\n { x: 0.421875, y: 0.296875 },\n { x: 0.421875, y: 0.296875 },\n { x: 0.453125, y: 0.296875 },\n { x: 0.453125, y: 0.296875 },\n { x: 0.484375, y: 0.296875 },\n { x: 0.484375, y: 0.296875 },\n { x: 0.515625, y: 0.296875 },\n { x: 0.515625, y: 0.296875 },\n { x: 0.546875, y: 0.296875 },\n { x: 0.546875, y: 0.296875 },\n { x: 0.578125, y: 0.296875 },\n { x: 0.578125, y: 0.296875 },\n { x: 0.609375, y: 0.296875 },\n { x: 0.609375, y: 0.296875 },\n { x: 0.640625, y: 0.296875 },\n { x: 0.640625, y: 0.296875 },\n { x: 0.671875, y: 0.296875 },\n { x: 0.671875, y: 0.296875 },\n { x: 0.703125, y: 0.296875 },\n { x: 0.703125, y: 0.296875 },\n { x: 0.734375, y: 0.296875 },\n { x: 0.734375, y: 0.296875 },\n { x: 0.765625, y: 0.296875 },\n { x: 0.765625, y: 0.296875 },\n { x: 0.796875, y: 0.296875 },\n { x: 0.796875, y: 0.296875 },\n { x: 0.828125, y: 0.296875 },\n { x: 0.828125, y: 0.296875 },\n { x: 0.859375, y: 0.296875 },\n { x: 0.859375, y: 0.296875 },\n { x: 0.890625, y: 0.296875 },\n { x: 0.890625, y: 0.296875 },\n { x: 0.921875, y: 0.296875 },\n { x: 0.921875, y: 0.296875 },\n { x: 0.953125, y: 0.296875 },\n { x: 0.953125, y: 0.296875 },\n { x: 0.984375, y: 0.296875 },\n { x: 0.984375, y: 0.296875 },\n { x: 0.015625, y: 0.328125 },\n { x: 0.015625, y: 0.328125 },\n { x: 0.046875, y: 0.328125 },\n { x: 0.046875, y: 0.328125 },\n { x: 0.078125, y: 0.328125 },\n { x: 0.078125, y: 0.328125 },\n { x: 0.109375, y: 0.328125 },\n { x: 0.109375, y: 0.328125 },\n { x: 0.140625, y: 0.328125 },\n { x: 0.140625, y: 0.328125 },\n { x: 0.171875, y: 0.328125 },\n { x: 0.171875, y: 0.328125 },\n { x: 0.203125, y: 0.328125 },\n { x: 0.203125, y: 0.328125 },\n { x: 0.234375, y: 0.328125 },\n { x: 0.234375, y: 0.328125 },\n { x: 0.265625, y: 0.328125 },\n { x: 0.265625, y: 0.328125 },\n { x: 0.296875, y: 0.328125 },\n { x: 0.296875, y: 0.328125 },\n { x: 0.328125, y: 0.328125 },\n { x: 0.328125, y: 0.328125 },\n { x: 0.359375, y: 0.328125 },\n { x: 0.359375, y: 0.328125 },\n { x: 0.390625, y: 0.328125 },\n { x: 0.390625, y: 0.328125 },\n { x: 0.421875, y: 0.328125 },\n { x: 0.421875, y: 0.328125 },\n { x: 0.453125, y: 0.328125 },\n { x: 0.453125, y: 0.328125 },\n { x: 0.484375, y: 0.328125 },\n { x: 0.484375, y: 0.328125 },\n { x: 0.515625, y: 0.328125 },\n { x: 0.515625, y: 0.328125 },\n { x: 0.546875, y: 0.328125 },\n { x: 0.546875, y: 0.328125 },\n { x: 0.578125, y: 0.328125 },\n { x: 0.578125, y: 0.328125 },\n { x: 0.609375, y: 0.328125 },\n { x: 0.609375, y: 0.328125 },\n { x: 0.640625, y: 0.328125 },\n { x: 0.640625, y: 0.328125 },\n { x: 0.671875, y: 0.328125 },\n { x: 0.671875, y: 0.328125 },\n { x: 0.703125, y: 0.328125 },\n { x: 0.703125, y: 0.328125 },\n { x: 0.734375, y: 0.328125 },\n { x: 0.734375, y: 0.328125 },\n { x: 0.765625, y: 0.328125 },\n { x: 0.765625, y: 0.328125 },\n { x: 0.796875, y: 0.328125 },\n { x: 0.796875, y: 0.328125 },\n { x: 0.828125, y: 0.328125 },\n { x: 0.828125, y: 0.328125 },\n { x: 0.859375, y: 0.328125 },\n { x: 0.859375, y: 0.328125 },\n { x: 0.890625, y: 0.328125 },\n { x: 0.890625, y: 0.328125 },\n { x: 0.921875, y: 0.328125 },\n { x: 0.921875, y: 0.328125 },\n { x: 0.953125, y: 0.328125 },\n { x: 0.953125, y: 0.328125 },\n { x: 0.984375, y: 0.328125 },\n { x: 0.984375, y: 0.328125 },\n { x: 0.015625, y: 0.359375 },\n { x: 0.015625, y: 0.359375 },\n { x: 0.046875, y: 0.359375 },\n { x: 0.046875, y: 0.359375 },\n { x: 0.078125, y: 0.359375 },\n { x: 0.078125, y: 0.359375 },\n { x: 0.109375, y: 0.359375 },\n { x: 0.109375, y: 0.359375 },\n { x: 0.140625, y: 0.359375 },\n { x: 0.140625, y: 0.359375 },\n { x: 0.171875, y: 0.359375 },\n { x: 0.171875, y: 0.359375 },\n { x: 0.203125, y: 0.359375 },\n { x: 0.203125, y: 0.359375 },\n { x: 0.234375, y: 0.359375 },\n { x: 0.234375, y: 0.359375 },\n { x: 0.265625, y: 0.359375 },\n { x: 0.265625, y: 0.359375 },\n { x: 0.296875, y: 0.359375 },\n { x: 0.296875, y: 0.359375 },\n { x: 0.328125, y: 0.359375 },\n { x: 0.328125, y: 0.359375 },\n { x: 0.359375, y: 0.359375 },\n { x: 0.359375, y: 0.359375 },\n { x: 0.390625, y: 0.359375 },\n { x: 0.390625, y: 0.359375 },\n { x: 0.421875, y: 0.359375 },\n { x: 0.421875, y: 0.359375 },\n { x: 0.453125, y: 0.359375 },\n { x: 0.453125, y: 0.359375 },\n { x: 0.484375, y: 0.359375 },\n { x: 0.484375, y: 0.359375 },\n { x: 0.515625, y: 0.359375 },\n { x: 0.515625, y: 0.359375 },\n { x: 0.546875, y: 0.359375 },\n { x: 0.546875, y: 0.359375 },\n { x: 0.578125, y: 0.359375 },\n { x: 0.578125, y: 0.359375 },\n { x: 0.609375, y: 0.359375 },\n { x: 0.609375, y: 0.359375 },\n { x: 0.640625, y: 0.359375 },\n { x: 0.640625, y: 0.359375 },\n { x: 0.671875, y: 0.359375 },\n { x: 0.671875, y: 0.359375 },\n { x: 0.703125, y: 0.359375 },\n { x: 0.703125, y: 0.359375 },\n { x: 0.734375, y: 0.359375 },\n { x: 0.734375, y: 0.359375 },\n { x: 0.765625, y: 0.359375 },\n { x: 0.765625, y: 0.359375 },\n { x: 0.796875, y: 0.359375 },\n { x: 0.796875, y: 0.359375 },\n { x: 0.828125, y: 0.359375 },\n { x: 0.828125, y: 0.359375 },\n { x: 0.859375, y: 0.359375 },\n { x: 0.859375, y: 0.359375 },\n { x: 0.890625, y: 0.359375 },\n { x: 0.890625, y: 0.359375 },\n { x: 0.921875, y: 0.359375 },\n { x: 0.921875, y: 0.359375 },\n { x: 0.953125, y: 0.359375 },\n { x: 0.953125, y: 0.359375 },\n { x: 0.984375, y: 0.359375 },\n { x: 0.984375, y: 0.359375 },\n { x: 0.015625, y: 0.390625 },\n { x: 0.015625, y: 0.390625 },\n { x: 0.046875, y: 0.390625 },\n { x: 0.046875, y: 0.390625 },\n { x: 0.078125, y: 0.390625 },\n { x: 0.078125, y: 0.390625 },\n { x: 0.109375, y: 0.390625 },\n { x: 0.109375, y: 0.390625 },\n { x: 0.140625, y: 0.390625 },\n { x: 0.140625, y: 0.390625 },\n { x: 0.171875, y: 0.390625 },\n { x: 0.171875, y: 0.390625 },\n { x: 0.203125, y: 0.390625 },\n { x: 0.203125, y: 0.390625 },\n { x: 0.234375, y: 0.390625 },\n { x: 0.234375, y: 0.390625 },\n { x: 0.265625, y: 0.390625 },\n { x: 0.265625, y: 0.390625 },\n { x: 0.296875, y: 0.390625 },\n { x: 0.296875, y: 0.390625 },\n { x: 0.328125, y: 0.390625 },\n { x: 0.328125, y: 0.390625 },\n { x: 0.359375, y: 0.390625 },\n { x: 0.359375, y: 0.390625 },\n { x: 0.390625, y: 0.390625 },\n { x: 0.390625, y: 0.390625 },\n { x: 0.421875, y: 0.390625 },\n { x: 0.421875, y: 0.390625 },\n { x: 0.453125, y: 0.390625 },\n { x: 0.453125, y: 0.390625 },\n { x: 0.484375, y: 0.390625 },\n { x: 0.484375, y: 0.390625 },\n { x: 0.515625, y: 0.390625 },\n { x: 0.515625, y: 0.390625 },\n { x: 0.546875, y: 0.390625 },\n { x: 0.546875, y: 0.390625 },\n { x: 0.578125, y: 0.390625 },\n { x: 0.578125, y: 0.390625 },\n { x: 0.609375, y: 0.390625 },\n { x: 0.609375, y: 0.390625 },\n { x: 0.640625, y: 0.390625 },\n { x: 0.640625, y: 0.390625 },\n { x: 0.671875, y: 0.390625 },\n { x: 0.671875, y: 0.390625 },\n { x: 0.703125, y: 0.390625 },\n { x: 0.703125, y: 0.390625 },\n { x: 0.734375, y: 0.390625 },\n { x: 0.734375, y: 0.390625 },\n { x: 0.765625, y: 0.390625 },\n { x: 0.765625, y: 0.390625 },\n { x: 0.796875, y: 0.390625 },\n { x: 0.796875, y: 0.390625 },\n { x: 0.828125, y: 0.390625 },\n { x: 0.828125, y: 0.390625 },\n { x: 0.859375, y: 0.390625 },\n { x: 0.859375, y: 0.390625 },\n { x: 0.890625, y: 0.390625 },\n { x: 0.890625, y: 0.390625 },\n { x: 0.921875, y: 0.390625 },\n { x: 0.921875, y: 0.390625 },\n { x: 0.953125, y: 0.390625 },\n { x: 0.953125, y: 0.390625 },\n { x: 0.984375, y: 0.390625 },\n { x: 0.984375, y: 0.390625 },\n { x: 0.015625, y: 0.421875 },\n { x: 0.015625, y: 0.421875 },\n { x: 0.046875, y: 0.421875 },\n { x: 0.046875, y: 0.421875 },\n { x: 0.078125, y: 0.421875 },\n { x: 0.078125, y: 0.421875 },\n { x: 0.109375, y: 0.421875 },\n { x: 0.109375, y: 0.421875 },\n { x: 0.140625, y: 0.421875 },\n { x: 0.140625, y: 0.421875 },\n { x: 0.171875, y: 0.421875 },\n { x: 0.171875, y: 0.421875 },\n { x: 0.203125, y: 0.421875 },\n { x: 0.203125, y: 0.421875 },\n { x: 0.234375, y: 0.421875 },\n { x: 0.234375, y: 0.421875 },\n { x: 0.265625, y: 0.421875 },\n { x: 0.265625, y: 0.421875 },\n { x: 0.296875, y: 0.421875 },\n { x: 0.296875, y: 0.421875 },\n { x: 0.328125, y: 0.421875 },\n { x: 0.328125, y: 0.421875 },\n { x: 0.359375, y: 0.421875 },\n { x: 0.359375, y: 0.421875 },\n { x: 0.390625, y: 0.421875 },\n { x: 0.390625, y: 0.421875 },\n { x: 0.421875, y: 0.421875 },\n { x: 0.421875, y: 0.421875 },\n { x: 0.453125, y: 0.421875 },\n { x: 0.453125, y: 0.421875 },\n { x: 0.484375, y: 0.421875 },\n { x: 0.484375, y: 0.421875 },\n { x: 0.515625, y: 0.421875 },\n { x: 0.515625, y: 0.421875 },\n { x: 0.546875, y: 0.421875 },\n { x: 0.546875, y: 0.421875 },\n { x: 0.578125, y: 0.421875 },\n { x: 0.578125, y: 0.421875 },\n { x: 0.609375, y: 0.421875 },\n { x: 0.609375, y: 0.421875 },\n { x: 0.640625, y: 0.421875 },\n { x: 0.640625, y: 0.421875 },\n { x: 0.671875, y: 0.421875 },\n { x: 0.671875, y: 0.421875 },\n { x: 0.703125, y: 0.421875 },\n { x: 0.703125, y: 0.421875 },\n { x: 0.734375, y: 0.421875 },\n { x: 0.734375, y: 0.421875 },\n { x: 0.765625, y: 0.421875 },\n { x: 0.765625, y: 0.421875 },\n { x: 0.796875, y: 0.421875 },\n { x: 0.796875, y: 0.421875 },\n { x: 0.828125, y: 0.421875 },\n { x: 0.828125, y: 0.421875 },\n { x: 0.859375, y: 0.421875 },\n { x: 0.859375, y: 0.421875 },\n { x: 0.890625, y: 0.421875 },\n { x: 0.890625, y: 0.421875 },\n { x: 0.921875, y: 0.421875 },\n { x: 0.921875, y: 0.421875 },\n { x: 0.953125, y: 0.421875 },\n { x: 0.953125, y: 0.421875 },\n { x: 0.984375, y: 0.421875 },\n { x: 0.984375, y: 0.421875 },\n { x: 0.015625, y: 0.453125 },\n { x: 0.015625, y: 0.453125 },\n { x: 0.046875, y: 0.453125 },\n { x: 0.046875, y: 0.453125 },\n { x: 0.078125, y: 0.453125 },\n { x: 0.078125, y: 0.453125 },\n { x: 0.109375, y: 0.453125 },\n { x: 0.109375, y: 0.453125 },\n { x: 0.140625, y: 0.453125 },\n { x: 0.140625, y: 0.453125 },\n { x: 0.171875, y: 0.453125 },\n { x: 0.171875, y: 0.453125 },\n { x: 0.203125, y: 0.453125 },\n { x: 0.203125, y: 0.453125 },\n { x: 0.234375, y: 0.453125 },\n { x: 0.234375, y: 0.453125 },\n { x: 0.265625, y: 0.453125 },\n { x: 0.265625, y: 0.453125 },\n { x: 0.296875, y: 0.453125 },\n { x: 0.296875, y: 0.453125 },\n { x: 0.328125, y: 0.453125 },\n { x: 0.328125, y: 0.453125 },\n { x: 0.359375, y: 0.453125 },\n { x: 0.359375, y: 0.453125 },\n { x: 0.390625, y: 0.453125 },\n { x: 0.390625, y: 0.453125 },\n { x: 0.421875, y: 0.453125 },\n { x: 0.421875, y: 0.453125 },\n { x: 0.453125, y: 0.453125 },\n { x: 0.453125, y: 0.453125 },\n { x: 0.484375, y: 0.453125 },\n { x: 0.484375, y: 0.453125 },\n { x: 0.515625, y: 0.453125 },\n { x: 0.515625, y: 0.453125 },\n { x: 0.546875, y: 0.453125 },\n { x: 0.546875, y: 0.453125 },\n { x: 0.578125, y: 0.453125 },\n { x: 0.578125, y: 0.453125 },\n { x: 0.609375, y: 0.453125 },\n { x: 0.609375, y: 0.453125 },\n { x: 0.640625, y: 0.453125 },\n { x: 0.640625, y: 0.453125 },\n { x: 0.671875, y: 0.453125 },\n { x: 0.671875, y: 0.453125 },\n { x: 0.703125, y: 0.453125 },\n { x: 0.703125, y: 0.453125 },\n { x: 0.734375, y: 0.453125 },\n { x: 0.734375, y: 0.453125 },\n { x: 0.765625, y: 0.453125 },\n { x: 0.765625, y: 0.453125 },\n { x: 0.796875, y: 0.453125 },\n { x: 0.796875, y: 0.453125 },\n { x: 0.828125, y: 0.453125 },\n { x: 0.828125, y: 0.453125 },\n { x: 0.859375, y: 0.453125 },\n { x: 0.859375, y: 0.453125 },\n { x: 0.890625, y: 0.453125 },\n { x: 0.890625, y: 0.453125 },\n { x: 0.921875, y: 0.453125 },\n { x: 0.921875, y: 0.453125 },\n { x: 0.953125, y: 0.453125 },\n { x: 0.953125, y: 0.453125 },\n { x: 0.984375, y: 0.453125 },\n { x: 0.984375, y: 0.453125 },\n { x: 0.015625, y: 0.484375 },\n { x: 0.015625, y: 0.484375 },\n { x: 0.046875, y: 0.484375 },\n { x: 0.046875, y: 0.484375 },\n { x: 0.078125, y: 0.484375 },\n { x: 0.078125, y: 0.484375 },\n { x: 0.109375, y: 0.484375 },\n { x: 0.109375, y: 0.484375 },\n { x: 0.140625, y: 0.484375 },\n { x: 0.140625, y: 0.484375 },\n { x: 0.171875, y: 0.484375 },\n { x: 0.171875, y: 0.484375 },\n { x: 0.203125, y: 0.484375 },\n { x: 0.203125, y: 0.484375 },\n { x: 0.234375, y: 0.484375 },\n { x: 0.234375, y: 0.484375 },\n { x: 0.265625, y: 0.484375 },\n { x: 0.265625, y: 0.484375 },\n { x: 0.296875, y: 0.484375 },\n { x: 0.296875, y: 0.484375 },\n { x: 0.328125, y: 0.484375 },\n { x: 0.328125, y: 0.484375 },\n { x: 0.359375, y: 0.484375 },\n { x: 0.359375, y: 0.484375 },\n { x: 0.390625, y: 0.484375 },\n { x: 0.390625, y: 0.484375 },\n { x: 0.421875, y: 0.484375 },\n { x: 0.421875, y: 0.484375 },\n { x: 0.453125, y: 0.484375 },\n { x: 0.453125, y: 0.484375 },\n { x: 0.484375, y: 0.484375 },\n { x: 0.484375, y: 0.484375 },\n { x: 0.515625, y: 0.484375 },\n { x: 0.515625, y: 0.484375 },\n { x: 0.546875, y: 0.484375 },\n { x: 0.546875, y: 0.484375 },\n { x: 0.578125, y: 0.484375 },\n { x: 0.578125, y: 0.484375 },\n { x: 0.609375, y: 0.484375 },\n { x: 0.609375, y: 0.484375 },\n { x: 0.640625, y: 0.484375 },\n { x: 0.640625, y: 0.484375 },\n { x: 0.671875, y: 0.484375 },\n { x: 0.671875, y: 0.484375 },\n { x: 0.703125, y: 0.484375 },\n { x: 0.703125, y: 0.484375 },\n { x: 0.734375, y: 0.484375 },\n { x: 0.734375, y: 0.484375 },\n { x: 0.765625, y: 0.484375 },\n { x: 0.765625, y: 0.484375 },\n { x: 0.796875, y: 0.484375 },\n { x: 0.796875, y: 0.484375 },\n { x: 0.828125, y: 0.484375 },\n { x: 0.828125, y: 0.484375 },\n { x: 0.859375, y: 0.484375 },\n { x: 0.859375, y: 0.484375 },\n { x: 0.890625, y: 0.484375 },\n { x: 0.890625, y: 0.484375 },\n { x: 0.921875, y: 0.484375 },\n { x: 0.921875, y: 0.484375 },\n { x: 0.953125, y: 0.484375 },\n { x: 0.953125, y: 0.484375 },\n { x: 0.984375, y: 0.484375 },\n { x: 0.984375, y: 0.484375 },\n { x: 0.015625, y: 0.515625 },\n { x: 0.015625, y: 0.515625 },\n { x: 0.046875, y: 0.515625 },\n { x: 0.046875, y: 0.515625 },\n { x: 0.078125, y: 0.515625 },\n { x: 0.078125, y: 0.515625 },\n { x: 0.109375, y: 0.515625 },\n { x: 0.109375, y: 0.515625 },\n { x: 0.140625, y: 0.515625 },\n { x: 0.140625, y: 0.515625 },\n { x: 0.171875, y: 0.515625 },\n { x: 0.171875, y: 0.515625 },\n { x: 0.203125, y: 0.515625 },\n { x: 0.203125, y: 0.515625 },\n { x: 0.234375, y: 0.515625 },\n { x: 0.234375, y: 0.515625 },\n { x: 0.265625, y: 0.515625 },\n { x: 0.265625, y: 0.515625 },\n { x: 0.296875, y: 0.515625 },\n { x: 0.296875, y: 0.515625 },\n { x: 0.328125, y: 0.515625 },\n { x: 0.328125, y: 0.515625 },\n { x: 0.359375, y: 0.515625 },\n { x: 0.359375, y: 0.515625 },\n { x: 0.390625, y: 0.515625 },\n { x: 0.390625, y: 0.515625 },\n { x: 0.421875, y: 0.515625 },\n { x: 0.421875, y: 0.515625 },\n { x: 0.453125, y: 0.515625 },\n { x: 0.453125, y: 0.515625 },\n { x: 0.484375, y: 0.515625 },\n { x: 0.484375, y: 0.515625 },\n { x: 0.515625, y: 0.515625 },\n { x: 0.515625, y: 0.515625 },\n { x: 0.546875, y: 0.515625 },\n { x: 0.546875, y: 0.515625 },\n { x: 0.578125, y: 0.515625 },\n { x: 0.578125, y: 0.515625 },\n { x: 0.609375, y: 0.515625 },\n { x: 0.609375, y: 0.515625 },\n { x: 0.640625, y: 0.515625 },\n { x: 0.640625, y: 0.515625 },\n { x: 0.671875, y: 0.515625 },\n { x: 0.671875, y: 0.515625 },\n { x: 0.703125, y: 0.515625 },\n { x: 0.703125, y: 0.515625 },\n { x: 0.734375, y: 0.515625 },\n { x: 0.734375, y: 0.515625 },\n { x: 0.765625, y: 0.515625 },\n { x: 0.765625, y: 0.515625 },\n { x: 0.796875, y: 0.515625 },\n { x: 0.796875, y: 0.515625 },\n { x: 0.828125, y: 0.515625 },\n { x: 0.828125, y: 0.515625 },\n { x: 0.859375, y: 0.515625 },\n { x: 0.859375, y: 0.515625 },\n { x: 0.890625, y: 0.515625 },\n { x: 0.890625, y: 0.515625 },\n { x: 0.921875, y: 0.515625 },\n { x: 0.921875, y: 0.515625 },\n { x: 0.953125, y: 0.515625 },\n { x: 0.953125, y: 0.515625 },\n { x: 0.984375, y: 0.515625 },\n { x: 0.984375, y: 0.515625 },\n { x: 0.015625, y: 0.546875 },\n { x: 0.015625, y: 0.546875 },\n { x: 0.046875, y: 0.546875 },\n { x: 0.046875, y: 0.546875 },\n { x: 0.078125, y: 0.546875 },\n { x: 0.078125, y: 0.546875 },\n { x: 0.109375, y: 0.546875 },\n { x: 0.109375, y: 0.546875 },\n { x: 0.140625, y: 0.546875 },\n { x: 0.140625, y: 0.546875 },\n { x: 0.171875, y: 0.546875 },\n { x: 0.171875, y: 0.546875 },\n { x: 0.203125, y: 0.546875 },\n { x: 0.203125, y: 0.546875 },\n { x: 0.234375, y: 0.546875 },\n { x: 0.234375, y: 0.546875 },\n { x: 0.265625, y: 0.546875 },\n { x: 0.265625, y: 0.546875 },\n { x: 0.296875, y: 0.546875 },\n { x: 0.296875, y: 0.546875 },\n { x: 0.328125, y: 0.546875 },\n { x: 0.328125, y: 0.546875 },\n { x: 0.359375, y: 0.546875 },\n { x: 0.359375, y: 0.546875 },\n { x: 0.390625, y: 0.546875 },\n { x: 0.390625, y: 0.546875 },\n { x: 0.421875, y: 0.546875 },\n { x: 0.421875, y: 0.546875 },\n { x: 0.453125, y: 0.546875 },\n { x: 0.453125, y: 0.546875 },\n { x: 0.484375, y: 0.546875 },\n { x: 0.484375, y: 0.546875 },\n { x: 0.515625, y: 0.546875 },\n { x: 0.515625, y: 0.546875 },\n { x: 0.546875, y: 0.546875 },\n { x: 0.546875, y: 0.546875 },\n { x: 0.578125, y: 0.546875 },\n { x: 0.578125, y: 0.546875 },\n { x: 0.609375, y: 0.546875 },\n { x: 0.609375, y: 0.546875 },\n { x: 0.640625, y: 0.546875 },\n { x: 0.640625, y: 0.546875 },\n { x: 0.671875, y: 0.546875 },\n { x: 0.671875, y: 0.546875 },\n { x: 0.703125, y: 0.546875 },\n { x: 0.703125, y: 0.546875 },\n { x: 0.734375, y: 0.546875 },\n { x: 0.734375, y: 0.546875 },\n { x: 0.765625, y: 0.546875 },\n { x: 0.765625, y: 0.546875 },\n { x: 0.796875, y: 0.546875 },\n { x: 0.796875, y: 0.546875 },\n { x: 0.828125, y: 0.546875 },\n { x: 0.828125, y: 0.546875 },\n { x: 0.859375, y: 0.546875 },\n { x: 0.859375, y: 0.546875 },\n { x: 0.890625, y: 0.546875 },\n { x: 0.890625, y: 0.546875 },\n { x: 0.921875, y: 0.546875 },\n { x: 0.921875, y: 0.546875 },\n { x: 0.953125, y: 0.546875 },\n { x: 0.953125, y: 0.546875 },\n { x: 0.984375, y: 0.546875 },\n { x: 0.984375, y: 0.546875 },\n { x: 0.015625, y: 0.578125 },\n { x: 0.015625, y: 0.578125 },\n { x: 0.046875, y: 0.578125 },\n { x: 0.046875, y: 0.578125 },\n { x: 0.078125, y: 0.578125 },\n { x: 0.078125, y: 0.578125 },\n { x: 0.109375, y: 0.578125 },\n { x: 0.109375, y: 0.578125 },\n { x: 0.140625, y: 0.578125 },\n { x: 0.140625, y: 0.578125 },\n { x: 0.171875, y: 0.578125 },\n { x: 0.171875, y: 0.578125 },\n { x: 0.203125, y: 0.578125 },\n { x: 0.203125, y: 0.578125 },\n { x: 0.234375, y: 0.578125 },\n { x: 0.234375, y: 0.578125 },\n { x: 0.265625, y: 0.578125 },\n { x: 0.265625, y: 0.578125 },\n { x: 0.296875, y: 0.578125 },\n { x: 0.296875, y: 0.578125 },\n { x: 0.328125, y: 0.578125 },\n { x: 0.328125, y: 0.578125 },\n { x: 0.359375, y: 0.578125 },\n { x: 0.359375, y: 0.578125 },\n { x: 0.390625, y: 0.578125 },\n { x: 0.390625, y: 0.578125 },\n { x: 0.421875, y: 0.578125 },\n { x: 0.421875, y: 0.578125 },\n { x: 0.453125, y: 0.578125 },\n { x: 0.453125, y: 0.578125 },\n { x: 0.484375, y: 0.578125 },\n { x: 0.484375, y: 0.578125 },\n { x: 0.515625, y: 0.578125 },\n { x: 0.515625, y: 0.578125 },\n { x: 0.546875, y: 0.578125 },\n { x: 0.546875, y: 0.578125 },\n { x: 0.578125, y: 0.578125 },\n { x: 0.578125, y: 0.578125 },\n { x: 0.609375, y: 0.578125 },\n { x: 0.609375, y: 0.578125 },\n { x: 0.640625, y: 0.578125 },\n { x: 0.640625, y: 0.578125 },\n { x: 0.671875, y: 0.578125 },\n { x: 0.671875, y: 0.578125 },\n { x: 0.703125, y: 0.578125 },\n { x: 0.703125, y: 0.578125 },\n { x: 0.734375, y: 0.578125 },\n { x: 0.734375, y: 0.578125 },\n { x: 0.765625, y: 0.578125 },\n { x: 0.765625, y: 0.578125 },\n { x: 0.796875, y: 0.578125 },\n { x: 0.796875, y: 0.578125 },\n { x: 0.828125, y: 0.578125 },\n { x: 0.828125, y: 0.578125 },\n { x: 0.859375, y: 0.578125 },\n { x: 0.859375, y: 0.578125 },\n { x: 0.890625, y: 0.578125 },\n { x: 0.890625, y: 0.578125 },\n { x: 0.921875, y: 0.578125 },\n { x: 0.921875, y: 0.578125 },\n { x: 0.953125, y: 0.578125 },\n { x: 0.953125, y: 0.578125 },\n { x: 0.984375, y: 0.578125 },\n { x: 0.984375, y: 0.578125 },\n { x: 0.015625, y: 0.609375 },\n { x: 0.015625, y: 0.609375 },\n { x: 0.046875, y: 0.609375 },\n { x: 0.046875, y: 0.609375 },\n { x: 0.078125, y: 0.609375 },\n { x: 0.078125, y: 0.609375 },\n { x: 0.109375, y: 0.609375 },\n { x: 0.109375, y: 0.609375 },\n { x: 0.140625, y: 0.609375 },\n { x: 0.140625, y: 0.609375 },\n { x: 0.171875, y: 0.609375 },\n { x: 0.171875, y: 0.609375 },\n { x: 0.203125, y: 0.609375 },\n { x: 0.203125, y: 0.609375 },\n { x: 0.234375, y: 0.609375 },\n { x: 0.234375, y: 0.609375 },\n { x: 0.265625, y: 0.609375 },\n { x: 0.265625, y: 0.609375 },\n { x: 0.296875, y: 0.609375 },\n { x: 0.296875, y: 0.609375 },\n { x: 0.328125, y: 0.609375 },\n { x: 0.328125, y: 0.609375 },\n { x: 0.359375, y: 0.609375 },\n { x: 0.359375, y: 0.609375 },\n { x: 0.390625, y: 0.609375 },\n { x: 0.390625, y: 0.609375 },\n { x: 0.421875, y: 0.609375 },\n { x: 0.421875, y: 0.609375 },\n { x: 0.453125, y: 0.609375 },\n { x: 0.453125, y: 0.609375 },\n { x: 0.484375, y: 0.609375 },\n { x: 0.484375, y: 0.609375 },\n { x: 0.515625, y: 0.609375 },\n { x: 0.515625, y: 0.609375 },\n { x: 0.546875, y: 0.609375 },\n { x: 0.546875, y: 0.609375 },\n { x: 0.578125, y: 0.609375 },\n { x: 0.578125, y: 0.609375 },\n { x: 0.609375, y: 0.609375 },\n { x: 0.609375, y: 0.609375 },\n { x: 0.640625, y: 0.609375 },\n { x: 0.640625, y: 0.609375 },\n { x: 0.671875, y: 0.609375 },\n { x: 0.671875, y: 0.609375 },\n { x: 0.703125, y: 0.609375 },\n { x: 0.703125, y: 0.609375 },\n { x: 0.734375, y: 0.609375 },\n { x: 0.734375, y: 0.609375 },\n { x: 0.765625, y: 0.609375 },\n { x: 0.765625, y: 0.609375 },\n { x: 0.796875, y: 0.609375 },\n { x: 0.796875, y: 0.609375 },\n { x: 0.828125, y: 0.609375 },\n { x: 0.828125, y: 0.609375 },\n { x: 0.859375, y: 0.609375 },\n { x: 0.859375, y: 0.609375 },\n { x: 0.890625, y: 0.609375 },\n { x: 0.890625, y: 0.609375 },\n { x: 0.921875, y: 0.609375 },\n { x: 0.921875, y: 0.609375 },\n { x: 0.953125, y: 0.609375 },\n { x: 0.953125, y: 0.609375 },\n { x: 0.984375, y: 0.609375 },\n { x: 0.984375, y: 0.609375 },\n { x: 0.015625, y: 0.640625 },\n { x: 0.015625, y: 0.640625 },\n { x: 0.046875, y: 0.640625 },\n { x: 0.046875, y: 0.640625 },\n { x: 0.078125, y: 0.640625 },\n { x: 0.078125, y: 0.640625 },\n { x: 0.109375, y: 0.640625 },\n { x: 0.109375, y: 0.640625 },\n { x: 0.140625, y: 0.640625 },\n { x: 0.140625, y: 0.640625 },\n { x: 0.171875, y: 0.640625 },\n { x: 0.171875, y: 0.640625 },\n { x: 0.203125, y: 0.640625 },\n { x: 0.203125, y: 0.640625 },\n { x: 0.234375, y: 0.640625 },\n { x: 0.234375, y: 0.640625 },\n { x: 0.265625, y: 0.640625 },\n { x: 0.265625, y: 0.640625 },\n { x: 0.296875, y: 0.640625 },\n { x: 0.296875, y: 0.640625 },\n { x: 0.328125, y: 0.640625 },\n { x: 0.328125, y: 0.640625 },\n { x: 0.359375, y: 0.640625 },\n { x: 0.359375, y: 0.640625 },\n { x: 0.390625, y: 0.640625 },\n { x: 0.390625, y: 0.640625 },\n { x: 0.421875, y: 0.640625 },\n { x: 0.421875, y: 0.640625 },\n { x: 0.453125, y: 0.640625 },\n { x: 0.453125, y: 0.640625 },\n { x: 0.484375, y: 0.640625 },\n { x: 0.484375, y: 0.640625 },\n { x: 0.515625, y: 0.640625 },\n { x: 0.515625, y: 0.640625 },\n { x: 0.546875, y: 0.640625 },\n { x: 0.546875, y: 0.640625 },\n { x: 0.578125, y: 0.640625 },\n { x: 0.578125, y: 0.640625 },\n { x: 0.609375, y: 0.640625 },\n { x: 0.609375, y: 0.640625 },\n { x: 0.640625, y: 0.640625 },\n { x: 0.640625, y: 0.640625 },\n { x: 0.671875, y: 0.640625 },\n { x: 0.671875, y: 0.640625 },\n { x: 0.703125, y: 0.640625 },\n { x: 0.703125, y: 0.640625 },\n { x: 0.734375, y: 0.640625 },\n { x: 0.734375, y: 0.640625 },\n { x: 0.765625, y: 0.640625 },\n { x: 0.765625, y: 0.640625 },\n { x: 0.796875, y: 0.640625 },\n { x: 0.796875, y: 0.640625 },\n { x: 0.828125, y: 0.640625 },\n { x: 0.828125, y: 0.640625 },\n { x: 0.859375, y: 0.640625 },\n { x: 0.859375, y: 0.640625 },\n { x: 0.890625, y: 0.640625 },\n { x: 0.890625, y: 0.640625 },\n { x: 0.921875, y: 0.640625 },\n { x: 0.921875, y: 0.640625 },\n { x: 0.953125, y: 0.640625 },\n { x: 0.953125, y: 0.640625 },\n { x: 0.984375, y: 0.640625 },\n { x: 0.984375, y: 0.640625 },\n { x: 0.015625, y: 0.671875 },\n { x: 0.015625, y: 0.671875 },\n { x: 0.046875, y: 0.671875 },\n { x: 0.046875, y: 0.671875 },\n { x: 0.078125, y: 0.671875 },\n { x: 0.078125, y: 0.671875 },\n { x: 0.109375, y: 0.671875 },\n { x: 0.109375, y: 0.671875 },\n { x: 0.140625, y: 0.671875 },\n { x: 0.140625, y: 0.671875 },\n { x: 0.171875, y: 0.671875 },\n { x: 0.171875, y: 0.671875 },\n { x: 0.203125, y: 0.671875 },\n { x: 0.203125, y: 0.671875 },\n { x: 0.234375, y: 0.671875 },\n { x: 0.234375, y: 0.671875 },\n { x: 0.265625, y: 0.671875 },\n { x: 0.265625, y: 0.671875 },\n { x: 0.296875, y: 0.671875 },\n { x: 0.296875, y: 0.671875 },\n { x: 0.328125, y: 0.671875 },\n { x: 0.328125, y: 0.671875 },\n { x: 0.359375, y: 0.671875 },\n { x: 0.359375, y: 0.671875 },\n { x: 0.390625, y: 0.671875 },\n { x: 0.390625, y: 0.671875 },\n { x: 0.421875, y: 0.671875 },\n { x: 0.421875, y: 0.671875 },\n { x: 0.453125, y: 0.671875 },\n { x: 0.453125, y: 0.671875 },\n { x: 0.484375, y: 0.671875 },\n { x: 0.484375, y: 0.671875 },\n { x: 0.515625, y: 0.671875 },\n { x: 0.515625, y: 0.671875 },\n { x: 0.546875, y: 0.671875 },\n { x: 0.546875, y: 0.671875 },\n { x: 0.578125, y: 0.671875 },\n { x: 0.578125, y: 0.671875 },\n { x: 0.609375, y: 0.671875 },\n { x: 0.609375, y: 0.671875 },\n { x: 0.640625, y: 0.671875 },\n { x: 0.640625, y: 0.671875 },\n { x: 0.671875, y: 0.671875 },\n { x: 0.671875, y: 0.671875 },\n { x: 0.703125, y: 0.671875 },\n { x: 0.703125, y: 0.671875 },\n { x: 0.734375, y: 0.671875 },\n { x: 0.734375, y: 0.671875 },\n { x: 0.765625, y: 0.671875 },\n { x: 0.765625, y: 0.671875 },\n { x: 0.796875, y: 0.671875 },\n { x: 0.796875, y: 0.671875 },\n { x: 0.828125, y: 0.671875 },\n { x: 0.828125, y: 0.671875 },\n { x: 0.859375, y: 0.671875 },\n { x: 0.859375, y: 0.671875 },\n { x: 0.890625, y: 0.671875 },\n { x: 0.890625, y: 0.671875 },\n { x: 0.921875, y: 0.671875 },\n { x: 0.921875, y: 0.671875 },\n { x: 0.953125, y: 0.671875 },\n { x: 0.953125, y: 0.671875 },\n { x: 0.984375, y: 0.671875 },\n { x: 0.984375, y: 0.671875 },\n { x: 0.015625, y: 0.703125 },\n { x: 0.015625, y: 0.703125 },\n { x: 0.046875, y: 0.703125 },\n { x: 0.046875, y: 0.703125 },\n { x: 0.078125, y: 0.703125 },\n { x: 0.078125, y: 0.703125 },\n { x: 0.109375, y: 0.703125 },\n { x: 0.109375, y: 0.703125 },\n { x: 0.140625, y: 0.703125 },\n { x: 0.140625, y: 0.703125 },\n { x: 0.171875, y: 0.703125 },\n { x: 0.171875, y: 0.703125 },\n { x: 0.203125, y: 0.703125 },\n { x: 0.203125, y: 0.703125 },\n { x: 0.234375, y: 0.703125 },\n { x: 0.234375, y: 0.703125 },\n { x: 0.265625, y: 0.703125 },\n { x: 0.265625, y: 0.703125 },\n { x: 0.296875, y: 0.703125 },\n { x: 0.296875, y: 0.703125 },\n { x: 0.328125, y: 0.703125 },\n { x: 0.328125, y: 0.703125 },\n { x: 0.359375, y: 0.703125 },\n { x: 0.359375, y: 0.703125 },\n { x: 0.390625, y: 0.703125 },\n { x: 0.390625, y: 0.703125 },\n { x: 0.421875, y: 0.703125 },\n { x: 0.421875, y: 0.703125 },\n { x: 0.453125, y: 0.703125 },\n { x: 0.453125, y: 0.703125 },\n { x: 0.484375, y: 0.703125 },\n { x: 0.484375, y: 0.703125 },\n { x: 0.515625, y: 0.703125 },\n { x: 0.515625, y: 0.703125 },\n { x: 0.546875, y: 0.703125 },\n { x: 0.546875, y: 0.703125 },\n { x: 0.578125, y: 0.703125 },\n { x: 0.578125, y: 0.703125 },\n { x: 0.609375, y: 0.703125 },\n { x: 0.609375, y: 0.703125 },\n { x: 0.640625, y: 0.703125 },\n { x: 0.640625, y: 0.703125 },\n { x: 0.671875, y: 0.703125 },\n { x: 0.671875, y: 0.703125 },\n { x: 0.703125, y: 0.703125 },\n { x: 0.703125, y: 0.703125 },\n { x: 0.734375, y: 0.703125 },\n { x: 0.734375, y: 0.703125 },\n { x: 0.765625, y: 0.703125 },\n { x: 0.765625, y: 0.703125 },\n { x: 0.796875, y: 0.703125 },\n { x: 0.796875, y: 0.703125 },\n { x: 0.828125, y: 0.703125 },\n { x: 0.828125, y: 0.703125 },\n { x: 0.859375, y: 0.703125 },\n { x: 0.859375, y: 0.703125 },\n { x: 0.890625, y: 0.703125 },\n { x: 0.890625, y: 0.703125 },\n { x: 0.921875, y: 0.703125 },\n { x: 0.921875, y: 0.703125 },\n { x: 0.953125, y: 0.703125 },\n { x: 0.953125, y: 0.703125 },\n { x: 0.984375, y: 0.703125 },\n { x: 0.984375, y: 0.703125 },\n { x: 0.015625, y: 0.734375 },\n { x: 0.015625, y: 0.734375 },\n { x: 0.046875, y: 0.734375 },\n { x: 0.046875, y: 0.734375 },\n { x: 0.078125, y: 0.734375 },\n { x: 0.078125, y: 0.734375 },\n { x: 0.109375, y: 0.734375 },\n { x: 0.109375, y: 0.734375 },\n { x: 0.140625, y: 0.734375 },\n { x: 0.140625, y: 0.734375 },\n { x: 0.171875, y: 0.734375 },\n { x: 0.171875, y: 0.734375 },\n { x: 0.203125, y: 0.734375 },\n { x: 0.203125, y: 0.734375 },\n { x: 0.234375, y: 0.734375 },\n { x: 0.234375, y: 0.734375 },\n { x: 0.265625, y: 0.734375 },\n { x: 0.265625, y: 0.734375 },\n { x: 0.296875, y: 0.734375 },\n { x: 0.296875, y: 0.734375 },\n { x: 0.328125, y: 0.734375 },\n { x: 0.328125, y: 0.734375 },\n { x: 0.359375, y: 0.734375 },\n { x: 0.359375, y: 0.734375 },\n { x: 0.390625, y: 0.734375 },\n { x: 0.390625, y: 0.734375 },\n { x: 0.421875, y: 0.734375 },\n { x: 0.421875, y: 0.734375 },\n { x: 0.453125, y: 0.734375 },\n { x: 0.453125, y: 0.734375 },\n { x: 0.484375, y: 0.734375 },\n { x: 0.484375, y: 0.734375 },\n { x: 0.515625, y: 0.734375 },\n { x: 0.515625, y: 0.734375 },\n { x: 0.546875, y: 0.734375 },\n { x: 0.546875, y: 0.734375 },\n { x: 0.578125, y: 0.734375 },\n { x: 0.578125, y: 0.734375 },\n { x: 0.609375, y: 0.734375 },\n { x: 0.609375, y: 0.734375 },\n { x: 0.640625, y: 0.734375 },\n { x: 0.640625, y: 0.734375 },\n { x: 0.671875, y: 0.734375 },\n { x: 0.671875, y: 0.734375 },\n { x: 0.703125, y: 0.734375 },\n { x: 0.703125, y: 0.734375 },\n { x: 0.734375, y: 0.734375 },\n { x: 0.734375, y: 0.734375 },\n { x: 0.765625, y: 0.734375 },\n { x: 0.765625, y: 0.734375 },\n { x: 0.796875, y: 0.734375 },\n { x: 0.796875, y: 0.734375 },\n { x: 0.828125, y: 0.734375 },\n { x: 0.828125, y: 0.734375 },\n { x: 0.859375, y: 0.734375 },\n { x: 0.859375, y: 0.734375 },\n { x: 0.890625, y: 0.734375 },\n { x: 0.890625, y: 0.734375 },\n { x: 0.921875, y: 0.734375 },\n { x: 0.921875, y: 0.734375 },\n { x: 0.953125, y: 0.734375 },\n { x: 0.953125, y: 0.734375 },\n { x: 0.984375, y: 0.734375 },\n { x: 0.984375, y: 0.734375 },\n { x: 0.015625, y: 0.765625 },\n { x: 0.015625, y: 0.765625 },\n { x: 0.046875, y: 0.765625 },\n { x: 0.046875, y: 0.765625 },\n { x: 0.078125, y: 0.765625 },\n { x: 0.078125, y: 0.765625 },\n { x: 0.109375, y: 0.765625 },\n { x: 0.109375, y: 0.765625 },\n { x: 0.140625, y: 0.765625 },\n { x: 0.140625, y: 0.765625 },\n { x: 0.171875, y: 0.765625 },\n { x: 0.171875, y: 0.765625 },\n { x: 0.203125, y: 0.765625 },\n { x: 0.203125, y: 0.765625 },\n { x: 0.234375, y: 0.765625 },\n { x: 0.234375, y: 0.765625 },\n { x: 0.265625, y: 0.765625 },\n { x: 0.265625, y: 0.765625 },\n { x: 0.296875, y: 0.765625 },\n { x: 0.296875, y: 0.765625 },\n { x: 0.328125, y: 0.765625 },\n { x: 0.328125, y: 0.765625 },\n { x: 0.359375, y: 0.765625 },\n { x: 0.359375, y: 0.765625 },\n { x: 0.390625, y: 0.765625 },\n { x: 0.390625, y: 0.765625 },\n { x: 0.421875, y: 0.765625 },\n { x: 0.421875, y: 0.765625 },\n { x: 0.453125, y: 0.765625 },\n { x: 0.453125, y: 0.765625 },\n { x: 0.484375, y: 0.765625 },\n { x: 0.484375, y: 0.765625 },\n { x: 0.515625, y: 0.765625 },\n { x: 0.515625, y: 0.765625 },\n { x: 0.546875, y: 0.765625 },\n { x: 0.546875, y: 0.765625 },\n { x: 0.578125, y: 0.765625 },\n { x: 0.578125, y: 0.765625 },\n { x: 0.609375, y: 0.765625 },\n { x: 0.609375, y: 0.765625 },\n { x: 0.640625, y: 0.765625 },\n { x: 0.640625, y: 0.765625 },\n { x: 0.671875, y: 0.765625 },\n { x: 0.671875, y: 0.765625 },\n { x: 0.703125, y: 0.765625 },\n { x: 0.703125, y: 0.765625 },\n { x: 0.734375, y: 0.765625 },\n { x: 0.734375, y: 0.765625 },\n { x: 0.765625, y: 0.765625 },\n { x: 0.765625, y: 0.765625 },\n { x: 0.796875, y: 0.765625 },\n { x: 0.796875, y: 0.765625 },\n { x: 0.828125, y: 0.765625 },\n { x: 0.828125, y: 0.765625 },\n { x: 0.859375, y: 0.765625 },\n { x: 0.859375, y: 0.765625 },\n { x: 0.890625, y: 0.765625 },\n { x: 0.890625, y: 0.765625 },\n { x: 0.921875, y: 0.765625 },\n { x: 0.921875, y: 0.765625 },\n { x: 0.953125, y: 0.765625 },\n { x: 0.953125, y: 0.765625 },\n { x: 0.984375, y: 0.765625 },\n { x: 0.984375, y: 0.765625 },\n { x: 0.015625, y: 0.796875 },\n { x: 0.015625, y: 0.796875 },\n { x: 0.046875, y: 0.796875 },\n { x: 0.046875, y: 0.796875 },\n { x: 0.078125, y: 0.796875 },\n { x: 0.078125, y: 0.796875 },\n { x: 0.109375, y: 0.796875 },\n { x: 0.109375, y: 0.796875 },\n { x: 0.140625, y: 0.796875 },\n { x: 0.140625, y: 0.796875 },\n { x: 0.171875, y: 0.796875 },\n { x: 0.171875, y: 0.796875 },\n { x: 0.203125, y: 0.796875 },\n { x: 0.203125, y: 0.796875 },\n { x: 0.234375, y: 0.796875 },\n { x: 0.234375, y: 0.796875 },\n { x: 0.265625, y: 0.796875 },\n { x: 0.265625, y: 0.796875 },\n { x: 0.296875, y: 0.796875 },\n { x: 0.296875, y: 0.796875 },\n { x: 0.328125, y: 0.796875 },\n { x: 0.328125, y: 0.796875 },\n { x: 0.359375, y: 0.796875 },\n { x: 0.359375, y: 0.796875 },\n { x: 0.390625, y: 0.796875 },\n { x: 0.390625, y: 0.796875 },\n { x: 0.421875, y: 0.796875 },\n { x: 0.421875, y: 0.796875 },\n { x: 0.453125, y: 0.796875 },\n { x: 0.453125, y: 0.796875 },\n { x: 0.484375, y: 0.796875 },\n { x: 0.484375, y: 0.796875 },\n { x: 0.515625, y: 0.796875 },\n { x: 0.515625, y: 0.796875 },\n { x: 0.546875, y: 0.796875 },\n { x: 0.546875, y: 0.796875 },\n { x: 0.578125, y: 0.796875 },\n { x: 0.578125, y: 0.796875 },\n { x: 0.609375, y: 0.796875 },\n { x: 0.609375, y: 0.796875 },\n { x: 0.640625, y: 0.796875 },\n { x: 0.640625, y: 0.796875 },\n { x: 0.671875, y: 0.796875 },\n { x: 0.671875, y: 0.796875 },\n { x: 0.703125, y: 0.796875 },\n { x: 0.703125, y: 0.796875 },\n { x: 0.734375, y: 0.796875 },\n { x: 0.734375, y: 0.796875 },\n { x: 0.765625, y: 0.796875 },\n { x: 0.765625, y: 0.796875 },\n { x: 0.796875, y: 0.796875 },\n { x: 0.796875, y: 0.796875 },\n { x: 0.828125, y: 0.796875 },\n { x: 0.828125, y: 0.796875 },\n { x: 0.859375, y: 0.796875 },\n { x: 0.859375, y: 0.796875 },\n { x: 0.890625, y: 0.796875 },\n { x: 0.890625, y: 0.796875 },\n { x: 0.921875, y: 0.796875 },\n { x: 0.921875, y: 0.796875 },\n { x: 0.953125, y: 0.796875 },\n { x: 0.953125, y: 0.796875 },\n { x: 0.984375, y: 0.796875 },\n { x: 0.984375, y: 0.796875 },\n { x: 0.015625, y: 0.828125 },\n { x: 0.015625, y: 0.828125 },\n { x: 0.046875, y: 0.828125 },\n { x: 0.046875, y: 0.828125 },\n { x: 0.078125, y: 0.828125 },\n { x: 0.078125, y: 0.828125 },\n { x: 0.109375, y: 0.828125 },\n { x: 0.109375, y: 0.828125 },\n { x: 0.140625, y: 0.828125 },\n { x: 0.140625, y: 0.828125 },\n { x: 0.171875, y: 0.828125 },\n { x: 0.171875, y: 0.828125 },\n { x: 0.203125, y: 0.828125 },\n { x: 0.203125, y: 0.828125 },\n { x: 0.234375, y: 0.828125 },\n { x: 0.234375, y: 0.828125 },\n { x: 0.265625, y: 0.828125 },\n { x: 0.265625, y: 0.828125 },\n { x: 0.296875, y: 0.828125 },\n { x: 0.296875, y: 0.828125 },\n { x: 0.328125, y: 0.828125 },\n { x: 0.328125, y: 0.828125 },\n { x: 0.359375, y: 0.828125 },\n { x: 0.359375, y: 0.828125 },\n { x: 0.390625, y: 0.828125 },\n { x: 0.390625, y: 0.828125 },\n { x: 0.421875, y: 0.828125 },\n { x: 0.421875, y: 0.828125 },\n { x: 0.453125, y: 0.828125 },\n { x: 0.453125, y: 0.828125 },\n { x: 0.484375, y: 0.828125 },\n { x: 0.484375, y: 0.828125 },\n { x: 0.515625, y: 0.828125 },\n { x: 0.515625, y: 0.828125 },\n { x: 0.546875, y: 0.828125 },\n { x: 0.546875, y: 0.828125 },\n { x: 0.578125, y: 0.828125 },\n { x: 0.578125, y: 0.828125 },\n { x: 0.609375, y: 0.828125 },\n { x: 0.609375, y: 0.828125 },\n { x: 0.640625, y: 0.828125 },\n { x: 0.640625, y: 0.828125 },\n { x: 0.671875, y: 0.828125 },\n { x: 0.671875, y: 0.828125 },\n { x: 0.703125, y: 0.828125 },\n { x: 0.703125, y: 0.828125 },\n { x: 0.734375, y: 0.828125 },\n { x: 0.734375, y: 0.828125 },\n { x: 0.765625, y: 0.828125 },\n { x: 0.765625, y: 0.828125 },\n { x: 0.796875, y: 0.828125 },\n { x: 0.796875, y: 0.828125 },\n { x: 0.828125, y: 0.828125 },\n { x: 0.828125, y: 0.828125 },\n { x: 0.859375, y: 0.828125 },\n { x: 0.859375, y: 0.828125 },\n { x: 0.890625, y: 0.828125 },\n { x: 0.890625, y: 0.828125 },\n { x: 0.921875, y: 0.828125 },\n { x: 0.921875, y: 0.828125 },\n { x: 0.953125, y: 0.828125 },\n { x: 0.953125, y: 0.828125 },\n { x: 0.984375, y: 0.828125 },\n { x: 0.984375, y: 0.828125 },\n { x: 0.015625, y: 0.859375 },\n { x: 0.015625, y: 0.859375 },\n { x: 0.046875, y: 0.859375 },\n { x: 0.046875, y: 0.859375 },\n { x: 0.078125, y: 0.859375 },\n { x: 0.078125, y: 0.859375 },\n { x: 0.109375, y: 0.859375 },\n { x: 0.109375, y: 0.859375 },\n { x: 0.140625, y: 0.859375 },\n { x: 0.140625, y: 0.859375 },\n { x: 0.171875, y: 0.859375 },\n { x: 0.171875, y: 0.859375 },\n { x: 0.203125, y: 0.859375 },\n { x: 0.203125, y: 0.859375 },\n { x: 0.234375, y: 0.859375 },\n { x: 0.234375, y: 0.859375 },\n { x: 0.265625, y: 0.859375 },\n { x: 0.265625, y: 0.859375 },\n { x: 0.296875, y: 0.859375 },\n { x: 0.296875, y: 0.859375 },\n { x: 0.328125, y: 0.859375 },\n { x: 0.328125, y: 0.859375 },\n { x: 0.359375, y: 0.859375 },\n { x: 0.359375, y: 0.859375 },\n { x: 0.390625, y: 0.859375 },\n { x: 0.390625, y: 0.859375 },\n { x: 0.421875, y: 0.859375 },\n { x: 0.421875, y: 0.859375 },\n { x: 0.453125, y: 0.859375 },\n { x: 0.453125, y: 0.859375 },\n { x: 0.484375, y: 0.859375 },\n { x: 0.484375, y: 0.859375 },\n { x: 0.515625, y: 0.859375 },\n { x: 0.515625, y: 0.859375 },\n { x: 0.546875, y: 0.859375 },\n { x: 0.546875, y: 0.859375 },\n { x: 0.578125, y: 0.859375 },\n { x: 0.578125, y: 0.859375 },\n { x: 0.609375, y: 0.859375 },\n { x: 0.609375, y: 0.859375 },\n { x: 0.640625, y: 0.859375 },\n { x: 0.640625, y: 0.859375 },\n { x: 0.671875, y: 0.859375 },\n { x: 0.671875, y: 0.859375 },\n { x: 0.703125, y: 0.859375 },\n { x: 0.703125, y: 0.859375 },\n { x: 0.734375, y: 0.859375 },\n { x: 0.734375, y: 0.859375 },\n { x: 0.765625, y: 0.859375 },\n { x: 0.765625, y: 0.859375 },\n { x: 0.796875, y: 0.859375 },\n { x: 0.796875, y: 0.859375 },\n { x: 0.828125, y: 0.859375 },\n { x: 0.828125, y: 0.859375 },\n { x: 0.859375, y: 0.859375 },\n { x: 0.859375, y: 0.859375 },\n { x: 0.890625, y: 0.859375 },\n { x: 0.890625, y: 0.859375 },\n { x: 0.921875, y: 0.859375 },\n { x: 0.921875, y: 0.859375 },\n { x: 0.953125, y: 0.859375 },\n { x: 0.953125, y: 0.859375 },\n { x: 0.984375, y: 0.859375 },\n { x: 0.984375, y: 0.859375 },\n { x: 0.015625, y: 0.890625 },\n { x: 0.015625, y: 0.890625 },\n { x: 0.046875, y: 0.890625 },\n { x: 0.046875, y: 0.890625 },\n { x: 0.078125, y: 0.890625 },\n { x: 0.078125, y: 0.890625 },\n { x: 0.109375, y: 0.890625 },\n { x: 0.109375, y: 0.890625 },\n { x: 0.140625, y: 0.890625 },\n { x: 0.140625, y: 0.890625 },\n { x: 0.171875, y: 0.890625 },\n { x: 0.171875, y: 0.890625 },\n { x: 0.203125, y: 0.890625 },\n { x: 0.203125, y: 0.890625 },\n { x: 0.234375, y: 0.890625 },\n { x: 0.234375, y: 0.890625 },\n { x: 0.265625, y: 0.890625 },\n { x: 0.265625, y: 0.890625 },\n { x: 0.296875, y: 0.890625 },\n { x: 0.296875, y: 0.890625 },\n { x: 0.328125, y: 0.890625 },\n { x: 0.328125, y: 0.890625 },\n { x: 0.359375, y: 0.890625 },\n { x: 0.359375, y: 0.890625 },\n { x: 0.390625, y: 0.890625 },\n { x: 0.390625, y: 0.890625 },\n { x: 0.421875, y: 0.890625 },\n { x: 0.421875, y: 0.890625 },\n { x: 0.453125, y: 0.890625 },\n { x: 0.453125, y: 0.890625 },\n { x: 0.484375, y: 0.890625 },\n { x: 0.484375, y: 0.890625 },\n { x: 0.515625, y: 0.890625 },\n { x: 0.515625, y: 0.890625 },\n { x: 0.546875, y: 0.890625 },\n { x: 0.546875, y: 0.890625 },\n { x: 0.578125, y: 0.890625 },\n { x: 0.578125, y: 0.890625 },\n { x: 0.609375, y: 0.890625 },\n { x: 0.609375, y: 0.890625 },\n { x: 0.640625, y: 0.890625 },\n { x: 0.640625, y: 0.890625 },\n { x: 0.671875, y: 0.890625 },\n { x: 0.671875, y: 0.890625 },\n { x: 0.703125, y: 0.890625 },\n { x: 0.703125, y: 0.890625 },\n { x: 0.734375, y: 0.890625 },\n { x: 0.734375, y: 0.890625 },\n { x: 0.765625, y: 0.890625 },\n { x: 0.765625, y: 0.890625 },\n { x: 0.796875, y: 0.890625 },\n { x: 0.796875, y: 0.890625 },\n { x: 0.828125, y: 0.890625 },\n { x: 0.828125, y: 0.890625 },\n { x: 0.859375, y: 0.890625 },\n { x: 0.859375, y: 0.890625 },\n { x: 0.890625, y: 0.890625 },\n { x: 0.890625, y: 0.890625 },\n { x: 0.921875, y: 0.890625 },\n { x: 0.921875, y: 0.890625 },\n { x: 0.953125, y: 0.890625 },\n { x: 0.953125, y: 0.890625 },\n { x: 0.984375, y: 0.890625 },\n { x: 0.984375, y: 0.890625 },\n { x: 0.015625, y: 0.921875 },\n { x: 0.015625, y: 0.921875 },\n { x: 0.046875, y: 0.921875 },\n { x: 0.046875, y: 0.921875 },\n { x: 0.078125, y: 0.921875 },\n { x: 0.078125, y: 0.921875 },\n { x: 0.109375, y: 0.921875 },\n { x: 0.109375, y: 0.921875 },\n { x: 0.140625, y: 0.921875 },\n { x: 0.140625, y: 0.921875 },\n { x: 0.171875, y: 0.921875 },\n { x: 0.171875, y: 0.921875 },\n { x: 0.203125, y: 0.921875 },\n { x: 0.203125, y: 0.921875 },\n { x: 0.234375, y: 0.921875 },\n { x: 0.234375, y: 0.921875 },\n { x: 0.265625, y: 0.921875 },\n { x: 0.265625, y: 0.921875 },\n { x: 0.296875, y: 0.921875 },\n { x: 0.296875, y: 0.921875 },\n { x: 0.328125, y: 0.921875 },\n { x: 0.328125, y: 0.921875 },\n { x: 0.359375, y: 0.921875 },\n { x: 0.359375, y: 0.921875 },\n { x: 0.390625, y: 0.921875 },\n { x: 0.390625, y: 0.921875 },\n { x: 0.421875, y: 0.921875 },\n { x: 0.421875, y: 0.921875 },\n { x: 0.453125, y: 0.921875 },\n { x: 0.453125, y: 0.921875 },\n { x: 0.484375, y: 0.921875 },\n { x: 0.484375, y: 0.921875 },\n { x: 0.515625, y: 0.921875 },\n { x: 0.515625, y: 0.921875 },\n { x: 0.546875, y: 0.921875 },\n { x: 0.546875, y: 0.921875 },\n { x: 0.578125, y: 0.921875 },\n { x: 0.578125, y: 0.921875 },\n { x: 0.609375, y: 0.921875 },\n { x: 0.609375, y: 0.921875 },\n { x: 0.640625, y: 0.921875 },\n { x: 0.640625, y: 0.921875 },\n { x: 0.671875, y: 0.921875 },\n { x: 0.671875, y: 0.921875 },\n { x: 0.703125, y: 0.921875 },\n { x: 0.703125, y: 0.921875 },\n { x: 0.734375, y: 0.921875 },\n { x: 0.734375, y: 0.921875 },\n { x: 0.765625, y: 0.921875 },\n { x: 0.765625, y: 0.921875 },\n { x: 0.796875, y: 0.921875 },\n { x: 0.796875, y: 0.921875 },\n { x: 0.828125, y: 0.921875 },\n { x: 0.828125, y: 0.921875 },\n { x: 0.859375, y: 0.921875 },\n { x: 0.859375, y: 0.921875 },\n { x: 0.890625, y: 0.921875 },\n { x: 0.890625, y: 0.921875 },\n { x: 0.921875, y: 0.921875 },\n { x: 0.921875, y: 0.921875 },\n { x: 0.953125, y: 0.921875 },\n { x: 0.953125, y: 0.921875 },\n { x: 0.984375, y: 0.921875 },\n { x: 0.984375, y: 0.921875 },\n { x: 0.015625, y: 0.953125 },\n { x: 0.015625, y: 0.953125 },\n { x: 0.046875, y: 0.953125 },\n { x: 0.046875, y: 0.953125 },\n { x: 0.078125, y: 0.953125 },\n { x: 0.078125, y: 0.953125 },\n { x: 0.109375, y: 0.953125 },\n { x: 0.109375, y: 0.953125 },\n { x: 0.140625, y: 0.953125 },\n { x: 0.140625, y: 0.953125 },\n { x: 0.171875, y: 0.953125 },\n { x: 0.171875, y: 0.953125 },\n { x: 0.203125, y: 0.953125 },\n { x: 0.203125, y: 0.953125 },\n { x: 0.234375, y: 0.953125 },\n { x: 0.234375, y: 0.953125 },\n { x: 0.265625, y: 0.953125 },\n { x: 0.265625, y: 0.953125 },\n { x: 0.296875, y: 0.953125 },\n { x: 0.296875, y: 0.953125 },\n { x: 0.328125, y: 0.953125 },\n { x: 0.328125, y: 0.953125 },\n { x: 0.359375, y: 0.953125 },\n { x: 0.359375, y: 0.953125 },\n { x: 0.390625, y: 0.953125 },\n { x: 0.390625, y: 0.953125 },\n { x: 0.421875, y: 0.953125 },\n { x: 0.421875, y: 0.953125 },\n { x: 0.453125, y: 0.953125 },\n { x: 0.453125, y: 0.953125 },\n { x: 0.484375, y: 0.953125 },\n { x: 0.484375, y: 0.953125 },\n { x: 0.515625, y: 0.953125 },\n { x: 0.515625, y: 0.953125 },\n { x: 0.546875, y: 0.953125 },\n { x: 0.546875, y: 0.953125 },\n { x: 0.578125, y: 0.953125 },\n { x: 0.578125, y: 0.953125 },\n { x: 0.609375, y: 0.953125 },\n { x: 0.609375, y: 0.953125 },\n { x: 0.640625, y: 0.953125 },\n { x: 0.640625, y: 0.953125 },\n { x: 0.671875, y: 0.953125 },\n { x: 0.671875, y: 0.953125 },\n { x: 0.703125, y: 0.953125 },\n { x: 0.703125, y: 0.953125 },\n { x: 0.734375, y: 0.953125 },\n { x: 0.734375, y: 0.953125 },\n { x: 0.765625, y: 0.953125 },\n { x: 0.765625, y: 0.953125 },\n { x: 0.796875, y: 0.953125 },\n { x: 0.796875, y: 0.953125 },\n { x: 0.828125, y: 0.953125 },\n { x: 0.828125, y: 0.953125 },\n { x: 0.859375, y: 0.953125 },\n { x: 0.859375, y: 0.953125 },\n { x: 0.890625, y: 0.953125 },\n { x: 0.890625, y: 0.953125 },\n { x: 0.921875, y: 0.953125 },\n { x: 0.921875, y: 0.953125 },\n { x: 0.953125, y: 0.953125 },\n { x: 0.953125, y: 0.953125 },\n { x: 0.984375, y: 0.953125 },\n { x: 0.984375, y: 0.953125 },\n { x: 0.015625, y: 0.984375 },\n { x: 0.015625, y: 0.984375 },\n { x: 0.046875, y: 0.984375 },\n { x: 0.046875, y: 0.984375 },\n { x: 0.078125, y: 0.984375 },\n { x: 0.078125, y: 0.984375 },\n { x: 0.109375, y: 0.984375 },\n { x: 0.109375, y: 0.984375 },\n { x: 0.140625, y: 0.984375 },\n { x: 0.140625, y: 0.984375 },\n { x: 0.171875, y: 0.984375 },\n { x: 0.171875, y: 0.984375 },\n { x: 0.203125, y: 0.984375 },\n { x: 0.203125, y: 0.984375 },\n { x: 0.234375, y: 0.984375 },\n { x: 0.234375, y: 0.984375 },\n { x: 0.265625, y: 0.984375 },\n { x: 0.265625, y: 0.984375 },\n { x: 0.296875, y: 0.984375 },\n { x: 0.296875, y: 0.984375 },\n { x: 0.328125, y: 0.984375 },\n { x: 0.328125, y: 0.984375 },\n { x: 0.359375, y: 0.984375 },\n { x: 0.359375, y: 0.984375 },\n { x: 0.390625, y: 0.984375 },\n { x: 0.390625, y: 0.984375 },\n { x: 0.421875, y: 0.984375 },\n { x: 0.421875, y: 0.984375 },\n { x: 0.453125, y: 0.984375 },\n { x: 0.453125, y: 0.984375 },\n { x: 0.484375, y: 0.984375 },\n { x: 0.484375, y: 0.984375 },\n { x: 0.515625, y: 0.984375 },\n { x: 0.515625, y: 0.984375 },\n { x: 0.546875, y: 0.984375 },\n { x: 0.546875, y: 0.984375 },\n { x: 0.578125, y: 0.984375 },\n { x: 0.578125, y: 0.984375 },\n { x: 0.609375, y: 0.984375 },\n { x: 0.609375, y: 0.984375 },\n { x: 0.640625, y: 0.984375 },\n { x: 0.640625, y: 0.984375 },\n { x: 0.671875, y: 0.984375 },\n { x: 0.671875, y: 0.984375 },\n { x: 0.703125, y: 0.984375 },\n { x: 0.703125, y: 0.984375 },\n { x: 0.734375, y: 0.984375 },\n { x: 0.734375, y: 0.984375 },\n { x: 0.765625, y: 0.984375 },\n { x: 0.765625, y: 0.984375 },\n { x: 0.796875, y: 0.984375 },\n { x: 0.796875, y: 0.984375 },\n { x: 0.828125, y: 0.984375 },\n { x: 0.828125, y: 0.984375 },\n { x: 0.859375, y: 0.984375 },\n { x: 0.859375, y: 0.984375 },\n { x: 0.890625, y: 0.984375 },\n { x: 0.890625, y: 0.984375 },\n { x: 0.921875, y: 0.984375 },\n { x: 0.921875, y: 0.984375 },\n { x: 0.953125, y: 0.984375 },\n { x: 0.953125, y: 0.984375 },\n { x: 0.984375, y: 0.984375 },\n { x: 0.984375, y: 0.984375 },\n { x: 0.03125, y: 0.03125 },\n { x: 0.03125, y: 0.03125 },\n { x: 0.09375, y: 0.03125 },\n { x: 0.09375, y: 0.03125 },\n { x: 0.15625, y: 0.03125 },\n { x: 0.15625, y: 0.03125 },\n { x: 0.21875, y: 0.03125 },\n { x: 0.21875, y: 0.03125 },\n { x: 0.28125, y: 0.03125 },\n { x: 0.28125, y: 0.03125 },\n { x: 0.34375, y: 0.03125 },\n { x: 0.34375, y: 0.03125 },\n { x: 0.40625, y: 0.03125 },\n { x: 0.40625, y: 0.03125 },\n { x: 0.46875, y: 0.03125 },\n { x: 0.46875, y: 0.03125 },\n { x: 0.53125, y: 0.03125 },\n { x: 0.53125, y: 0.03125 },\n { x: 0.59375, y: 0.03125 },\n { x: 0.59375, y: 0.03125 },\n { x: 0.65625, y: 0.03125 },\n { x: 0.65625, y: 0.03125 },\n { x: 0.71875, y: 0.03125 },\n { x: 0.71875, y: 0.03125 },\n { x: 0.78125, y: 0.03125 },\n { x: 0.78125, y: 0.03125 },\n { x: 0.84375, y: 0.03125 },\n { x: 0.84375, y: 0.03125 },\n { x: 0.90625, y: 0.03125 },\n { x: 0.90625, y: 0.03125 },\n { x: 0.96875, y: 0.03125 },\n { x: 0.96875, y: 0.03125 },\n { x: 0.03125, y: 0.09375 },\n { x: 0.03125, y: 0.09375 },\n { x: 0.09375, y: 0.09375 },\n { x: 0.09375, y: 0.09375 },\n { x: 0.15625, y: 0.09375 },\n { x: 0.15625, y: 0.09375 },\n { x: 0.21875, y: 0.09375 },\n { x: 0.21875, y: 0.09375 },\n { x: 0.28125, y: 0.09375 },\n { x: 0.28125, y: 0.09375 },\n { x: 0.34375, y: 0.09375 },\n { x: 0.34375, y: 0.09375 },\n { x: 0.40625, y: 0.09375 },\n { x: 0.40625, y: 0.09375 },\n { x: 0.46875, y: 0.09375 },\n { x: 0.46875, y: 0.09375 },\n { x: 0.53125, y: 0.09375 },\n { x: 0.53125, y: 0.09375 },\n { x: 0.59375, y: 0.09375 },\n { x: 0.59375, y: 0.09375 },\n { x: 0.65625, y: 0.09375 },\n { x: 0.65625, y: 0.09375 },\n { x: 0.71875, y: 0.09375 },\n { x: 0.71875, y: 0.09375 },\n { x: 0.78125, y: 0.09375 },\n { x: 0.78125, y: 0.09375 },\n { x: 0.84375, y: 0.09375 },\n { x: 0.84375, y: 0.09375 },\n { x: 0.90625, y: 0.09375 },\n { x: 0.90625, y: 0.09375 },\n { x: 0.96875, y: 0.09375 },\n { x: 0.96875, y: 0.09375 },\n { x: 0.03125, y: 0.15625 },\n { x: 0.03125, y: 0.15625 },\n { x: 0.09375, y: 0.15625 },\n { x: 0.09375, y: 0.15625 },\n { x: 0.15625, y: 0.15625 },\n { x: 0.15625, y: 0.15625 },\n { x: 0.21875, y: 0.15625 },\n { x: 0.21875, y: 0.15625 },\n { x: 0.28125, y: 0.15625 },\n { x: 0.28125, y: 0.15625 },\n { x: 0.34375, y: 0.15625 },\n { x: 0.34375, y: 0.15625 },\n { x: 0.40625, y: 0.15625 },\n { x: 0.40625, y: 0.15625 },\n { x: 0.46875, y: 0.15625 },\n { x: 0.46875, y: 0.15625 },\n { x: 0.53125, y: 0.15625 },\n { x: 0.53125, y: 0.15625 },\n { x: 0.59375, y: 0.15625 },\n { x: 0.59375, y: 0.15625 },\n { x: 0.65625, y: 0.15625 },\n { x: 0.65625, y: 0.15625 },\n { x: 0.71875, y: 0.15625 },\n { x: 0.71875, y: 0.15625 },\n { x: 0.78125, y: 0.15625 },\n { x: 0.78125, y: 0.15625 },\n { x: 0.84375, y: 0.15625 },\n { x: 0.84375, y: 0.15625 },\n { x: 0.90625, y: 0.15625 },\n { x: 0.90625, y: 0.15625 },\n { x: 0.96875, y: 0.15625 },\n { x: 0.96875, y: 0.15625 },\n { x: 0.03125, y: 0.21875 },\n { x: 0.03125, y: 0.21875 },\n { x: 0.09375, y: 0.21875 },\n { x: 0.09375, y: 0.21875 },\n { x: 0.15625, y: 0.21875 },\n { x: 0.15625, y: 0.21875 },\n { x: 0.21875, y: 0.21875 },\n { x: 0.21875, y: 0.21875 },\n { x: 0.28125, y: 0.21875 },\n { x: 0.28125, y: 0.21875 },\n { x: 0.34375, y: 0.21875 },\n { x: 0.34375, y: 0.21875 },\n { x: 0.40625, y: 0.21875 },\n { x: 0.40625, y: 0.21875 },\n { x: 0.46875, y: 0.21875 },\n { x: 0.46875, y: 0.21875 },\n { x: 0.53125, y: 0.21875 },\n { x: 0.53125, y: 0.21875 },\n { x: 0.59375, y: 0.21875 },\n { x: 0.59375, y: 0.21875 },\n { x: 0.65625, y: 0.21875 },\n { x: 0.65625, y: 0.21875 },\n { x: 0.71875, y: 0.21875 },\n { x: 0.71875, y: 0.21875 },\n { x: 0.78125, y: 0.21875 },\n { x: 0.78125, y: 0.21875 },\n { x: 0.84375, y: 0.21875 },\n { x: 0.84375, y: 0.21875 },\n { x: 0.90625, y: 0.21875 },\n { x: 0.90625, y: 0.21875 },\n { x: 0.96875, y: 0.21875 },\n { x: 0.96875, y: 0.21875 },\n { x: 0.03125, y: 0.28125 },\n { x: 0.03125, y: 0.28125 },\n { x: 0.09375, y: 0.28125 },\n { x: 0.09375, y: 0.28125 },\n { x: 0.15625, y: 0.28125 },\n { x: 0.15625, y: 0.28125 },\n { x: 0.21875, y: 0.28125 },\n { x: 0.21875, y: 0.28125 },\n { x: 0.28125, y: 0.28125 },\n { x: 0.28125, y: 0.28125 },\n { x: 0.34375, y: 0.28125 },\n { x: 0.34375, y: 0.28125 },\n { x: 0.40625, y: 0.28125 },\n { x: 0.40625, y: 0.28125 },\n { x: 0.46875, y: 0.28125 },\n { x: 0.46875, y: 0.28125 },\n { x: 0.53125, y: 0.28125 },\n { x: 0.53125, y: 0.28125 },\n { x: 0.59375, y: 0.28125 },\n { x: 0.59375, y: 0.28125 },\n { x: 0.65625, y: 0.28125 },\n { x: 0.65625, y: 0.28125 },\n { x: 0.71875, y: 0.28125 },\n { x: 0.71875, y: 0.28125 },\n { x: 0.78125, y: 0.28125 },\n { x: 0.78125, y: 0.28125 },\n { x: 0.84375, y: 0.28125 },\n { x: 0.84375, y: 0.28125 },\n { x: 0.90625, y: 0.28125 },\n { x: 0.90625, y: 0.28125 },\n { x: 0.96875, y: 0.28125 },\n { x: 0.96875, y: 0.28125 },\n { x: 0.03125, y: 0.34375 },\n { x: 0.03125, y: 0.34375 },\n { x: 0.09375, y: 0.34375 },\n { x: 0.09375, y: 0.34375 },\n { x: 0.15625, y: 0.34375 },\n { x: 0.15625, y: 0.34375 },\n { x: 0.21875, y: 0.34375 },\n { x: 0.21875, y: 0.34375 },\n { x: 0.28125, y: 0.34375 },\n { x: 0.28125, y: 0.34375 },\n { x: 0.34375, y: 0.34375 },\n { x: 0.34375, y: 0.34375 },\n { x: 0.40625, y: 0.34375 },\n { x: 0.40625, y: 0.34375 },\n { x: 0.46875, y: 0.34375 },\n { x: 0.46875, y: 0.34375 },\n { x: 0.53125, y: 0.34375 },\n { x: 0.53125, y: 0.34375 },\n { x: 0.59375, y: 0.34375 },\n { x: 0.59375, y: 0.34375 },\n { x: 0.65625, y: 0.34375 },\n { x: 0.65625, y: 0.34375 },\n { x: 0.71875, y: 0.34375 },\n { x: 0.71875, y: 0.34375 },\n { x: 0.78125, y: 0.34375 },\n { x: 0.78125, y: 0.34375 },\n { x: 0.84375, y: 0.34375 },\n { x: 0.84375, y: 0.34375 },\n { x: 0.90625, y: 0.34375 },\n { x: 0.90625, y: 0.34375 },\n { x: 0.96875, y: 0.34375 },\n { x: 0.96875, y: 0.34375 },\n { x: 0.03125, y: 0.40625 },\n { x: 0.03125, y: 0.40625 },\n { x: 0.09375, y: 0.40625 },\n { x: 0.09375, y: 0.40625 },\n { x: 0.15625, y: 0.40625 },\n { x: 0.15625, y: 0.40625 },\n { x: 0.21875, y: 0.40625 },\n { x: 0.21875, y: 0.40625 },\n { x: 0.28125, y: 0.40625 },\n { x: 0.28125, y: 0.40625 },\n { x: 0.34375, y: 0.40625 },\n { x: 0.34375, y: 0.40625 },\n { x: 0.40625, y: 0.40625 },\n { x: 0.40625, y: 0.40625 },\n { x: 0.46875, y: 0.40625 },\n { x: 0.46875, y: 0.40625 },\n { x: 0.53125, y: 0.40625 },\n { x: 0.53125, y: 0.40625 },\n { x: 0.59375, y: 0.40625 },\n { x: 0.59375, y: 0.40625 },\n { x: 0.65625, y: 0.40625 },\n { x: 0.65625, y: 0.40625 },\n { x: 0.71875, y: 0.40625 },\n { x: 0.71875, y: 0.40625 },\n { x: 0.78125, y: 0.40625 },\n { x: 0.78125, y: 0.40625 },\n { x: 0.84375, y: 0.40625 },\n { x: 0.84375, y: 0.40625 },\n { x: 0.90625, y: 0.40625 },\n { x: 0.90625, y: 0.40625 },\n { x: 0.96875, y: 0.40625 },\n { x: 0.96875, y: 0.40625 },\n { x: 0.03125, y: 0.46875 },\n { x: 0.03125, y: 0.46875 },\n { x: 0.09375, y: 0.46875 },\n { x: 0.09375, y: 0.46875 },\n { x: 0.15625, y: 0.46875 },\n { x: 0.15625, y: 0.46875 },\n { x: 0.21875, y: 0.46875 },\n { x: 0.21875, y: 0.46875 },\n { x: 0.28125, y: 0.46875 },\n { x: 0.28125, y: 0.46875 },\n { x: 0.34375, y: 0.46875 },\n { x: 0.34375, y: 0.46875 },\n { x: 0.40625, y: 0.46875 },\n { x: 0.40625, y: 0.46875 },\n { x: 0.46875, y: 0.46875 },\n { x: 0.46875, y: 0.46875 },\n { x: 0.53125, y: 0.46875 },\n { x: 0.53125, y: 0.46875 },\n { x: 0.59375, y: 0.46875 },\n { x: 0.59375, y: 0.46875 },\n { x: 0.65625, y: 0.46875 },\n { x: 0.65625, y: 0.46875 },\n { x: 0.71875, y: 0.46875 },\n { x: 0.71875, y: 0.46875 },\n { x: 0.78125, y: 0.46875 },\n { x: 0.78125, y: 0.46875 },\n { x: 0.84375, y: 0.46875 },\n { x: 0.84375, y: 0.46875 },\n { x: 0.90625, y: 0.46875 },\n { x: 0.90625, y: 0.46875 },\n { x: 0.96875, y: 0.46875 },\n { x: 0.96875, y: 0.46875 },\n { x: 0.03125, y: 0.53125 },\n { x: 0.03125, y: 0.53125 },\n { x: 0.09375, y: 0.53125 },\n { x: 0.09375, y: 0.53125 },\n { x: 0.15625, y: 0.53125 },\n { x: 0.15625, y: 0.53125 },\n { x: 0.21875, y: 0.53125 },\n { x: 0.21875, y: 0.53125 },\n { x: 0.28125, y: 0.53125 },\n { x: 0.28125, y: 0.53125 },\n { x: 0.34375, y: 0.53125 },\n { x: 0.34375, y: 0.53125 },\n { x: 0.40625, y: 0.53125 },\n { x: 0.40625, y: 0.53125 },\n { x: 0.46875, y: 0.53125 },\n { x: 0.46875, y: 0.53125 },\n { x: 0.53125, y: 0.53125 },\n { x: 0.53125, y: 0.53125 },\n { x: 0.59375, y: 0.53125 },\n { x: 0.59375, y: 0.53125 },\n { x: 0.65625, y: 0.53125 },\n { x: 0.65625, y: 0.53125 },\n { x: 0.71875, y: 0.53125 },\n { x: 0.71875, y: 0.53125 },\n { x: 0.78125, y: 0.53125 },\n { x: 0.78125, y: 0.53125 },\n { x: 0.84375, y: 0.53125 },\n { x: 0.84375, y: 0.53125 },\n { x: 0.90625, y: 0.53125 },\n { x: 0.90625, y: 0.53125 },\n { x: 0.96875, y: 0.53125 },\n { x: 0.96875, y: 0.53125 },\n { x: 0.03125, y: 0.59375 },\n { x: 0.03125, y: 0.59375 },\n { x: 0.09375, y: 0.59375 },\n { x: 0.09375, y: 0.59375 },\n { x: 0.15625, y: 0.59375 },\n { x: 0.15625, y: 0.59375 },\n { x: 0.21875, y: 0.59375 },\n { x: 0.21875, y: 0.59375 },\n { x: 0.28125, y: 0.59375 },\n { x: 0.28125, y: 0.59375 },\n { x: 0.34375, y: 0.59375 },\n { x: 0.34375, y: 0.59375 },\n { x: 0.40625, y: 0.59375 },\n { x: 0.40625, y: 0.59375 },\n { x: 0.46875, y: 0.59375 },\n { x: 0.46875, y: 0.59375 },\n { x: 0.53125, y: 0.59375 },\n { x: 0.53125, y: 0.59375 },\n { x: 0.59375, y: 0.59375 },\n { x: 0.59375, y: 0.59375 },\n { x: 0.65625, y: 0.59375 },\n { x: 0.65625, y: 0.59375 },\n { x: 0.71875, y: 0.59375 },\n { x: 0.71875, y: 0.59375 },\n { x: 0.78125, y: 0.59375 },\n { x: 0.78125, y: 0.59375 },\n { x: 0.84375, y: 0.59375 },\n { x: 0.84375, y: 0.59375 },\n { x: 0.90625, y: 0.59375 },\n { x: 0.90625, y: 0.59375 },\n { x: 0.96875, y: 0.59375 },\n { x: 0.96875, y: 0.59375 },\n { x: 0.03125, y: 0.65625 },\n { x: 0.03125, y: 0.65625 },\n { x: 0.09375, y: 0.65625 },\n { x: 0.09375, y: 0.65625 },\n { x: 0.15625, y: 0.65625 },\n { x: 0.15625, y: 0.65625 },\n { x: 0.21875, y: 0.65625 },\n { x: 0.21875, y: 0.65625 },\n { x: 0.28125, y: 0.65625 },\n { x: 0.28125, y: 0.65625 },\n { x: 0.34375, y: 0.65625 },\n { x: 0.34375, y: 0.65625 },\n { x: 0.40625, y: 0.65625 },\n { x: 0.40625, y: 0.65625 },\n { x: 0.46875, y: 0.65625 },\n { x: 0.46875, y: 0.65625 },\n { x: 0.53125, y: 0.65625 },\n { x: 0.53125, y: 0.65625 },\n { x: 0.59375, y: 0.65625 },\n { x: 0.59375, y: 0.65625 },\n { x: 0.65625, y: 0.65625 },\n { x: 0.65625, y: 0.65625 },\n { x: 0.71875, y: 0.65625 },\n { x: 0.71875, y: 0.65625 },\n { x: 0.78125, y: 0.65625 },\n { x: 0.78125, y: 0.65625 },\n { x: 0.84375, y: 0.65625 },\n { x: 0.84375, y: 0.65625 },\n { x: 0.90625, y: 0.65625 },\n { x: 0.90625, y: 0.65625 },\n { x: 0.96875, y: 0.65625 },\n { x: 0.96875, y: 0.65625 },\n { x: 0.03125, y: 0.71875 },\n { x: 0.03125, y: 0.71875 },\n { x: 0.09375, y: 0.71875 },\n { x: 0.09375, y: 0.71875 },\n { x: 0.15625, y: 0.71875 },\n { x: 0.15625, y: 0.71875 },\n { x: 0.21875, y: 0.71875 },\n { x: 0.21875, y: 0.71875 },\n { x: 0.28125, y: 0.71875 },\n { x: 0.28125, y: 0.71875 },\n { x: 0.34375, y: 0.71875 },\n { x: 0.34375, y: 0.71875 },\n { x: 0.40625, y: 0.71875 },\n { x: 0.40625, y: 0.71875 },\n { x: 0.46875, y: 0.71875 },\n { x: 0.46875, y: 0.71875 },\n { x: 0.53125, y: 0.71875 },\n { x: 0.53125, y: 0.71875 },\n { x: 0.59375, y: 0.71875 },\n { x: 0.59375, y: 0.71875 },\n { x: 0.65625, y: 0.71875 },\n { x: 0.65625, y: 0.71875 },\n { x: 0.71875, y: 0.71875 },\n { x: 0.71875, y: 0.71875 },\n { x: 0.78125, y: 0.71875 },\n { x: 0.78125, y: 0.71875 },\n { x: 0.84375, y: 0.71875 },\n { x: 0.84375, y: 0.71875 },\n { x: 0.90625, y: 0.71875 },\n { x: 0.90625, y: 0.71875 },\n { x: 0.96875, y: 0.71875 },\n { x: 0.96875, y: 0.71875 },\n { x: 0.03125, y: 0.78125 },\n { x: 0.03125, y: 0.78125 },\n { x: 0.09375, y: 0.78125 },\n { x: 0.09375, y: 0.78125 },\n { x: 0.15625, y: 0.78125 },\n { x: 0.15625, y: 0.78125 },\n { x: 0.21875, y: 0.78125 },\n { x: 0.21875, y: 0.78125 },\n { x: 0.28125, y: 0.78125 },\n { x: 0.28125, y: 0.78125 },\n { x: 0.34375, y: 0.78125 },\n { x: 0.34375, y: 0.78125 },\n { x: 0.40625, y: 0.78125 },\n { x: 0.40625, y: 0.78125 },\n { x: 0.46875, y: 0.78125 },\n { x: 0.46875, y: 0.78125 },\n { x: 0.53125, y: 0.78125 },\n { x: 0.53125, y: 0.78125 },\n { x: 0.59375, y: 0.78125 },\n { x: 0.59375, y: 0.78125 },\n { x: 0.65625, y: 0.78125 },\n { x: 0.65625, y: 0.78125 },\n { x: 0.71875, y: 0.78125 },\n { x: 0.71875, y: 0.78125 },\n { x: 0.78125, y: 0.78125 },\n { x: 0.78125, y: 0.78125 },\n { x: 0.84375, y: 0.78125 },\n { x: 0.84375, y: 0.78125 },\n { x: 0.90625, y: 0.78125 },\n { x: 0.90625, y: 0.78125 },\n { x: 0.96875, y: 0.78125 },\n { x: 0.96875, y: 0.78125 },\n { x: 0.03125, y: 0.84375 },\n { x: 0.03125, y: 0.84375 },\n { x: 0.09375, y: 0.84375 },\n { x: 0.09375, y: 0.84375 },\n { x: 0.15625, y: 0.84375 },\n { x: 0.15625, y: 0.84375 },\n { x: 0.21875, y: 0.84375 },\n { x: 0.21875, y: 0.84375 },\n { x: 0.28125, y: 0.84375 },\n { x: 0.28125, y: 0.84375 },\n { x: 0.34375, y: 0.84375 },\n { x: 0.34375, y: 0.84375 },\n { x: 0.40625, y: 0.84375 },\n { x: 0.40625, y: 0.84375 },\n { x: 0.46875, y: 0.84375 },\n { x: 0.46875, y: 0.84375 },\n { x: 0.53125, y: 0.84375 },\n { x: 0.53125, y: 0.84375 },\n { x: 0.59375, y: 0.84375 },\n { x: 0.59375, y: 0.84375 },\n { x: 0.65625, y: 0.84375 },\n { x: 0.65625, y: 0.84375 },\n { x: 0.71875, y: 0.84375 },\n { x: 0.71875, y: 0.84375 },\n { x: 0.78125, y: 0.84375 },\n { x: 0.78125, y: 0.84375 },\n { x: 0.84375, y: 0.84375 },\n { x: 0.84375, y: 0.84375 },\n { x: 0.90625, y: 0.84375 },\n { x: 0.90625, y: 0.84375 },\n { x: 0.96875, y: 0.84375 },\n { x: 0.96875, y: 0.84375 },\n { x: 0.03125, y: 0.90625 },\n { x: 0.03125, y: 0.90625 },\n { x: 0.09375, y: 0.90625 },\n { x: 0.09375, y: 0.90625 },\n { x: 0.15625, y: 0.90625 },\n { x: 0.15625, y: 0.90625 },\n { x: 0.21875, y: 0.90625 },\n { x: 0.21875, y: 0.90625 },\n { x: 0.28125, y: 0.90625 },\n { x: 0.28125, y: 0.90625 },\n { x: 0.34375, y: 0.90625 },\n { x: 0.34375, y: 0.90625 },\n { x: 0.40625, y: 0.90625 },\n { x: 0.40625, y: 0.90625 },\n { x: 0.46875, y: 0.90625 },\n { x: 0.46875, y: 0.90625 },\n { x: 0.53125, y: 0.90625 },\n { x: 0.53125, y: 0.90625 },\n { x: 0.59375, y: 0.90625 },\n { x: 0.59375, y: 0.90625 },\n { x: 0.65625, y: 0.90625 },\n { x: 0.65625, y: 0.90625 },\n { x: 0.71875, y: 0.90625 },\n { x: 0.71875, y: 0.90625 },\n { x: 0.78125, y: 0.90625 },\n { x: 0.78125, y: 0.90625 },\n { x: 0.84375, y: 0.90625 },\n { x: 0.84375, y: 0.90625 },\n { x: 0.90625, y: 0.90625 },\n { x: 0.90625, y: 0.90625 },\n { x: 0.96875, y: 0.90625 },\n { x: 0.96875, y: 0.90625 },\n { x: 0.03125, y: 0.96875 },\n { x: 0.03125, y: 0.96875 },\n { x: 0.09375, y: 0.96875 },\n { x: 0.09375, y: 0.96875 },\n { x: 0.15625, y: 0.96875 },\n { x: 0.15625, y: 0.96875 },\n { x: 0.21875, y: 0.96875 },\n { x: 0.21875, y: 0.96875 },\n { x: 0.28125, y: 0.96875 },\n { x: 0.28125, y: 0.96875 },\n { x: 0.34375, y: 0.96875 },\n { x: 0.34375, y: 0.96875 },\n { x: 0.40625, y: 0.96875 },\n { x: 0.40625, y: 0.96875 },\n { x: 0.46875, y: 0.96875 },\n { x: 0.46875, y: 0.96875 },\n { x: 0.53125, y: 0.96875 },\n { x: 0.53125, y: 0.96875 },\n { x: 0.59375, y: 0.96875 },\n { x: 0.59375, y: 0.96875 },\n { x: 0.65625, y: 0.96875 },\n { x: 0.65625, y: 0.96875 },\n { x: 0.71875, y: 0.96875 },\n { x: 0.71875, y: 0.96875 },\n { x: 0.78125, y: 0.96875 },\n { x: 0.78125, y: 0.96875 },\n { x: 0.84375, y: 0.96875 },\n { x: 0.84375, y: 0.96875 },\n { x: 0.90625, y: 0.96875 },\n { x: 0.90625, y: 0.96875 },\n { x: 0.96875, y: 0.96875 },\n { x: 0.96875, y: 0.96875 },\n { x: 0.0625, y: 0.0625 },\n { x: 0.0625, y: 0.0625 },\n { x: 0.0625, y: 0.0625 },\n { x: 0.0625, y: 0.0625 },\n { x: 0.0625, y: 0.0625 },\n { x: 0.0625, y: 0.0625 },\n { x: 0.1875, y: 0.0625 },\n { x: 0.1875, y: 0.0625 },\n { x: 0.1875, y: 0.0625 },\n { x: 0.1875, y: 0.0625 },\n { x: 0.1875, y: 0.0625 },\n { x: 0.1875, y: 0.0625 },\n { x: 0.3125, y: 0.0625 },\n { x: 0.3125, y: 0.0625 },\n { x: 0.3125, y: 0.0625 },\n { x: 0.3125, y: 0.0625 },\n { x: 0.3125, y: 0.0625 },\n { x: 0.3125, y: 0.0625 },\n { x: 0.4375, y: 0.0625 },\n { x: 0.4375, y: 0.0625 },\n { x: 0.4375, y: 0.0625 },\n { x: 0.4375, y: 0.0625 },\n { x: 0.4375, y: 0.0625 },\n { x: 0.4375, y: 0.0625 },\n { x: 0.5625, y: 0.0625 },\n { x: 0.5625, y: 0.0625 },\n { x: 0.5625, y: 0.0625 },\n { x: 0.5625, y: 0.0625 },\n { x: 0.5625, y: 0.0625 },\n { x: 0.5625, y: 0.0625 },\n { x: 0.6875, y: 0.0625 },\n { x: 0.6875, y: 0.0625 },\n { x: 0.6875, y: 0.0625 },\n { x: 0.6875, y: 0.0625 },\n { x: 0.6875, y: 0.0625 },\n { x: 0.6875, y: 0.0625 },\n { x: 0.8125, y: 0.0625 },\n { x: 0.8125, y: 0.0625 },\n { x: 0.8125, y: 0.0625 },\n { x: 0.8125, y: 0.0625 },\n { x: 0.8125, y: 0.0625 },\n { x: 0.8125, y: 0.0625 },\n { x: 0.9375, y: 0.0625 },\n { x: 0.9375, y: 0.0625 },\n { x: 0.9375, y: 0.0625 },\n { x: 0.9375, y: 0.0625 },\n { x: 0.9375, y: 0.0625 },\n { x: 0.9375, y: 0.0625 },\n { x: 0.0625, y: 0.1875 },\n { x: 0.0625, y: 0.1875 },\n { x: 0.0625, y: 0.1875 },\n { x: 0.0625, y: 0.1875 },\n { x: 0.0625, y: 0.1875 },\n { x: 0.0625, y: 0.1875 },\n { x: 0.1875, y: 0.1875 },\n { x: 0.1875, y: 0.1875 },\n { x: 0.1875, y: 0.1875 },\n { x: 0.1875, y: 0.1875 },\n { x: 0.1875, y: 0.1875 },\n { x: 0.1875, y: 0.1875 },\n { x: 0.3125, y: 0.1875 },\n { x: 0.3125, y: 0.1875 },\n { x: 0.3125, y: 0.1875 },\n { x: 0.3125, y: 0.1875 },\n { x: 0.3125, y: 0.1875 },\n { x: 0.3125, y: 0.1875 },\n { x: 0.4375, y: 0.1875 },\n { x: 0.4375, y: 0.1875 },\n { x: 0.4375, y: 0.1875 },\n { x: 0.4375, y: 0.1875 },\n { x: 0.4375, y: 0.1875 },\n { x: 0.4375, y: 0.1875 },\n { x: 0.5625, y: 0.1875 },\n { x: 0.5625, y: 0.1875 },\n { x: 0.5625, y: 0.1875 },\n { x: 0.5625, y: 0.1875 },\n { x: 0.5625, y: 0.1875 },\n { x: 0.5625, y: 0.1875 },\n { x: 0.6875, y: 0.1875 },\n { x: 0.6875, y: 0.1875 },\n { x: 0.6875, y: 0.1875 },\n { x: 0.6875, y: 0.1875 },\n { x: 0.6875, y: 0.1875 },\n { x: 0.6875, y: 0.1875 },\n { x: 0.8125, y: 0.1875 },\n { x: 0.8125, y: 0.1875 },\n { x: 0.8125, y: 0.1875 },\n { x: 0.8125, y: 0.1875 },\n { x: 0.8125, y: 0.1875 },\n { x: 0.8125, y: 0.1875 },\n { x: 0.9375, y: 0.1875 },\n { x: 0.9375, y: 0.1875 },\n { x: 0.9375, y: 0.1875 },\n { x: 0.9375, y: 0.1875 },\n { x: 0.9375, y: 0.1875 },\n { x: 0.9375, y: 0.1875 },\n { x: 0.0625, y: 0.3125 },\n { x: 0.0625, y: 0.3125 },\n { x: 0.0625, y: 0.3125 },\n { x: 0.0625, y: 0.3125 },\n { x: 0.0625, y: 0.3125 },\n { x: 0.0625, y: 0.3125 },\n { x: 0.1875, y: 0.3125 },\n { x: 0.1875, y: 0.3125 },\n { x: 0.1875, y: 0.3125 },\n { x: 0.1875, y: 0.3125 },\n { x: 0.1875, y: 0.3125 },\n { x: 0.1875, y: 0.3125 },\n { x: 0.3125, y: 0.3125 },\n { x: 0.3125, y: 0.3125 },\n { x: 0.3125, y: 0.3125 },\n { x: 0.3125, y: 0.3125 },\n { x: 0.3125, y: 0.3125 },\n { x: 0.3125, y: 0.3125 },\n { x: 0.4375, y: 0.3125 },\n { x: 0.4375, y: 0.3125 },\n { x: 0.4375, y: 0.3125 },\n { x: 0.4375, y: 0.3125 },\n { x: 0.4375, y: 0.3125 },\n { x: 0.4375, y: 0.3125 },\n { x: 0.5625, y: 0.3125 },\n { x: 0.5625, y: 0.3125 },\n { x: 0.5625, y: 0.3125 },\n { x: 0.5625, y: 0.3125 },\n { x: 0.5625, y: 0.3125 },\n { x: 0.5625, y: 0.3125 },\n { x: 0.6875, y: 0.3125 },\n { x: 0.6875, y: 0.3125 },\n { x: 0.6875, y: 0.3125 },\n { x: 0.6875, y: 0.3125 },\n { x: 0.6875, y: 0.3125 },\n { x: 0.6875, y: 0.3125 },\n { x: 0.8125, y: 0.3125 },\n { x: 0.8125, y: 0.3125 },\n { x: 0.8125, y: 0.3125 },\n { x: 0.8125, y: 0.3125 },\n { x: 0.8125, y: 0.3125 },\n { x: 0.8125, y: 0.3125 },\n { x: 0.9375, y: 0.3125 },\n { x: 0.9375, y: 0.3125 },\n { x: 0.9375, y: 0.3125 },\n { x: 0.9375, y: 0.3125 },\n { x: 0.9375, y: 0.3125 },\n { x: 0.9375, y: 0.3125 },\n { x: 0.0625, y: 0.4375 },\n { x: 0.0625, y: 0.4375 },\n { x: 0.0625, y: 0.4375 },\n { x: 0.0625, y: 0.4375 },\n { x: 0.0625, y: 0.4375 },\n { x: 0.0625, y: 0.4375 },\n { x: 0.1875, y: 0.4375 },\n { x: 0.1875, y: 0.4375 },\n { x: 0.1875, y: 0.4375 },\n { x: 0.1875, y: 0.4375 },\n { x: 0.1875, y: 0.4375 },\n { x: 0.1875, y: 0.4375 },\n { x: 0.3125, y: 0.4375 },\n { x: 0.3125, y: 0.4375 },\n { x: 0.3125, y: 0.4375 },\n { x: 0.3125, y: 0.4375 },\n { x: 0.3125, y: 0.4375 },\n { x: 0.3125, y: 0.4375 },\n { x: 0.4375, y: 0.4375 },\n { x: 0.4375, y: 0.4375 },\n { x: 0.4375, y: 0.4375 },\n { x: 0.4375, y: 0.4375 },\n { x: 0.4375, y: 0.4375 },\n { x: 0.4375, y: 0.4375 },\n { x: 0.5625, y: 0.4375 },\n { x: 0.5625, y: 0.4375 },\n { x: 0.5625, y: 0.4375 },\n { x: 0.5625, y: 0.4375 },\n { x: 0.5625, y: 0.4375 },\n { x: 0.5625, y: 0.4375 },\n { x: 0.6875, y: 0.4375 },\n { x: 0.6875, y: 0.4375 },\n { x: 0.6875, y: 0.4375 },\n { x: 0.6875, y: 0.4375 },\n { x: 0.6875, y: 0.4375 },\n { x: 0.6875, y: 0.4375 },\n { x: 0.8125, y: 0.4375 },\n { x: 0.8125, y: 0.4375 },\n { x: 0.8125, y: 0.4375 },\n { x: 0.8125, y: 0.4375 },\n { x: 0.8125, y: 0.4375 },\n { x: 0.8125, y: 0.4375 },\n { x: 0.9375, y: 0.4375 },\n { x: 0.9375, y: 0.4375 },\n { x: 0.9375, y: 0.4375 },\n { x: 0.9375, y: 0.4375 },\n { x: 0.9375, y: 0.4375 },\n { x: 0.9375, y: 0.4375 },\n { x: 0.0625, y: 0.5625 },\n { x: 0.0625, y: 0.5625 },\n { x: 0.0625, y: 0.5625 },\n { x: 0.0625, y: 0.5625 },\n { x: 0.0625, y: 0.5625 },\n { x: 0.0625, y: 0.5625 },\n { x: 0.1875, y: 0.5625 },\n { x: 0.1875, y: 0.5625 },\n { x: 0.1875, y: 0.5625 },\n { x: 0.1875, y: 0.5625 },\n { x: 0.1875, y: 0.5625 },\n { x: 0.1875, y: 0.5625 },\n { x: 0.3125, y: 0.5625 },\n { x: 0.3125, y: 0.5625 },\n { x: 0.3125, y: 0.5625 },\n { x: 0.3125, y: 0.5625 },\n { x: 0.3125, y: 0.5625 },\n { x: 0.3125, y: 0.5625 },\n { x: 0.4375, y: 0.5625 },\n { x: 0.4375, y: 0.5625 },\n { x: 0.4375, y: 0.5625 },\n { x: 0.4375, y: 0.5625 },\n { x: 0.4375, y: 0.5625 },\n { x: 0.4375, y: 0.5625 },\n { x: 0.5625, y: 0.5625 },\n { x: 0.5625, y: 0.5625 },\n { x: 0.5625, y: 0.5625 },\n { x: 0.5625, y: 0.5625 },\n { x: 0.5625, y: 0.5625 },\n { x: 0.5625, y: 0.5625 },\n { x: 0.6875, y: 0.5625 },\n { x: 0.6875, y: 0.5625 },\n { x: 0.6875, y: 0.5625 },\n { x: 0.6875, y: 0.5625 },\n { x: 0.6875, y: 0.5625 },\n { x: 0.6875, y: 0.5625 },\n { x: 0.8125, y: 0.5625 },\n { x: 0.8125, y: 0.5625 },\n { x: 0.8125, y: 0.5625 },\n { x: 0.8125, y: 0.5625 },\n { x: 0.8125, y: 0.5625 },\n { x: 0.8125, y: 0.5625 },\n { x: 0.9375, y: 0.5625 },\n { x: 0.9375, y: 0.5625 },\n { x: 0.9375, y: 0.5625 },\n { x: 0.9375, y: 0.5625 },\n { x: 0.9375, y: 0.5625 },\n { x: 0.9375, y: 0.5625 },\n { x: 0.0625, y: 0.6875 },\n { x: 0.0625, y: 0.6875 },\n { x: 0.0625, y: 0.6875 },\n { x: 0.0625, y: 0.6875 },\n { x: 0.0625, y: 0.6875 },\n { x: 0.0625, y: 0.6875 },\n { x: 0.1875, y: 0.6875 },\n { x: 0.1875, y: 0.6875 },\n { x: 0.1875, y: 0.6875 },\n { x: 0.1875, y: 0.6875 },\n { x: 0.1875, y: 0.6875 },\n { x: 0.1875, y: 0.6875 },\n { x: 0.3125, y: 0.6875 },\n { x: 0.3125, y: 0.6875 },\n { x: 0.3125, y: 0.6875 },\n { x: 0.3125, y: 0.6875 },\n { x: 0.3125, y: 0.6875 },\n { x: 0.3125, y: 0.6875 },\n { x: 0.4375, y: 0.6875 },\n { x: 0.4375, y: 0.6875 },\n { x: 0.4375, y: 0.6875 },\n { x: 0.4375, y: 0.6875 },\n { x: 0.4375, y: 0.6875 },\n { x: 0.4375, y: 0.6875 },\n { x: 0.5625, y: 0.6875 },\n { x: 0.5625, y: 0.6875 },\n { x: 0.5625, y: 0.6875 },\n { x: 0.5625, y: 0.6875 },\n { x: 0.5625, y: 0.6875 },\n { x: 0.5625, y: 0.6875 },\n { x: 0.6875, y: 0.6875 },\n { x: 0.6875, y: 0.6875 },\n { x: 0.6875, y: 0.6875 },\n { x: 0.6875, y: 0.6875 },\n { x: 0.6875, y: 0.6875 },\n { x: 0.6875, y: 0.6875 },\n { x: 0.8125, y: 0.6875 },\n { x: 0.8125, y: 0.6875 },\n { x: 0.8125, y: 0.6875 },\n { x: 0.8125, y: 0.6875 },\n { x: 0.8125, y: 0.6875 },\n { x: 0.8125, y: 0.6875 },\n { x: 0.9375, y: 0.6875 },\n { x: 0.9375, y: 0.6875 },\n { x: 0.9375, y: 0.6875 },\n { x: 0.9375, y: 0.6875 },\n { x: 0.9375, y: 0.6875 },\n { x: 0.9375, y: 0.6875 },\n { x: 0.0625, y: 0.8125 },\n { x: 0.0625, y: 0.8125 },\n { x: 0.0625, y: 0.8125 },\n { x: 0.0625, y: 0.8125 },\n { x: 0.0625, y: 0.8125 },\n { x: 0.0625, y: 0.8125 },\n { x: 0.1875, y: 0.8125 },\n { x: 0.1875, y: 0.8125 },\n { x: 0.1875, y: 0.8125 },\n { x: 0.1875, y: 0.8125 },\n { x: 0.1875, y: 0.8125 },\n { x: 0.1875, y: 0.8125 },\n { x: 0.3125, y: 0.8125 },\n { x: 0.3125, y: 0.8125 },\n { x: 0.3125, y: 0.8125 },\n { x: 0.3125, y: 0.8125 },\n { x: 0.3125, y: 0.8125 },\n { x: 0.3125, y: 0.8125 },\n { x: 0.4375, y: 0.8125 },\n { x: 0.4375, y: 0.8125 },\n { x: 0.4375, y: 0.8125 },\n { x: 0.4375, y: 0.8125 },\n { x: 0.4375, y: 0.8125 },\n { x: 0.4375, y: 0.8125 },\n { x: 0.5625, y: 0.8125 },\n { x: 0.5625, y: 0.8125 },\n { x: 0.5625, y: 0.8125 },\n { x: 0.5625, y: 0.8125 },\n { x: 0.5625, y: 0.8125 },\n { x: 0.5625, y: 0.8125 },\n { x: 0.6875, y: 0.8125 },\n { x: 0.6875, y: 0.8125 },\n { x: 0.6875, y: 0.8125 },\n { x: 0.6875, y: 0.8125 },\n { x: 0.6875, y: 0.8125 },\n { x: 0.6875, y: 0.8125 },\n { x: 0.8125, y: 0.8125 },\n { x: 0.8125, y: 0.8125 },\n { x: 0.8125, y: 0.8125 },\n { x: 0.8125, y: 0.8125 },\n { x: 0.8125, y: 0.8125 },\n { x: 0.8125, y: 0.8125 },\n { x: 0.9375, y: 0.8125 },\n { x: 0.9375, y: 0.8125 },\n { x: 0.9375, y: 0.8125 },\n { x: 0.9375, y: 0.8125 },\n { x: 0.9375, y: 0.8125 },\n { x: 0.9375, y: 0.8125 },\n { x: 0.0625, y: 0.9375 },\n { x: 0.0625, y: 0.9375 },\n { x: 0.0625, y: 0.9375 },\n { x: 0.0625, y: 0.9375 },\n { x: 0.0625, y: 0.9375 },\n { x: 0.0625, y: 0.9375 },\n { x: 0.1875, y: 0.9375 },\n { x: 0.1875, y: 0.9375 },\n { x: 0.1875, y: 0.9375 },\n { x: 0.1875, y: 0.9375 },\n { x: 0.1875, y: 0.9375 },\n { x: 0.1875, y: 0.9375 },\n { x: 0.3125, y: 0.9375 },\n { x: 0.3125, y: 0.9375 },\n { x: 0.3125, y: 0.9375 },\n { x: 0.3125, y: 0.9375 },\n { x: 0.3125, y: 0.9375 },\n { x: 0.3125, y: 0.9375 },\n { x: 0.4375, y: 0.9375 },\n { x: 0.4375, y: 0.9375 },\n { x: 0.4375, y: 0.9375 },\n { x: 0.4375, y: 0.9375 },\n { x: 0.4375, y: 0.9375 },\n { x: 0.4375, y: 0.9375 },\n { x: 0.5625, y: 0.9375 },\n { x: 0.5625, y: 0.9375 },\n { x: 0.5625, y: 0.9375 },\n { x: 0.5625, y: 0.9375 },\n { x: 0.5625, y: 0.9375 },\n { x: 0.5625, y: 0.9375 },\n { x: 0.6875, y: 0.9375 },\n { x: 0.6875, y: 0.9375 },\n { x: 0.6875, y: 0.9375 },\n { x: 0.6875, y: 0.9375 },\n { x: 0.6875, y: 0.9375 },\n { x: 0.6875, y: 0.9375 },\n { x: 0.8125, y: 0.9375 },\n { x: 0.8125, y: 0.9375 },\n { x: 0.8125, y: 0.9375 },\n { x: 0.8125, y: 0.9375 },\n { x: 0.8125, y: 0.9375 },\n { x: 0.8125, y: 0.9375 },\n { x: 0.9375, y: 0.9375 },\n { x: 0.9375, y: 0.9375 },\n { x: 0.9375, y: 0.9375 },\n { x: 0.9375, y: 0.9375 },\n { x: 0.9375, y: 0.9375 },\n { x: 0.9375, y: 0.9375 },\n];\n", "import * as tf from '../../dist/tfjs.esm.js';\nimport * as box from './box';\nimport * as anchors from './anchors';\nimport { Tensor, GraphModel } from '../tfjs/types';\n\nexport class HandDetector {\n model: GraphModel;\n anchors: number[][];\n anchorsTensor: Tensor;\n inputSize: number;\n inputSizeTensor: Tensor;\n doubleInputSizeTensor: Tensor;\n\n constructor(model) {\n this.model = model;\n this.anchors = anchors.anchors.map((anchor) => [anchor.x, anchor.y]);\n this.anchorsTensor = tf.tensor2d(this.anchors);\n // @ts-ignore model is not undefined here\n this.inputSize = this.model?.inputs[0].shape[2];\n this.inputSizeTensor = tf.tensor1d([this.inputSize, this.inputSize]);\n this.doubleInputSizeTensor = tf.tensor1d([this.inputSize * 2, this.inputSize * 2]);\n }\n\n normalizeBoxes(boxes) {\n return tf.tidy(() => {\n const boxOffsets = tf.slice(boxes, [0, 0], [-1, 2]);\n const boxSizes = tf.slice(boxes, [0, 2], [-1, 2]);\n const boxCenterPoints = tf.add(tf.div(boxOffsets, this.inputSizeTensor), this.anchorsTensor);\n const halfBoxSizes = tf.div(boxSizes, this.doubleInputSizeTensor);\n const startPoints = tf.mul(tf.sub(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n const endPoints = tf.mul(tf.add(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n return tf.concat2d([startPoints, endPoints], 1);\n });\n }\n\n normalizeLandmarks(rawPalmLandmarks, index) {\n return tf.tidy(() => {\n const landmarks = tf.add(tf.div(tf.reshape(rawPalmLandmarks, [-1, 7, 2]), this.inputSizeTensor), this.anchors[index]);\n return tf.mul(landmarks, this.inputSizeTensor);\n });\n }\n\n async getBoxes(input, config) {\n const batched = this.model.predict(input) as Tensor;\n const predictions = tf.squeeze(batched);\n tf.dispose(batched);\n const scoresT = tf.tidy(() => tf.squeeze(tf.sigmoid(tf.slice(predictions, [0, 0], [-1, 1]))));\n const scores = await scoresT.data();\n const rawBoxes = tf.slice(predictions, [0, 1], [-1, 4]);\n const boxes = this.normalizeBoxes(rawBoxes);\n tf.dispose(rawBoxes);\n const filteredT = await tf.image.nonMaxSuppressionAsync(boxes, scores, config.hand.maxDetected, config.hand.iouThreshold, config.hand.minConfidence);\n const filtered = await filteredT.array();\n\n tf.dispose(scoresT);\n tf.dispose(filteredT);\n const hands: Array<{ box: Tensor, palmLandmarks: Tensor, confidence: number }> = [];\n for (const index of filtered) {\n if (scores[index] >= config.hand.minConfidence) {\n const matchingBox = tf.slice(boxes, [index, 0], [1, -1]);\n const rawPalmLandmarks = tf.slice(predictions, [index, 5], [1, 14]);\n const palmLandmarks = tf.tidy(() => tf.reshape(this.normalizeLandmarks(rawPalmLandmarks, index), [-1, 2]));\n tf.dispose(rawPalmLandmarks);\n hands.push({ box: matchingBox, palmLandmarks, confidence: scores[index] });\n }\n }\n tf.dispose(predictions);\n tf.dispose(boxes);\n return hands;\n }\n\n async estimateHandBounds(input, config): Promise<{ startPoint: number[]; endPoint: number[]; palmLandmarks: number[]; confidence: number }[]> {\n const inputHeight = input.shape[1];\n const inputWidth = input.shape[2];\n const image = tf.tidy(() => tf.sub(tf.div(tf.image.resizeBilinear(input, [this.inputSize, this.inputSize]), 127.5), 1));\n const predictions = await this.getBoxes(image, config);\n tf.dispose(image);\n const hands: Array<{ startPoint: number[]; endPoint: number[]; palmLandmarks: number[]; confidence: number }> = [];\n if (!predictions || predictions.length === 0) return hands;\n for (const prediction of predictions) {\n const boxes = await prediction.box.data();\n const startPoint = boxes.slice(0, 2);\n const endPoint = boxes.slice(2, 4);\n const palmLandmarks = await prediction.palmLandmarks.array();\n tf.dispose(prediction.box);\n tf.dispose(prediction.palmLandmarks);\n hands.push(box.scaleBoxCoordinates({ startPoint, endPoint, palmLandmarks, confidence: prediction.confidence }, [inputWidth / this.inputSize, inputHeight / this.inputSize]));\n }\n return hands;\n }\n}\n", "export function normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\n\nexport function computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\n\nexport const buildTranslationMatrix = (x, y) => [[1, 0, x], [0, 1, y], [0, 0, 1]];\n\nexport function dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\n\nexport function getColumnFrom2DArr(arr, columnIndex) {\n const column: Array<number> = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\n\nexport function multiplyTransformMatrices(mat1, mat2) {\n const product: Array<number[]> = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\n\nexport function buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\n\nexport function invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\n\nexport function rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\n", "import * as tf from '../../dist/tfjs.esm.js';\nimport * as box from './box';\nimport * as util from './util';\nimport * as detector from './handdetector';\nimport { Tensor, GraphModel } from '../tfjs/types';\n\nconst palmBoxEnlargeFactor = 5; // default 3\nconst handBoxEnlargeFactor = 1.65; // default 1.65\nconst palmLandmarkIds = [0, 5, 9, 13, 17, 1, 2];\nconst palmLandmarksPalmBase = 0;\nconst palmLandmarksMiddleFingerBase = 2;\n\nexport class HandPipeline {\n handDetector: detector.HandDetector;\n handPoseModel: GraphModel;\n inputSize: number;\n storedBoxes: Array<{ startPoint: number[]; endPoint: number[]; palmLandmarks: number[]; confidence: number } | null>;\n skipped: number;\n detectedHands: number;\n\n constructor(handDetector, handPoseModel) {\n this.handDetector = handDetector;\n this.handPoseModel = handPoseModel;\n // @ts-ignore model is not undefined here\n this.inputSize = this.handPoseModel?.inputs[0].shape[2];\n this.storedBoxes = [];\n this.skipped = 0;\n this.detectedHands = 0;\n }\n\n // eslint-disable-next-line class-methods-use-this\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint };\n }\n\n getBoxForPalmLandmarks(palmLandmarks, rotationMatrix) {\n const rotatedPalmLandmarks = palmLandmarks.map((coord) => util.rotatePoint([...coord, 1], rotationMatrix));\n const boxAroundPalm = this.calculateLandmarksBoundingBox(rotatedPalmLandmarks);\n return box.enlargeBox(box.squarifyBox(boxAroundPalm), palmBoxEnlargeFactor);\n }\n\n getBoxForHandLandmarks(landmarks) {\n const boundingBox = this.calculateLandmarksBoundingBox(landmarks);\n const boxAroundHand = box.enlargeBox(box.squarifyBox(boundingBox), handBoxEnlargeFactor);\n boxAroundHand.palmLandmarks = [];\n for (let i = 0; i < palmLandmarkIds.length; i++) {\n boxAroundHand.palmLandmarks.push(landmarks[palmLandmarkIds[i]].slice(0, 2));\n }\n return boxAroundHand;\n }\n\n transformRawCoords(rawCoords, box2, angle, rotationMatrix) {\n const boxSize = box.getBoxSize(box2);\n const scaleFactor = [boxSize[0] / this.inputSize, boxSize[1] / this.inputSize, (boxSize[0] + boxSize[1]) / this.inputSize / 2];\n const coordsScaled = rawCoords.map((coord) => [\n scaleFactor[0] * (coord[0] - this.inputSize / 2),\n scaleFactor[1] * (coord[1] - this.inputSize / 2),\n scaleFactor[2] * coord[2],\n ]);\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => {\n const rotated = util.rotatePoint(coord, coordsRotationMatrix);\n return [...rotated, coord[2]];\n });\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...box.getBoxCenter(box2), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => [\n Math.trunc(coord[0] + originalBoxCenter[0]),\n Math.trunc(coord[1] + originalBoxCenter[1]),\n Math.trunc(coord[2]),\n ]);\n }\n\n async estimateHands(image, config) {\n let useFreshBox = false;\n\n // run new detector every skipFrames unless we only want box to start with\n let boxes;\n\n // console.log(this.skipped, config.hand.skipFrames, !config.hand.landmarks, !config.skipFrame);\n if ((this.skipped === 0) || (this.skipped > config.hand.skipFrames) || !config.hand.landmarks || !config.skipFrame) {\n boxes = await this.handDetector.estimateHandBounds(image, config);\n this.skipped = 0;\n }\n if (config.skipFrame) this.skipped++;\n\n // if detector result count doesn't match current working set, use it to reset current working set\n if (boxes && (boxes.length > 0) && ((boxes.length !== this.detectedHands) && (this.detectedHands !== config.hand.maxDetected) || !config.hand.landmarks)) {\n this.detectedHands = 0;\n this.storedBoxes = [...boxes];\n // for (const possible of boxes) this.storedBoxes.push(possible);\n if (this.storedBoxes.length > 0) useFreshBox = true;\n }\n const hands: Array<{ landmarks?: number[], confidence: number, box: { topLeft: number[], bottomRight: number[] } }> = [];\n\n // go through working set of boxes\n for (let i = 0; i < this.storedBoxes.length; i++) {\n const currentBox = this.storedBoxes[i];\n if (!currentBox) continue;\n if (config.hand.landmarks) {\n const angle = config.hand.rotation ? util.computeRotation(currentBox.palmLandmarks[palmLandmarksPalmBase], currentBox.palmLandmarks[palmLandmarksMiddleFingerBase]) : 0;\n const palmCenter = box.getBoxCenter(currentBox);\n const palmCenterNormalized = [palmCenter[0] / image.shape[2], palmCenter[1] / image.shape[1]];\n const rotatedImage = config.hand.rotation && tf.ENV.flags.IS_BROWSER ? tf.image.rotateWithOffset(image, angle, 0, palmCenterNormalized) : image.clone();\n const rotationMatrix = util.buildRotationMatrix(-angle, palmCenter);\n const newBox = useFreshBox ? this.getBoxForPalmLandmarks(currentBox.palmLandmarks, rotationMatrix) : currentBox;\n const croppedInput = box.cutBoxFromImageAndResize(newBox, rotatedImage, [this.inputSize, this.inputSize]);\n const handImage = tf.div(croppedInput, 255);\n tf.dispose(croppedInput);\n tf.dispose(rotatedImage);\n const [confidenceT, keypoints] = await this.handPoseModel.predict(handImage) as Array<Tensor>;\n tf.dispose(handImage);\n const confidence = confidenceT.dataSync()[0];\n tf.dispose(confidenceT);\n if (confidence >= config.hand.minConfidence) {\n const keypointsReshaped = tf.reshape(keypoints, [-1, 3]);\n const rawCoords = await keypointsReshaped.array();\n tf.dispose(keypoints);\n tf.dispose(keypointsReshaped);\n const coords = this.transformRawCoords(rawCoords, newBox, angle, rotationMatrix);\n const nextBoundingBox = this.getBoxForHandLandmarks(coords);\n this.storedBoxes[i] = { ...nextBoundingBox, confidence };\n const result = {\n landmarks: coords,\n confidence,\n box: { topLeft: nextBoundingBox.startPoint, bottomRight: nextBoundingBox.endPoint },\n };\n hands.push(result);\n } else {\n this.storedBoxes[i] = null;\n }\n tf.dispose(keypoints);\n } else {\n // const enlarged = box.enlargeBox(box.squarifyBox(box.shiftBox(currentBox, HAND_BOX_SHIFT_VECTOR)), handBoxEnlargeFactor);\n const enlarged = box.enlargeBox(box.squarifyBox(currentBox), handBoxEnlargeFactor);\n const result = {\n confidence: currentBox.confidence,\n box: { topLeft: enlarged.startPoint, bottomRight: enlarged.endPoint },\n };\n hands.push(result);\n }\n }\n this.storedBoxes = this.storedBoxes.filter((a) => a !== null);\n this.detectedHands = hands.length;\n return hands;\n }\n}\n", "/**\n * HandPose module entry point\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport * as handdetector from './handdetector';\nimport * as handpipeline from './handpipeline';\nimport { Hand } from '../result';\nimport { Tensor, GraphModel } from '../tfjs/types';\nimport { Config } from '../config';\n\nconst meshAnnotations = {\n thumb: [1, 2, 3, 4],\n indexFinger: [5, 6, 7, 8],\n middleFinger: [9, 10, 11, 12],\n ringFinger: [13, 14, 15, 16],\n pinky: [17, 18, 19, 20],\n palmBase: [0],\n};\n\nlet handDetectorModel: GraphModel | null;\nlet handPoseModel: GraphModel | null;\nlet handPipeline: handpipeline.HandPipeline;\n\nexport async function predict(input: Tensor, config: Config): Promise<Hand[]> {\n const predictions = await handPipeline.estimateHands(input, config);\n if (!predictions) return [];\n const hands: Array<Hand> = [];\n for (let i = 0; i < predictions.length; i++) {\n const annotations = {};\n if (predictions[i].landmarks) {\n for (const key of Object.keys(meshAnnotations)) {\n // @ts-ignore landmarks are not undefined\n annotations[key] = meshAnnotations[key].map((index) => predictions[i].landmarks[index]);\n }\n }\n\n const keypoints = predictions[i].landmarks as unknown as Array<[number, number, number]>;\n\n let box: [number, number, number, number] = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, 0, 0]; // maximums so conditionals work\n let boxRaw: [number, number, number, number] = [0, 0, 0, 0];\n if (keypoints && keypoints.length > 0) { // if we have landmarks, calculate box based on landmarks\n for (const pt of keypoints) {\n if (pt[0] < box[0]) box[0] = pt[0];\n if (pt[1] < box[1]) box[1] = pt[1];\n if (pt[0] > box[2]) box[2] = pt[0];\n if (pt[1] > box[3]) box[3] = pt[1];\n }\n box[2] -= box[0];\n box[3] -= box[1];\n boxRaw = [box[0] / (input.shape[2] || 0), box[1] / (input.shape[1] || 0), box[2] / (input.shape[2] || 0), box[3] / (input.shape[1] || 0)];\n } else { // otherwise use box from prediction\n box = predictions[i].box ? [\n Math.trunc(Math.max(0, predictions[i].box.topLeft[0])),\n Math.trunc(Math.max(0, predictions[i].box.topLeft[1])),\n Math.trunc(Math.min((input.shape[2] || 0), predictions[i].box.bottomRight[0]) - Math.max(0, predictions[i].box.topLeft[0])),\n Math.trunc(Math.min((input.shape[1] || 0), predictions[i].box.bottomRight[1]) - Math.max(0, predictions[i].box.topLeft[1])),\n ] : [0, 0, 0, 0];\n boxRaw = [\n (predictions[i].box.topLeft[0]) / (input.shape[2] || 0),\n (predictions[i].box.topLeft[1]) / (input.shape[1] || 0),\n (predictions[i].box.bottomRight[0] - predictions[i].box.topLeft[0]) / (input.shape[2] || 0),\n (predictions[i].box.bottomRight[1] - predictions[i].box.topLeft[1]) / (input.shape[1] || 0),\n ];\n }\n hands.push({ id: i, score: Math.round(100 * predictions[i].confidence) / 100, box, boxRaw, keypoints, annotations });\n }\n return hands;\n}\n\nexport async function load(config: Config): Promise<[GraphModel | null, GraphModel | null]> {\n if (!handDetectorModel || !handPoseModel) {\n // @ts-ignore type mismatch on GraphModel\n [handDetectorModel, handPoseModel] = await Promise.all([\n config.hand.enabled ? tf.loadGraphModel(join(config.modelBasePath, config.hand.detector.modelPath), { fromTFHub: config.hand.detector.modelPath.includes('tfhub.dev') }) : null,\n config.hand.landmarks ? tf.loadGraphModel(join(config.modelBasePath, config.hand.skeleton.modelPath), { fromTFHub: config.hand.skeleton.modelPath.includes('tfhub.dev') }) : null,\n ]);\n if (config.hand.enabled) {\n if (!handDetectorModel || !handDetectorModel['modelUrl']) log('load model failed:', config.hand.detector.modelPath);\n else if (config.debug) log('load model:', handDetectorModel['modelUrl']);\n if (!handPoseModel || !handPoseModel['modelUrl']) log('load model failed:', config.hand.skeleton.modelPath);\n else if (config.debug) log('load model:', handPoseModel['modelUrl']);\n }\n } else {\n if (config.debug) log('cached model:', handDetectorModel['modelUrl']);\n if (config.debug) log('cached model:', handPoseModel['modelUrl']);\n }\n const handDetector = new handdetector.HandDetector(handDetectorModel);\n handPipeline = new handpipeline.HandPipeline(handDetector, handPoseModel);\n return [handDetectorModel, handPoseModel];\n}\n", "export const full = [\n 'nose',\n 'leftEyeInside',\n 'leftEye',\n 'leftEyeOutside',\n 'rightEyeInside',\n 'rightEye',\n 'rightEyeOutside',\n 'leftEar',\n 'rightEar',\n 'leftMouth',\n 'rightMouth',\n 'leftShoulder',\n 'rightShoulder',\n 'leftElbow',\n 'rightElbow',\n 'leftWrist',\n 'rightWrist',\n 'leftPalm',\n 'rightPalm',\n 'leftIndex',\n 'rightIndex',\n 'leftPinky',\n 'rightPinky',\n 'leftHip',\n 'rightHip',\n 'leftKnee',\n 'rightKnee',\n 'leftAnkle',\n 'rightAnkle',\n 'leftHeel',\n 'rightHeel',\n 'leftFoot',\n 'rightFoot',\n 'midHip',\n 'forehead',\n 'leftThumb',\n 'leftHand',\n 'rightThumb',\n 'rightHand',\n];\n\nexport const upper = [\n 'nose',\n 'leftEyeInside',\n 'leftEye',\n 'leftEyeOutside',\n 'rightEyeInside',\n 'rightEye',\n 'rightEyeOutside',\n 'leftEar',\n 'rightEar',\n 'leftMouth',\n 'rightMouth',\n 'leftShoulder',\n 'rightShoulder',\n 'leftElbow',\n 'rightElbow',\n 'left:15',\n 'right:16',\n 'left:17',\n 'right:18',\n 'left:19',\n 'right:20',\n 'left:21',\n 'right:22',\n 'leftChest',\n 'rightChest',\n 'neck',\n 'forehead',\n 'left:27',\n 'right:28',\n 'left:29',\n 'right:30',\n];\n", "/**\n * BlazePose Module\n */\n\n// paper: https://ai.googleblog.com/2020/08/on-device-real-time-body-pose-tracking.html\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport * as annotations from './annotations';\nimport { Tensor, GraphModel } from '../tfjs/types';\nimport { Body } from '../result';\nimport { Config } from '../config';\n\nlet model: GraphModel;\n\nexport async function load(config: Config): Promise<GraphModel> {\n if (!model) {\n // @ts-ignore type mismatch for Graphmodel\n model = await tf.loadGraphModel(join(config.modelBasePath, config.body.modelPath));\n model['width'] = parseInt(model['signature'].inputs['input_1:0'].tensorShape.dim[2].size);\n model['height'] = parseInt(model['signature'].inputs['input_1:0'].tensorShape.dim[1].size);\n if (!model || !model['modelUrl']) log('load model failed:', config.body.modelPath);\n else if (config.debug) log('load model:', model['modelUrl']);\n } else if (config.debug) log('cached model:', model['modelUrl']);\n return model;\n}\n\nexport async function predict(image: Tensor, config: Config): Promise<Body[]> {\n if (!model) return [];\n if (!config.body.enabled) return [];\n const imgSize = { width: (image.shape[2] || 0), height: (image.shape[1] || 0) };\n const resize = tf.image.resizeBilinear(image, [model['width'], model['height']], false);\n const normalize = tf.div(resize, [255.0]);\n tf.dispose(resize);\n const resT = await model.predict(normalize) as Array<Tensor>;\n const findT = resT.find((t) => (t.size === 195 || t.size === 155));\n const points = await findT?.data() || []; // order of output tensors may change between models, full has 195 and upper has 155 items\n resT.forEach((t) => tf.dispose(t));\n tf.dispose(normalize);\n const keypoints: Array<{ id, part, position: [number, number, number], positionRaw: [number, number, number], score, presence }> = [];\n const labels = points?.length === 195 ? annotations.full : annotations.upper; // full model has 39 keypoints, upper has 31 keypoints\n const depth = 5; // each points has x,y,z,visibility,presence\n for (let i = 0; i < points.length / depth; i++) {\n keypoints.push({\n id: i,\n part: labels[i],\n position: [\n Math.trunc(imgSize.width * points[depth * i + 0] / 255), // return normalized x value istead of 0..255\n Math.trunc(imgSize.height * points[depth * i + 1] / 255), // return normalized y value istead of 0..255\n Math.trunc(points[depth * i + 2]) + 0, // fix negative zero\n ],\n positionRaw: [\n points[depth * i + 0] / 255, // return x value normalized to 0..1\n points[depth * i + 1] / 255, // return y value normalized to 0..1\n points[depth * i + 2] + 0, // fix negative zero\n ],\n score: (100 - Math.trunc(100 / (1 + Math.exp(points[depth * i + 3])))) / 100, // reverse sigmoid value\n presence: (100 - Math.trunc(100 / (1 + Math.exp(points[depth * i + 4])))) / 100, // reverse sigmoid value\n });\n }\n const x = keypoints.map((a) => a.position[0]);\n const y = keypoints.map((a) => a.position[1]);\n const box: [number, number, number, number] = [\n Math.min(...x),\n Math.min(...y),\n Math.max(...x) - Math.min(...x),\n Math.max(...y) - Math.min(...x),\n ];\n const boxRaw: [number, number, number, number] = [0, 0, 0, 0]; // not yet implemented\n const score = keypoints.reduce((prev, curr) => (curr.score > prev ? curr.score : prev), 0);\n return [{ id: 0, score, box, boxRaw, keypoints }];\n}\n", "/**\n * EfficientPose Module\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport { Body } from '../result';\nimport { GraphModel, Tensor } from '../tfjs/types';\nimport { Config } from '../config';\n\nlet model: GraphModel;\n\ntype Keypoints = { score: number, part: string, position: [number, number], positionRaw: [number, number] };\n\nconst keypoints: Array<Keypoints> = [];\nlet box: [number, number, number, number] = [0, 0, 0, 0];\nlet boxRaw: [number, number, number, number] = [0, 0, 0, 0];\nlet score = 0;\nlet skipped = Number.MAX_SAFE_INTEGER;\n\nconst bodyParts = ['head', 'neck', 'rightShoulder', 'rightElbow', 'rightWrist', 'chest', 'leftShoulder', 'leftElbow', 'leftWrist', 'pelvis', 'rightHip', 'rightKnee', 'rightAnkle', 'leftHip', 'leftKnee', 'leftAnkle'];\n\nexport async function load(config: Config): Promise<GraphModel> {\n if (!model) {\n // @ts-ignore type mismatch on GraphModel\n model = await tf.loadGraphModel(join(config.modelBasePath, config.body.modelPath));\n if (!model || !model['modelUrl']) log('load model failed:', config.body.modelPath);\n else if (config.debug) log('load model:', model['modelUrl']);\n } else if (config.debug) log('cached model:', model['modelUrl']);\n return model;\n}\n\n// performs argmax and max functions on a 2d tensor\nfunction max2d(inputs, minScore) {\n const [width, height] = inputs.shape;\n return tf.tidy(() => {\n // modulus op implemented in tf\n const mod = (a, b) => tf.sub(a, tf.mul(tf.div(a, tf.scalar(b, 'int32')), tf.scalar(b, 'int32')));\n // combine all data\n const reshaped = tf.reshape(inputs, [height * width]);\n // get highest score\n const newScore = tf.max(reshaped, 0).dataSync()[0]; // inside tf.tidy\n if (newScore > minScore) {\n // skip coordinate calculation is score is too low\n const coords = tf.argMax(reshaped, 0);\n const x = mod(coords, width).dataSync()[0]; // inside tf.tidy\n const y = tf.div(coords, tf.scalar(width, 'int32')).dataSync()[0]; // inside tf.tidy\n return [x, y, newScore];\n }\n return [0, 0, newScore];\n });\n}\n\nexport async function predict(image: Tensor, config: Config): Promise<Body[]> {\n if ((skipped < config.body.skipFrames) && config.skipFrame && Object.keys(keypoints).length > 0) {\n skipped++;\n return [{ id: 0, score, box, boxRaw, keypoints }];\n }\n skipped = 0;\n return new Promise(async (resolve) => {\n const tensor = tf.tidy(() => {\n if (!model.inputs[0].shape) return null;\n const resize = tf.image.resizeBilinear(image, [model.inputs[0].shape[2], model.inputs[0].shape[1]], false);\n const enhance = tf.mul(resize, 2);\n const norm = enhance.sub(1);\n return norm;\n });\n\n let resT;\n if (config.body.enabled) resT = await model.predict(tensor);\n tf.dispose(tensor);\n\n if (resT) {\n keypoints.length = 0;\n const squeeze = resT.squeeze();\n tf.dispose(resT);\n // body parts are basically just a stack of 2d tensors\n const stack = squeeze.unstack(2);\n tf.dispose(squeeze);\n // process each unstacked tensor as a separate body part\n for (let id = 0; id < stack.length; id++) {\n // actual processing to get coordinates and score\n const [x, y, partScore] = max2d(stack[id], config.body.minConfidence);\n if (score > config.body.minConfidence) {\n keypoints.push({\n score: Math.round(100 * partScore) / 100,\n part: bodyParts[id],\n positionRaw: [ // normalized to 0..1\n // @ts-ignore model is not undefined here\n x / model.inputs[0].shape[2], y / model.inputs[0].shape[1],\n ],\n position: [ // normalized to input image size\n // @ts-ignore model is not undefined here\n Math.round(image.shape[2] * x / model.inputs[0].shape[2]), Math.round(image.shape[1] * y / model.inputs[0].shape[1]),\n ],\n });\n }\n }\n stack.forEach((s) => tf.dispose(s));\n }\n score = keypoints.reduce((prev, curr) => (curr.score > prev ? curr.score : prev), 0);\n const x = keypoints.map((a) => a.position[0]);\n const y = keypoints.map((a) => a.position[1]);\n box = [\n Math.min(...x),\n Math.min(...y),\n Math.max(...x) - Math.min(...x),\n Math.max(...y) - Math.min(...y),\n ];\n const xRaw = keypoints.map((a) => a.positionRaw[0]);\n const yRaw = keypoints.map((a) => a.positionRaw[1]);\n boxRaw = [\n Math.min(...xRaw),\n Math.min(...yRaw),\n Math.max(...xRaw) - Math.min(...xRaw),\n Math.max(...yRaw) - Math.min(...yRaw),\n ];\n resolve([{ id: 0, score, box, boxRaw, keypoints }]);\n });\n}\n", "/**\n * EfficientPose Module\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport { Body } from '../result';\nimport { GraphModel, Tensor } from '../tfjs/types';\nimport { Config } from '../config';\n\nlet model: GraphModel;\n\ntype Keypoints = { score: number, part: string, position: [number, number], positionRaw: [number, number] };\n\nconst keypoints: Array<Keypoints> = [];\nlet box: [number, number, number, number] = [0, 0, 0, 0];\nlet boxRaw: [number, number, number, number] = [0, 0, 0, 0];\nlet score = 0;\nlet skipped = Number.MAX_SAFE_INTEGER;\n\nconst bodyParts = ['nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder', 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist', 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle'];\n\nexport async function load(config: Config): Promise<GraphModel> {\n if (!model) {\n // @ts-ignore type mismatch on GraphModel\n model = await tf.loadGraphModel(join(config.modelBasePath, config.body.modelPath));\n if (!model || !model['modelUrl']) log('load model failed:', config.body.modelPath);\n else if (config.debug) log('load model:', model['modelUrl']);\n } else if (config.debug) log('cached model:', model['modelUrl']);\n return model;\n}\n\nexport async function predict(image: Tensor, config: Config): Promise<Body[]> {\n if ((skipped < config.body.skipFrames) && config.skipFrame && Object.keys(keypoints).length > 0) {\n skipped++;\n return [{ id: 0, score, box, boxRaw, keypoints }];\n }\n skipped = 0;\n return new Promise(async (resolve) => {\n const tensor = tf.tidy(() => {\n if (!model.inputs[0].shape) return null;\n const resize = tf.image.resizeBilinear(image, [model.inputs[0].shape[2], model.inputs[0].shape[1]], false);\n const cast = tf.cast(resize, 'int32');\n return cast;\n });\n\n let resT;\n if (config.body.enabled) resT = await model.predict(tensor);\n tf.dispose(tensor);\n\n if (resT) {\n keypoints.length = 0;\n const res = await resT.array();\n tf.dispose(resT);\n const kpt = res[0][0];\n for (let id = 0; id < kpt.length; id++) {\n score = kpt[id][2];\n if (score > config.body.minConfidence) {\n keypoints.push({\n score: Math.round(100 * score) / 100,\n part: bodyParts[id],\n positionRaw: [ // normalized to 0..1\n kpt[id][1],\n kpt[id][0],\n ],\n position: [ // normalized to input image size\n Math.round((image.shape[2] || 0) * kpt[id][1]),\n Math.round((image.shape[1] || 0) * kpt[id][0]),\n ],\n });\n }\n }\n }\n score = keypoints.reduce((prev, curr) => (curr.score > prev ? curr.score : prev), 0);\n const x = keypoints.map((a) => a.position[0]);\n const y = keypoints.map((a) => a.position[1]);\n box = [\n Math.min(...x),\n Math.min(...y),\n Math.max(...x) - Math.min(...x),\n Math.max(...y) - Math.min(...y),\n ];\n const xRaw = keypoints.map((a) => a.positionRaw[0]);\n const yRaw = keypoints.map((a) => a.positionRaw[1]);\n boxRaw = [\n Math.min(...xRaw),\n Math.min(...yRaw),\n Math.max(...xRaw) - Math.min(...xRaw),\n Math.max(...yRaw) - Math.min(...yRaw),\n ];\n resolve([{ id: 0, score, box, boxRaw, keypoints }]);\n });\n}\n", "/**\n * CoCo Labels used by object detection modules\n */\nexport const labels = [\n { class: 1, label: 'person' },\n { class: 2, label: 'bicycle' },\n { class: 3, label: 'car' },\n { class: 4, label: 'motorcycle' },\n { class: 5, label: 'airplane' },\n { class: 6, label: 'bus' },\n { class: 7, label: 'train' },\n { class: 8, label: 'truck' },\n { class: 9, label: 'boat' },\n { class: 10, label: 'traffic light' },\n { class: 11, label: 'fire hydrant' },\n { class: 12, label: 'stop sign' },\n { class: 13, label: 'parking meter' },\n { class: 14, label: 'bench' },\n { class: 15, label: 'bird' },\n { class: 16, label: 'cat' },\n { class: 17, label: 'dog' },\n { class: 18, label: 'horse' },\n { class: 19, label: 'sheep' },\n { class: 20, label: 'cow' },\n { class: 21, label: 'elephant' },\n { class: 22, label: 'bear' },\n { class: 23, label: 'zebra' },\n { class: 24, label: 'giraffe' },\n { class: 25, label: 'backpack' },\n { class: 26, label: 'umbrella' },\n { class: 27, label: 'handbag' },\n { class: 28, label: 'tie' },\n { class: 29, label: 'suitcase' },\n { class: 30, label: 'frisbee' },\n { class: 31, label: 'skis' },\n { class: 32, label: 'snowboard' },\n { class: 33, label: 'sports ball' },\n { class: 34, label: 'kite' },\n { class: 35, label: 'baseball bat' },\n { class: 36, label: 'baseball glove' },\n { class: 37, label: 'skateboard' },\n { class: 38, label: 'surfboard' },\n { class: 39, label: 'tennis racket' },\n { class: 40, label: 'bottle' },\n { class: 41, label: 'wine glass' },\n { class: 42, label: 'cup' },\n { class: 43, label: 'fork' },\n { class: 44, label: 'knife' },\n { class: 45, label: 'spoon' },\n { class: 46, label: 'bowl' },\n { class: 47, label: 'banana' },\n { class: 48, label: 'apple' },\n { class: 49, label: 'sandwich' },\n { class: 50, label: 'orange' },\n { class: 51, label: 'broccoli' },\n { class: 52, label: 'carrot' },\n { class: 53, label: 'hot dog' },\n { class: 54, label: 'pizza' },\n { class: 55, label: 'donut' },\n { class: 56, label: 'cake' },\n { class: 57, label: 'chair' },\n { class: 58, label: 'couch' },\n { class: 59, label: 'potted plant' },\n { class: 60, label: 'bed' },\n { class: 61, label: 'dining table' },\n { class: 62, label: 'toilet' },\n { class: 63, label: 'tv' },\n { class: 64, label: 'laptop' },\n { class: 65, label: 'mouse' },\n { class: 66, label: 'remote' },\n { class: 67, label: 'keyboard' },\n { class: 68, label: 'cell phone' },\n { class: 69, label: 'microwave' },\n { class: 70, label: 'oven' },\n { class: 71, label: 'toaster' },\n { class: 72, label: 'sink' },\n { class: 73, label: 'refrigerator' },\n { class: 74, label: 'book' },\n { class: 75, label: 'clock' },\n { class: 76, label: 'vase' },\n { class: 77, label: 'scissors' },\n { class: 78, label: 'teddy bear' },\n { class: 79, label: 'hair drier' },\n { class: 80, label: 'toothbrush' },\n];\n", "/**\n * NanoDet object detection module\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport { labels } from './labels';\nimport { Item } from '../result';\nimport { GraphModel, Tensor } from '../tfjs/types';\nimport { Config } from '../config';\n\nlet model;\nlet last: Array<Item> = [];\nlet skipped = Number.MAX_SAFE_INTEGER;\n\nconst scaleBox = 2.5; // increase box size\n\nexport async function load(config: Config): Promise<GraphModel> {\n if (!model) {\n model = await tf.loadGraphModel(join(config.modelBasePath, config.object.modelPath));\n const inputs = Object.values(model.modelSignature['inputs']);\n model.inputSize = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : null;\n if (!model.inputSize) throw new Error(`Human: Cannot determine model inputSize: ${config.object.modelPath}`);\n if (!model || !model.modelUrl) log('load model failed:', config.object.modelPath);\n else if (config.debug) log('load model:', model.modelUrl);\n } else if (config.debug) log('cached model:', model.modelUrl);\n return model;\n}\n\nasync function process(res, inputSize, outputShape, config) {\n let id = 0;\n let results: Array<Item> = [];\n for (const strideSize of [1, 2, 4]) { // try each stride size as it detects large/medium/small objects\n // find scores, boxes, classes\n tf.tidy(async () => { // wrap in tidy to automatically deallocate temp tensors\n const baseSize = strideSize * 13; // 13x13=169, 26x26=676, 52x52=2704\n // find boxes and scores output depending on stride\n const scoresT = res.find((a) => (a.shape[1] === (baseSize ** 2) && a.shape[2] === labels.length))?.squeeze();\n const featuresT = res.find((a) => (a.shape[1] === (baseSize ** 2) && a.shape[2] < labels.length))?.squeeze();\n const boxesMax = featuresT.reshape([-1, 4, featuresT.shape[1] / 4]); // reshape [output] to [4, output / 4] where number is number of different features inside each stride\n const boxIdx = await boxesMax.argMax(2).array(); // what we need is indexes of features with highest scores, not values itself\n const scores = await scoresT.array(); // optionally use exponential scores or just as-is\n for (let i = 0; i < scoresT.shape[0]; i++) { // total strides (x * y matrix)\n for (let j = 0; j < scoresT.shape[1]; j++) { // one score for each class\n const score = scores[i][j]; // get score for current position\n if (score > config.object.minConfidence && j !== 61) {\n const cx = (0.5 + Math.trunc(i % baseSize)) / baseSize; // center.x normalized to range 0..1\n const cy = (0.5 + Math.trunc(i / baseSize)) / baseSize; // center.y normalized to range 0..1\n const boxOffset = boxIdx[i].map((a) => a * (baseSize / strideSize / inputSize)); // just grab indexes of features with highest scores\n const [x, y] = [\n cx - (scaleBox / strideSize * boxOffset[0]),\n cy - (scaleBox / strideSize * boxOffset[1]),\n ];\n const [w, h] = [\n cx + (scaleBox / strideSize * boxOffset[2]) - x,\n cy + (scaleBox / strideSize * boxOffset[3]) - y,\n ];\n let boxRaw = [x, y, w, h]; // results normalized to range 0..1\n boxRaw = boxRaw.map((a) => Math.max(0, Math.min(a, 1))); // fix out-of-bounds coords\n const box = [ // results normalized to input image pixels\n boxRaw[0] * outputShape[0],\n boxRaw[1] * outputShape[1],\n boxRaw[2] * outputShape[0],\n boxRaw[3] * outputShape[1],\n ];\n const result = {\n id: id++,\n // strideSize,\n score: Math.round(100 * score) / 100,\n class: j + 1,\n label: labels[j].label,\n // center: [Math.trunc(outputShape[0] * cx), Math.trunc(outputShape[1] * cy)],\n // centerRaw: [cx, cy],\n box: (box.map((a) => Math.trunc(a))) as [number, number, number, number],\n boxRaw: boxRaw as [number, number, number, number],\n };\n results.push(result);\n }\n }\n }\n });\n }\n // deallocate tensors\n res.forEach((t) => tf.dispose(t));\n\n // normally nms is run on raw results, but since boxes need to be calculated this way we skip calulcation of\n // unnecessary boxes and run nms only on good candidates (basically it just does IOU analysis as scores are already filtered)\n const nmsBoxes = results.map((a) => [a.boxRaw[1], a.boxRaw[0], a.boxRaw[3], a.boxRaw[2]]); // switches coordinates from x,y to y,x as expected by tf.nms\n const nmsScores = results.map((a) => a.score);\n let nmsIdx: Array<number> = [];\n if (nmsBoxes && nmsBoxes.length > 0) {\n const nms = await tf.image.nonMaxSuppressionAsync(nmsBoxes, nmsScores, config.object.maxDetected, config.object.iouThreshold, config.object.minConfidence);\n nmsIdx = await nms.data();\n tf.dispose(nms);\n }\n\n // filter & sort results\n results = results\n .filter((_val, idx) => nmsIdx.includes(idx))\n .sort((a, b) => (b.score - a.score));\n\n return results;\n}\n\nexport async function predict(image: Tensor, config: Config): Promise<Item[]> {\n if ((skipped < config.object.skipFrames) && config.skipFrame && (last.length > 0)) {\n skipped++;\n return last;\n }\n skipped = 0;\n return new Promise(async (resolve) => {\n const outputSize = [image.shape[2], image.shape[1]];\n const resize = tf.image.resizeBilinear(image, [model.inputSize, model.inputSize], false);\n const norm = tf.div(resize, 255);\n const transpose = norm.transpose([0, 3, 1, 2]);\n tf.dispose(norm);\n tf.dispose(resize);\n\n let objectT;\n if (config.object.enabled) objectT = await model.predict(transpose);\n tf.dispose(transpose);\n\n const obj = await process(objectT, model.inputSize, outputSize, config);\n last = obj;\n resolve(obj);\n });\n}\n", "/**\n * CenterNet object detection module\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport { labels } from './labels';\nimport { Item } from '../result';\nimport { GraphModel, Tensor } from '../tfjs/types';\nimport { Config } from '../config';\n\nlet model;\nlet last: Item[] = [];\nlet skipped = Number.MAX_SAFE_INTEGER;\n\nexport async function load(config: Config): Promise<GraphModel> {\n if (!model) {\n model = await tf.loadGraphModel(join(config.modelBasePath, config.object.modelPath));\n const inputs = Object.values(model.modelSignature['inputs']);\n model.inputSize = Array.isArray(inputs) ? parseInt(inputs[0].tensorShape.dim[2].size) : null;\n if (!model.inputSize) throw new Error(`Human: Cannot determine model inputSize: ${config.object.modelPath}`);\n if (!model || !model.modelUrl) log('load model failed:', config.object.modelPath);\n else if (config.debug) log('load model:', model.modelUrl);\n } else if (config.debug) log('cached model:', model.modelUrl);\n return model;\n}\n\nasync function process(res: Tensor, inputSize, outputShape, config: Config) {\n if (!res) return [];\n const results: Array<Item> = [];\n const detections = await res.array();\n const squeezeT = tf.squeeze(res);\n tf.dispose(res);\n const arr = tf.split(squeezeT, 6, 1); // x1, y1, x2, y2, score, class\n tf.dispose(squeezeT);\n const stackT = tf.stack([arr[1], arr[0], arr[3], arr[2]], 1); // reorder dims as tf.nms expects y, x\n const boxesT = tf.squeeze(stackT);\n const scoresT = tf.squeeze(arr[4]);\n const classesT = tf.squeeze(arr[5]);\n arr.forEach((t) => tf.dispose(t));\n const nmsT = await tf.image.nonMaxSuppressionAsync(boxesT, scoresT, config.object.maxDetected, config.object.iouThreshold, config.object.minConfidence);\n tf.dispose(boxesT);\n tf.dispose(scoresT);\n tf.dispose(classesT);\n const nms = await nmsT.data();\n tf.dispose(nmsT);\n let i = 0;\n for (const id of nms) {\n const score = Math.trunc(100 * detections[0][id][4]) / 100;\n const classVal = detections[0][id][5];\n const label = labels[classVal].label;\n const [x, y] = [\n detections[0][id][0] / inputSize,\n detections[0][id][1] / inputSize,\n ];\n const boxRaw = [\n x,\n y,\n detections[0][id][2] / inputSize - x,\n detections[0][id][3] / inputSize - y,\n ] as [number, number, number, number];\n const box = [\n Math.trunc(boxRaw[0] * outputShape[0]),\n Math.trunc(boxRaw[1] * outputShape[1]),\n Math.trunc(boxRaw[2] * outputShape[0]),\n Math.trunc(boxRaw[3] * outputShape[1]),\n ] as [number, number, number, number];\n results.push({ id: i++, score, class: classVal, label, box, boxRaw });\n }\n return results;\n}\n\nexport async function predict(input: Tensor, config: Config): Promise<Item[]> {\n if ((skipped < config.object.skipFrames) && config.skipFrame && (last.length > 0)) {\n skipped++;\n return last;\n }\n skipped = 0;\n return new Promise(async (resolve) => {\n const outputSize = [input.shape[2], input.shape[1]];\n const resize = tf.image.resizeBilinear(input, [model.inputSize, model.inputSize]);\n const objectT = config.object.enabled ? model.execute(resize, ['tower_0/detections']) : null;\n tf.dispose(resize);\n\n const obj = await process(objectT, model.inputSize, outputSize, config);\n last = obj;\n resolve(obj);\n });\n}\n", "/*\nWebGLImageFilter by Dominic Szablewski: <https://github.com/phoboslab/WebGLImageFilter>\n*/\n\nfunction GLProgram(gl, vertexSource, fragmentSource) {\n const _collect = function (source, prefix, collection) {\n const r = new RegExp('\\\\b' + prefix + ' \\\\w+ (\\\\w+)', 'ig');\n source.replace(r, (match, name) => {\n collection[name] = 0;\n return match;\n });\n };\n\n const _compile = function (source, type) {\n const shader = gl.createShader(type);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw new Error('Filter: GL compile failed', gl.getShaderInfoLog(shader));\n return shader;\n };\n\n this.uniform = {};\n this.attribute = {};\n const _vsh = _compile(vertexSource, gl.VERTEX_SHADER);\n const _fsh = _compile(fragmentSource, gl.FRAGMENT_SHADER);\n this.id = gl.createProgram();\n gl.attachShader(this.id, _vsh);\n gl.attachShader(this.id, _fsh);\n gl.linkProgram(this.id);\n\n if (!gl.getProgramParameter(this.id, gl.LINK_STATUS)) throw new Error('Filter: GL link failed', gl.getProgramInfoLog(this.id));\n\n gl.useProgram(this.id);\n // Collect attributes\n _collect(vertexSource, 'attribute', this.attribute);\n for (const a in this.attribute) this.attribute[a] = gl.getAttribLocation(this.id, a);\n // Collect uniforms\n _collect(vertexSource, 'uniform', this.uniform);\n _collect(fragmentSource, 'uniform', this.uniform);\n for (const u in this.uniform) this.uniform[u] = gl.getUniformLocation(this.id, u);\n}\n\n// export const GLImageFilter = function (params) {\nexport function GLImageFilter(params) {\n if (!params) params = { };\n let _drawCount = 0;\n let _sourceTexture = null;\n let _lastInChain = false;\n let _currentFramebufferIndex = -1;\n let _tempFramebuffers = [null, null];\n let _filterChain = [];\n let _width = -1;\n let _height = -1;\n let _vertexBuffer = null;\n let _currentProgram = null;\n const _filter = {};\n const _canvas = params.canvas || document.createElement('canvas');\n // key is the shader program source, value is the compiled program\n const _shaderProgramCache = { };\n const DRAW = { INTERMEDIATE: 1 };\n const gl = _canvas.getContext('webgl');\n if (!gl) throw new Error('Filter: getContext() failed');\n\n this.addFilter = function (name) {\n // eslint-disable-next-line prefer-rest-params\n const args = Array.prototype.slice.call(arguments, 1);\n const filter = _filter[name];\n _filterChain.push({ func: filter, args });\n };\n\n this.reset = function () {\n _filterChain = [];\n };\n\n const _resize = function (width, height) {\n // Same width/height? Nothing to do here\n if (width === _width && height === _height) { return; }\n _canvas.width = width;\n _width = width;\n _canvas.height = height;\n _height = height;\n // Create the context if we don't have it yet\n if (!_vertexBuffer) {\n // Create the vertex buffer for the two triangles [x, y, u, v] * 6\n const vertices = new Float32Array([\n -1, -1, 0, 1, 1, -1, 1, 1, -1, 1, 0, 0,\n -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0,\n ]);\n // eslint-disable-next-line no-unused-expressions\n (_vertexBuffer = gl.createBuffer(), gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer));\n gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n }\n gl.viewport(0, 0, _width, _height);\n // Delete old temp framebuffers\n _tempFramebuffers = [null, null];\n };\n\n const _createFramebufferTexture = function (width, height) {\n const fbo = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n const renderbuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n return { fbo, texture };\n };\n\n const _getTempFramebuffer = function (index) {\n _tempFramebuffers[index] = _tempFramebuffers[index] || _createFramebufferTexture(_width, _height);\n return _tempFramebuffers[index];\n };\n\n const _draw = function (flags = null) {\n let source = null;\n let target = null;\n let flipY = false;\n // Set up the source\n if (_drawCount === 0) {\n // First draw call - use the source texture\n source = _sourceTexture;\n } else {\n // All following draw calls use the temp buffer last drawn to\n source = _getTempFramebuffer(_currentFramebufferIndex)?.texture;\n }\n _drawCount++;\n // Set up the target\n if (_lastInChain && !(flags & DRAW.INTERMEDIATE)) {\n // Last filter in our chain - draw directly to the WebGL Canvas. We may\n // also have to flip the image vertically now\n target = null;\n flipY = _drawCount % 2 === 0;\n } else {\n // Intermediate draw call - get a temp buffer to draw to\n _currentFramebufferIndex = (_currentFramebufferIndex + 1) % 2;\n target = _getTempFramebuffer(_currentFramebufferIndex)?.fbo;\n }\n // Bind the source and target and draw the two triangles\n gl.bindTexture(gl.TEXTURE_2D, source);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target);\n gl.uniform1f(_currentProgram.uniform.flipY, (flipY ? -1 : 1));\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n };\n\n this.apply = function (image) {\n _resize(image.width, image.height);\n _drawCount = 0;\n // Create the texture for the input image if we haven't yet\n if (!_sourceTexture) _sourceTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, _sourceTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\n // No filters? Just draw\n if (_filterChain.length === 0) {\n // const program = _compileShader(SHADER.FRAGMENT_IDENTITY);\n _draw();\n return _canvas;\n }\n for (let i = 0; i < _filterChain.length; i++) {\n _lastInChain = (i === _filterChain.length - 1);\n const f = _filterChain[i];\n f.func.apply(this, f.args || []);\n }\n return _canvas;\n };\n\n const _compileShader = function (fragmentSource) {\n if (_shaderProgramCache[fragmentSource]) {\n _currentProgram = _shaderProgramCache[fragmentSource];\n gl.useProgram(_currentProgram.id);\n return _currentProgram;\n }\n // Compile shaders\n const SHADER = {};\n SHADER.VERTEX_IDENTITY = [\n 'precision highp float;',\n 'attribute vec2 pos;',\n 'attribute vec2 uv;',\n 'varying vec2 vUv;',\n 'uniform float flipY;',\n 'void main(void) {',\n 'vUv = uv;',\n 'gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);',\n '}',\n ].join('\\n');\n SHADER.FRAGMENT_IDENTITY = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'void main(void) {',\n 'gl_FragColor = texture2D(texture, vUv);',\n '}',\n ].join('\\n');\n _currentProgram = new GLProgram(gl, SHADER.VERTEX_IDENTITY, fragmentSource);\n const floatSize = Float32Array.BYTES_PER_ELEMENT;\n const vertSize = 4 * floatSize;\n gl.enableVertexAttribArray(_currentProgram.attribute.pos);\n gl.vertexAttribPointer(_currentProgram.attribute.pos, 2, gl.FLOAT, false, vertSize, 0 * floatSize);\n gl.enableVertexAttribArray(_currentProgram.attribute.uv);\n gl.vertexAttribPointer(_currentProgram.attribute.uv, 2, gl.FLOAT, false, vertSize, 2 * floatSize);\n _shaderProgramCache[fragmentSource] = _currentProgram;\n return _currentProgram;\n };\n\n // -------------------------------------------------------------------------\n // Color Matrix Filter\n _filter.colorMatrix = function (matrix) {\n // Create a Float32 Array and normalize the offset component to 0-1\n const m = new Float32Array(matrix);\n m[4] /= 255;\n m[9] /= 255;\n m[14] /= 255;\n m[19] /= 255;\n // Can we ignore the alpha value? Makes things a bit faster.\n const shader = (m[18] === 1 && m[3] === 0 && m[8] === 0 && m[13] === 0 && m[15] === 0 && m[16] === 0 && m[17] === 0 && m[19] === 0)\n ? _filter.colorMatrix.SHADER.WITHOUT_ALPHA\n : _filter.colorMatrix.SHADER.WITH_ALPHA;\n const program = _compileShader(shader);\n gl.uniform1fv(program.uniform.m, m);\n _draw();\n };\n _filter.colorMatrix.SHADER = {};\n _filter.colorMatrix.SHADER.WITH_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];',\n 'gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];',\n '}',\n ].join('\\n');\n _filter.colorMatrix.SHADER.WITHOUT_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];',\n 'gl_FragColor.a = c.a;',\n '}',\n ].join('\\n');\n\n _filter.brightness = function (brightness) {\n const b = (brightness || 0) + 1;\n _filter.colorMatrix([\n b, 0, 0, 0, 0,\n 0, b, 0, 0, 0,\n 0, 0, b, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.saturation = function (amount) {\n const x = (amount || 0) * 2 / 3 + 1;\n const y = ((x - 1) * -0.5);\n _filter.colorMatrix([\n x, y, y, 0, 0,\n y, x, y, 0, 0,\n y, y, x, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturate = function () {\n _filter.saturation(-1);\n };\n\n _filter.contrast = function (amount) {\n const v = (amount || 0) + 1;\n const o = -128 * (v - 1);\n\n _filter.colorMatrix([\n v, 0, 0, 0, o,\n 0, v, 0, 0, o,\n 0, 0, v, 0, o,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.negative = function () {\n _filter.contrast(-2);\n };\n\n _filter.hue = function (rotation) {\n rotation = (rotation || 0) / 180 * Math.PI;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n const lumR = 0.213;\n const lumG = 0.715;\n const lumB = 0.072;\n\n _filter.colorMatrix([\n lumR + cos * (1 - lumR) + sin * (-lumR), lumG + cos * (-lumG) + sin * (-lumG), lumB + cos * (-lumB) + sin * (1 - lumB), 0, 0,\n lumR + cos * (-lumR) + sin * (0.143), lumG + cos * (1 - lumG) + sin * (0.140), lumB + cos * (-lumB) + sin * (-0.283), 0, 0,\n lumR + cos * (-lumR) + sin * (-(1 - lumR)), lumG + cos * (-lumG) + sin * (lumG), lumB + cos * (1 - lumB) + sin * (lumB), 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturateLuminance = function () {\n _filter.colorMatrix([\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.sepia = function () {\n _filter.colorMatrix([\n 0.393, 0.7689999, 0.18899999, 0, 0,\n 0.349, 0.6859999, 0.16799999, 0, 0,\n 0.272, 0.5339999, 0.13099999, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.brownie = function () {\n _filter.colorMatrix([\n 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,\n -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,\n 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.vintagePinhole = function () {\n _filter.colorMatrix([\n 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,\n 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,\n 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.kodachrome = function () {\n _filter.colorMatrix([\n 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,\n -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,\n -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.technicolor = function () {\n _filter.colorMatrix([\n 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,\n -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,\n -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.polaroid = function () {\n _filter.colorMatrix([\n 1.438, -0.062, -0.062, 0, 0,\n -0.122, 1.378, -0.122, 0, 0,\n -0.016, -0.016, 1.483, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.shiftToBGR = function () {\n _filter.colorMatrix([\n 0, 0, 1, 0, 0,\n 0, 1, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Convolution Filter\n _filter.convolution = function (matrix) {\n const m = new Float32Array(matrix);\n const pixelSizeX = 1 / _width;\n const pixelSizeY = 1 / _height;\n const program = _compileShader(_filter.convolution.SHADER);\n gl.uniform1fv(program.uniform.m, m);\n gl.uniform2f(program.uniform.px, pixelSizeX, pixelSizeY);\n _draw();\n };\n\n _filter.convolution.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n 'uniform float m[9];',\n 'void main(void) {',\n 'vec4 c11 = texture2D(texture, vUv - px);', // top left\n 'vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));', // top center\n 'vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));', // top right\n 'vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );', // mid left\n 'vec4 c22 = texture2D(texture, vUv);', // mid center\n 'vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );', // mid right\n 'vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );', // bottom left\n 'vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );', // bottom center\n 'vec4 c33 = texture2D(texture, vUv + px );', // bottom right\n 'gl_FragColor = ',\n 'c11 * m[0] + c12 * m[1] + c22 * m[2] +',\n 'c21 * m[3] + c22 * m[4] + c23 * m[5] +',\n 'c31 * m[6] + c32 * m[7] + c33 * m[8];',\n 'gl_FragColor.a = c22.a;',\n '}',\n ].join('\\n');\n\n _filter.detectEdges = function () {\n _filter.convolution.call(this, [\n 0, 1, 0,\n 1, -4, 1,\n 0, 1, 0,\n ]);\n };\n\n _filter.sobelX = function () {\n _filter.convolution.call(this, [\n -1, 0, 1,\n -2, 0, 2,\n -1, 0, 1,\n ]);\n };\n\n _filter.sobelY = function () {\n _filter.convolution.call(this, [\n -1, -2, -1,\n 0, 0, 0,\n 1, 2, 1,\n ]);\n };\n\n _filter.sharpen = function (amount) {\n const a = amount || 1;\n _filter.convolution.call(this, [\n 0, -1 * a, 0,\n -1 * a, 1 + 4 * a, -1 * a,\n 0, -1 * a, 0,\n ]);\n };\n\n _filter.emboss = function (size) {\n const s = size || 1;\n _filter.convolution.call(this, [\n -2 * s, -1 * s, 0,\n -1 * s, 1, 1 * s,\n 0, 1 * s, 2 * s,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Blur Filter\n _filter.blur = function (size) {\n const blurSizeX = (size / 7) / _width;\n const blurSizeY = (size / 7) / _height;\n const program = _compileShader(_filter.blur.SHADER);\n // Vertical\n gl.uniform2f(program.uniform.px, 0, blurSizeY);\n _draw(DRAW.INTERMEDIATE);\n // Horizontal\n gl.uniform2f(program.uniform.px, blurSizeX, 0);\n _draw();\n };\n\n _filter.blur.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv )*0.159576912161;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;',\n '}',\n ].join('\\n');\n\n // -------------------------------------------------------------------------\n // Pixelate Filter\n _filter.pixelate = function (size) {\n const blurSizeX = (size) / _width;\n const blurSizeY = (size) / _height;\n const program = _compileShader(_filter.pixelate.SHADER);\n // Horizontal\n gl.uniform2f(program.uniform.size, blurSizeX, blurSizeY);\n _draw();\n };\n\n _filter.pixelate.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform vec2 size;',\n 'uniform sampler2D texture;',\n 'vec2 pixelate(vec2 coord, vec2 size) {',\n 'return floor( coord / size ) * size;',\n '}',\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'vec2 coord = pixelate(vUv, size);',\n 'gl_FragColor += texture2D(texture, coord);',\n '}',\n ].join('\\n');\n}\n", "/**\n * Image Processing module used by Human\n */\n\nimport * as tf from '../../dist/tfjs.esm.js';\nimport * as fxImage from './imagefx';\nimport { Tensor } from '../tfjs/types';\nimport { Config } from '../config';\n\ntype Input = Tensor | typeof Image | ImageData | ImageBitmap | HTMLImageElement | HTMLMediaElement | HTMLVideoElement | HTMLCanvasElement | OffscreenCanvas;\n\nconst maxSize = 2048;\n// internal temp canvases\nlet inCanvas;\nlet outCanvas;\n// instance of fximage\nlet fx;\n\n// process input image and return tensor\n// input can be tensor, imagedata, htmlimageelement, htmlvideoelement\n// input is resized and run through imagefx filter\nexport function process(input: Input, config: Config): { tensor: Tensor | null, canvas: OffscreenCanvas | HTMLCanvasElement } {\n let tensor;\n if (!input) throw new Error('Human: Input is missing');\n // sanity checks since different browsers do not implement all dom elements\n if (\n !(input instanceof tf.Tensor)\n && !(typeof Image !== 'undefined' && input instanceof Image)\n && !(typeof ImageData !== 'undefined' && input instanceof ImageData)\n && !(typeof ImageBitmap !== 'undefined' && input instanceof ImageBitmap)\n && !(typeof HTMLImageElement !== 'undefined' && input instanceof HTMLImageElement)\n && !(typeof HTMLMediaElement !== 'undefined' && input instanceof HTMLMediaElement)\n && !(typeof HTMLVideoElement !== 'undefined' && input instanceof HTMLVideoElement)\n && !(typeof HTMLCanvasElement !== 'undefined' && input instanceof HTMLCanvasElement)\n && !(typeof OffscreenCanvas !== 'undefined' && input instanceof OffscreenCanvas)\n ) {\n throw new Error('Human: Input type is not recognized');\n }\n if (input instanceof tf.Tensor) {\n // if input is tensor, use as-is\n if (input.shape && input.shape.length === 4 && input.shape[0] === 1 && input.shape[3] === 3) tensor = tf.clone(input);\n else throw new Error(`Human: Input tensor shape must be [1, height, width, 3] and instead was ${input.shape}`);\n } else {\n // check if resizing will be needed\n const originalWidth = input['naturalWidth'] || input['videoWidth'] || input['width'] || (input['shape'] && (input['shape'][1] > 0));\n const originalHeight = input['naturalHeight'] || input['videoHeight'] || input['height'] || (input['shape'] && (input['shape'][2] > 0));\n if (!originalWidth || !originalHeight) return { tensor: null, canvas: inCanvas }; // video may become temporarily unavailable due to onresize\n let targetWidth = originalWidth;\n let targetHeight = originalHeight;\n if (targetWidth > maxSize) {\n targetWidth = maxSize;\n targetHeight = targetWidth * originalHeight / originalWidth;\n }\n if (targetHeight > maxSize) {\n targetHeight = maxSize;\n targetWidth = targetHeight * originalWidth / originalHeight;\n }\n\n // create our canvas and resize it if needed\n if (config.filter.width > 0) targetWidth = config.filter.width;\n else if (config.filter.height > 0) targetWidth = originalWidth * (config.filter.height / originalHeight);\n if (config.filter.height > 0) targetHeight = config.filter.height;\n else if (config.filter.width > 0) targetHeight = originalHeight * (config.filter.width / originalWidth);\n if (!targetWidth || !targetHeight) throw new Error('Human: Input cannot determine dimension');\n if (!inCanvas || (inCanvas?.width !== targetWidth) || (inCanvas?.height !== targetHeight)) {\n inCanvas = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(targetWidth, targetHeight) : document.createElement('canvas');\n if (inCanvas?.width !== targetWidth) inCanvas.width = targetWidth;\n if (inCanvas?.height !== targetHeight) inCanvas.height = targetHeight;\n }\n\n // draw input to our canvas\n const ctx = inCanvas.getContext('2d');\n if (input instanceof ImageData) {\n ctx.putImageData(input, 0, 0);\n } else {\n if (config.filter.flip && typeof ctx.translate !== 'undefined') {\n ctx.translate(originalWidth, 0);\n ctx.scale(-1, 1);\n ctx.drawImage(input, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas?.width, inCanvas?.height);\n ctx.setTransform(1, 0, 0, 1, 0, 0); // resets transforms to defaults\n } else {\n ctx.drawImage(input, 0, 0, originalWidth, originalHeight, 0, 0, inCanvas?.width, inCanvas?.height);\n }\n }\n\n // imagefx transforms using gl\n if (config.filter.enabled) {\n if (!fx || !outCanvas || (inCanvas.width !== outCanvas.width) || (inCanvas?.height !== outCanvas?.height)) {\n outCanvas = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(inCanvas?.width, inCanvas?.height) : document.createElement('canvas');\n if (outCanvas?.width !== inCanvas?.width) outCanvas.width = inCanvas?.width;\n if (outCanvas?.height !== inCanvas?.height) outCanvas.height = inCanvas?.height;\n // log('created FX filter');\n fx = tf.ENV.flags.IS_BROWSER ? new fxImage.GLImageFilter({ canvas: outCanvas }) : null; // && (typeof document !== 'undefined')\n }\n if (!fx) return { tensor: null, canvas: inCanvas };\n fx.reset();\n fx.addFilter('brightness', config.filter.brightness); // must have at least one filter enabled\n if (config.filter.contrast !== 0) fx.addFilter('contrast', config.filter.contrast);\n if (config.filter.sharpness !== 0) fx.addFilter('sharpen', config.filter.sharpness);\n if (config.filter.blur !== 0) fx.addFilter('blur', config.filter.blur);\n if (config.filter.saturation !== 0) fx.addFilter('saturation', config.filter.saturation);\n if (config.filter.hue !== 0) fx.addFilter('hue', config.filter.hue);\n if (config.filter.negative) fx.addFilter('negative');\n if (config.filter.sepia) fx.addFilter('sepia');\n if (config.filter.vintage) fx.addFilter('brownie');\n if (config.filter.sepia) fx.addFilter('sepia');\n if (config.filter.kodachrome) fx.addFilter('kodachrome');\n if (config.filter.technicolor) fx.addFilter('technicolor');\n if (config.filter.polaroid) fx.addFilter('polaroid');\n if (config.filter.pixelate !== 0) fx.addFilter('pixelate', config.filter.pixelate);\n fx.apply(inCanvas);\n // read pixel data\n /*\n const gl = outCanvas.getContext('webgl');\n if (gl) {\n const glBuffer = new Uint8Array(outCanvas.width * outCanvas.height * 4);\n const pixBuffer = new Uint8Array(outCanvas.width * outCanvas.height * 3);\n gl.readPixels(0, 0, outCanvas.width, outCanvas.height, gl.RGBA, gl.UNSIGNED_BYTE, glBuffer);\n // gl returns rbga while we only need rgb, so discarding alpha channel\n // gl returns starting point as lower left, so need to invert vertical\n let i = 0;\n for (let y = outCanvas.height - 1; y >= 0; y--) {\n for (let x = 0; x < outCanvas.width; x++) {\n const index = (x + y * outCanvas.width) * 4;\n pixBuffer[i++] = glBuffer[index + 0];\n pixBuffer[i++] = glBuffer[index + 1];\n pixBuffer[i++] = glBuffer[index + 2];\n }\n }\n outCanvas.data = pixBuffer;\n const shape = [outCanvas.height, outCanvas.width, 3];\n const pixels = tf.tensor3d(outCanvas.data, shape, 'float32');\n tensor = tf.expandDims(pixels, 0);\n tf.dispose(pixels);\n }\n */\n } else {\n outCanvas = inCanvas;\n if (fx) fx = null;\n }\n\n // create tensor from image if tensor is not already defined\n if (!tensor) {\n let pixels;\n if (outCanvas.data) { // if we have data, just convert to tensor\n const shape = [outCanvas.height, outCanvas.width, 3];\n pixels = tf.tensor3d(outCanvas.data, shape, 'int32');\n } else if (outCanvas instanceof ImageData) { // if input is imagedata, just use it\n pixels = tf.browser ? tf.browser.fromPixels(outCanvas) : null;\n } else if (config.backend === 'webgl' || config.backend === 'humangl') { // tf kernel-optimized method to get imagedata\n // we cant use canvas as-is as it already has a context, so we do a silly one more canvas\n const tempCanvas = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(targetWidth, targetHeight) : document.createElement('canvas');\n tempCanvas.width = targetWidth;\n tempCanvas.height = targetHeight;\n const tempCtx = tempCanvas.getContext('2d');\n tempCtx?.drawImage(outCanvas, 0, 0);\n pixels = tf.browser ? tf.browser.fromPixels(tempCanvas) : null;\n } else { // cpu and wasm kernel does not implement efficient fromPixels method\n // we cant use canvas as-is as it already has a context, so we do a silly one more canvas and do fromPixels on ImageData instead\n const tempCanvas = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(targetWidth, targetHeight) : document.createElement('canvas');\n tempCanvas.width = targetWidth;\n tempCanvas.height = targetHeight;\n const tempCtx = tempCanvas.getContext('2d');\n tempCtx?.drawImage(outCanvas, 0, 0);\n const data = tempCtx?.getImageData(0, 0, targetWidth, targetHeight);\n pixels = tf.browser ? tf.browser.fromPixels(data) : null;\n }\n if (pixels) {\n const casted = tf.cast(pixels, 'float32');\n tensor = tf.expandDims(casted, 0);\n tf.dispose(pixels);\n tf.dispose(casted);\n }\n }\n }\n const canvas = config.filter.return ? outCanvas : null;\n return { tensor, canvas };\n}\n", "/**\n * EfficientPose Module\n */\n\nimport { log, join } from '../helpers';\nimport * as tf from '../../dist/tfjs.esm.js';\nimport * as image from '../image/image';\nimport { GraphModel, Tensor } from '../tfjs/types';\nimport { Config } from '../config';\n\ntype Input = Tensor | typeof Image | ImageData | ImageBitmap | HTMLImageElement | HTMLMediaElement | HTMLVideoElement | HTMLCanvasElement | OffscreenCanvas;\n\nlet model: GraphModel;\nlet busy = false;\n\nexport async function load(config: Config): Promise<GraphModel> {\n if (!model) {\n // @ts-ignore type mismatch on GraphModel\n model = await tf.loadGraphModel(join(config.modelBasePath, config.segmentation.modelPath));\n if (!model || !model['modelUrl']) log('load model failed:', config.segmentation.modelPath);\n else if (config.debug) log('load model:', model['modelUrl']);\n } else if (config.debug) log('cached model:', model['modelUrl']);\n return model;\n}\n\nexport async function predict(input: { tensor: Tensor | null, canvas: OffscreenCanvas | HTMLCanvasElement }): Promise<Uint8ClampedArray | null> {\n const width = input.tensor?.shape[1] || 0;\n const height = input.tensor?.shape[2] || 0;\n if (!input.tensor) return null;\n if (!model || !model.inputs[0].shape) return null;\n const resizeInput = tf.image.resizeBilinear(input.tensor, [model.inputs[0].shape[1], model.inputs[0].shape[2]], false);\n const norm = tf.div(resizeInput, 255);\n const res = model.predict(norm) as Tensor;\n // meet output: 1,256,256,1\n // selfie output: 1,144,256,2\n tf.dispose(resizeInput);\n tf.dispose(norm);\n\n const squeeze = tf.squeeze(res, 0);\n let resizeOutput;\n if (squeeze.shape[2] === 2) {\n // model meet has two channels for fg and bg\n const softmax = squeeze.softmax();\n const [bg, fg] = tf.unstack(softmax, 2);\n const expand = tf.expandDims(fg, 2);\n const pad = tf.expandDims(expand, 0);\n tf.dispose(softmax);\n tf.dispose(bg);\n tf.dispose(fg);\n // running sofmax before unstack creates 2x2 matrix so we only take upper-left quadrant\n const crop = tf.image.cropAndResize(pad, [[0, 0, 0.5, 0.5]], [0], [width, height]);\n // otherwise run softmax after unstack and use standard resize\n // resizeOutput = tf.image.resizeBilinear(expand, [input.tensor?.shape[1], input.tensor?.shape[2]]);\n resizeOutput = tf.squeeze(crop, 0);\n tf.dispose(crop);\n tf.dispose(expand);\n tf.dispose(pad);\n } else { // model selfie has a single channel that we can use directly\n resizeOutput = tf.image.resizeBilinear(squeeze, [width, height]);\n }\n\n if (typeof document === 'undefined') return resizeOutput.data(); // we're running in nodejs so return alpha array as-is\n\n const overlay = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(width, height) : document.createElement('canvas');\n overlay.width = width;\n overlay.height = height;\n if (tf.browser) await tf.browser.toPixels(resizeOutput, overlay);\n tf.dispose(resizeOutput);\n tf.dispose(squeeze);\n tf.dispose(res);\n\n // get alpha channel data\n const alphaCanvas = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(width, height) : document.createElement('canvas'); // need one more copy since input may already have gl context so 2d context fails\n alphaCanvas.width = width;\n alphaCanvas.height = height;\n const ctxAlpha = alphaCanvas.getContext('2d') as CanvasRenderingContext2D;\n ctxAlpha.filter = 'blur(8px';\n await ctxAlpha.drawImage(overlay, 0, 0);\n const alpha = ctxAlpha.getImageData(0, 0, width, height).data;\n\n // get original canvas merged with overlay\n const original = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(width, height) : document.createElement('canvas'); // need one more copy since input may already have gl context so 2d context fails\n original.width = width;\n original.height = height;\n const ctx = original.getContext('2d') as CanvasRenderingContext2D;\n if (input.canvas) await ctx.drawImage(input.canvas, 0, 0);\n // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation // best options are: darken, color-burn, multiply\n ctx.globalCompositeOperation = 'darken';\n ctx.filter = 'blur(8px)'; // use css filter for bluring, can be done with gaussian blur manually instead\n await ctx.drawImage(overlay, 0, 0);\n ctx.globalCompositeOperation = 'source-over'; // reset\n ctx.filter = 'none'; // reset\n\n input.canvas = original;\n\n return alpha;\n}\n\nexport async function process(input: Input, background: Input | undefined, config: Config): Promise<HTMLCanvasElement | OffscreenCanvas | null> {\n if (busy) return null;\n busy = true;\n if (!model) await load(config);\n const img = image.process(input, config);\n const alpha = await predict(img);\n tf.dispose(img.tensor);\n\n if (background && alpha) {\n const tmp = image.process(background, config);\n const bg = tmp.canvas;\n tf.dispose(tmp.tensor);\n const fg = img.canvas;\n const fgData = fg.getContext('2d')?.getImageData(0, 0, fg.width, fg.height).data as Uint8ClampedArray;\n\n const c = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(fg.width, fg.height) : document.createElement('canvas');\n c.width = fg.width;\n c.height = fg.height;\n const ctx = c.getContext('2d') as CanvasRenderingContext2D;\n\n ctx.globalCompositeOperation = 'copy'; // reset\n ctx.drawImage(bg, 0, 0, c.width, c.height);\n const cData = ctx.getImageData(0, 0, c.width, c.height) as ImageData;\n for (let i = 0; i < c.width * c.height; i++) { // this should be done with globalCompositeOperation instead of looping through image data\n cData.data[4 * i + 0] = ((255 - alpha[4 * i + 0]) / 255.0 * cData.data[4 * i + 0]) + (alpha[4 * i + 0] / 255.0 * fgData[4 * i + 0]);\n cData.data[4 * i + 1] = ((255 - alpha[4 * i + 1]) / 255.0 * cData.data[4 * i + 1]) + (alpha[4 * i + 1] / 255.0 * fgData[4 * i + 1]);\n cData.data[4 * i + 2] = ((255 - alpha[4 * i + 2]) / 255.0 * cData.data[4 * i + 2]) + (alpha[4 * i + 2] / 255.0 * fgData[4 * i + 2]);\n cData.data[4 * i + 3] = ((255 - alpha[4 * i + 3]) / 255.0 * cData.data[4 * i + 3]) + (alpha[4 * i + 3] / 255.0 * fgData[4 * i + 3]);\n }\n ctx.putImageData(cData, 0, 0);\n img.canvas = c;\n }\n busy = false;\n return img.canvas;\n}\n", "import * as facemesh from './blazeface/facemesh';\nimport * as faceres from './faceres/faceres';\nimport * as emotion from './emotion/emotion';\nimport * as posenet from './posenet/posenet';\nimport * as handpose from './handpose/handpose';\nimport * as blazepose from './blazepose/blazepose';\nimport * as efficientpose from './efficientpose/efficientpose';\nimport * as movenet from './movenet/movenet';\nimport * as nanodet from './object/nanodet';\nimport * as centernet from './object/centernet';\nimport * as segmentation from './segmentation/segmentation';\n// import * as agegenderrace from './gear/agegenderrace';\n\n/** Load method preloads all instance.configured models on-demand\n * - Not explicitly required as any required model is load implicitly on it's first run\n * @param userinstance.config?: {@link instance.config}\n*/\nexport async function load(instance) {\n if (instance.config.async) { // load models concurrently\n [\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.face,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.emotion,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.handpose,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.posenet,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.blazepose,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.efficientpose,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.movenet,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.nanodet,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.centernet,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.faceres,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n instance.models.segmentation,\n // @ts-ignore models loaded via promise array cannot be correctly inferred\n // instance.models.agegenderrace,\n ] = await Promise.all([\n instance.models.face || (instance.config.face.enabled ? facemesh.load(instance.config) : null),\n instance.models.emotion || ((instance.config.face.enabled && instance.config.face.emotion.enabled) ? emotion.load(instance.config) : null),\n instance.models.handpose || (instance.config.hand.enabled ? handpose.load(instance.config) : null),\n instance.models.posenet || (instance.config.body.enabled && instance.config.body.modelPath.includes('posenet') ? posenet.load(instance.config) : null),\n instance.models.blazepose || (instance.config.body.enabled && instance.config.body.modelPath.includes('blazepose') ? blazepose.load(instance.config) : null),\n instance.models.efficientpose || (instance.config.body.enabled && instance.config.body.modelPath.includes('efficientpose') ? efficientpose.load(instance.config) : null),\n instance.models.movenet || (instance.config.body.enabled && instance.config.body.modelPath.includes('movenet') ? movenet.load(instance.config) : null),\n instance.models.nanodet || (instance.config.object.enabled && instance.config.object.modelPath.includes('nanodet') ? nanodet.load(instance.config) : null),\n instance.models.centernet || (instance.config.object.enabled && instance.config.object.modelPath.includes('centernet') ? centernet.load(instance.config) : null),\n instance.models.faceres || ((instance.config.face.enabled && instance.config.face.description.enabled) ? faceres.load(instance.config) : null),\n instance.models.segmentation || (instance.config.segmentation.enabled ? segmentation.load(instance.config) : null),\n // instance.models.agegenderrace || ((instance.config.face.enabled && instance.config.face.agegenderrace.enabled) ? agegenderrace.load(instance.config) : null),\n ]);\n } else { // load models sequentially\n if (instance.config.face.enabled && !instance.models.face) instance.models.face = await facemesh.load(instance.config);\n if (instance.config.face.enabled && instance.config.face.emotion.enabled && !instance.models.emotion) instance.models.emotion = await emotion.load(instance.config);\n if (instance.config.hand.enabled && !instance.models.handpose) instance.models.handpose = await handpose.load(instance.config);\n if (instance.config.body.enabled && !instance.models.posenet && instance.config.body.modelPath.includes('posenet')) instance.models.posenet = await posenet.load(instance.config);\n if (instance.config.body.enabled && !instance.models.blazepose && instance.config.body.modelPath.includes('blazepose')) instance.models.blazepose = await blazepose.load(instance.config);\n if (instance.config.body.enabled && !instance.models.efficientpose && instance.config.body.modelPath.includes('efficientpose')) instance.models.efficientpose = await blazepose.load(instance.config);\n if (instance.config.body.enabled && !instance.models.movenet && instance.config.body.modelPath.includes('movenet')) instance.models.movenet = await movenet.load(instance.config);\n if (instance.config.object.enabled && !instance.models.nanodet && instance.config.object.modelPath.includes('nanodet')) instance.models.nanodet = await nanodet.load(instance.config);\n if (instance.config.object.enabled && !instance.models.centernet && instance.config.object.modelPath.includes('centernet')) instance.models.centernet = await centernet.load(instance.config);\n if (instance.config.face.enabled && instance.config.face.description.enabled && !instance.models.faceres) instance.models.faceres = await faceres.load(instance.config);\n if (instance.config.segmentation.enabled && !instance.models.segmentation) instance.models.segmentation = await segmentation.load(instance.config);\n // if (instance.config.face.enabled && instance.config.face.agegenderrace.enabled && !instance.models.agegenderrace) instance.models.agegenderrace = await agegenderrace.load(instance.config);\n }\n}\n", "/**\n * Module that analyzes person age\n * Obsolete\n */\n\nimport { log, now } from './helpers';\nimport * as tf from '../dist/tfjs.esm.js';\nimport * as facemesh from './blazeface/facemesh';\nimport * as emotion from './emotion/emotion';\nimport * as faceres from './faceres/faceres';\nimport { Face } from './result';\nimport { Tensor } from './tfjs/types';\n\n// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars\nconst rad2deg = (theta) => Math.round((theta * 180) / Math.PI);\n\nconst calculateGaze = (face): { bearing: number, strength: number } => {\n const radians = (pt1, pt2) => Math.atan2(pt1[1] - pt2[1], pt1[0] - pt2[0]); // function to calculate angle between any two points\n if (!face.annotations['rightEyeIris'] || !face.annotations['leftEyeIris']) return { bearing: 0, strength: 0 };\n\n const offsetIris = [0, -0.1]; // iris center may not align with average of eye extremes\n const eyeRatio = 1; // factor to normalize changes x vs y\n\n const left = face.mesh[33][2] > face.mesh[263][2]; // pick left or right eye depending which one is closer bazed on outsize point z axis\n const irisCenter = left ? face.mesh[473] : face.mesh[468];\n const eyeCenter = left // eye center is average of extreme points on x axis for both x and y, ignoring y extreme points as eyelids naturally open/close more when gazing up/down so relative point is less precise\n ? [(face.mesh[133][0] + face.mesh[33][0]) / 2, (face.mesh[133][1] + face.mesh[33][1]) / 2]\n : [(face.mesh[263][0] + face.mesh[362][0]) / 2, (face.mesh[263][1] + face.mesh[362][1]) / 2];\n const eyeSize = left // eye size is difference between extreme points for both x and y, used to normalize & squarify eye dimensions\n ? [face.mesh[133][0] - face.mesh[33][0], face.mesh[23][1] - face.mesh[27][1]]\n : [face.mesh[263][0] - face.mesh[362][0], face.mesh[253][1] - face.mesh[257][1]];\n\n const eyeDiff = [ // x distance between extreme point and center point normalized with eye size\n (eyeCenter[0] - irisCenter[0]) / eyeSize[0] - offsetIris[0],\n eyeRatio * (irisCenter[1] - eyeCenter[1]) / eyeSize[1] - offsetIris[1],\n ];\n let strength = Math.sqrt((eyeDiff[0] ** 2) + (eyeDiff[1] ** 2)); // vector length is a diagonal between two differences\n strength = Math.min(strength, face.boxRaw[2] / 2, face.boxRaw[3] / 2); // limit strength to half of box size to avoid clipping due to low precision\n const bearing = (radians([0, 0], eyeDiff) + (Math.PI / 2)) % Math.PI; // using eyeDiff instead eyeCenter/irisCenter combo due to manual adjustments and rotate clockwise 90degrees\n\n return { bearing, strength };\n};\n\nconst calculateFaceAngle = (face, imageSize): {\n angle: { pitch: number, yaw: number, roll: number },\n matrix: [number, number, number, number, number, number, number, number, number],\n gaze: { bearing: number, strength: number },\n} => {\n // const degrees = (theta) => Math.abs(((theta * 180) / Math.PI) % 360);\n const normalize = (v) => { // normalize vector\n const length = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);\n v[0] /= length;\n v[1] /= length;\n v[2] /= length;\n return v;\n };\n const subVectors = (a, b) => { // vector subtraction (a - b)\n const x = a[0] - b[0];\n const y = a[1] - b[1];\n const z = a[2] - b[2];\n return [x, y, z];\n };\n const crossVectors = (a, b) => { // vector cross product (a x b)\n const x = a[1] * b[2] - a[2] * b[1];\n const y = a[2] * b[0] - a[0] * b[2];\n const z = a[0] * b[1] - a[1] * b[0];\n return [x, y, z];\n };\n // 3x3 rotation matrix to Euler angles based on https://www.geometrictools.com/Documentation/EulerAngles.pdf\n const rotationMatrixToEulerAngle = (r) => {\n // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars\n const [r00, r01, r02, r10, r11, r12, r20, r21, r22] = r;\n let thetaX; let thetaY; let thetaZ;\n if (r10 < 1) { // YZX calculation\n if (r10 > -1) {\n thetaZ = Math.asin(r10);\n thetaY = Math.atan2(-r20, r00);\n thetaX = Math.atan2(-r12, r11);\n } else {\n thetaZ = -Math.PI / 2;\n thetaY = -Math.atan2(r21, r22);\n thetaX = 0;\n }\n } else {\n thetaZ = Math.PI / 2;\n thetaY = Math.atan2(r21, r22);\n thetaX = 0;\n }\n return { pitch: 2 * -thetaX, yaw: 2 * -thetaY, roll: 2 * -thetaZ };\n };\n // simple Euler angle calculation based existing 3D mesh\n // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars\n const meshToEulerAngle = (mesh) => {\n const radians = (a1, a2, b1, b2) => Math.atan2(b2 - a2, b1 - a1);\n // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars\n const angle = {\n // values are in radians in range of -pi/2 to pi/2 which is -90 to +90 degrees, value of 0 means center\n // pitch is face move up/down\n pitch: radians(mesh[10][1], mesh[10][2], mesh[152][1], mesh[152][2]), // looking at y,z of top and bottom points of the face\n // yaw is face turn left/right\n yaw: radians(mesh[33][0], mesh[33][2], mesh[263][0], mesh[263][2]), // looking at x,z of outside corners of leftEye and rightEye\n // roll is face lean left/right\n roll: radians(mesh[33][0], mesh[33][1], mesh[263][0], mesh[263][1]), // looking at x,y of outside corners of leftEye and rightEye\n };\n return angle;\n };\n\n // initialize gaze and mesh\n const mesh = face.meshRaw;\n if (!mesh || mesh.length < 300) return { angle: { pitch: 0, yaw: 0, roll: 0 }, matrix: [1, 0, 0, 0, 1, 0, 0, 0, 1], gaze: { bearing: 0, strength: 0 } };\n\n const size = Math.max(face.boxRaw[2] * imageSize[0], face.boxRaw[3] * imageSize[1]) / 1.5;\n // top, bottom, left, right\n const pts = [mesh[10], mesh[152], mesh[234], mesh[454]].map((pt) => [\n // make the xyz coordinates proportional, independent of the image/box size\n pt[0] * imageSize[0] / size,\n pt[1] * imageSize[1] / size,\n pt[2],\n ]);\n\n const y_axis = normalize(subVectors(pts[1], pts[0]));\n let x_axis = normalize(subVectors(pts[3], pts[2]));\n const z_axis = normalize(crossVectors(x_axis, y_axis));\n // adjust x_axis to make sure that all axes are perpendicular to each other\n x_axis = crossVectors(y_axis, z_axis);\n\n // Rotation Matrix from Axis Vectors - http://renderdan.blogspot.com/2006/05/rotation-matrix-from-axis-vectors.html\n // 3x3 rotation matrix is flatten to array in row-major order. Note that the rotation represented by this matrix is inverted.\n const matrix: [number, number, number, number, number, number, number, number, number] = [\n x_axis[0], x_axis[1], x_axis[2],\n y_axis[0], y_axis[1], y_axis[2],\n z_axis[0], z_axis[1], z_axis[2],\n ];\n const angle = rotationMatrixToEulerAngle(matrix);\n // const angle = meshToEulerAngle(mesh);\n\n // we have iris keypoints so we can calculate gaze direction\n const gaze = mesh.length === 478 ? calculateGaze(face) : { bearing: 0, strength: 0 };\n\n return { angle, matrix, gaze };\n};\n\nexport const detectFace = async (parent /* instance of human */, input: Tensor): Promise<Face[]> => {\n // run facemesh, includes blazeface and iris\n // eslint-disable-next-line no-async-promise-executor\n let timeStamp;\n let ageRes;\n let gearRes;\n let genderRes;\n let emotionRes;\n let embeddingRes;\n let descRes;\n const faceRes: Array<Face> = [];\n parent.state = 'run:face';\n timeStamp = now();\n const faces = await facemesh.predict(input, parent.config);\n parent.performance.face = Math.trunc(now() - timeStamp);\n if (!input.shape || input.shape.length !== 4) return [];\n if (!faces) return [];\n // for (const face of faces) {\n for (let i = 0; i < faces.length; i++) {\n parent.analyze('Get Face');\n\n // is something went wrong, skip the face\n // @ts-ignore possibly undefined\n if (!faces[i].tensor || faces[i].tensor['isDisposedInternal']) {\n log('Face object is disposed:', faces[i].tensor);\n continue;\n }\n\n const rotation = calculateFaceAngle(faces[i], [input.shape[2], input.shape[1]]);\n\n // run emotion, inherits face from blazeface\n parent.analyze('Start Emotion:');\n if (parent.config.async) {\n emotionRes = parent.config.face.emotion.enabled ? emotion.predict(faces[i].tensor || tf.tensor([]), parent.config, i, faces.length) : {};\n } else {\n parent.state = 'run:emotion';\n timeStamp = now();\n emotionRes = parent.config.face.emotion.enabled ? await emotion.predict(faces[i].tensor || tf.tensor([]), parent.config, i, faces.length) : {};\n parent.performance.emotion = Math.trunc(now() - timeStamp);\n }\n parent.analyze('End Emotion:');\n\n // run gear, inherits face from blazeface\n /*\n parent.analyze('Start GEAR:');\n if (parent.config.async) {\n gearRes = parent.config.face.agegenderrace.enabled ? agegenderrace.predict(faces[i].tensor || tf.tensor([]), parent.config, i, faces.length) : {};\n } else {\n parent.state = 'run:gear';\n timeStamp = now();\n gearRes = parent.config.face.agegenderrace.enabled ? await agegenderrace.predict(faces[i].tensor || tf.tensor([]), parent.config, i, faces.length) : {};\n parent.performance.emotion = Math.trunc(now() - timeStamp);\n }\n parent.analyze('End GEAR:');\n */\n\n // run emotion, inherits face from blazeface\n parent.analyze('Start Description:');\n if (parent.config.async) {\n descRes = parent.config.face.description.enabled ? faceres.predict(faces[i].tensor || tf.tensor([]), parent.config, i, faces.length) : [];\n } else {\n parent.state = 'run:description';\n timeStamp = now();\n descRes = parent.config.face.description.enabled ? await faceres.predict(faces[i].tensor || tf.tensor([]), parent.config, i, faces.length) : [];\n parent.performance.embedding = Math.trunc(now() - timeStamp);\n }\n parent.analyze('End Description:');\n\n // if async wait for results\n if (parent.config.async) {\n [ageRes, genderRes, emotionRes, embeddingRes, descRes, gearRes] = await Promise.all([ageRes, genderRes, emotionRes, embeddingRes, descRes, gearRes]);\n }\n\n parent.analyze('Finish Face:');\n\n // calculate iris distance\n // iris: array[ center, left, top, right, bottom]\n if (!parent.config.face.iris.enabled && faces[i]?.annotations?.leftEyeIris && faces[i]?.annotations?.rightEyeIris) {\n delete faces[i].annotations.leftEyeIris;\n delete faces[i].annotations.rightEyeIris;\n }\n const irisSize = (faces[i].annotations?.leftEyeIris && faces[i].annotations?.rightEyeIris)\n /* note: average human iris size is 11.7mm */\n ? Math.max(Math.abs(faces[i].annotations.leftEyeIris[3][0] - faces[i].annotations.leftEyeIris[1][0]), Math.abs(faces[i].annotations.rightEyeIris[4][1] - faces[i].annotations.rightEyeIris[2][1])) / input.shape[2]\n : 0;\n\n // optionally return tensor\n const tensor = parent.config.face.detector.return ? tf.squeeze(faces[i].tensor) : null;\n // dispose original face tensor\n tf.dispose(faces[i].tensor);\n // delete temp face image\n if (faces[i].tensor) delete faces[i].tensor;\n // combine results\n faceRes.push({\n ...faces[i],\n id: i,\n age: descRes.age,\n gender: descRes.gender,\n genderScore: descRes.genderScore,\n embedding: descRes.descriptor,\n emotion: emotionRes,\n iris: irisSize !== 0 ? Math.trunc(500 / irisSize / 11.7) / 100 : 0,\n rotation,\n tensor,\n });\n\n parent.analyze('End Face');\n }\n parent.analyze('End FaceMesh:');\n if (parent.config.async) {\n if (parent.performance.face) delete parent.performance.face;\n if (parent.performance.age) delete parent.performance.age;\n if (parent.performance.gender) delete parent.performance.gender;\n if (parent.performance.emotion) delete parent.performance.emotion;\n }\n return faceRes;\n};\n", "/**\n * Gesture detection module\n */\n\nimport { Gesture } from '../result';\n\n/**\n * @typedef FaceGesture\n */\nexport type FaceGesture =\n `facing ${'left' | 'center' | 'right'}`\n | `blink ${'left' | 'right'} eye`\n | `mouth ${number}% open`\n | `head ${'up' | 'down'}`;\n\n/**\n * @typedef IrisGesture\n */\nexport type IrisGesture =\n 'facing center'\n | `looking ${'left' | 'right' | 'up' | 'down'}`\n | 'looking center';\n\n/**\n * @typedef BodyGesture\n */\nexport type BodyGesture =\n `leaning ${'left' | 'right'}`\n | `raise ${'left' | 'right'} hand`\n | 'i give up';\n\n/**\n * @typedef BodyGesture\n */\nexport type HandGesture =\n `${'thumb' | 'index finger' | 'middle finger' | 'ring finger' | 'pinky'} forward`\n | `${'thumb' | 'index finger' | 'middle finger' | 'ring finger' | 'pinky'} up`;\n\nexport const body = (res): Gesture[] => {\n if (!res) return [];\n const gestures: Array<{ body: number, gesture: BodyGesture }> = [];\n for (let i = 0; i < res.length; i++) {\n // raising hands\n const leftWrist = res[i].keypoints.find((a) => (a.part === 'leftWrist'));\n const rightWrist = res[i].keypoints.find((a) => (a.part === 'rightWrist'));\n const nose = res[i].keypoints.find((a) => (a.part === 'nose'));\n if (nose && leftWrist && rightWrist && (leftWrist.position.y < nose.position.y) && (rightWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'i give up' });\n else if (nose && leftWrist && (leftWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'raise left hand' });\n else if (nose && rightWrist && (rightWrist.position.y < nose.position.y)) gestures.push({ body: i, gesture: 'raise right hand' });\n\n // leaning\n const leftShoulder = res[i].keypoints.find((a) => (a.part === 'leftShoulder'));\n const rightShoulder = res[i].keypoints.find((a) => (a.part === 'rightShoulder'));\n if (leftShoulder && rightShoulder) gestures.push({ body: i, gesture: `leaning ${(leftShoulder.position.y > rightShoulder.position.y) ? 'left' : 'right'}` });\n }\n return gestures;\n};\n\nexport const face = (res): Gesture[] => {\n if (!res) return [];\n const gestures: Array<{ face: number, gesture: FaceGesture }> = [];\n for (let i = 0; i < res.length; i++) {\n if (res[i].mesh && res[i].mesh.length > 0) {\n const eyeFacing = res[i].mesh[33][2] - res[i].mesh[263][2];\n if (Math.abs(eyeFacing) < 10) gestures.push({ face: i, gesture: 'facing center' });\n else gestures.push({ face: i, gesture: `facing ${eyeFacing < 0 ? 'left' : 'right'}` });\n const openLeft = Math.abs(res[i].mesh[374][1] - res[i].mesh[386][1]) / Math.abs(res[i].mesh[443][1] - res[i].mesh[450][1]); // center of eye inner lid y coord div center of wider eye border y coord\n if (openLeft < 0.2) gestures.push({ face: i, gesture: 'blink left eye' });\n const openRight = Math.abs(res[i].mesh[145][1] - res[i].mesh[159][1]) / Math.abs(res[i].mesh[223][1] - res[i].mesh[230][1]); // center of eye inner lid y coord div center of wider eye border y coord\n if (openRight < 0.2) gestures.push({ face: i, gesture: 'blink right eye' });\n const mouthOpen = Math.min(100, 500 * Math.abs(res[i].mesh[13][1] - res[i].mesh[14][1]) / Math.abs(res[i].mesh[10][1] - res[i].mesh[152][1]));\n if (mouthOpen > 10) gestures.push({ face: i, gesture: `mouth ${Math.trunc(mouthOpen)}% open` });\n const chinDepth = res[i].mesh[152][2];\n if (Math.abs(chinDepth) > 10) gestures.push({ face: i, gesture: `head ${chinDepth < 0 ? 'up' : 'down'}` });\n }\n }\n return gestures;\n};\n\nexport const iris = (res): Gesture[] => {\n if (!res) return [];\n const gestures: Array<{ iris: number, gesture: IrisGesture }> = [];\n for (let i = 0; i < res.length; i++) {\n if (!res[i].annotations || !res[i].annotations.leftEyeIris || !res[i].annotations.rightEyeIris) continue;\n const sizeXLeft = res[i].annotations.leftEyeIris[3][0] - res[i].annotations.leftEyeIris[1][0];\n const sizeYLeft = res[i].annotations.leftEyeIris[4][1] - res[i].annotations.leftEyeIris[2][1];\n const areaLeft = Math.abs(sizeXLeft * sizeYLeft);\n\n const sizeXRight = res[i].annotations.rightEyeIris[3][0] - res[i].annotations.rightEyeIris[1][0];\n const sizeYRight = res[i].annotations.rightEyeIris[4][1] - res[i].annotations.rightEyeIris[2][1];\n const areaRight = Math.abs(sizeXRight * sizeYRight);\n\n let center = false;\n const difference = Math.abs(areaLeft - areaRight) / Math.max(areaLeft, areaRight);\n if (difference < 0.25) {\n center = true;\n gestures.push({ iris: i, gesture: 'facing center' });\n }\n\n const rightIrisCenterX = Math.abs(res[i].mesh[33][0] - res[i].annotations.rightEyeIris[0][0]) / res[i].box[2];\n const leftIrisCenterX = Math.abs(res[i].mesh[263][0] - res[i].annotations.leftEyeIris[0][0]) / res[i].box[2];\n if (leftIrisCenterX > 0.06 || rightIrisCenterX > 0.06) center = false;\n if (leftIrisCenterX > 0.06) gestures.push({ iris: i, gesture: 'looking right' });\n if (rightIrisCenterX > 0.06) gestures.push({ iris: i, gesture: 'looking left' });\n\n const rightIrisCenterY = Math.abs(res[i].mesh[145][1] - res[i].annotations.rightEyeIris[0][1]) / res[i].box[3];\n const leftIrisCenterY = Math.abs(res[i].mesh[374][1] - res[i].annotations.leftEyeIris[0][1]) / res[i].box[3];\n if (leftIrisCenterY < 0.01 || rightIrisCenterY < 0.01 || leftIrisCenterY > 0.022 || rightIrisCenterY > 0.022) center = false;\n if (leftIrisCenterY < 0.01 || rightIrisCenterY < 0.01) gestures.push({ iris: i, gesture: 'looking down' });\n if (leftIrisCenterY > 0.022 || rightIrisCenterY > 0.022) gestures.push({ iris: i, gesture: 'looking up' });\n\n // still center;\n if (center) gestures.push({ iris: i, gesture: 'looking center' });\n }\n return gestures;\n};\n\nexport const hand = (res): Gesture[] => {\n if (!res) return [];\n const gestures: Array<{ hand: number, gesture: HandGesture }> = [];\n for (let i = 0; i < res.length; i++) {\n const fingers: Array<{ name: string, position: number }> = [];\n for (const [finger, pos] of Object.entries(res[i]['annotations'])) {\n if (finger !== 'palmBase' && Array.isArray(pos)) fingers.push({ name: finger.toLowerCase(), position: pos[0] }); // get tip of each finger\n }\n if (fingers && fingers.length > 0) {\n const closest = fingers.reduce((best, a) => (best.position[2] < a.position[2] ? best : a));\n gestures.push({ hand: i, gesture: `${closest.name} forward` as HandGesture });\n const highest = fingers.reduce((best, a) => (best.position[1] < a.position[1] ? best : a));\n gestures.push({ hand: i, gesture: `${highest.name} up` as HandGesture });\n }\n }\n return gestures;\n};\n", "/**\n * Module that implements helper draw functions, exposed as human.draw\n */\n\nimport { TRI468 as triangulation } from '../blazeface/coords';\nimport { mergeDeep, now } from '../helpers';\nimport type { Result, Face, Body, Hand, Item, Gesture, Person } from '../result';\n\n/**\n * Draw Options\n * Accessed via `human.draw.options` or provided per each draw method as the drawOptions optional parameter\n * -color: draw color\n * -labelColor: color for labels\n * -shadowColor: optional shadow color for labels\n * -font: font for labels\n * -lineHeight: line height for labels, used for multi-line labels,\n * -lineWidth: width of any lines,\n * -pointSize: size of any point,\n * -roundRect: for boxes, round corners by this many pixels,\n * -drawPoints: should points be drawn,\n * -drawLabels: should labels be drawn,\n * -drawBoxes: should boxes be drawn,\n * -drawPolygons: should polygons be drawn,\n * -fillPolygons: should drawn polygons be filled,\n * -useDepth: use z-axis coordinate as color shade,\n * -useCurves: draw polygons as cures or as lines,\n * -bufferedOutput: experimental: allows to call draw methods multiple times for each detection and interpolate results between results thus achieving smoother animations\n */\nexport interface DrawOptions {\n color: string,\n labelColor: string,\n shadowColor: string,\n font: string,\n lineHeight: number,\n lineWidth: number,\n pointSize: number,\n roundRect: number,\n drawPoints: boolean,\n drawLabels: boolean,\n drawBoxes: boolean,\n drawPolygons: boolean,\n drawGaze: boolean,\n fillPolygons: boolean,\n useDepth: boolean,\n useCurves: boolean,\n bufferedOutput: boolean,\n}\n\nexport const options: DrawOptions = {\n color: <string>'rgba(173, 216, 230, 0.6)', // 'lightblue' with light alpha channel\n labelColor: <string>'rgba(173, 216, 230, 1)', // 'lightblue' with dark alpha channel\n shadowColor: <string>'black',\n font: <string>'small-caps 14px \"Segoe UI\"',\n lineHeight: <number>18,\n lineWidth: <number>4,\n pointSize: <number>2,\n roundRect: <number>8,\n drawPoints: <boolean>false,\n drawLabels: <boolean>true,\n drawBoxes: <boolean>true,\n drawPolygons: <boolean>true,\n drawGaze: <boolean>true,\n fillPolygons: <boolean>false,\n useDepth: <boolean>true,\n useCurves: <boolean>false,\n bufferedOutput: <boolean>true,\n};\n\nconst rad2deg = (theta) => Math.round((theta * 180) / Math.PI);\n\nfunction point(ctx, x, y, z = 0, localOptions) {\n ctx.fillStyle = localOptions.useDepth && z ? `rgba(${127.5 + (2 * z)}, ${127.5 - (2 * z)}, 255, 0.3)` : localOptions.color;\n ctx.beginPath();\n ctx.arc(x, y, localOptions.pointSize, 0, 2 * Math.PI);\n ctx.fill();\n}\n\nfunction rect(ctx, x, y, width, height, localOptions) {\n ctx.beginPath();\n if (localOptions.useCurves) {\n const cx = (x + x + width) / 2;\n const cy = (y + y + height) / 2;\n ctx.ellipse(cx, cy, width / 2, height / 2, 0, 0, 2 * Math.PI);\n } else {\n ctx.lineWidth = localOptions.lineWidth;\n ctx.moveTo(x + localOptions.roundRect, y);\n ctx.lineTo(x + width - localOptions.roundRect, y);\n ctx.quadraticCurveTo(x + width, y, x + width, y + localOptions.roundRect);\n ctx.lineTo(x + width, y + height - localOptions.roundRect);\n ctx.quadraticCurveTo(x + width, y + height, x + width - localOptions.roundRect, y + height);\n ctx.lineTo(x + localOptions.roundRect, y + height);\n ctx.quadraticCurveTo(x, y + height, x, y + height - localOptions.roundRect);\n ctx.lineTo(x, y + localOptions.roundRect);\n ctx.quadraticCurveTo(x, y, x + localOptions.roundRect, y);\n ctx.closePath();\n }\n ctx.stroke();\n}\n\nfunction lines(ctx, points: [number, number, number?][] = [], localOptions) {\n if (points === undefined || points.length === 0) return;\n ctx.beginPath();\n ctx.moveTo(points[0][0], points[0][1]);\n for (const pt of points) {\n const z = pt[2] || 0;\n ctx.strokeStyle = localOptions.useDepth && z ? `rgba(${127.5 + (2 * z)}, ${127.5 - (2 * z)}, 255, 0.3)` : localOptions.color;\n ctx.fillStyle = localOptions.useDepth && z ? `rgba(${127.5 + (2 * z)}, ${127.5 - (2 * z)}, 255, 0.3)` : localOptions.color;\n ctx.lineTo(pt[0], Math.round(pt[1]));\n }\n ctx.stroke();\n if (localOptions.fillPolygons) {\n ctx.closePath();\n ctx.fill();\n }\n}\n\nfunction curves(ctx, points: [number, number, number?][] = [], localOptions) {\n if (points === undefined || points.length === 0) return;\n if (!localOptions.useCurves || points.length <= 2) {\n lines(ctx, points, localOptions);\n return;\n }\n ctx.moveTo(points[0][0], points[0][1]);\n for (let i = 0; i < points.length - 2; i++) {\n const xc = (points[i][0] + points[i + 1][0]) / 2;\n const yc = (points[i][1] + points[i + 1][1]) / 2;\n ctx.quadraticCurveTo(points[i][0], points[i][1], xc, yc);\n }\n ctx.quadraticCurveTo(points[points.length - 2][0], points[points.length - 2][1], points[points.length - 1][0], points[points.length - 1][1]);\n ctx.stroke();\n if (localOptions.fillPolygons) {\n ctx.closePath();\n ctx.fill();\n }\n}\n\nexport async function gesture(inCanvas: HTMLCanvasElement, result: Array<Gesture>, drawOptions?: DrawOptions) {\n const localOptions = mergeDeep(options, drawOptions);\n if (!result || !inCanvas) return;\n if (!(inCanvas instanceof HTMLCanvasElement)) return;\n const ctx = inCanvas.getContext('2d');\n if (!ctx) return;\n ctx.font = localOptions.font;\n ctx.fillStyle = localOptions.color;\n let i = 1;\n for (let j = 0; j < result.length; j++) {\n let where: unknown[] = []; // what&where is a record\n let what: unknown[] = []; // what&where is a record\n [where, what] = Object.entries(result[j]);\n if ((what.length > 1) && ((what[1] as string).length > 0)) {\n const who = where[1] as number > 0 ? `#${where[1]}` : '';\n const label = `${where[0]} ${who}: ${what[1]}`;\n if (localOptions.shadowColor && localOptions.shadowColor !== '') {\n ctx.fillStyle = localOptions.shadowColor;\n ctx.fillText(label, 8, 2 + (i * localOptions.lineHeight));\n }\n ctx.fillStyle = localOptions.labelColor;\n ctx.fillText(label, 6, 0 + (i * localOptions.lineHeight));\n i += 1;\n }\n }\n}\n\nexport async function face(inCanvas: HTMLCanvasElement, result: Array<Face>, drawOptions?: DrawOptions) {\n const localOptions = mergeDeep(options, drawOptions);\n if (!result || !inCanvas) return;\n if (!(inCanvas instanceof HTMLCanvasElement)) return;\n const ctx = inCanvas.getContext('2d');\n if (!ctx) return;\n for (const f of result) {\n ctx.font = localOptions.font;\n ctx.strokeStyle = localOptions.color;\n ctx.fillStyle = localOptions.color;\n if (localOptions.drawBoxes) rect(ctx, f.box[0], f.box[1], f.box[2], f.box[3], localOptions);\n // silly hack since fillText does not suport new line\n const labels:string[] = [];\n labels.push(`face: ${Math.trunc(100 * f.score)}%`);\n if (f.genderScore) labels.push(`${f.gender || ''} ${Math.trunc(100 * f.genderScore)}%`);\n if (f.age) labels.push(`age: ${f.age || ''}`);\n if (f.iris) labels.push(`distance: ${f.iris}`);\n if (f.emotion && f.emotion.length > 0) {\n const emotion = f.emotion.map((a) => `${Math.trunc(100 * a.score)}% ${a.emotion}`);\n if (emotion.length > 3) emotion.length = 3;\n labels.push(emotion.join(' '));\n }\n if (f.rotation && f.rotation.angle && f.rotation.gaze) {\n if (f.rotation.angle.roll) labels.push(`roll: ${rad2deg(f.rotation.angle.roll)}\u00B0 yaw:${rad2deg(f.rotation.angle.yaw)}\u00B0 pitch:${rad2deg(f.rotation.angle.pitch)}\u00B0`);\n if (f.rotation.gaze.bearing) labels.push(`gaze: ${rad2deg(f.rotation.gaze.bearing)}\u00B0`);\n }\n if (labels.length === 0) labels.push('face');\n ctx.fillStyle = localOptions.color;\n for (let i = labels.length - 1; i >= 0; i--) {\n const x = Math.max(f.box[0], 0);\n const y = i * localOptions.lineHeight + f.box[1];\n if (localOptions.shadowColor && localOptions.shadowColor !== '') {\n ctx.fillStyle = localOptions.shadowColor;\n ctx.fillText(labels[i], x + 5, y + 16);\n }\n ctx.fillStyle = localOptions.labelColor;\n ctx.fillText(labels[i], x + 4, y + 15);\n }\n ctx.lineWidth = 1;\n if (f.mesh && f.mesh.length > 0) {\n if (localOptions.drawPoints) {\n for (const pt of f.mesh) point(ctx, pt[0], pt[1], pt[2], localOptions);\n // for (const pt of f.meshRaw) point(ctx, pt[0] * inCanvas.offsetWidth, pt[1] * inCanvas.offsetHeight, pt[2]);\n }\n if (localOptions.drawPolygons) {\n ctx.lineWidth = 1;\n for (let i = 0; i < triangulation.length / 3; i++) {\n const points = [\n triangulation[i * 3 + 0],\n triangulation[i * 3 + 1],\n triangulation[i * 3 + 2],\n ].map((index) => f.mesh[index]);\n lines(ctx, points, localOptions);\n }\n // iris: array[center, left, top, right, bottom]\n if (f.annotations && f.annotations['leftEyeIris']) {\n ctx.strokeStyle = localOptions.useDepth ? 'rgba(255, 200, 255, 0.3)' : localOptions.color;\n ctx.beginPath();\n const sizeX = Math.abs(f.annotations['leftEyeIris'][3][0] - f.annotations['leftEyeIris'][1][0]) / 2;\n const sizeY = Math.abs(f.annotations['leftEyeIris'][4][1] - f.annotations['leftEyeIris'][2][1]) / 2;\n ctx.ellipse(f.annotations['leftEyeIris'][0][0], f.annotations['leftEyeIris'][0][1], sizeX, sizeY, 0, 0, 2 * Math.PI);\n ctx.stroke();\n if (localOptions.fillPolygons) {\n ctx.fillStyle = localOptions.useDepth ? 'rgba(255, 255, 200, 0.3)' : localOptions.color;\n ctx.fill();\n }\n }\n if (f.annotations && f.annotations['rightEyeIris']) {\n ctx.strokeStyle = localOptions.useDepth ? 'rgba(255, 200, 255, 0.3)' : localOptions.color;\n ctx.beginPath();\n const sizeX = Math.abs(f.annotations['rightEyeIris'][3][0] - f.annotations['rightEyeIris'][1][0]) / 2;\n const sizeY = Math.abs(f.annotations['rightEyeIris'][4][1] - f.annotations['rightEyeIris'][2][1]) / 2;\n ctx.ellipse(f.annotations['rightEyeIris'][0][0], f.annotations['rightEyeIris'][0][1], sizeX, sizeY, 0, 0, 2 * Math.PI);\n ctx.stroke();\n if (localOptions.fillPolygons) {\n ctx.fillStyle = localOptions.useDepth ? 'rgba(255, 255, 200, 0.3)' : localOptions.color;\n ctx.fill();\n }\n }\n if (localOptions.drawGaze && f.rotation?.gaze?.strength && f.rotation?.gaze?.bearing && f.annotations['leftEyeIris'] && f.annotations['rightEyeIris'] && f.annotations['leftEyeIris'][0] && f.annotations['rightEyeIris'][0]) {\n ctx.strokeStyle = 'pink';\n ctx.beginPath();\n\n const leftGaze = [\n f.annotations['leftEyeIris'][0][0] + (Math.sin(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[3]),\n f.annotations['leftEyeIris'][0][1] + (Math.cos(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[2]),\n ];\n ctx.moveTo(f.annotations['leftEyeIris'][0][0], f.annotations['leftEyeIris'][0][1]);\n ctx.lineTo(leftGaze[0], leftGaze[1]);\n\n const rightGaze = [\n f.annotations['rightEyeIris'][0][0] + (Math.sin(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[3]),\n f.annotations['rightEyeIris'][0][1] + (Math.cos(f.rotation.gaze.bearing) * f.rotation.gaze.strength * f.box[2]),\n ];\n ctx.moveTo(f.annotations['rightEyeIris'][0][0], f.annotations['rightEyeIris'][0][1]);\n ctx.lineTo(rightGaze[0], rightGaze[1]);\n\n ctx.stroke();\n }\n }\n }\n }\n}\n\nexport async function body(inCanvas: HTMLCanvasElement, result: Array<Body>, drawOptions?: DrawOptions) {\n const localOptions = mergeDeep(options, drawOptions);\n if (!result || !inCanvas) return;\n if (!(inCanvas instanceof HTMLCanvasElement)) return;\n const ctx = inCanvas.getContext('2d');\n if (!ctx) return;\n ctx.lineJoin = 'round';\n for (let i = 0; i < result.length; i++) {\n ctx.strokeStyle = localOptions.color;\n ctx.fillStyle = localOptions.color;\n ctx.lineWidth = localOptions.lineWidth;\n ctx.font = localOptions.font;\n if (localOptions.drawBoxes && result[i].box && result[i].box?.length === 4) {\n // @ts-ignore box may not exist\n rect(ctx, result[i].box[0], result[i].box[1], result[i].box[2], result[i].box[3], localOptions);\n if (localOptions.drawLabels) {\n if (localOptions.shadowColor && localOptions.shadowColor !== '') {\n ctx.fillStyle = localOptions.shadowColor;\n // @ts-ignore box may not exist\n ctx.fillText(`body ${100 * result[i].score}%`, result[i].box[0] + 3, 1 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);\n }\n ctx.fillStyle = localOptions.labelColor;\n // @ts-ignore box may not exist\n ctx.fillText(`body ${100 * result[i].score}%`, result[i].box[0] + 2, 0 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);\n }\n }\n if (localOptions.drawPoints) {\n for (let pt = 0; pt < result[i].keypoints.length; pt++) {\n ctx.fillStyle = localOptions.useDepth && result[i].keypoints[pt].position[2] ? `rgba(${127.5 + (2 * (result[i].keypoints[pt].position[2] || 0))}, ${127.5 - (2 * (result[i].keypoints[pt].position[2] || 0))}, 255, 0.5)` : localOptions.color;\n point(ctx, result[i].keypoints[pt].position[0], result[i].keypoints[pt].position[1], 0, localOptions);\n }\n }\n if (localOptions.drawLabels) {\n ctx.font = localOptions.font;\n if (result[i].keypoints) {\n for (const pt of result[i].keypoints) {\n ctx.fillStyle = localOptions.useDepth && pt.position[2] ? `rgba(${127.5 + (2 * pt.position[2])}, ${127.5 - (2 * pt.position[2])}, 255, 0.5)` : localOptions.color;\n ctx.fillText(`${pt.part} ${Math.trunc(100 * pt.score)}%`, pt.position[0] + 4, pt.position[1] + 4);\n }\n }\n }\n if (localOptions.drawPolygons && result[i].keypoints) {\n let part;\n const points: [number, number, number?][] = [];\n // shoulder line\n points.length = 0;\n part = result[i].keypoints.find((a) => a.part === 'leftShoulder');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightShoulder');\n if (part) points.push([part.position[0], part.position[1]]);\n curves(ctx, points, localOptions);\n // torso main\n points.length = 0;\n part = result[i].keypoints.find((a) => a.part === 'rightShoulder');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightHip');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftHip');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftShoulder');\n if (part) points.push([part.position[0], part.position[1]]);\n if (points.length === 4) lines(ctx, points, localOptions); // only draw if we have complete torso\n // leg left\n points.length = 0;\n part = result[i].keypoints.find((a) => a.part === 'leftHip');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftKnee');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftAnkle');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftHeel');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftFoot');\n if (part) points.push([part.position[0], part.position[1]]);\n curves(ctx, points, localOptions);\n // leg right\n points.length = 0;\n part = result[i].keypoints.find((a) => a.part === 'rightHip');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightKnee');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightAnkle');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightHeel');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightFoot');\n if (part) points.push([part.position[0], part.position[1]]);\n curves(ctx, points, localOptions);\n // arm left\n points.length = 0;\n part = result[i].keypoints.find((a) => a.part === 'leftShoulder');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftElbow');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftWrist');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'leftPalm');\n if (part) points.push([part.position[0], part.position[1]]);\n curves(ctx, points, localOptions);\n // arm right\n points.length = 0;\n part = result[i].keypoints.find((a) => a.part === 'rightShoulder');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightElbow');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightWrist');\n if (part) points.push([part.position[0], part.position[1]]);\n part = result[i].keypoints.find((a) => a.part === 'rightPalm');\n if (part) points.push([part.position[0], part.position[1]]);\n curves(ctx, points, localOptions);\n // draw all\n }\n }\n}\n\nexport async function hand(inCanvas: HTMLCanvasElement, result: Array<Hand>, drawOptions?: DrawOptions) {\n const localOptions = mergeDeep(options, drawOptions);\n if (!result || !inCanvas) return;\n if (!(inCanvas instanceof HTMLCanvasElement)) return;\n const ctx = inCanvas.getContext('2d');\n if (!ctx) return;\n ctx.lineJoin = 'round';\n ctx.font = localOptions.font;\n for (const h of result) {\n if (localOptions.drawBoxes) {\n ctx.strokeStyle = localOptions.color;\n ctx.fillStyle = localOptions.color;\n rect(ctx, h.box[0], h.box[1], h.box[2], h.box[3], localOptions);\n if (localOptions.drawLabels) {\n if (localOptions.shadowColor && localOptions.shadowColor !== '') {\n ctx.fillStyle = localOptions.shadowColor;\n ctx.fillText('hand', h.box[0] + 3, 1 + h.box[1] + localOptions.lineHeight, h.box[2]);\n }\n ctx.fillStyle = localOptions.labelColor;\n ctx.fillText('hand', h.box[0] + 2, 0 + h.box[1] + localOptions.lineHeight, h.box[2]);\n }\n ctx.stroke();\n }\n if (localOptions.drawPoints) {\n if (h.keypoints && h.keypoints.length > 0) {\n for (const pt of h.keypoints) {\n ctx.fillStyle = localOptions.useDepth ? `rgba(${127.5 + (2 * pt[2])}, ${127.5 - (2 * pt[2])}, 255, 0.5)` : localOptions.color;\n point(ctx, pt[0], pt[1], 0, localOptions);\n }\n }\n }\n if (localOptions.drawLabels) {\n const addHandLabel = (part, title) => {\n ctx.fillStyle = localOptions.useDepth ? `rgba(${127.5 + (2 * part[part.length - 1][2])}, ${127.5 - (2 * part[part.length - 1][2])}, 255, 0.5)` : localOptions.color;\n ctx.fillText(title, part[part.length - 1][0] + 4, part[part.length - 1][1] + 4);\n };\n ctx.font = localOptions.font;\n addHandLabel(h.annotations['indexFinger'], 'index');\n addHandLabel(h.annotations['middleFinger'], 'middle');\n addHandLabel(h.annotations['ringFinger'], 'ring');\n addHandLabel(h.annotations['pinky'], 'pinky');\n addHandLabel(h.annotations['thumb'], 'thumb');\n addHandLabel(h.annotations['palmBase'], 'palm');\n }\n if (localOptions.drawPolygons) {\n const addHandLine = (part) => {\n if (!part) return;\n for (let i = 0; i < part.length; i++) {\n ctx.beginPath();\n ctx.strokeStyle = localOptions.useDepth ? `rgba(${127.5 + (2 * part[i][2])}, ${127.5 - (2 * part[i][2])}, 255, 0.5)` : localOptions.color;\n ctx.moveTo(part[i > 0 ? i - 1 : 0][0], part[i > 0 ? i - 1 : 0][1]);\n ctx.lineTo(part[i][0], part[i][1]);\n ctx.stroke();\n }\n };\n ctx.lineWidth = localOptions.lineWidth;\n addHandLine(h.annotations['indexFinger']);\n addHandLine(h.annotations['middleFinger']);\n addHandLine(h.annotations['ringFinger']);\n addHandLine(h.annotations['pinky']);\n addHandLine(h.annotations['thumb']);\n // addPart(h.annotations.palmBase);\n }\n }\n}\n\nexport async function object(inCanvas: HTMLCanvasElement, result: Array<Item>, drawOptions?: DrawOptions) {\n const localOptions = mergeDeep(options, drawOptions);\n if (!result || !inCanvas) return;\n if (!(inCanvas instanceof HTMLCanvasElement)) return;\n const ctx = inCanvas.getContext('2d');\n if (!ctx) return;\n ctx.lineJoin = 'round';\n ctx.font = localOptions.font;\n for (const h of result) {\n if (localOptions.drawBoxes) {\n ctx.strokeStyle = localOptions.color;\n ctx.fillStyle = localOptions.color;\n rect(ctx, h.box[0], h.box[1], h.box[2], h.box[3], localOptions);\n if (localOptions.drawLabels) {\n const label = `${h.label} ${Math.round(100 * h.score)}%`;\n if (localOptions.shadowColor && localOptions.shadowColor !== '') {\n ctx.fillStyle = localOptions.shadowColor;\n ctx.fillText(label, h.box[0] + 3, 1 + h.box[1] + localOptions.lineHeight, h.box[2]);\n }\n ctx.fillStyle = localOptions.labelColor;\n ctx.fillText(label, h.box[0] + 2, 0 + h.box[1] + localOptions.lineHeight, h.box[2]);\n }\n ctx.stroke();\n }\n }\n}\n\nexport async function person(inCanvas: HTMLCanvasElement, result: Array<Person>, drawOptions?: DrawOptions) {\n const localOptions = mergeDeep(options, drawOptions);\n if (!result || !inCanvas) return;\n if (!(inCanvas instanceof HTMLCanvasElement)) return;\n const ctx = inCanvas.getContext('2d');\n if (!ctx) return;\n ctx.lineJoin = 'round';\n ctx.font = localOptions.font;\n\n for (let i = 0; i < result.length; i++) {\n if (localOptions.drawBoxes) {\n ctx.strokeStyle = localOptions.color;\n ctx.fillStyle = localOptions.color;\n rect(ctx, result[i].box[0], result[i].box[1], result[i].box[2], result[i].box[3], localOptions);\n if (localOptions.drawLabels) {\n const label = `person #${i}`;\n if (localOptions.shadowColor && localOptions.shadowColor !== '') {\n ctx.fillStyle = localOptions.shadowColor;\n ctx.fillText(label, result[i].box[0] + 3, 1 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);\n }\n ctx.fillStyle = localOptions.labelColor;\n ctx.fillText(label, result[i].box[0] + 2, 0 + result[i].box[1] + localOptions.lineHeight, result[i].box[2]);\n }\n ctx.stroke();\n }\n }\n}\n\nexport async function canvas(inCanvas: HTMLCanvasElement, outCanvas: HTMLCanvasElement) {\n if (!inCanvas || !outCanvas) return;\n if (!(inCanvas instanceof HTMLCanvasElement) || !(outCanvas instanceof HTMLCanvasElement)) return;\n const outCtx = inCanvas.getContext('2d');\n outCtx?.drawImage(inCanvas, 0, 0);\n}\n\nexport async function all(inCanvas: HTMLCanvasElement, result: Result, drawOptions?: DrawOptions) {\n const timestamp = now();\n const localOptions = mergeDeep(options, drawOptions);\n if (!result || !inCanvas) return;\n if (!(inCanvas instanceof HTMLCanvasElement)) return;\n\n face(inCanvas, result.face, localOptions);\n body(inCanvas, result.body, localOptions);\n hand(inCanvas, result.hand, localOptions);\n object(inCanvas, result.object, localOptions);\n // person(inCanvas, result.persons, localOptions);\n gesture(inCanvas, result.gesture, localOptions); // gestures do not have buffering\n\n /*\n if (!bufferedResult) bufferedResult = result; // first pass\n else if (localOptions.bufferedOutput) calcBuffered(result); // do results interpolation\n else bufferedResult = result; // or just use results as-is\n const promises: Promise<void>[] = [];\n promises.push(face(inCanvas, bufferedResult.face, localOptions));\n promises.push(body(inCanvas, bufferedResult.body, localOptions));\n promises.push(hand(inCanvas, bufferedResult.hand, localOptions));\n promises.push(object(inCanvas, bufferedResult.object, localOptions));\n // promises.push(person(inCanvas, bufferedResult.persons, localOptions));\n promises.push(gesture(inCanvas, result.gesture, localOptions)); // gestures do not have buffering\n // await Promise.all(promises);\n */\n result.performance.draw = Math.trunc(now() - timestamp);\n}\n", "/**\n * Module that analyzes existing results and recombines them into a unified person object\n */\n\nimport { Face, Body, Hand, Gesture, Person } from './result';\n\nexport function join(faces: Array<Face>, bodies: Array<Body>, hands: Array<Hand>, gestures: Array<Gesture>, shape: Array<number> | undefined): Array<Person> {\n let id = 0;\n const persons: Array<Person> = [];\n for (const face of faces) { // person is defined primarily by face and then we append other objects as found\n const person: Person = { id: id++, face, body: null, hands: { left: null, right: null }, gestures: [], box: [0, 0, 0, 0] };\n for (const body of bodies) {\n if (face.box[0] > body.box[0] // x within body\n && face.box[0] < body.box[0] + body.box[2]\n && face.box[1] + face.box[3] > body.box[1] // y within body\n && face.box[1] + face.box[3] < body.box[1] + body.box[3]) {\n person.body = body;\n }\n }\n if (person.body) { // only try to join hands if body is found\n for (const hand of hands) {\n if (hand.box[0] + hand.box[2] > person.body.box[0] // x within body for left hand\n && hand.box[0] + hand.box[2] < person.body.box[0] + person.body.box[2]\n && hand.box[1] + hand.box[3] > person.body.box[1] // x within body for left hand\n && hand.box[1] + hand.box[3] < person.body.box[1] + person.body.box[3]) {\n if (person.hands) person.hands.left = hand;\n }\n if (hand.box[0] < person.body.box[0] + person.body.box[2] // x within body for right hand\n && hand.box[0] > person.body.box[0]\n && hand.box[1] + hand.box[3] > person.body.box[1] // x within body for right hand\n && hand.box[1] + hand.box[3] < person.body.box[1] + person.body.box[3]) {\n if (person.hands) person.hands.right = hand;\n }\n }\n }\n for (const gesture of gestures) { // append all gestures according to ids\n if (gesture['face'] !== undefined && gesture['face'] === face.id) person.gestures?.push(gesture);\n else if (gesture['iris'] !== undefined && gesture['iris'] === face.id) person.gestures?.push(gesture);\n else if (gesture['body'] !== undefined && gesture['body'] === person.body?.id) person.gestures?.push(gesture);\n else if (gesture['hand'] !== undefined && gesture['hand'] === person.hands?.left?.id) person.gestures?.push(gesture);\n else if (gesture['hand'] !== undefined && gesture['hand'] === person.hands?.right?.id) person.gestures?.push(gesture);\n }\n\n // create new overarching box from all boxes beloning to person\n const x: number[] = [];\n const y: number[] = [];\n const extractXY = (box) => { // extract all [x, y] coordinates from boxes [x, y, width, height]\n if (box && box.length === 4) {\n x.push(box[0], box[0] + box[2]);\n y.push(box[1], box[1] + box[3]);\n }\n };\n extractXY(person.face?.box);\n extractXY(person.body?.box);\n extractXY(person.hands?.left?.box);\n extractXY(person.hands?.right?.box);\n const minX = Math.min(...x);\n const minY = Math.min(...y);\n person.box = [minX, minY, Math.max(...x) - minX, Math.max(...y) - minY]; // create new overarching box\n\n // shape is known so we calculate boxRaw as well\n if (shape && shape.length === 4) person.boxRaw = [person.box[0] / shape[2], person.box[1] / shape[1], person.box[2] / shape[2], person.box[3] / shape[1]];\n\n persons.push(person);\n }\n return persons;\n}\n", "/**\n * Module that interpolates results for smoother animations\n */\n\nimport type { Result, Face, Body, Hand, Item, Gesture, Person } from './result';\n\nconst bufferedResult: Result = { face: [], body: [], hand: [], gesture: [], object: [], persons: [], performance: {}, timestamp: 0 };\n\nexport function calc(newResult: Result): Result {\n // each record is only updated using deep clone when number of detected record changes, otherwise it will converge by itself\n // otherwise bufferedResult is a shallow clone of result plus updated local calculated values\n // thus mixing by-reference and by-value assignments to minimize memory operations\n\n const elapsed = Date.now() - newResult.timestamp;\n // curve fitted: buffer = 8 - ln(delay)\n // interpolation formula: current = ((buffer - 1) * previous + live) / buffer\n // - at 50ms delay buffer = ~4.1 => 28% towards live data\n // - at 250ms delay buffer = ~2.5 => 40% towards live data\n // - at 500ms delay buffer = ~1.8 => 55% towards live data\n // - at 750ms delay buffer = ~1.4 => 71% towards live data\n // - at 1sec delay buffer = 1 which means live data is used\n const bufferedFactor = elapsed < 1000 ? 8 - Math.log(elapsed) : 1;\n\n bufferedResult.canvas = newResult.canvas;\n\n // interpolate body results\n if (!bufferedResult.body || (newResult.body.length !== bufferedResult.body.length)) {\n bufferedResult.body = JSON.parse(JSON.stringify(newResult.body as Body[])); // deep clone once\n } else {\n for (let i = 0; i < newResult.body.length; i++) {\n const box = newResult.body[i].box // update box\n .map((b, j) => ((bufferedFactor - 1) * bufferedResult.body[i].box[j] + b) / bufferedFactor) as [number, number, number, number];\n const boxRaw = newResult.body[i].boxRaw // update boxRaw\n .map((b, j) => ((bufferedFactor - 1) * bufferedResult.body[i].boxRaw[j] + b) / bufferedFactor) as [number, number, number, number];\n const keypoints = (newResult.body[i].keypoints // update keypoints\n .map((keypoint, j) => ({\n score: keypoint.score,\n part: keypoint.part,\n position: [\n bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * bufferedResult.body[i].keypoints[j].position[0] + keypoint.position[0]) / bufferedFactor : keypoint.position[0],\n bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * bufferedResult.body[i].keypoints[j].position[1] + keypoint.position[1]) / bufferedFactor : keypoint.position[1],\n ],\n positionRaw: [\n bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * bufferedResult.body[i].keypoints[j].positionRaw[0] + keypoint.positionRaw[0]) / bufferedFactor : keypoint.position[0],\n bufferedResult.body[i].keypoints[j] ? ((bufferedFactor - 1) * bufferedResult.body[i].keypoints[j].positionRaw[1] + keypoint.positionRaw[1]) / bufferedFactor : keypoint.position[1],\n ],\n }))) as Array<{ score: number, part: string, position: [number, number, number?], positionRaw: [number, number, number?] }>;\n bufferedResult.body[i] = { ...newResult.body[i], box, boxRaw, keypoints }; // shallow clone plus updated values\n }\n }\n\n // interpolate hand results\n if (!bufferedResult.hand || (newResult.hand.length !== bufferedResult.hand.length)) {\n bufferedResult.hand = JSON.parse(JSON.stringify(newResult.hand as Hand[])); // deep clone once\n } else {\n for (let i = 0; i < newResult.hand.length; i++) {\n const box = (newResult.hand[i].box// update box\n .map((b, j) => ((bufferedFactor - 1) * bufferedResult.hand[i].box[j] + b) / bufferedFactor)) as [number, number, number, number];\n const boxRaw = (newResult.hand[i].boxRaw // update boxRaw\n .map((b, j) => ((bufferedFactor - 1) * bufferedResult.hand[i].boxRaw[j] + b) / bufferedFactor)) as [number, number, number, number];\n const keypoints = newResult.hand[i].keypoints // update landmarks\n .map((landmark, j) => landmark\n .map((coord, k) => (((bufferedFactor - 1) * bufferedResult.hand[i].keypoints[j][k] + coord) / bufferedFactor)) as [number, number, number]);\n const keys = Object.keys(newResult.hand[i].annotations); // update annotations\n const annotations = {};\n for (const key of keys) {\n annotations[key] = newResult.hand[i].annotations[key]\n .map((val, j) => val.map((coord, k) => ((bufferedFactor - 1) * bufferedResult.hand[i].annotations[key][j][k] + coord) / bufferedFactor));\n }\n bufferedResult.hand[i] = { ...newResult.hand[i], box, boxRaw, keypoints, annotations }; // shallow clone plus updated values\n }\n }\n\n // interpolate face results\n if (!bufferedResult.face || (newResult.face.length !== bufferedResult.face.length)) {\n bufferedResult.face = JSON.parse(JSON.stringify(newResult.face as Face[])); // deep clone once\n } else {\n for (let i = 0; i < newResult.face.length; i++) {\n const box = (newResult.face[i].box // update box\n .map((b, j) => ((bufferedFactor - 1) * bufferedResult.face[i].box[j] + b) / bufferedFactor)) as [number, number, number, number];\n const boxRaw = (newResult.face[i].boxRaw // update boxRaw\n .map((b, j) => ((bufferedFactor - 1) * bufferedResult.face[i].boxRaw[j] + b) / bufferedFactor)) as [number, number, number, number];\n const rotation: {\n matrix: [number, number, number, number, number, number, number, number, number],\n angle: { roll: number, yaw: number, pitch: number },\n gaze: { bearing: number, strength: number }\n } = { matrix: [0, 0, 0, 0, 0, 0, 0, 0, 0], angle: { roll: 0, yaw: 0, pitch: 0 }, gaze: { bearing: 0, strength: 0 } };\n rotation.matrix = newResult.face[i].rotation?.matrix as [number, number, number, number, number, number, number, number, number];\n rotation.angle = {\n roll: ((bufferedFactor - 1) * (bufferedResult.face[i].rotation?.angle?.roll || 0) + (newResult.face[i].rotation?.angle?.roll || 0)) / bufferedFactor,\n yaw: ((bufferedFactor - 1) * (bufferedResult.face[i].rotation?.angle?.yaw || 0) + (newResult.face[i].rotation?.angle?.yaw || 0)) / bufferedFactor,\n pitch: ((bufferedFactor - 1) * (bufferedResult.face[i].rotation?.angle?.pitch || 0) + (newResult.face[i].rotation?.angle?.pitch || 0)) / bufferedFactor,\n };\n rotation.gaze = {\n // not fully correct due projection on circle, also causes wrap-around draw on jump from negative to positive\n bearing: ((bufferedFactor - 1) * (bufferedResult.face[i].rotation?.gaze?.bearing || 0) + (newResult.face[i].rotation?.gaze?.bearing || 0)) / bufferedFactor,\n strength: ((bufferedFactor - 1) * (bufferedResult.face[i].rotation?.gaze?.strength || 0) + (newResult.face[i].rotation?.gaze?.strength || 0)) / bufferedFactor,\n };\n bufferedResult.face[i] = { ...newResult.face[i], rotation, box, boxRaw }; // shallow clone plus updated values\n }\n }\n\n // interpolate object detection results\n if (!bufferedResult.object || (newResult.object.length !== bufferedResult.object.length)) {\n bufferedResult.object = JSON.parse(JSON.stringify(newResult.object as Item[])); // deep clone once\n } else {\n for (let i = 0; i < newResult.object.length; i++) {\n const box = (newResult.object[i].box // update box\n .map((b, j) => ((bufferedFactor - 1) * bufferedResult.object[i].box[j] + b) / bufferedFactor)) as [number, number, number, number];\n const boxRaw = (newResult.object[i].boxRaw // update boxRaw\n .map((b, j) => ((bufferedFactor - 1) * bufferedResult.object[i].boxRaw[j] + b) / bufferedFactor)) as [number, number, number, number];\n bufferedResult.object[i] = { ...newResult.object[i], box, boxRaw }; // shallow clone plus updated values\n }\n }\n\n // interpolate person results\n if (newResult.persons) {\n const newPersons = newResult.persons; // trigger getter function\n if (!bufferedResult.persons || (newPersons.length !== bufferedResult.persons.length)) {\n bufferedResult.persons = JSON.parse(JSON.stringify(newPersons as Person[]));\n } else {\n for (let i = 0; i < newPersons.length; i++) { // update person box, we don't update the rest as it's updated as reference anyhow\n bufferedResult.persons[i].box = (newPersons[i].box\n .map((box, j) => ((bufferedFactor - 1) * bufferedResult.persons[i].box[j] + box) / bufferedFactor)) as [number, number, number, number];\n }\n }\n }\n\n // just copy latest gestures without interpolation\n if (newResult.gesture) bufferedResult.gesture = newResult.gesture as Gesture[];\n if (newResult.performance) bufferedResult.performance = newResult.performance;\n\n return bufferedResult;\n}\n", "/**\n * Embedded sample images used during warmup in dataURL format\n */\n\n// data:image/jpeg;base64,\nexport const face = `\n/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUA\nAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQu\nbmV0IDQuMi4xMwAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxob\nIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgBAAEAAwEhAAIRAQMRAf/E\nAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAE\nEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZH\nSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1\ntre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEB\nAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXET\nIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFla\nY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp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lBhEMohlFerLlBjEMohMVTEARDKCITsAk2AEgAAAkAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAD/\n2Q==`;\n", "/**\n * Human main module\n */\n\nimport { log, now, mergeDeep } from './helpers';\nimport { Config, defaults } from './config';\nimport { Result, Gesture } from './result';\nimport * as sysinfo from './sysinfo';\nimport * as tf from '../dist/tfjs.esm.js';\nimport * as backend from './tfjs/backend';\nimport * as models from './models';\nimport * as face from './face';\nimport * as facemesh from './blazeface/facemesh';\nimport * as faceres from './faceres/faceres';\nimport * as posenet from './posenet/posenet';\nimport * as handpose from './handpose/handpose';\nimport * as blazepose from './blazepose/blazepose';\nimport * as efficientpose from './efficientpose/efficientpose';\nimport * as movenet from './movenet/movenet';\nimport * as nanodet from './object/nanodet';\nimport * as centernet from './object/centernet';\nimport * as segmentation from './segmentation/segmentation';\nimport * as gesture from './gesture/gesture';\nimport * as image from './image/image';\nimport * as draw from './draw/draw';\nimport * as persons from './persons';\nimport * as interpolate from './interpolate';\nimport * as sample from './sample';\nimport * as app from '../package.json';\nimport { Tensor, GraphModel } from './tfjs/types';\n\n// export types\nexport type { Config } from './config';\nexport type { Result, Face, Hand, Body, Item, Gesture, Person } from './result';\nexport type { DrawOptions } from './draw/draw';\n\n/** Defines all possible input types for **Human** detection\n * @typedef Input Type\n */\nexport type Input = Tensor | typeof Image | ImageData | ImageBitmap | HTMLImageElement | HTMLMediaElement | HTMLVideoElement | HTMLCanvasElement | OffscreenCanvas;\n\n/** Error message\n * @typedef Error Type\n */\nexport type Error = { error: string };\n\n/** Instance of TensorFlow/JS\n * @external\n */\nexport type TensorFlow = typeof tf;\n\n/**\n * **Human** library main class\n *\n * All methods and properties are available only as members of Human class\n *\n * - Configuration object definition: {@link Config}\n * - Results object definition: {@link Result}\n * - Possible inputs: {@link Input}\n *\n * @param userConfig: {@link Config}\n */\nexport class Human {\n /** Current version of Human library in *semver* format */\n version: string;\n /** Current configuration\n * - Details: {@link Config}\n */\n config: Config;\n /** Last known result of detect run\n * - Can be accessed anytime after initial detection\n */\n result: Result;\n /** Current state of Human library\n * - Can be polled to determine operations that are currently executed\n * - Progresses through: 'config', 'check', 'backend', 'load', 'run:<model>', 'idle'\n */\n state: string;\n /** @internal: Instance of current image being processed */\n image: { tensor: Tensor | null, canvas: OffscreenCanvas | HTMLCanvasElement | null };\n /** @internal: Instance of TensorFlow/JS used by Human\n * - Can be embedded or externally provided\n */\n tf: TensorFlow;\n /** Draw helper classes that can draw detected objects on canvas using specified draw\n * - options: {@link DrawOptions} global settings for all draw operations, can be overriden for each draw method\n * - face: draw detected faces\n * - body: draw detected people and body parts\n * - hand: draw detected hands and hand parts\n * - canvas: draw processed canvas which is a processed copy of the input\n * - all: meta-function that performs: canvas, face, body, hand\n */\n draw: {\n options: draw.DrawOptions,\n gesture: typeof draw.gesture,\n face: typeof draw.face,\n body: typeof draw.body,\n hand: typeof draw.hand,\n canvas: typeof draw.canvas,\n all: typeof draw.all,\n };\n /** @internal: Currently loaded models */\n models: {\n face: [unknown, GraphModel | null, GraphModel | null] | null,\n posenet: GraphModel | null,\n blazepose: GraphModel | null,\n efficientpose: GraphModel | null,\n movenet: GraphModel | null,\n handpose: [GraphModel | null, GraphModel | null] | null,\n age: GraphModel | null,\n gender: GraphModel | null,\n emotion: GraphModel | null,\n embedding: GraphModel | null,\n nanodet: GraphModel | null,\n centernet: GraphModel | null,\n faceres: GraphModel | null,\n segmentation: GraphModel | null,\n };\n /** Reference face triangualtion array of 468 points, used for triangle references between points */\n faceTriangulation: typeof facemesh.triangulation;\n /** Refernce UV map of 468 values, used for 3D mapping of the face mesh */\n faceUVMap: typeof facemesh.uvmap;\n /** Platform and agent information detected by Human */\n sysinfo: { platform: string, agent: string };\n /** Performance object that contains values for all recently performed operations */\n performance: Record<string, number>; // perf members are dynamically defined as needed\n #numTensors: number;\n #analyzeMemoryLeaks: boolean;\n #checkSanity: boolean;\n #firstRun: boolean;\n #lastInputSum: number;\n #lastCacheDiff: number;\n\n // definition end\n\n /**\n * Creates instance of Human library that is futher used for all operations\n * @param userConfig: {@link Config}\n */\n constructor(userConfig?: Config | Record<string, unknown>) {\n this.config = mergeDeep(defaults, userConfig || {});\n this.tf = tf;\n this.draw = draw;\n this.version = app.version;\n this.state = 'idle';\n this.#numTensors = 0;\n this.#analyzeMemoryLeaks = false;\n this.#checkSanity = false;\n this.#firstRun = true;\n this.#lastCacheDiff = 0;\n this.performance = { backend: 0, load: 0, image: 0, frames: 0, cached: 0, changed: 0, total: 0, draw: 0 };\n // object that contains all initialized models\n this.models = {\n face: null,\n posenet: null,\n blazepose: null,\n efficientpose: null,\n movenet: null,\n handpose: null,\n age: null,\n gender: null,\n emotion: null,\n embedding: null,\n nanodet: null,\n centernet: null,\n faceres: null,\n segmentation: null,\n };\n // export access to image processing\n // @ts-ignore eslint-typescript cannot correctly infer type in anonymous function\n this.image = (input: Input) => image.process(input, this.config);\n // export raw access to underlying models\n this.faceTriangulation = facemesh.triangulation;\n this.faceUVMap = facemesh.uvmap;\n // include platform info\n this.sysinfo = sysinfo.info();\n this.#lastInputSum = 1;\n }\n\n // helper function: measure tensor leak\n /** @hidden */\n analyze = (...msg) => {\n if (!this.#analyzeMemoryLeaks) return;\n const currentTensors = this.tf.engine().state.numTensors;\n const previousTensors = this.#numTensors;\n this.#numTensors = currentTensors;\n const leaked = currentTensors - previousTensors;\n if (leaked !== 0) log(...msg, leaked);\n }\n\n // quick sanity check on inputs\n /** @hidden */\n #sanity = (input): null | string => {\n if (!this.#checkSanity) return null;\n if (!input) return 'input is not defined';\n if (this.tf.ENV.flags.IS_NODE && !(input instanceof tf.Tensor)) return 'input must be a tensor';\n try {\n this.tf.getBackend();\n } catch {\n return 'backend not loaded';\n }\n return null;\n }\n\n /** Simmilarity method calculates simmilarity between two provided face descriptors (face embeddings)\n * - Calculation is based on normalized Minkowski distance between\n *\n * @param embedding1: face descriptor as array of numbers\n * @param embedding2: face descriptor as array of numbers\n * @returns similarity: number\n */\n // eslint-disable-next-line class-methods-use-this\n similarity(embedding1: Array<number>, embedding2: Array<number>): number {\n return faceres.similarity(embedding1, embedding2);\n }\n\n /**\n * Segmentation method takes any input and returns processed canvas with body segmentation\n * Optional parameter background is used to fill the background with specific input\n * Segmentation is not triggered as part of detect process\n *\n * @param input: {@link Input}\n * @param background?: {@link Input}\n * @returns Canvas\n */\n segmentation(input: Input, background?: Input) {\n return segmentation.process(input, background, this.config);\n }\n\n /** Enhance method performs additional enhacements to face image previously detected for futher processing\n * @param input: Tensor as provided in human.result.face[n].tensor\n * @returns Tensor\n */\n // eslint-disable-next-line class-methods-use-this\n enhance(input: Tensor): Tensor | null {\n // @ts-ignore type mismach for Tensor\n return faceres.enhance(input);\n }\n\n /** Math method find best match between provided face descriptor and predefined database of known descriptors\n * @param faceEmbedding: face descriptor previsouly calculated on any face\n * @param db: array of mapping of face descriptors to known values\n * @param threshold: minimum score for matching to be considered in the result\n * @returns best match\n */\n // eslint-disable-next-line class-methods-use-this\n match(faceEmbedding: Array<number>, db: Array<{ name: string, source: string, embedding: number[] }>, threshold = 0): { name: string, source: string, similarity: number, embedding: number[] } {\n return faceres.match(faceEmbedding, db, threshold);\n }\n\n /** Load method preloads all configured models on-demand\n * - Not explicitly required as any required model is load implicitly on it's first run\n * @param userConfig?: {@link Config}\n */\n async load(userConfig?: Config | Record<string, unknown>) {\n this.state = 'load';\n const timeStamp = now();\n if (userConfig) this.config = mergeDeep(this.config, userConfig) as Config;\n\n if (this.#firstRun) { // print version info on first run and check for correct backend setup\n if (this.config.debug) log(`version: ${this.version}`);\n if (this.config.debug) log(`tfjs version: ${this.tf.version_core}`);\n if (this.config.debug) log('platform:', this.sysinfo.platform);\n if (this.config.debug) log('agent:', this.sysinfo.agent);\n\n await this.#checkBackend(true);\n if (this.tf.ENV.flags.IS_BROWSER) {\n if (this.config.debug) log('configuration:', this.config);\n if (this.config.debug) log('tf flags:', this.tf.ENV.flags);\n }\n }\n\n await models.load(this); // actually loads models\n\n if (this.#firstRun) { // print memory stats on first run\n if (this.config.debug) log('tf engine state:', this.tf.engine().state.numBytes, 'bytes', this.tf.engine().state.numTensors, 'tensors');\n this.#firstRun = false;\n }\n\n const current = Math.trunc(now() - timeStamp);\n if (current > (this.performance.load as number || 0)) this.performance.load = current;\n }\n\n // check if backend needs initialization if it changed\n /** @hidden */\n #checkBackend = async (force = false) => {\n if (this.config.backend && (this.config.backend.length > 0) && force || (this.tf.getBackend() !== this.config.backend)) {\n const timeStamp = now();\n this.state = 'backend';\n /* force backend reload\n if (this.config.backend in tf.engine().registry) {\n const backendFactory = tf.findBackendFactory(this.config.backend);\n tf.removeBackend(this.config.backend);\n tf.registerBackend(this.config.backend, backendFactory);\n } else {\n log('Backend not registred:', this.config.backend);\n }\n */\n\n if (this.config.backend && this.config.backend.length > 0) {\n // @ts-ignore ignore missing type for WorkerGlobalScope as that is the point\n if (typeof window === 'undefined' && typeof WorkerGlobalScope !== 'undefined' && this.config.debug) log('running inside web worker');\n\n // force browser vs node backend\n if (this.tf.ENV.flags.IS_BROWSER && this.config.backend === 'tensorflow') this.config.backend = 'webgl';\n if (this.tf.ENV.flags.IS_NODE && (this.config.backend === 'webgl' || this.config.backend === 'humangl')) this.config.backend = 'tensorflow';\n\n if (this.config.debug) log('setting backend:', this.config.backend);\n\n if (this.config.backend === 'wasm') {\n if (this.config.debug) log('wasm path:', this.config.wasmPath);\n if (typeof this.tf?.setWasmPaths !== 'undefined') this.tf.setWasmPaths(this.config.wasmPath);\n else throw new Error('Human: WASM backend is not loaded');\n const simd = await this.tf.env().getAsync('WASM_HAS_SIMD_SUPPORT');\n const mt = await this.tf.env().getAsync('WASM_HAS_MULTITHREAD_SUPPORT');\n if (this.config.debug) log(`wasm execution: ${simd ? 'SIMD' : 'no SIMD'} ${mt ? 'multithreaded' : 'singlethreaded'}`);\n if (this.config.debug && !simd) log('warning: wasm simd support is not enabled');\n }\n\n if (this.config.backend === 'humangl') backend.register();\n try {\n await this.tf.setBackend(this.config.backend);\n } catch (err) {\n log('error: cannot set backend:', this.config.backend, err);\n }\n }\n this.tf.enableProdMode();\n // this.tf.enableDebugMode();\n if (this.tf.getBackend() === 'webgl' || this.tf.getBackend() === 'humangl') {\n this.tf.ENV.set('CHECK_COMPUTATION_FOR_ERRORS', false);\n this.tf.ENV.set('WEBGL_CPU_FORWARD', true);\n this.tf.ENV.set('WEBGL_PACK_DEPTHWISECONV', false);\n this.tf.ENV.set('WEBGL_USE_SHAPES_UNIFORMS', true);\n // if (!this.config.object.enabled) this.tf.ENV.set('WEBGL_FORCE_F16_TEXTURES', true); // safe to use 16bit precision\n if (typeof this.config['deallocate'] !== 'undefined' && this.config['deallocate']) { // hidden param\n log('changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:', true);\n this.tf.ENV.set('WEBGL_DELETE_TEXTURE_THRESHOLD', 0);\n }\n // @ts-ignore getGPGPUContext only exists on WebGL backend\n const gl = await this.tf.backend().getGPGPUContext().gl;\n if (this.config.debug) log(`gl version:${gl.getParameter(gl.VERSION)} renderer:${gl.getParameter(gl.RENDERER)}`);\n }\n await this.tf.ready();\n this.performance.backend = Math.trunc(now() - timeStamp);\n }\n }\n\n /**\n * Runs interpolation using last known result and returns smoothened result\n * Interpolation is based on time since last known result so can be called independently\n *\n * @param result?: {@link Result} optional use specific result set to run interpolation on\n * @returns result: {@link Result}\n */\n next = (result?: Result) => interpolate.calc(result || this.result) as Result;\n\n // check if input changed sufficiently to trigger new detections\n /** @hidden */\n #skipFrame = async (input) => {\n if (this.config.cacheSensitivity === 0) return false;\n const resizeFact = 32;\n const reduced: Tensor = tf.image.resizeBilinear(input, [Math.trunc(input.shape[1] / resizeFact), Math.trunc(input.shape[2] / resizeFact)]);\n // use tensor sum\n /*\n const sumT = this.tf.sum(reduced);\n const sum = sumT.dataSync()[0] as number;\n sumT.dispose();\n */\n // use js loop sum, faster than uploading tensor to gpu calculating and downloading back\n const reducedData = await reduced.data(); // raw image rgb array\n let sum = 0;\n for (let i = 0; i < reducedData.length / 3; i++) sum += reducedData[3 * i + 2]; // look only at green value of each pixel\n\n reduced.dispose();\n const diff = 100 * (Math.max(sum, this.#lastInputSum) / Math.min(sum, this.#lastInputSum) - 1);\n this.#lastInputSum = sum;\n // if previous frame was skipped, skip this frame if changed more than cacheSensitivity\n // if previous frame was not skipped, then look for cacheSensitivity or difference larger than one in previous frame to avoid resetting cache in subsequent frames unnecessarily\n const skipFrame = diff < Math.max(this.config.cacheSensitivity, this.#lastCacheDiff);\n // if difference is above 10x threshold, don't use last value to force reset cache for significant change of scenes or images\n this.#lastCacheDiff = diff > 10 * this.config.cacheSensitivity ? 0 : diff;\n return skipFrame;\n }\n\n /** Main detection method\n * - Analyze configuration: {@link Config}\n * - Pre-process input: {@link Input}\n * - Run inference for all configured models\n * - Process and return result: {@link Result}\n *\n * @param input: Input\n * @param userConfig?: {@link Config}\n * @returns result: {@link Result}\n */\n async detect(input: Input, userConfig?: Config | Record<string, unknown>): Promise<Result | Error> {\n // detection happens inside a promise\n return new Promise(async (resolve) => {\n this.state = 'config';\n let timeStamp;\n let elapsedTime;\n\n // update configuration\n this.config = mergeDeep(this.config, userConfig) as Config;\n\n // sanity checks\n this.state = 'check';\n const error = this.#sanity(input);\n if (error) {\n log(error, input);\n resolve({ error });\n }\n\n const timeStart = now();\n\n // configure backend\n await this.#checkBackend();\n\n // load models if enabled\n await this.load();\n\n /*\n // function disabled in favor of inputChanged\n // disable video optimization for inputs of type image, but skip if inside worker thread\n let previousVideoOptimized;\n // @ts-ignore ignore missing type for WorkerGlobalScope as that is the point\n if (input && this.config.videoOptimized && (typeof window !== 'undefined') && (typeof WorkerGlobalScope !== 'undefined') && (\n (typeof HTMLImageElement !== 'undefined' && input instanceof HTMLImageElement)\n || (typeof Image !== 'undefined' && input instanceof Image)\n || (typeof ImageData !== 'undefined' && input instanceof ImageData)\n || (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap))\n ) {\n log('disabling video optimization');\n previousVideoOptimized = this.config.videoOptimized;\n this.config.videoOptimized = false;\n }\n */\n\n timeStamp = now();\n let process = image.process(input, this.config);\n this.performance.image = Math.trunc(now() - timeStamp);\n this.analyze('Get Image:');\n\n // run segmentation preprocessing\n if (this.config.segmentation.enabled && process && process.tensor) {\n this.analyze('Start Segmentation:');\n this.state = 'run:segmentation';\n timeStamp = now();\n await segmentation.predict(process);\n elapsedTime = Math.trunc(now() - timeStamp);\n if (elapsedTime > 0) this.performance.segmentation = elapsedTime;\n if (process.canvas) {\n // replace input\n tf.dispose(process.tensor);\n process = image.process(process.canvas, this.config);\n }\n this.analyze('End Segmentation:');\n }\n\n if (!process || !process.tensor) {\n log('could not convert input to tensor');\n resolve({ error: 'could not convert input to tensor' });\n return;\n }\n\n timeStamp = now();\n this.config.skipFrame = await this.#skipFrame(process.tensor);\n if (!this.performance.frames) this.performance.frames = 0;\n if (!this.performance.cached) this.performance.cached = 0;\n (this.performance.frames as number)++;\n if (this.config.skipFrame) this.performance.cached++;\n this.performance.changed = Math.trunc(now() - timeStamp);\n this.analyze('Check Changed:');\n\n // prepare where to store model results\n // keep them with weak typing as it can be promise or not\n let faceRes;\n let bodyRes;\n let handRes;\n let objectRes;\n\n // run face detection followed by all models that rely on face bounding box: face mesh, age, gender, emotion\n if (this.config.async) {\n faceRes = this.config.face.enabled ? face.detectFace(this, process.tensor) : [];\n if (this.performance.face) delete this.performance.face;\n } else {\n this.state = 'run:face';\n timeStamp = now();\n faceRes = this.config.face.enabled ? await face.detectFace(this, process.tensor) : [];\n elapsedTime = Math.trunc(now() - timeStamp);\n if (elapsedTime > 0) this.performance.face = elapsedTime;\n }\n\n // run body: can be posenet, blazepose, efficientpose, movenet\n this.analyze('Start Body:');\n if (this.config.async) {\n if (this.config.body.modelPath.includes('posenet')) bodyRes = this.config.body.enabled ? posenet.predict(process.tensor, this.config) : [];\n else if (this.config.body.modelPath.includes('blazepose')) bodyRes = this.config.body.enabled ? blazepose.predict(process.tensor, this.config) : [];\n else if (this.config.body.modelPath.includes('efficientpose')) bodyRes = this.config.body.enabled ? efficientpose.predict(process.tensor, this.config) : [];\n else if (this.config.body.modelPath.includes('movenet')) bodyRes = this.config.body.enabled ? movenet.predict(process.tensor, this.config) : [];\n if (this.performance.body) delete this.performance.body;\n } else {\n this.state = 'run:body';\n timeStamp = now();\n if (this.config.body.modelPath.includes('posenet')) bodyRes = this.config.body.enabled ? await posenet.predict(process.tensor, this.config) : [];\n else if (this.config.body.modelPath.includes('blazepose')) bodyRes = this.config.body.enabled ? await blazepose.predict(process.tensor, this.config) : [];\n else if (this.config.body.modelPath.includes('efficientpose')) bodyRes = this.config.body.enabled ? await efficientpose.predict(process.tensor, this.config) : [];\n else if (this.config.body.modelPath.includes('movenet')) bodyRes = this.config.body.enabled ? await movenet.predict(process.tensor, this.config) : [];\n elapsedTime = Math.trunc(now() - timeStamp);\n if (elapsedTime > 0) this.performance.body = elapsedTime;\n }\n this.analyze('End Body:');\n\n // run handpose\n this.analyze('Start Hand:');\n if (this.config.async) {\n handRes = this.config.hand.enabled ? handpose.predict(process.tensor, this.config) : [];\n if (this.performance.hand) delete this.performance.hand;\n } else {\n this.state = 'run:hand';\n timeStamp = now();\n handRes = this.config.hand.enabled ? await handpose.predict(process.tensor, this.config) : [];\n elapsedTime = Math.trunc(now() - timeStamp);\n if (elapsedTime > 0) this.performance.hand = elapsedTime;\n }\n this.analyze('End Hand:');\n\n // run nanodet\n this.analyze('Start Object:');\n if (this.config.async) {\n if (this.config.object.modelPath.includes('nanodet')) objectRes = this.config.object.enabled ? nanodet.predict(process.tensor, this.config) : [];\n else if (this.config.object.modelPath.includes('centernet')) objectRes = this.config.object.enabled ? centernet.predict(process.tensor, this.config) : [];\n if (this.performance.object) delete this.performance.object;\n } else {\n this.state = 'run:object';\n timeStamp = now();\n if (this.config.object.modelPath.includes('nanodet')) objectRes = this.config.object.enabled ? await nanodet.predict(process.tensor, this.config) : [];\n else if (this.config.object.modelPath.includes('centernet')) objectRes = this.config.object.enabled ? await centernet.predict(process.tensor, this.config) : [];\n elapsedTime = Math.trunc(now() - timeStamp);\n if (elapsedTime > 0) this.performance.object = elapsedTime;\n }\n this.analyze('End Object:');\n\n // if async wait for results\n if (this.config.async) [faceRes, bodyRes, handRes, objectRes] = await Promise.all([faceRes, bodyRes, handRes, objectRes]);\n\n // run gesture analysis last\n let gestureRes: Gesture[] = [];\n if (this.config.gesture.enabled) {\n timeStamp = now();\n gestureRes = [...gesture.face(faceRes), ...gesture.body(bodyRes), ...gesture.hand(handRes), ...gesture.iris(faceRes)];\n if (!this.config.async) this.performance.gesture = Math.trunc(now() - timeStamp);\n else if (this.performance.gesture) delete this.performance.gesture;\n }\n\n this.performance.total = Math.trunc(now() - timeStart);\n this.state = 'idle';\n this.result = {\n face: faceRes,\n body: bodyRes,\n hand: handRes,\n gesture: gestureRes,\n object: objectRes,\n performance: this.performance,\n canvas: process.canvas,\n timestamp: Date.now(),\n get persons() { return persons.join(faceRes, bodyRes, handRes, gestureRes, process?.tensor?.shape); },\n };\n\n // finally dispose input tensor\n tf.dispose(process.tensor);\n\n // log('Result:', result);\n resolve(this.result);\n });\n }\n\n /** @hidden */\n #warmupBitmap = async () => {\n const b64toBlob = (base64, type = 'application/octet-stream') => fetch(`data:${type};base64,${base64}`).then((res) => res.blob());\n let blob;\n let res;\n switch (this.config.warmup) {\n case 'face': blob = await b64toBlob(sample.face); break;\n case 'full': blob = await b64toBlob(sample.body); break;\n default: blob = null;\n }\n if (blob) {\n const bitmap = await createImageBitmap(blob);\n res = await this.detect(bitmap, this.config);\n bitmap.close();\n }\n return res;\n }\n\n /** @hidden */\n #warmupCanvas = async () => new Promise((resolve) => {\n let src;\n let size = 0;\n switch (this.config.warmup) {\n case 'face':\n size = 256;\n src = 'data:image/jpeg;base64,' + sample.face;\n break;\n case 'full':\n case 'body':\n size = 1200;\n src = 'data:image/jpeg;base64,' + sample.body;\n break;\n default:\n src = null;\n }\n // src = encodeURI('../assets/human-sample-upper.jpg');\n const img = new Image();\n img.onload = async () => {\n const canvas = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(size, size) : document.createElement('canvas');\n canvas.width = img.naturalWidth;\n canvas.height = img.naturalHeight;\n const ctx = canvas.getContext('2d');\n ctx?.drawImage(img, 0, 0);\n // const data = ctx?.getImageData(0, 0, canvas.height, canvas.width);\n const res = await this.detect(canvas, this.config);\n resolve(res);\n };\n if (src) img.src = src;\n else resolve(null);\n });\n\n /** @hidden */\n #warmupNode = async () => {\n const atob = (str) => Buffer.from(str, 'base64');\n let img;\n if (this.config.warmup === 'face') img = atob(sample.face);\n if (this.config.warmup === 'body' || this.config.warmup === 'full') img = atob(sample.body);\n if (!img) return null;\n let res;\n if (typeof tf['node'] !== 'undefined') {\n const data = tf['node'].decodeJpeg(img);\n const expanded = data.expandDims(0);\n this.tf.dispose(data);\n // log('Input:', expanded);\n res = await this.detect(expanded, this.config);\n this.tf.dispose(expanded);\n } else {\n if (this.config.debug) log('Warmup tfjs-node not loaded');\n /*\n const input = await canvasJS.loadImage(img);\n const canvas = canvasJS.createCanvas(input.width, input.height);\n const ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0, input.width, input.height);\n res = await this.detect(input, this.config);\n */\n }\n return res;\n }\n\n /** Warmup method pre-initializes all configured models for faster inference\n * - can take significant time on startup\n * - only used for `webgl` and `humangl` backends\n * @param userConfig?: Config\n */\n async warmup(userConfig?: Config | Record<string, unknown>): Promise<Result | { error }> {\n const t0 = now();\n if (userConfig) this.config = mergeDeep(this.config, userConfig) as Config;\n if (!this.config.warmup || this.config.warmup === 'none') return { error: 'null' };\n let res;\n if (typeof createImageBitmap === 'function') res = await this.#warmupBitmap();\n else if (typeof Image !== 'undefined') res = await this.#warmupCanvas();\n else res = await this.#warmupNode();\n const t1 = now();\n if (this.config.debug) log('Warmup', this.config.warmup, Math.round(t1 - t0), 'ms', res);\n return res;\n }\n}\n\n/**\n * Class Human is also available as default export\n */\nexport { Human as default };\n"], "mappings": ";;;;;;gmBAKO,YAAc,EAAgB,EAAsB,CACzD,GA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AI,QAAA,IACvC,EACF,GAAI,CAAC,OAAQ,CAAC,GAAS,QAAA,EAAS,MAAO,CAAC,KAAM,EAAG,SAAU,MAC/D,EAAI,KAAK,GACT,EAAc,KAAK,GACnB,EAAc,KAAK,GACnB,EAAc,KAAK,GACnB,EAAc,KAAK,GACnB,EAAc,KAAK,GAGrB,GAAM,GAAS,GAAK,CAAC,OAAQ,EAAK,QAAA,EAAS,MAAO,CAAC,KAAM,KAEzD,SAAc,QAAQ,AAAA,GAAK,EAAQ,8BAA8B,IAE1D,EAGF,GAAM,IAAyC,CACpD,WAAY,GACZ,YAAa,MACb,WAAY,ICoGR,GAAgC,CACpC,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,IAGF,OAAW,KAAgB,IACzB,GAAe,GE/VjB,GAAA,IAAA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WAAY,GACZ,YAAa,QACb,WAAY,KCqER,IAAgC,CACpC,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,GACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,KAGF,OAAW,KAAgB,KACzB,GAAe,GExUjB,GAAY,IAAZ,AAAA,UAAY,EAAQ,CAClB,EAAA,EAAA,QAAA,GAAA,UACA,EAAA,EAAA,MAAA,GAAA,QACA,EAAA,EAAA,KAAA,GAAA,OACA,EAAA,EAAA,OAAA,GAAA,SACA,EAAA,EAAA,UAAA,GAAA,cALU,IAAA,IAAQ,KASpB,GAAY,IAAZ,AAAA,UAAY,EAAiB,CAC3B,EAAA,EAAA,OAAA,GAAA,SACA,EAAA,EAAA,KAAA,GAAA,OACA,EAAA,EAAA,MAAA,GAAA,QACA,EAAA,EAAA,MAAA,GAAA,QACA,EAAA,EAAA,UAAA,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,KAA6B,CACxC,WAAY,GACZ,YAAa,OACb,WAAY,KCpCd,aAAmB,EAAqD,CACtE,GAAM,CAAC,OAAQ,CAAC,KAAI,QAAA,GAAW,EACzB,EAAM,EAAQ,WAAW,EAAE,MAAO,EAAE,OAE1C,MADgB,GAAQ,mBAAmB,GACnC,KAAK,GACN,EAGF,GAAM,KAAgC,CAC3C,WAAY,GACZ,YAAa,OACb,WAAY,KCsFR,IAAgC,CACpC,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGF,OAAW,KAAgB,KACzB,GAAe,GCtMjB,GAAM,IAAM,KAMZ,GAAI,aAIA,wBAAyB,SAAY,YAAY,SAAS,GAAI,YAAW,CACvE,EAAG,GAAI,IAAK,IAAK,EAAG,EAAG,EAAG,EAAG,EAAI,EAAG,EAAK,GAAI,EAAI,EAAG,EACpD,EAAG,EAAI,EAAK,GAAK,EAAG,EAAG,EAAG,EAAG,GAAI,EAAG,IAAK,GAAI,GAAI,OAOvD,GAAI,aAAa,+BAAgC,SAAW,CAG1D,GAAI,GAAI,IAAI,WACV,MAAO,GAGT,GAAI,CAGF,UAAI,kBAAiB,MAAM,YAAY,GAAI,mBAAkB,IAGtD,YAAY,SAAS,GAAI,YAAW,CACzC,EAAG,GAAI,IAAK,IAAK,EAAG,EAAI,EAAI,EAAG,EA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