2.e1845539.chunk.js.map 6.4 MB

1
  1. {"version":3,"sources":["../../../src/io/router_registry.ts","../../../src/io/indexed_db.ts","../../../src/io/local_storage.ts","../../../src/io/model_management.ts","../../../src/platforms/platform_browser.ts","../../src/base_side_effects.ts","../../../src/io/browser_files.ts","../../../src/io/progress.ts","../../../src/io/weights_loader.ts","../../../src/io/http.ts","../../../src/io/passthrough.ts","../../../src/ops/browser.ts","../../src/serialization.ts","../../src/version.ts","../../../src/optimizers/optimizer.ts","../../../src/optimizers/adadelta_optimizer.ts","../../../src/optimizers/adagrad_optimizer.ts","../../../src/optimizers/adam_optimizer.ts","../../../src/optimizers/adamax_optimizer.ts","../../../src/optimizers/sgd_optimizer.ts","../../../src/optimizers/momentum_optimizer.ts","../../../src/optimizers/rmsprop_optimizer.ts","../../../src/optimizers/optimizer_constructors.ts","../../src/train.ts","../../../src/ops/concat_util.ts","../../../src/ops/reduce_util.ts","../../../src/ops/rotate_util.ts","../../../src/ops/array_ops_util.ts","../../../src/ops/gather_nd_util.ts","../../../src/ops/erf_util.ts","../../src/log.ts","../../../src/backends/complex_util.ts","../../../src/backends/einsum_util.ts","../../../src/ops/split_util.ts","../../../src/ops/segment_util.ts","../../../src/backends/backend_util.ts","../../../../src/operations/executors/utils.ts","../../src/tensor_util_env.ts","../../src/kernel_names.ts","../node_modules/react/index.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/regenerator/index.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/slicedToArray.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/classCallCheck.js","../../../src/ops/operation.ts","../../src/profiler.ts","../../src/tape.ts","../../src/engine.ts","../../src/tensor_format.ts","../../src/tensor.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/createClass.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js","../../../src/ops/reshape.ts","../node_modules/@babel/runtime/helpers/esm/extends.js","../../src/util_base.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/inherits.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/typeof.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/createSuper.js","../../../src/ops/mul.ts","../../src/hash_util.ts","../../src/util.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js","../node_modules/react/jsx-runtime.js","../node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js","../../../src/ops/cast.ts","../node_modules/clsx/dist/clsx.m.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","../../../src/ops/add.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/get.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/superPropBase.js","../../../src/ops/sub.ts","../node_modules/prop-types/index.js","../../../src/ops/div.ts","../../../src/ops/sum.ts","../../../src/ops/scalar.ts","../../../src/ops/broadcast_util.ts","../node_modules/@material-ui/styles/esm/withStyles/withStyles.js","../node_modules/@material-ui/core/esm/styles/withStyles.js","../../../src/ops/zeros_like.ts","../../../src/ops/basic_lstm_cell.ts","../../../src/ops/batchnorm2d.ts","../../../src/ops/batchnorm3d.ts","../../../src/ops/batchnorm4d.ts","../../../src/ops/concat_1d.ts","../../../src/ops/concat_2d.ts","../../../src/ops/concat_3d.ts","../../../src/ops/concat_4d.ts","../../../src/ops/conv3d_transpose.ts","../../../src/ops/diag.ts","../../../src/ops/eye.ts","../../../src/ops/meshgrid.ts","../../../src/ops/moments.ts","../../../src/ops/multi_rnn_cell.ts","../../../src/ops/outer_product.ts","../../../src/ops/pad1d.ts","../../../src/ops/pad2d.ts","../../../src/ops/pad3d.ts","../../../src/ops/pad4d.ts","../../../src/ops/rand.ts","../../../src/ops/random_gamma.ts","../../../src/ops/random_normal.ts","../../../src/ops/reverse_1d.ts","../../../src/ops/reverse_2d.ts","../../../src/ops/reverse_3d.ts","../../../src/ops/reverse_4d.ts","../../../src/ops/slice1d.ts","../../../src/ops/slice2d.ts","../../../src/ops/slice3d.ts","../../../src/ops/slice4d.ts","../../../src/ops/tensor2d.ts","../../../src/ops/tensor4d.ts","../../../src/ops/tensor5d.ts","../../../src/ops/tensor6d.ts","../../../src/ops/variable.ts","../../../src/ops/boolean_mask.ts","../../../src/ops/moving_average.ts","../../../src/ops/dropout.ts","../../../src/ops/dropout_util.ts","../../../src/ops/signal_ops_util.ts","../../../src/ops/in_top_k.ts","../../../../src/ops/fused/conv2d.ts","../../../../src/ops/fused/depthwise_conv2d.ts","../../../../src/ops/fused/mat_mul.ts","../../../../src/ops/signal/hamming_window.ts","../../../../src/ops/signal/hann_window.ts","../../../../src/ops/signal/frame.ts","../../../../src/ops/signal/stft.ts","../../../../src/ops/image/crop_and_resize.ts","../../../../src/ops/image/flip_left_right.ts","../../../../src/ops/image/rotate_with_offset.ts","../../../src/ops/nonmax_util.ts","../../../../src/ops/image/non_max_suppression.ts","../../../../src/ops/image/non_max_suppression_async.ts","../../../../src/ops/image/non_max_suppression_with_score.ts","../../../../src/ops/image/non_max_suppression_with_score_async.ts","../../../../src/ops/image/non_max_suppression_padded.ts","../../../../src/ops/image/non_max_suppression_padded_async.ts","../../../../src/ops/image/threshold.ts","../../../../src/ops/image/transform.ts","../../../../src/ops/linalg/band_part.ts","../../../../src/ops/linalg/gram_schmidt.ts","../../../../src/ops/linalg/qr.ts","../../../../src/ops/losses/compute_weighted_loss.ts","../../../../src/ops/losses/absolute_difference.ts","../../../../src/ops/losses/cosine_distance.ts","../../../../src/ops/losses/hinge_loss.ts","../../../../src/ops/losses/huber_loss.ts","../../../../src/ops/losses/log_loss.ts","../../../../src/ops/losses/mean_squared_error.ts","../../../../src/ops/losses/sigmoid_cross_entropy.ts","../../../../src/ops/losses/softmax_cross_entropy.ts","../../../../src/ops/sparse/sparse_fill_empty_rows.ts","../../../../src/ops/sparse/sparse_reshape.ts","../../../../src/ops/sparse/sparse_segment_mean.ts","../../../../src/ops/sparse/sparse_segment_sum.ts","../../../../src/ops/string/string_n_grams.ts","../../../../src/ops/string/string_split.ts","../../../../src/ops/string/string_to_hash_bucket_fast.ts","../../../src/ops/ops.ts","../../src/environment.ts","../../src/tensor_util.ts","../../../src/ops/square.ts","../../../src/ops/mat_mul.ts","../node_modules/@material-ui/core/esm/utils/capitalize.js","../../../src/ops/slice.ts","../../src/globals.ts","../../../src/ops/neg.ts","../node_modules/@material-ui/core/esm/styles/colorManipulator.js","../../../src/ops/conv_util.ts","../../../src/ops/concat.ts","../node_modules/@material-ui/core/esm/utils/useForkRef.js","../../../src/ops/where.ts","../../../src/io/io_utils.ts","../node_modules/react-dom/index.js","../../../src/gradients/Abs_grad.ts","../../../src/gradients/Acos_grad.ts","../../../src/gradients/Acosh_grad.ts","../../../src/gradients/Add_grad.ts","../../../src/gradients/AddN_grad.ts","../../../src/gradients/ArgMax_grad.ts","../../../src/gradients/ArgMin_grad.ts","../../../src/gradients/Asin_grad.ts","../../../src/gradients/Asinh_grad.ts","../../../src/gradients/Atan2_grad.ts","../../../src/gradients/Atan_grad.ts","../../../src/gradients/Atanh_grad.ts","../../../src/ops/avg_pool_3d_grad.ts","../../../src/gradients/AvgPool3D_grad.ts","../../../src/ops/avg_pool_grad.ts","../../../src/gradients/AvgPool_grad.ts","../../../src/gradients/BatchMatMul_grad.ts","../../../src/gradients/BatchToSpaceND_grad.ts","../../../src/gradients/BroadcastTo_grad.ts","../../../src/gradients/Cast_grad.ts","../../../src/gradients/Ceil_grad.ts","../../../src/gradients/ClipByValue_grad.ts","../../../src/gradients/ComplexAbs_grad.ts","../../../src/gradients/Concat_grad.ts","../../../src/gradients/Conv2D_grad.ts","../../../src/gradients/Conv2DBackpropInput_grad.ts","../../../src/ops/conv3d_backprop_filter.ts","../../../src/gradients/Conv3D_grad.ts","../../../src/gradients/Cos_grad.ts","../../../src/gradients/Cosh_grad.ts","../../../src/gradients/Cumsum_grad.ts","../../../src/gradients/DepthwiseConv2dNative_grad.ts","../../../src/gradients/Dilation2D_grad.ts","../../../src/gradients/Elu_grad.ts","../../../src/gradients/Erf_grad.ts","../../../src/gradients/Exp_grad.ts","../../../src/gradients/ExpandDims_grad.ts","../../../src/gradients/Expm1_grad.ts","../../../src/gradients/Floor_grad.ts","../../../src/gradients/FloorDiv_grad.ts","../../../src/gradients/FusedBatchNorm_grad.ts","../../../src/gradients/GatherV2_grad.ts","../../../src/gradients/GreaterEqual_grad.ts","../../../src/gradients/Identity_grad.ts","../../../src/gradients/IsFinite_grad.ts","../../../src/gradients/IsInf_grad.ts","../../../src/gradients/IsNan_grad.ts","../../../src/gradients/LeakyRelu_grad.ts","../../../src/gradients/Log1p_grad.ts","../../../src/gradients/Log_grad.ts","../../../src/gradients/LogSoftmax_grad.ts","../../../src/ops/local_response_normalization_backprop.ts","../../../src/gradients/LRN_grad.ts","../../../src/gradients/min_max_grad_util.ts","../../../src/gradients/Max_grad.ts","../../../src/gradients/Maximum_grad.ts","../../../src/ops/max_pool_3d_grad.ts","../../../src/gradients/MaxPool3D_grad.ts","../../../src/ops/max_pool_grad.ts","../../../src/gradients/MaxPool_grad.ts","../../../src/gradients/Mean_grad.ts","../../../src/gradients/Min_grad.ts","../../../src/gradients/Minimum_grad.ts","../../../src/gradients/MirrorPad_grad.ts","../../../src/gradients/Mod_grad.ts","../../../src/gradients/Multiply_grad.ts","../../../src/gradients/Neg_grad.ts","../../../src/gradients/OneHot_grad.ts","../../../src/gradients/OnesLike_grad.ts","../../../src/gradients/Pack_grad.ts","../../../src/gradients/PadV2_grad.ts","../../../src/gradients/Pow_grad.ts","../../../src/gradients/Prelu_grad.ts","../../../src/gradients/RealDiv_grad.ts","../../../src/gradients/Reciprocal_grad.ts","../../../src/gradients/Relu6_grad.ts","../../../src/gradients/Relu_grad.ts","../../../src/gradients/Reshape_grad.ts","../../../src/gradients/ResizeBilinear_grad.ts","../../../src/gradients/ResizeNearestNeighbor_grad.ts","../../../src/gradients/Reverse_grad.ts","../../../src/gradients/Round_grad.ts","../../../src/gradients/Rsqrt_grad.ts","../../../src/gradients/Select_grad.ts","../../../src/gradients/Selu_grad.ts","../../../src/gradients/Sigmoid_grad.ts","../../../src/gradients/Sign_grad.ts","../../../src/gradients/Sin_grad.ts","../../../src/gradients/Sinh_grad.ts","../../../src/gradients/Slice_grad.ts","../../../src/gradients/Softmax_grad.ts","../../../src/gradients/Softplus_grad.ts","../../../src/gradients/SpaceToBatchND_grad.ts","../../../src/gradients/SplitV_grad.ts","../../../src/gradients/Sqrt_grad.ts","../../../src/gradients/Square_grad.ts","../../../src/gradients/SquaredDifference_grad.ts","../../../src/gradients/Step_grad.ts","../../../src/gradients/Sub_grad.ts","../../../src/gradients/Sum_grad.ts","../../../src/gradients/Tan_grad.ts","../../../src/gradients/Tanh_grad.ts","../../../src/gradients/Tile_grad.ts","../../../src/gradients/Transpose_grad.ts","../../../src/gradients/Unpack_grad.ts","../../../src/gradients/UnsortedSegmentSum_grad.ts","../../src/register_all_gradients.ts","../../../src/gradients/ZerosLike_grad.ts","../../../../src/public/chained_ops/abs.ts","../../../../src/public/chained_ops/acos.ts","../../../../src/public/chained_ops/acosh.ts","../../../../src/public/chained_ops/add.ts","../../../../src/public/chained_ops/all.ts","../../../../src/public/chained_ops/any.ts","../../../../src/public/chained_ops/arg_max.ts","../../../../src/public/chained_ops/arg_min.ts","../../../../src/public/chained_ops/as_scalar.ts","../../../../src/public/chained_ops/as_type.ts","../../../../src/public/chained_ops/as1d.ts","../../../../src/public/chained_ops/as2d.ts","../../../../src/public/chained_ops/as3d.ts","../../../../src/public/chained_ops/as4d.ts","../../../../src/public/chained_ops/as5d.ts","../../../../src/public/chained_ops/asin.ts","../../../../src/public/chained_ops/asinh.ts","../../../../src/public/chained_ops/atan.ts","../../../../src/public/chained_ops/atan2.ts","../../../../src/public/chained_ops/atanh.ts","../../../../src/public/chained_ops/avg_pool.ts","../../../../src/public/chained_ops/batch_to_space_nd.ts","../../../../src/public/chained_ops/batchnorm.ts","../../../../src/public/chained_ops/broadcast_to.ts","../../../../src/public/chained_ops/cast.ts","../../../../src/public/chained_ops/ceil.ts","../../../../src/public/chained_ops/clip_by_value.ts","../../../../src/public/chained_ops/concat.ts","../../../../src/public/chained_ops/conv1d.ts","../../../../src/public/chained_ops/conv2d_transpose.ts","../../../../src/public/chained_ops/conv2d.ts","../../../../src/public/chained_ops/cos.ts","../../../../src/public/chained_ops/cosh.ts","../../../../src/public/chained_ops/cumsum.ts","../../../../src/public/chained_ops/depth_to_space.ts","../../../../src/public/chained_ops/depthwise_conv2d.ts","../../../../src/public/chained_ops/dilation2d.ts","../../../../src/public/chained_ops/div_no_nan.ts","../../../../src/public/chained_ops/div.ts","../../../../src/public/chained_ops/dot.ts","../../../../src/public/chained_ops/elu.ts","../../../../src/public/chained_ops/equal.ts","../../../../src/public/chained_ops/erf.ts","../../../../src/public/chained_ops/exp.ts","../../../../src/public/chained_ops/expand_dims.ts","../../../../src/public/chained_ops/expm1.ts","../../../../src/public/chained_ops/fft.ts","../../../../src/public/chained_ops/flatten.ts","../../../../src/public/chained_ops/floor.ts","../../../../src/public/chained_ops/floorDiv.ts","../../../../src/public/chained_ops/gather.ts","../../../../src/public/chained_ops/greater_equal.ts","../../../../src/public/chained_ops/greater.ts","../../../../src/public/chained_ops/ifft.ts","../../../../src/public/chained_ops/irfft.ts","../../../../src/public/chained_ops/is_finite.ts","../../../../src/public/chained_ops/is_inf.ts","../../../../src/public/chained_ops/is_nan.ts","../../../../src/public/chained_ops/leaky_relu.ts","../../../../src/public/chained_ops/less_equal.ts","../../../../src/public/chained_ops/less.ts","../../../../src/public/chained_ops/local_response_normalization.ts","../../../../src/public/chained_ops/log_sigmoid.ts","../../../../src/public/chained_ops/log_softmax.ts","../../../../src/public/chained_ops/log_sum_exp.ts","../../../../src/public/chained_ops/log.ts","../../../../src/public/chained_ops/log1p.ts","../../../../src/public/chained_ops/logical_and.ts","../../../../src/public/chained_ops/logical_not.ts","../../../../src/public/chained_ops/logical_or.ts","../../../../src/public/chained_ops/logical_xor.ts","../../../../src/public/chained_ops/mat_mul.ts","../../../../src/public/chained_ops/max_pool.ts","../../../../src/public/chained_ops/max.ts","../../../../src/public/chained_ops/maximum.ts","../../../../src/public/chained_ops/mean.ts","../../../../src/public/chained_ops/min.ts","../../../../src/public/chained_ops/minimum.ts","../../../../src/public/chained_ops/mirror_pad.ts","../../../../src/public/chained_ops/mod.ts","../../../../src/public/chained_ops/mul.ts","../../../../src/public/chained_ops/neg.ts","../../../../src/public/chained_ops/norm.ts","../../../../src/public/chained_ops/not_equal.ts","../../../../src/public/chained_ops/one_hot.ts","../../../../src/public/chained_ops/ones_like.ts","../../../../src/public/chained_ops/pad.ts","../../../../src/public/chained_ops/pool.ts","../../../../src/public/chained_ops/pow.ts","../../../../src/public/chained_ops/prelu.ts","../../../../src/public/chained_ops/prod.ts","../../../../src/public/chained_ops/reciprocal.ts","../../../../src/public/chained_ops/relu.ts","../../../../src/public/chained_ops/relu6.ts","../../../../src/public/chained_ops/reshape_as.ts","../../../../src/public/chained_ops/reshape.ts","../../../../src/public/chained_ops/resize_bilinear.ts","../../../../src/public/chained_ops/resize_nearest_neighbor.ts","../../../../src/public/chained_ops/reverse.ts","../../../../src/public/chained_ops/rfft.ts","../../../../src/public/chained_ops/round.ts","../../../../src/public/chained_ops/rsqrt.ts","../../../../src/public/chained_ops/selu.ts","../../../../src/public/chained_ops/separable_conv2d.ts","../../../../src/public/chained_ops/sigmoid.ts","../../../../src/public/chained_ops/sign.ts","../../../../src/public/chained_ops/sin.ts","../../../../src/public/chained_ops/sinh.ts","../../../../src/public/chained_ops/slice.ts","../../../../src/public/chained_ops/softmax.ts","../../../../src/public/chained_ops/softplus.ts","../../../../src/public/chained_ops/space_to_batch_nd.ts","../../../../src/public/chained_ops/split.ts","../../../../src/public/chained_ops/sqrt.ts","../../../../src/public/chained_ops/square.ts","../../../../src/public/chained_ops/squared_difference.ts","../../../../src/public/chained_ops/squeeze.ts","../../../../src/public/chained_ops/stack.ts","../../../../src/public/chained_ops/step.ts","../../../../src/public/chained_ops/strided_slice.ts","../../../../src/public/chained_ops/sub.ts","../../../../src/public/chained_ops/sum.ts","../../../../src/public/chained_ops/tan.ts","../../../../src/public/chained_ops/tanh.ts","../../../../src/public/chained_ops/tile.ts","../../../../src/public/chained_ops/to_bool.ts","../../../../src/public/chained_ops/to_float.ts","../../../../src/public/chained_ops/to_int.ts","../../../../src/public/chained_ops/topk.ts","../../../../src/public/chained_ops/transpose.ts","../../../../src/public/chained_ops/unique.ts","../../../../src/public/chained_ops/unsorted_segment_sum.ts","../../../../src/public/chained_ops/unstack.ts","../../../../src/public/chained_ops/where.ts","../../../../src/public/chained_ops/zeros_like.ts","../../../src/backend/common.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/construct.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js","../../src/errors.ts","../../../src/utils/generic_utils.ts","../../src/constraints.ts","../../../src/keras_format/common.ts","../../src/common.ts","../../../src/utils/math_utils.ts","../../../src/backend/tfjs_backend.ts","../../../src/keras_format/initializer_config.ts","../../src/initializers.ts","../../../src/backend/state.ts","../../../src/utils/types_utils.ts","../../../src/utils/variable_utils.ts","../../src/variables.ts","../../../src/engine/topology.ts","../../../src/engine/input_layer.ts","../../src/base_callbacks.ts","../../src/logs.ts","../../../src/layers/serialization.ts","../../src/losses.ts","../../src/metrics.ts","../../src/user_defined_metadata.ts","../../../src/utils/layer_utils.ts","../../../src/utils/serialization_utils.ts","../../../src/engine/executor.ts","../../../src/engine/training_utils.ts","../../../src/engine/training_dataset.ts","../../../src/engine/training_tensors.ts","../../../src/engine/training.ts","../../src/optimizers.ts","../../../src/engine/container.ts","../../src/models.ts","../../src/activations.ts","../../src/regularizers.ts","../../../src/layers/advanced_activations.ts","../../../src/utils/conv_utils.ts","../../../src/layers/convolutional.ts","../../../src/layers/convolutional_depthwise.ts","../../../src/layers/recurrent.ts","../../../src/layers/convolutional_recurrent.ts","../../../src/layers/core.ts","../../../src/layers/embeddings.ts","../../../src/layers/merge.ts","../../../src/layers/noise.ts","../../../src/layers/normalization.ts","../../../src/layers/padding.ts","../../../src/layers/pooling.ts","../../../src/layers/wrappers.ts","../../src/callbacks.ts","../../../../src/operations/custom_op/node_value_impl.ts","../../../src/executor/tensor_utils.ts","../../../src/executor/tensor_array.ts","../../../src/executor/tensor_list.ts","../../../../src/operations/executors/control_executor.ts","../../../../src/operations/executors/convolution_executor.ts","../../../../src/operations/executors/dynamic_executor.ts","../../../src/executor/hash_table.ts","../../../../src/operations/executors/hash_table_executor.ts","../../../src/operations/operation_executor.ts","../../../../src/operations/executors/arithmetic_executor.ts","../../../../src/operations/executors/basic_math_executor.ts","../../../../src/operations/executors/creation_executor.ts","../../../../src/operations/executors/evaluation_executor.ts","../../../../src/operations/executors/image_executor.ts","../../../../src/operations/executors/graph_executor.ts","../../../../src/operations/executors/logical_executor.ts","../../../../src/operations/executors/matrices_executor.ts","../../../../src/operations/executors/normalization_executor.ts","../../../../src/operations/executors/reduction_executor.ts","../../../../src/operations/executors/slice_join_executor.ts","../../../../src/operations/executors/sparse_executor.ts","../../../../src/operations/executors/spectral_executor.ts","../../../../src/operations/executors/string_executor.ts","../../../../src/operations/executors/transformation_executor.ts","../../../src/executor/execution_context.ts","../../../src/executor/model_analysis.ts","../../../src/executor/graph_executor.ts","../../../src/executor/resource_manager.ts","../../../src/executor/graph_model.ts","../../src/dataset.ts","../../../src/datasets/text_line_dataset.ts","../../../src/datasets/csv_dataset.ts","../../../src/iterators/microphone_iterator.ts","../../../src/iterators/webcam_iterator.ts","../../src/datasource.ts","../../../src/iterators/file_chunk_iterator.ts","../../../src/iterators/url_chunk_iterator.ts","../../../src/util/source_util.ts","../../../src/sources/file_data_source.ts","../../../src/sources/url_data_source.ts","../../src/readers.ts","../../src/cpu_util.ts","../../src/backend_cpu.ts","../../../src/utils/unary_utils.ts","../../src/base.ts","../../../src/kernels/Elu.ts","../../../src/kernels/Identity.ts","../../../src/kernels/LeakyRelu.ts","../../../src/utils/binary_impl.ts","../../../src/kernels/Prelu.ts","../../../src/kernels/Relu.ts","../../../src/kernels/Relu6.ts","../../../src/kernels/Sigmoid.ts","../../../src/utils/fused_utils.ts","../../../src/kernels/Complex.ts","../../../src/utils/zeros_impl.ts","../../../src/kernels/Real.ts","../../../src/kernels/Cast.ts","../../../src/utils/binary_utils.ts","../../../src/kernels/Add.ts","../../../src/kernels/Reshape.ts","../../../src/kernels/BatchMatMul.ts","../../../src/kernels/_FusedMatMul.ts","../../../src/kernels/Abs.ts","../../../src/kernels/Acos.ts","../../../src/kernels/Acosh.ts","../../../src/kernels/AddN.ts","../../../src/kernels/Transpose_impl.ts","../../../src/kernels/Transpose.ts","../../../src/kernels/All.ts","../../../src/kernels/Any.ts","../../../src/kernels/ArgMax.ts","../../../src/kernels/ArgMin.ts","../../../src/kernels/Asin.ts","../../../src/kernels/Asinh.ts","../../../src/kernels/Atan.ts","../../../src/kernels/Atan2.ts","../../../src/kernels/Atanh.ts","../../../src/utils/pool_utils.ts","../../../src/kernels/AvgPool.ts","../../../src/kernels/AvgPool3D.ts","../../../src/kernels/AvgPool3DGrad.ts","../../../src/kernels/AvgPoolGrad.ts","../../../src/kernels/BatchNorm.ts","../../../src/kernels/Slice.ts","../../../src/kernels/BatchToSpaceND.ts","../../../src/kernels/Bincount_impl.ts","../../../src/kernels/Bincount.ts","../../../src/utils/unary_impl.ts","../../../src/kernels/Ceil.ts","../../../src/kernels/Clip.ts","../../../src/kernels/ComplexAbs.ts","../../../src/kernels/Concat_impl.ts","../../../src/kernels/Imag.ts","../../../src/kernels/Concat.ts","../../../src/kernels/Conv2D.ts","../../../src/kernels/Conv2DBackpropFilter.ts","../../../src/kernels/Conv2DBackpropInput.ts","../../../src/kernels/Conv3D.ts","../../../src/kernels/Conv3DBackpropFilterV2.ts","../../../src/kernels/Conv3DBackpropInputV2.ts","../../../src/kernels/Cos.ts","../../../src/kernels/Cosh.ts","../../../src/kernels/CropAndResize.ts","../../../src/kernels/Cumsum.ts","../../../src/kernels/DenseBincount.ts","../../../src/kernels/DepthToSpace.ts","../../../src/kernels/DepthwiseConv2dNative.ts","../../../src/kernels/DepthwiseConv2dNativeBackpropFilter.ts","../../../src/kernels/DepthwiseConv2dNativeBackpropInput.ts","../../../src/kernels/Diag.ts","../../../src/kernels/Dilation2D.ts","../../../src/kernels/Dilation2DBackpropFilter.ts","../../../src/kernels/Dilation2DBackpropInput.ts","../../../src/kernels/Multiply.ts","../../../src/kernels/Sum.ts","../../../src/kernels/Einsum.ts","../../../src/kernels/EluGrad.ts","../../../src/kernels/Equal.ts","../../../src/kernels/Erf.ts","../../../src/kernels/Exp.ts","../../../src/kernels/ExpandDims.ts","../../../src/kernels/Expm1.ts","../../../src/kernels/RealDiv.ts","../../../src/kernels/Sub.ts","../../../src/utils/fft_utils.ts","../../../src/kernels/FFT.ts","../../../src/kernels/Fill.ts","../../../src/kernels/FlipLeftRight.ts","../../../src/kernels/Floor.ts","../../../src/kernels/FloorDiv.ts","../../../src/kernels/FusedConv2D.ts","../../../src/kernels/FusedDepthwiseConv2D.ts","../../../src/kernels/GatherNd_Impl.ts","../../../src/kernels/GatherNd.ts","../../../src/kernels/GatherV2_impl.ts","../../../src/kernels/GatherV2.ts","../../../src/kernels/Greater.ts","../../../src/kernels/GreaterEqual.ts","../../../src/kernels/IFFT.ts","../../../src/kernels/IsFinite.ts","../../../src/kernels/IsInf.ts","../../../src/kernels/IsNaN.ts","../../../src/kernels/Less.ts","../../../src/kernels/LessEqual.ts","../../../src/kernels/LinSpace_impl.ts","../../../src/kernels/LinSpace.ts","../../../src/kernels/Log.ts","../../../src/kernels/Log1p.ts","../../../src/kernels/LogicalAnd.ts","../../../src/kernels/LogicalNot.ts","../../../src/kernels/LogicalOr.ts","../../../src/kernels/LRN.ts","../../../src/kernels/LRNGrad.ts","../../../src/kernels/Max_impl.ts","../../../src/kernels/Max.ts","../../../src/kernels/Maximum.ts","../../../src/kernels/MaxPool.ts","../../../src/kernels/MaxPool3D.ts","../../../src/kernels/MaxPool3DGrad.ts","../../../src/kernels/MaxPoolGrad.ts","../../../src/kernels/MaxPoolWithArgmax.ts","../../../src/kernels/MaxPoolWithArgmax_impl.ts","../../../src/kernels/Mean.ts","../../../src/kernels/Min.ts","../../../src/kernels/Minimum.ts","../../../src/kernels/MirrorPad.ts","../../../src/kernels/Mod.ts","../../../src/kernels/Softmax.ts","../../../src/kernels/Multinomial.ts","../../../src/kernels/Neg.ts","../../../src/kernels/NonMaxSuppressionV3.ts","../../../src/kernels/NonMaxSuppressionV4.ts","../../../src/kernels/NonMaxSuppressionV5.ts","../../../src/kernels/NotEqual.ts","../../../src/kernels/OneHot.ts","../../../src/kernels/ZerosLike.ts","../../../src/kernels/OnesLike.ts","../../../src/kernels/Pack.ts","../../../src/kernels/PadV2.ts","../../../src/kernels/Pow.ts","../../../src/kernels/Prod.ts","../../../src/kernels/Range_impl.ts","../../../src/kernels/Range.ts","../../../src/kernels/Reciprocal.ts","../../../src/kernels/ResizeBilinear.ts","../../../src/kernels/ResizeBilinearGrad.ts","../../../src/kernels/ResizeNearestNeighbor.ts","../../../src/kernels/ResizeNearestNeighborGrad.ts","../../../src/kernels/Reverse.ts","../../../src/kernels/RotateWithOffset.ts","../../../src/kernels/Round.ts","../../../src/kernels/Rsqrt.ts","../../../src/kernels/Scatter_impl.ts","../../../src/kernels/ScatterNd.ts","../../../src/kernels/Select.ts","../../../src/kernels/Selu.ts","../../../src/kernels/Sign.ts","../../../src/kernels/Sin.ts","../../../src/kernels/Sinh.ts","../../../src/kernels/Softplus.ts","../../../src/kernels/SpaceToBatchND.ts","../../../src/kernels/SparseFillEmptyRows_impl.ts","../../../src/kernels/SparseFillEmptyRows.ts","../../../src/kernels/SparseReshape_impl.ts","../../../src/kernels/SparseReshape.ts","../../../src/kernels/SparseSegmentReduction_impl.ts","../../../src/kernels/SparseSegmentMean.ts","../../../src/kernels/SparseSegmentSum.ts","../../../src/kernels/SparseToDense.ts","../../../src/kernels/SplitV.ts","../../../src/kernels/Sqrt.ts","../../../src/kernels/Square.ts","../../../src/kernels/SquaredDifference.ts","../../../src/kernels/Step.ts","../../../src/kernels/StridedSlice_impl.ts","../../../src/kernels/StridedSlice.ts","../../../src/kernels/StringNGrams_impl.ts","../../../src/kernels/StringNGrams.ts","../../../src/kernels/StringSplit_impl.ts","../../../src/kernels/StringSplit.ts","../../../src/kernels/StringToHashBucketFast_impl.ts","../../../src/kernels/StringToHashBucketFast.ts","../../../src/kernels/Tan.ts","../../../src/kernels/Tanh.ts","../../../src/kernels/Tile_impl.ts","../../../src/kernels/Tile.ts","../../../src/kernels/TopK_impl.ts","../../../src/kernels/TopK.ts","../../../src/kernels/Transform.ts","../../../src/kernels/Unique_impl.ts","../../../src/kernels/Unique.ts","../../../src/kernels/Unpack.ts","../../src/register_all_kernels.ts","../../../src/kernels/UnsortedSegmentSum.ts","../../src/canvas_util.ts","../../src/tex_util.ts","../../src/webgl_util.ts","../../src/flags_webgl.ts","../../src/glsl_version.ts","../../src/shader_compiler_util.ts","../../src/decode_matrix_gpu.ts","../../src/decode_matrix_packed_gpu.ts","../../src/encode_float_gpu.ts","../../src/encode_float_packed_gpu.ts","../../src/encode_matrix_gpu.ts","../../src/encode_matrix_packed_gpu.ts","../../src/gpgpu_util.ts","../../src/gpgpu_context.ts","../../src/shader_compiler.ts","../../src/gpgpu_math.ts","../../../src/kernel_utils/shared.ts","../../src/packing_util.ts","../../src/pack_gpu.ts","../../src/reshape_packed_gpu.ts","../../src/texture_manager.ts","../../src/unaryop_gpu.ts","../../src/unaryop_packed_gpu.ts","../../src/unpack_gpu.ts","../../src/backend_webgl.ts","../../src/binaryop_gpu.ts","../../src/binaryop_packed_gpu.ts","../../../src/kernel_utils/kernel_funcs_utils.ts","../../src/mulmat_packed_gpu.ts","../../src/binaryop_complex_gpu.ts","../../../src/kernel_utils/reshape.ts","../../src/mean_gpu.ts","../../src/reduce_gpu.ts","../../../src/kernel_utils/reduce.ts","../../src/transpose_gpu.ts","../../src/transpose_packed_gpu.ts","../../../src/kernels/Sum_impl.ts","../../../src/kernels/BatchMatMul_impl.ts","../../src/addn_gpu.ts","../../src/addn_packed_gpu.ts","../../src/argminmax_gpu.ts","../../src/argminmax_packed_gpu.ts","../../../src/kernel_utils/arg_min_max.ts","../../src/pool_gpu.ts","../../src/avg_pool_backprop_gpu.ts","../../src/batchnorm_gpu.ts","../../src/batchnorm_packed_gpu.ts","../../src/slice_gpu.ts","../../src/slice_packed_gpu.ts","../../../src/kernel_utils/int.ts","../../src/clip_gpu.ts","../../src/clip_packed_gpu.ts","../../../src/kernels/ClipByValue.ts","../../src/complex_abs_gpu.ts","../../src/concat_gpu.ts","../../src/concat_packed_gpu.ts","../../src/conv_gpu.ts","../../src/im2col_packed_gpu.ts","../../../src/kernels/Conv2D_impl.ts","../../src/conv_backprop_gpu.ts","../../src/crop_and_resize_gpu.ts","../../src/cumsum_gpu.ts","../../src/depth_to_space_gpu.ts","../../src/conv_gpu_depthwise.ts","../../src/conv_packed_gpu_depthwise.ts","../../src/conv_backprop_gpu_depthwise.ts","../../src/diag_gpu.ts","../../src/dilation_gpu.ts","../../src/fft_gpu.ts","../../../src/kernels/FFT_impl.ts","../../src/fill_gpu.ts","../../../src/kernels/FromPixels.ts","../../src/flip_left_right_gpu.ts","../../../../src/kernels/FromPixels_utils/from_pixels_gpu.ts","../../../../src/kernels/FromPixels_utils/from_pixels_packed_gpu.ts","../../src/gather_nd_gpu.ts","../../src/gather_gpu.ts","../../src/lrn_gpu.ts","../../src/lrn_packed_gpu.ts","../../src/lrn_grad_gpu.ts","../../src/max_pool_backprop_gpu.ts","../../../src/kernels/Mean_impl.ts","../../src/mirror_pad_gpu.ts","../../src/mirror_pad_packed_gpu.ts","../../src/multinomial_gpu.ts","../../src/onehot_gpu.ts","../../src/pad_gpu.ts","../../src/pad_packed_gpu.ts","../../src/resize_bilinear_gpu.ts","../../src/resize_bilinear_packed_gpu.ts","../../src/resize_bilinear_backprop_gpu.ts","../../src/resize_nearest_neighbor_gpu.ts","../../src/resize_nearest_neighbor_packed_gpu.ts","../../src/resize_nearest_neighbor_backprop_gpu.ts","../../src/reverse_gpu.ts","../../src/reverse_packed_gpu.ts","../../src/rotate_gpu.ts","../../src/scatter_gpu.ts","../../src/select_gpu.ts","../../src/strided_slice_gpu.ts","../../src/tile_gpu.ts","../../src/top_k_gpu.ts","../../src/transform_gpu.ts","../../src/segment_gpu.ts","../../src/index.ts","../../src/gradients.ts","../../../src/ops/loss_ops_utils.ts","../node_modules/@babel/runtime/helpers/esm/defineProperty.js","../../../src/ops/sqrt.ts","../../modules/HistoryContext.js","../../modules/createNameContext.js","../../modules/RouterContext.js","../../modules/Router.js","../../modules/MemoryRouter.js","../../modules/Lifecycle.js","../../modules/generatePath.js","../../modules/Redirect.js","../../modules/matchPath.js","../../modules/Route.js","../../modules/StaticRouter.js","../../modules/Switch.js","../../modules/hooks.js","../../../src/ops/axis_util.ts","../../../src/ops/exp.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../../../src/ops/greater.ts","../../../src/ops/abs.ts","../../../src/ops/fused_util.ts","../../../src/util/deep_clone.ts","../../../src/util/ring_buffer.ts","../../../src/util/growing_ring_buffer.ts","../../../src/iterators/lazy_iterator.ts","../../../src/ops/buffer.ts","../../../src/ops/reverse.ts","../../../src/ops/tensor1d.ts","../../../src/ops/tensor_ops_util.ts","../node_modules/@material-ui/core/esm/utils/ownerDocument.js","../../../src/ops/pow.ts","../../../src/ops/ones.ts","../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../../../src/ops/less_equal.ts","../../../src/ops/pad.ts","../../../src/ops/transpose.ts","../node_modules/@material-ui/core/esm/utils/useEventCallback.js","../../../src/operations/operation_mapper.ts","../../../src/ops/complex.ts","../../../src/ops/logical_and.ts","../../../src/ops/split.ts","../../../src/ops/stack.ts","../../src/kernel_registry.ts","../../../src/ops/expand_dims.ts","../node_modules/@material-ui/core/esm/SvgIcon/SvgIcon.js","../node_modules/@material-ui/core/esm/utils/createSvgIcon.js","../node_modules/tiny-invariant/dist/tiny-invariant.esm.js","../node_modules/webpack/buildin/amd-define.js","../../../src/ops/conv2d.ts","../../../src/ops/greater_equal.ts","../../../src/ops/clone.ts","../../../src/ops/sigmoid.ts","../../../src/ops/max.ts","../../../src/util/deep_map.ts","../node_modules/resolve-pathname/esm/resolve-pathname.js","../node_modules/value-equal/esm/value-equal.js","../node_modules/history/esm/history.js","../../../src/ops/log.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/defineProperty.js","../../../src/backends/non_max_suppression_util.ts","../../../src/backends/non_max_suppression_impl.ts","../../../src/ops/zeros.ts","../../../src/ops/relu.ts","../../../src/ops/step.ts","../../../src/ops/unstack.ts","../../../src/ops/batchnorm.ts","../../../src/ops/batchnorm_util.ts","../../../src/ops/tensor.ts","../../../src/ops/tile.ts","../node_modules/@material-ui/core/esm/styles/useTheme.js","../node_modules/@babel/runtime/helpers/esm/toConsumableArray.js","../node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js","../node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js","../node_modules/seedrandom/index.js","../../../src/data/compiled_api.ts","../node_modules/tiny-warning/dist/tiny-warning.esm.js","../../../src/ops/mean.ts","../node_modules/@material-ui/core/esm/utils/debounce.js","../../src/types.ts","../../../src/ops/batch_to_space_nd.ts","../../../src/ops/depthwise_conv2d.ts","../../../src/ops/equal.ts","../../../src/ops/fill.ts","../../../src/ops/gather.ts","../../../src/ops/logical_not.ts","../../../src/ops/maximum.ts","../../../src/ops/space_to_batch_nd.ts","../../../src/ops/squeeze.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js","../../../src/ops/broadcast_to.ts","../../../src/ops/rand_util.ts","../../../src/ops/range.ts","../node_modules/@material-ui/system/esm/merge.js","../node_modules/@material-ui/core/esm/styles/createBreakpoints.js","../node_modules/@material-ui/core/esm/styles/createMixins.js","../node_modules/@material-ui/core/esm/colors/common.js","../node_modules/@material-ui/core/esm/colors/grey.js","../node_modules/@material-ui/core/esm/colors/indigo.js","../node_modules/@material-ui/core/esm/colors/pink.js","../node_modules/@material-ui/core/esm/colors/red.js","../node_modules/@material-ui/core/esm/colors/orange.js","../node_modules/@material-ui/core/esm/colors/blue.js","../node_modules/@material-ui/core/esm/colors/green.js","../node_modules/@material-ui/core/esm/styles/createPalette.js","../node_modules/@material-ui/core/esm/styles/createTypography.js","../node_modules/@material-ui/core/esm/styles/shadows.js","../node_modules/@material-ui/core/esm/styles/shape.js","../node_modules/@material-ui/core/esm/styles/createSpacing.js","../node_modules/@material-ui/core/esm/styles/transitions.js","../node_modules/@material-ui/core/esm/styles/createMuiTheme.js","../node_modules/@material-ui/core/esm/styles/defaultTheme.js","../node_modules/@material-ui/core/esm/utils/setRef.js","../../../../src/operations/custom_op/register.ts","../../../src/ops/min.ts","../../../src/ops/real.ts","../../../../src/ops/spectral/ifft.ts","../node_modules/@babel/runtime/helpers/esm/typeof.js","../../src/global_util.ts","../node_modules/webpack/buildin/global.js","../node_modules/webpack/buildin/module.js","../node_modules/webpack/buildin/amd-options.js","../node_modules/react-is/index.js","../../../src/ops/scatter_nd_util.ts","../../../src/ops/slice_util.ts","../../../src/ops/avg_pool.ts","../../../src/ops/cos.ts","../../../src/ops/cumsum.ts","../../../src/ops/floorDiv.ts","../../../src/ops/elu.ts","../../../src/ops/floor.ts","../../../src/ops/imag.ts","../../../src/ops/leaky_relu.ts","../../../src/ops/less.ts","../../../src/ops/log_sum_exp.ts","../../../src/ops/logical_or.ts","../../../src/ops/max_pool.ts","../../../src/ops/minimum.ts","../../../src/ops/not_equal.ts","../../../src/ops/prelu.ts","../../../src/ops/relu6.ts","../../../../src/ops/spectral/fft.ts","../../../../src/ops/spectral/rfft.ts","../../../src/ops/squared_difference.ts","../../../src/ops/unsorted_segment_sum.ts","../../../src/ops/norm.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../../../src/ops/conv2d_backprop_input.ts","../../src/test_util.ts","../../../src/ops/conv2d_backprop_filter.ts","../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../node_modules/@material-ui/core/esm/utils/ownerWindow.js","../node_modules/@babel/runtime/helpers/esm/slicedToArray.js","../node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js","../node_modules/@babel/runtime/helpers/esm/createClass.js","../node_modules/@material-ui/core/esm/utils/isMuiElement.js","../node_modules/react-transition-group/esm/TransitionGroupContext.js","../node_modules/@material-ui/core/esm/List/ListContext.js","../../src/flags.ts","../node_modules/object-assign/index.js","../../../src/backends/backend.ts","../../../src/ops/tanh.ts","../../../src/ops/selu_util.ts","../../modules/BrowserRouter.js","../../modules/HashRouter.js","../../modules/utils/locationUtils.js","../../modules/Link.js","../../modules/NavLink.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js","../../../src/io/types.ts","../node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js","../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","../node_modules/process/browser.js","../../src/device_util.ts","../../../src/ops/print.ts","../../../src/ops/all.ts","../../../src/ops/any.ts","../../../src/ops/arg_max.ts","../../../src/ops/arg_min.ts","../../../src/ops/atan2.ts","../../../src/ops/bincount.ts","../../../src/ops/conv1d.ts","../../../src/ops/conv2d_transpose.ts","../../../src/ops/cosh.ts","../../../src/ops/depth_to_space.ts","../../../src/ops/dilation2d.ts","../../../src/ops/div_no_nan.ts","../../../src/ops/dot.ts","../../../src/ops/local_response_normalization.ts","../../../src/ops/log1p.ts","../../../src/ops/softplus.ts","../../../src/ops/logical_xor.ts","../../../src/ops/mirror_pad.ts","../../../src/ops/mod.ts","../../../src/ops/one_hot.ts","../../../src/ops/pool.ts","../../../src/ops/prod.ts","../../../src/ops/random_uniform.ts","../../../src/ops/round.ts","../../../src/ops/rsqrt.ts","../../../src/ops/selu.ts","../../../src/ops/separable_conv2d.ts","../../../src/ops/sin.ts","../../../src/ops/sinh.ts","../../../../src/ops/spectral/irfft.ts","../../../src/ops/tensor3d.ts","../../../src/ops/topk.ts","../../../src/ops/unique.ts","../../../src/ops/where_async.ts","../../../src/backends/where_impl.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/iterableToArray.js","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js","../../../src/ops/conv3d_backprop_input.ts","../../../../src/ops/image/resize_nearest_neighbor.ts","../node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/toArray.js","../../../../src/ops/image/resize_bilinear.ts","../../../src/ops/depthwise_conv2d_native_backprop_input.ts","../../../src/ops/depthwise_conv2d_native_backprop_filter.ts","../node_modules/react-helmet/es/Helmet.js","../node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js","../node_modules/@material-ui/system/esm/breakpoints.js","../node_modules/@material-ui/core/esm/styles/zIndex.js","../node_modules/buffer/index.js","../node_modules/long/src/long.js","../node_modules/classnames/index.js","../node_modules/mini-create-react-context/dist/esm/index.js","../node_modules/react-router/node_modules/path-to-regexp/index.js","../../../src/ops/acos.ts","../../../src/ops/acosh.ts","../../../src/ops/add_n.ts","../../../src/ops/asin.ts","../../../src/ops/asinh.ts","../../../src/ops/atan.ts","../../../src/ops/atanh.ts","../../../src/ops/avg_pool_3d.ts","../../../src/ops/ceil.ts","../../../src/ops/clip_by_value.ts","../../../src/ops/conv3d.ts","../../../src/ops/dense_bincount.ts","../../../src/ops/einsum.ts","../../../src/ops/erf.ts","../../../src/ops/expm1.ts","../../../src/ops/is_finite.ts","../../../src/ops/is_inf.ts","../../../src/ops/is_nan.ts","../../../src/ops/linspace.ts","../../../src/ops/log_sigmoid.ts","../../../src/ops/log_softmax.ts","../../../src/ops/max_pool_3d.ts","../../../src/ops/max_pool_with_argmax.ts","../../../src/ops/multinomial.ts","../../../src/ops/ones_like.ts","../../../src/ops/reciprocal.ts","../../../src/ops/setdiff1d_async.ts","../../../src/ops/sign.ts","../../../src/ops/softmax.ts","../../../src/ops/strided_slice.ts","../../../src/ops/tan.ts","../../../src/ops/truncated_normal.ts","../../../src/ops/scatter_nd.ts","../../../src/ops/gather_nd.ts","../../src/browser_util.ts","../../../src/ops/sparse_to_dense_util.ts","../../../src/ops/sparse_to_dense.ts","../../../../src/operations/op_list/arithmetic.ts","../../../../src/operations/op_list/basic_math.ts","../../../../src/operations/op_list/control.ts","../../../../src/operations/op_list/convolution.ts","../../../../src/operations/op_list/creation.ts","../../../../src/operations/op_list/dynamic.ts","../../../../src/operations/op_list/evaluation.ts","../../../../src/operations/op_list/graph.ts","../../../../src/operations/op_list/hash_table.ts","../../../../src/operations/op_list/image.ts","../../../../src/operations/op_list/logical.ts","../../../../src/operations/op_list/matrices.ts","../../../../src/operations/op_list/normalization.ts","../../../../src/operations/op_list/reduction.ts","../../../../src/operations/op_list/slice_join.ts","../../../../src/operations/op_list/sparse.ts","../../../../src/operations/op_list/spectral.ts","../../../../src/operations/op_list/string.ts","../../../../src/operations/op_list/transformation.ts","../../../src/iterators/byte_chunk_iterator.ts","../../../src/iterators/string_iterator.ts","../node_modules/react-side-effect/lib/index.js","../node_modules/react-fast-compare/index.js","../node_modules/@babel/runtime/helpers/esm/iterableToArray.js","../node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js","../node_modules/@babel/runtime/helpers/esm/nonIterableRest.js","../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../node_modules/@material-ui/utils/esm/formatMuiErrorMessage.js","../node_modules/@material-ui/core/esm/utils/useIsFocusVisible.js","../node_modules/react-transition-group/esm/utils/ChildMapping.js","../node_modules/react-transition-group/esm/TransitionGroup.js","../node_modules/@material-ui/core/esm/ButtonBase/Ripple.js","../node_modules/@material-ui/core/esm/ButtonBase/TouchRipple.js","../node_modules/@material-ui/core/esm/ButtonBase/ButtonBase.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/scheduler/index.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/regenerator-runtime/runtime.js","../node_modules/base64-js/index.js","../node_modules/ieee754/index.js","../node_modules/isarray/index.js","../../../src/platforms/platform_node.ts","../node_modules/seedrandom/lib/alea.js","../node_modules/seedrandom/lib/xor128.js","../node_modules/seedrandom/lib/xorwow.js","../node_modules/seedrandom/lib/xorshift7.js","../node_modules/seedrandom/lib/xor4096.js","../node_modules/seedrandom/lib/tychei.js","../node_modules/seedrandom/seedrandom.js","../node_modules/timers-browserify/main.js","../node_modules/setimmediate/setImmediate.js","../node_modules/prop-types/factoryWithThrowingShims.js","../node_modules/prop-types/lib/ReactPropTypesSecret.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react-is/cjs/react-is.production.min.js","../node_modules/react-router/node_modules/isarray/index.js","../node_modules/@material-ui/utils/esm/deepmerge.js","../node_modules/@material-ui/core/esm/Paper/Paper.js","../node_modules/is-in-browser/dist/module.js","../node_modules/jss/dist/jss.esm.js","../node_modules/@material-ui/styles/esm/makeStyles/multiKeyStore.js","../node_modules/@material-ui/styles/esm/ThemeProvider/nested.js","../node_modules/@material-ui/styles/esm/createGenerateClassName/createGenerateClassName.js","../node_modules/jss-plugin-rule-value-function/dist/jss-plugin-rule-value-function.esm.js","../node_modules/jss-plugin-global/dist/jss-plugin-global.esm.js","../node_modules/jss-plugin-nested/dist/jss-plugin-nested.esm.js","../node_modules/hyphenate-style-name/index.js","../node_modules/jss-plugin-camel-case/dist/jss-plugin-camel-case.esm.js","../node_modules/jss-plugin-default-unit/dist/jss-plugin-default-unit.esm.js","../node_modules/css-vendor/dist/css-vendor.esm.js","../node_modules/jss-plugin-vendor-prefixer/dist/jss-plugin-vendor-prefixer.esm.js","../node_modules/jss-plugin-props-sort/dist/jss-plugin-props-sort.esm.js","../node_modules/@material-ui/styles/esm/jssPreset/jssPreset.js","../node_modules/@material-ui/styles/esm/StylesProvider/StylesProvider.js","../node_modules/@material-ui/styles/esm/makeStyles/indexCounter.js","../node_modules/@material-ui/styles/esm/getStylesCreator/getStylesCreator.js","../node_modules/@material-ui/styles/esm/getStylesCreator/noopTheme.js","../node_modules/@material-ui/styles/esm/makeStyles/makeStyles.js","../node_modules/@material-ui/styles/esm/useTheme/ThemeContext.js","../node_modules/@material-ui/styles/esm/useTheme/useTheme.js","../node_modules/@material-ui/styles/esm/mergeClasses/mergeClasses.js","../node_modules/@material-ui/core/esm/Typography/Typography.js","../node_modules/@material-ui/styles/esm/getThemeProps/getThemeProps.js","../node_modules/@material-ui/core/esm/LinearProgress/LinearProgress.js","../node_modules/@material-ui/core/esm/Button/Button.js","../node_modules/@material-ui/core/esm/styles/makeStyles.js","../node_modules/@material-ui/icons/esm/Description.js","../node_modules/@material-ui/icons/esm/GitHub.js","../node_modules/@material-ui/icons/esm/Camera.js","../node_modules/@material-ui/core/esm/CssBaseline/CssBaseline.js","../node_modules/@material-ui/core/esm/AppBar/AppBar.js","../node_modules/@material-ui/core/esm/Toolbar/Toolbar.js","../node_modules/@material-ui/core/esm/Tab/Tab.js","../node_modules/@material-ui/core/esm/FormControl/formControlState.js","../node_modules/@material-ui/core/esm/FormControl/FormControlContext.js","../node_modules/@material-ui/core/esm/TextareaAutosize/TextareaAutosize.js","../node_modules/@material-ui/core/esm/InputBase/utils.js","../node_modules/@material-ui/core/esm/InputBase/InputBase.js","../node_modules/@material-ui/core/esm/Input/Input.js","../node_modules/@material-ui/core/esm/FilledInput/FilledInput.js","../node_modules/@material-ui/core/esm/OutlinedInput/NotchedOutline.js","../node_modules/@material-ui/core/esm/OutlinedInput/OutlinedInput.js","../node_modules/@material-ui/core/esm/FormControl/useFormControl.js","../node_modules/@material-ui/core/esm/FormLabel/FormLabel.js","../node_modules/@material-ui/core/esm/InputLabel/InputLabel.js","../node_modules/@material-ui/core/esm/FormControl/FormControl.js","../node_modules/@material-ui/core/esm/FormHelperText/FormHelperText.js","../node_modules/@material-ui/core/esm/utils/createChainedFunction.js","../node_modules/@material-ui/core/esm/Portal/Portal.js","../node_modules/@material-ui/core/esm/utils/getScrollbarSize.js","../node_modules/@material-ui/core/esm/Modal/ModalManager.js","../node_modules/@babel/runtime/helpers/esm/classCallCheck.js","../node_modules/@material-ui/core/esm/Unstable_TrapFocus/Unstable_TrapFocus.js","../node_modules/@material-ui/core/esm/Modal/SimpleBackdrop.js","../node_modules/@material-ui/core/esm/Modal/Modal.js","../node_modules/react-transition-group/esm/config.js","../node_modules/react-transition-group/esm/Transition.js","../node_modules/@material-ui/core/esm/transitions/utils.js","../node_modules/@material-ui/core/esm/Grow/Grow.js","../node_modules/@material-ui/core/esm/Popover/Popover.js","../node_modules/@material-ui/core/esm/List/List.js","../node_modules/@material-ui/core/esm/MenuList/MenuList.js","../node_modules/@material-ui/core/esm/Menu/Menu.js","../node_modules/@material-ui/core/esm/Select/SelectInput.js","../node_modules/@material-ui/core/esm/utils/useControlled.js","../node_modules/@material-ui/core/esm/internal/svg-icons/ArrowDropDown.js","../node_modules/@material-ui/core/esm/NativeSelect/NativeSelectInput.js","../node_modules/@material-ui/core/esm/NativeSelect/NativeSelect.js","../node_modules/@material-ui/core/esm/Select/Select.js","../node_modules/@material-ui/core/esm/TextField/TextField.js","../node_modules/@material-ui/system/esm/css.js","../node_modules/@material-ui/system/esm/compose.js","../node_modules/@material-ui/system/esm/style.js","../node_modules/@material-ui/system/esm/borders.js","../node_modules/@material-ui/system/esm/display.js","../node_modules/@material-ui/system/esm/flexbox.js","../node_modules/@material-ui/system/esm/grid.js","../node_modules/@material-ui/system/esm/positions.js","../node_modules/@material-ui/system/esm/palette.js","../node_modules/@material-ui/system/esm/shadows.js","../node_modules/@material-ui/system/esm/sizing.js","../node_modules/@material-ui/system/esm/typography.js","../node_modules/@material-ui/styles/esm/styled/styled.js","../node_modules/@material-ui/core/esm/styles/styled.js","../node_modules/@material-ui/core/esm/Box/Box.js","../node_modules/@material-ui/core/esm/utils/scrollLeft.js","../node_modules/@material-ui/core/esm/internal/animate.js","../node_modules/@material-ui/core/esm/Tabs/ScrollbarSize.js","../node_modules/@material-ui/core/esm/Tabs/TabIndicator.js","../node_modules/@material-ui/core/esm/internal/svg-icons/KeyboardArrowLeft.js","../node_modules/@material-ui/core/esm/internal/svg-icons/KeyboardArrowRight.js","../node_modules/@material-ui/core/esm/TabScrollButton/TabScrollButton.js","../node_modules/@material-ui/core/esm/Tabs/Tabs.js","../node_modules/@material-ui/core/esm/ListItem/ListItem.js","../node_modules/@material-ui/core/esm/MenuItem/MenuItem.js","../node_modules/@material-ui/core/esm/internal/svg-icons/Cancel.js","../node_modules/@material-ui/core/esm/Chip/Chip.js","../node_modules/@material-ui/core/esm/internal/svg-icons/Person.js","../node_modules/@material-ui/core/esm/Avatar/Avatar.js","../node_modules/@material-ui/system/esm/spacing.js","../node_modules/@material-ui/system/esm/memoize.js"],"names":["this","saveRouters","loadRouters","IORouterRegistry","instance","saveRouter","getInstance","push","loadRouter","url","getHandlers","loadOptions","handlerType","validHandlers","forEach","router","handler","registerSaveRouter","loudRouter","registerLoadRouter","getSaveHandlers","getLoadHandlers","DATABASE_NAME","MODEL_STORE_NAME","INFO_STORE_NAME","getIndexedDBFactory","getBool","Error","theWindow","window","self","factory","indexedDB","mozIndexedDB","webkitIndexedDB","msIndexedDB","shimIndexedDB","setUpDatabase","openRequest","db","result","createObjectStore","keyPath","modelPath","modelArtifacts","a","modelTopology","ArrayBuffer","databaseAction","Promise","resolve","reject","open","onupgradeneeded","onsuccess","modelTx","transaction","getRequest","objectStore","get","close","onerror","error","oncomplete","modelArtifactsInfo","infoTx","infoStore","putInfoRequest","put","putModelRequest","deleteInfoRequest","delete","URL_SCHEME","Array","isArray","startsWith","slice","length","tx","getAllInfoRequest","getAll","out","item","path","key","getInfoRequest","deleteModelData","deleteModelRequest","PATH_SEPARATOR","PATH_PREFIX","INFO_SUFFIX","MODEL_TOPOLOGY_SUFFIX","WEIGHT_SPECS_SUFFIX","WEIGHT_DATA_SUFFIX","MODEL_METADATA_SUFFIX","getModelKeys","info","join","topology","weightSpecs","weightData","modelMetadata","removeItems","keys","Object","values","localStorage","removeItem","getModelPathFromKey","items","split","LS","JSON","stringify","setItem","metadata","format","generatedBy","convertedBy","signature","undefined","userDefinedMetadata","modelInitializer","trainingConfig","modelTopologyBytes","weightSpecsBytes","weightDataBytes","parse","getItem","modelTopologyType","metadataString","weightDataBase64","prefix","suffix","i","endsWith","URL_SCHEME_SUFFIX","managers","ModelStoreManagerRegistry","scheme","manager","indexOf","registry","parseURL","getSchemes","cloneModelInternal","sourceURL","destURL","deleteSource","loadHandlers","loadHandler","saveHandlers","saveHandler","sourceScheme","sourcePath","sameMedium","load","getManager","removeModel","save","saveResult","schemes","listModels","schemeOut","schemeAndPath","copyModel","moveModel","init","fetch","performance","now","text","encoding","textEncoder","TextEncoder","encode","bytes","TextDecoder","decode","setPlatform","registerManager","err","opHandler","buffer","cast","clone","print","defer","f","setTimeout","then","fileNamePrefix","BrowserDownloads","modelJsonFileName","weightDataFileName","document","weightsURL","URL","createObjectURL","Blob","type","weightsManifest","paths","weights","modelJSON","modelJsonURL","jsonAnchor","modelJsonAnchor","createElement","download","href","dispatchEvent","MouseEvent","weightDataAnchor","files","jsonFile","weightsFiles","jsonReader","FileReader","onload","event","target","modelArtifactsPromise","loadWeights","name","readAsText","entry","pathToFile","checkManifestAndWeightFiles","promises","map","loadWeightsFile","all","buffers","file","weightFileReader","readAsArrayBuffer","manifest","basenames","fileNames","pathBasename","browserFiles","browserDownloads","monitorPromisesProgress","onProgress","startFraction","endFraction","checkPromises","checkFraction","resolvedPromise","promise","value","fraction","loadWeightsAsArrayBuffer","fetchURLs","fetchFunc","platform","requests","fetchURL","requestInit","isBinary","fetchStartFraction","fetchEndFraction","responses","bufferPromises","response","arrayBuffer","bufferStartFraction","bufferEndFraction","filePathPrefix","weightNames","weightsLoaderFactory","fetchUrls","fetchWeightsFunction","groupIndicesToFetchMap","groupWeightsToFetch","weightsFound","allManifestWeightNames","manifestGroupConfig","groupIndex","groupOffset","weightsEntry","rawDtype","quantization","dtype","weightsBytes","shape","enqueueWeightsForFetchingFn","manifestEntry","sizeBytes","weightName","weightIndex","every","found","weightsNotFound","filter","_","groupIndicesToFetch","reduce","accumulator","shouldFetch","filepath","fetchUrl","weightsTensorMap","bufferIndexOffset","numBuffers","groupBytes","byteLength","groupBuffer","groupByteBuffer","Uint8Array","groupBufferOffset","set","byteBuffer","nameToTensorMap","DEFAULT_METHOD","weightPathPrefix","weightUrlConverter","body","assign","method","FormData","modelTopologyAndWeightManifest","append","ok","status","modelConfigRequest","json","message","weightPath","parseUrl","pathPrefix","urlPromises","weightsGroup","lastSlash","lastIndexOf","lastSearchParam","substring","isHTTPScheme","match","URL_SCHEME_REGEX","httpRouter","urlItem","http","browserHTTPRequest","fromMemory","arguments","isModelArtifacts","console","warn","withSaveHandler","fromPixels2DContext","fromPixels_","pixels","numChannels","isPixelData","isImageData","isVideo","isImage","isCanvasLike","isImageBitmap","data","ImageData","HTMLVideoElement","HTMLImageElement","getContext","ImageBitmap","constructor","HAVE_CURRENT_DATA_READY_STATE","readyState","kernel","backendName","inputs","attrs","runKernel","vals","videoWidth","videoHeight","width","height","getImageData","canvas","drawImage","Int32Array","numPixels","channel","outShape","tensor3d","canWrapPixelsToImageBitmap","hasOwnProperty","isNonEmptyPixels","fromPixelsAsync","createImageBitmap","premultiplyAlpha","imageBitmap","toPixels","img","$img","originalImgTensor","dispose","rank","depth","multiplier","Uint8ClampedArray","rgba","d","j","Math","round","ctx","imageData","putImageData","fromPixels","className","cls","config","classNameMap","SerializationMap","getMap","fromConfig","registerClass","register","version","returnCost","varList","computeGradients","grads","gradArray","v","tensor","applyGradients","iterations_","iterations","scalar","weightValues","getClassName","defineProperty","Symbol","hasInstance","minimize","learningRate","rho","epsilon","accumulatedGrads","accumulatedUpdates","backend","variableGradients","registeredVariables","originalName","variable","gradient","accumulatedGrad","accumulatedUpdate","newAccumulatedGrad","add","mul","square","updates","div","sqrt","newAccumulatedUpdate","newValue","incrementIterations","variables","saveIterations","concat","extractIterations","variableCount","initialAccumulatorValue","fill","beta1","beta2","accumulatedFirstMoment","accumulatedSecondMoment","accBeta1","accBeta2","varNames","oneMinusAccBeta1","sub","oneMinusAccBeta2","firstMoment","secondMoment","newFirstMoment","newSecondMoment","biasCorrectedFirstMoment","biasCorrectedSecondMoment","pow","decay","accumulatedWeightedInfNorm","iteration","variableNames","lr","weightedInfNorm","ut0","ut1","abs","newWeightedInfNorm","maximum","setLearningRate","c","momentum","useNesterov","accumulations","m","accumulation","newAccumulation","centered","accumulatedMeanSquares","accumulatedMoments","accumulatedMeanGrads","trainable","accumulatedMeanSquare","newAccumulatedMeanSquare","accumulatedMeanGrad","newAccumulatedMeanGrad","gradContribution","newAccumulatedMoments","train","sgd","adadelta","adagrad","rmsprop","adamax","adam","assertParamsConsistent","shapes","axis","firstShape","r","computeOutShape","outputShape","PARALLELIZE_THRESHOLD","computeOptimalWindowSize","inSize","floor","getImageCenter","center","imageHeight","imageWidth","getReshaped","inputShape","blockShape","prod","batchToSpace","reshaped","spatialLength","getPermuted","reshapedRank","blockShapeRank","permuted","permutedBeforeBatch","permutedAfterBatch","getReshapedPermuted","reshapedPermuted","getSliceBeginCoords","crops","sliceBeginCoords","getSliceSize","uncroppedShape","sliceSize","prepareAndValidate","indices","tensorRank","indicesRank","indicesShape","sliceRank","nResult","resultShape","pop","strides","stride","ERF_P","ERF_A1","ERF_A2","ERF_A3","ERF_A4","ERF_A5","log","mergeRealAndImagArrays","real","imag","Float32Array","splitRealAndImagArrays","complex","complexWithEvenIndex","len","ceil","complexWithOddIndex","getComplexWithIndex","index","assignToTypedArray","exponents","n","inverse","x","PI","cos","sin","exponent","k","ARROW","ARROW_REGEX","decodeEinsumEquation","equation","numTensors","numArrows","replace","inputString","outputString","inputTerms","numInputs","allDims","dimName","some","inputTerm","idDims","Set","size","numDims","summedDims","getEinsumPermutation","nDims","permutationIndices","expandDims","checkEinsumDimSizes","tensors","dimSizes","getEinsumComputePath","nSteps","steps","computedTermIndices","termIndices","findTermsWithDim","termIndex","isIdentityPermutation","perm","dim","prepareSplitSize","numOrSizeSplits","splitSizes","numOfNegs","count","negIndex","total","b","segOpComputeOptimalWindowSize","numSegments","res","done","aShape","collectGatherOpShapeInfo","batchDims","xRank","dimSize","batchSize","outerSize","fromUint8ToStringArray","val","fromStringArrayToUint8","strings","s","getParamValue","paramName","node","tensorMap","context","resourceManager","inputParam","inputParams","inputIndexStart","start","end","inputIndexEnd","getTensor","inputNames","dataSync","toNestedArray","attrParam","attrParams","tensorsMap","parseNodeName","nodeName","getHashTableHandleByName","contextId","currentContextIds","find","getNodeNameWithContextId","getTensorsForCurrentContenxt","currentContextId","getNodeNameAndIndex","inputName","outputName","parts","Number","getPadding","pad","explicitPadding","cloneTensor","kept","inferShape","firstElem","deepAssertShapeConsistency","subShape","assertDtype","expectedDtype","actualDType","argName","functionName","convertToTensor","parseAsDtype","inferredDtype","inferredShape","skipTypedArray","makeTensor","convertToTensorArray","arg","t","Abs","Acos","Acosh","Add","AddN","All","Any","ArgMax","ArgMin","Asin","Asinh","Atan","Atanh","Atan2","AvgPool","AvgPoolGrad","AvgPool3D","AvgPool3DGrad","BatchMatMul","BatchToSpaceND","Bincount","BroadcastTo","Cast","Ceil","ClipByValue","Complex","ComplexAbs","Concat","Conv2D","Conv2DBackpropFilter","Conv2DBackpropInput","Conv3D","Conv3DBackpropFilterV2","Conv3DBackpropInputV2","Cos","Cosh","Cumsum","CropAndResize","DenseBincount","DepthToSpace","DepthwiseConv2dNative","DepthwiseConv2dNativeBackpropFilter","DepthwiseConv2dNativeBackpropInput","Diag","Dilation2D","Dilation2DBackpropInput","Dilation2DBackpropFilter","RealDiv","Einsum","Elu","EluGrad","Erf","Equal","Exp","ExpandDims","Expm1","FFT","Fill","FlipLeftRight","Floor","FloorDiv","FusedBatchNorm","GatherV2","GatherNd","Greater","GreaterEqual","Identity","IFFT","Imag","IsFinite","IsInf","IsNan","LeakyRelu","Less","LessEqual","LinSpace","Log","Log1p","LogicalAnd","LogicalNot","LogicalOr","LogSoftmax","LRN","LRNGrad","Max","Maximum","MaxPool","MaxPoolGrad","MaxPool3D","MaxPool3DGrad","MaxPoolWithArgmax","Mean","Min","Minimum","MirrorPad","Mod","Multinomial","Multiply","Neg","NotEqual","NonMaxSuppressionV3","NonMaxSuppressionV4","NonMaxSuppressionV5","OnesLike","OneHot","Pack","PadV2","Pow","Prelu","Prod","Range","Real","Reciprocal","Relu","Reshape","ResizeNearestNeighbor","ResizeNearestNeighborGrad","ResizeBilinear","ResizeBilinearGrad","Relu6","Reverse","Round","Rsqrt","ScatterNd","Select","Selu","Slice","Sin","Sinh","Sign","Sigmoid","Softplus","Sqrt","Sum","SpaceToBatchND","SplitV","Softmax","SparseFillEmptyRows","SparseReshape","SparseSegmentMean","SparseSegmentSum","SparseToDense","SquaredDifference","Square","StridedSlice","StringNGrams","StringSplit","StringToHashBucketFast","Sub","Tan","Tanh","Tile","TopK","Transform","Transpose","Unique","Unpack","UnsortedSegmentSum","ZerosLike","Step","FromPixels","RotateWithOffset","_FusedMatMul","FusedConv2D","FusedDepthwiseConv2D","module","exports","require","_slicedToArray","arr","arrayWithHoles","iterator","_arr","_n","_d","_e","_s","_i","next","unsupportedIterableToArray","nonIterableRest","_classCallCheck","Constructor","TypeError","OP_SCOPE_SUFFIX","op","opName","fn","f2","startScope","endScope","ex","configurable","backendTimer","logger","kernelName","outputs","timer","holdResultWrapperFn","util","timerAvailable","time","kernelMs","output","tensorVals","num","isNaN","isFinite","checkComputationForErrors","timeMs","timing","extraInfo","getExtraProfileInfo","kernelProfile","valueContainer","logKernelProfile","paddedName","toString","inputShapesDescription","input","inputRank","getFilteredNodesXToY","tape","xs","y","tensorsFromX","nodesFromX","id","nodeInputs","anyInputFromX","tensorsLeadToY","nodesToY","filteredTape","prunedInputs","nodeInput","prunedNode","backpropagateGradients","tensorAccumulatedGradientMap","tidy","dys","o","gradTensor","inputGradients","dx","curGradient","isRegisteredKernelInvocation","kernelInvocation","nextTapeNodeId","numBytes","numStringTensors","numDataBuffers","gradientDepth","kernelDepth","scopeStack","numDataMovesStack","nextScopeId","tensorInfo","WeakMap","profiling","activeProfile","newBytes","newTensors","peakBytes","kernels","from","variableName","ENV","registryFactory","pendingBackendInitId","state","pendingBackendInit","backendInstance","sortedBackends","getSortedBackends","initializeBackend","success","setBackend","initializeBackendsAndReturnBest","asyncInit","priority","setupRegisteredKernels","profiler","setupFunc","disposeFunc","registryFactoryEntry","promiseId","catch","stack","disposeRegisteredKernels","sort","dataId","srcBackend","readSync","refCount","disposeData","move","shouldCheckForMemLeaks","nameOrFn","String","scopedRun","Engine","nextTensorId","nextVariableId","ENGINE","addTapeNode","activeScope","dy","gradInputs","runKernelFunc","numDataIdsBefore","outInfos","numDataIdsAfter","numDataIds","numOutputDataIds","numMoves","dataIdsLeaked","kernelParams","kernelFunc","saved","isTapeOn","startingBytecount","startingNumTensors","kernelOrScopeName","checkKernelForMemLeak","outTensors","outInfo","makeTensorFromDataId","tensorsToSave","getTensorsForGradient","saveTensorsForBackwardMode","forwardFunc","saveFunc","keep","outs","backwardsFunc","profileKernel","bytesAdded","totalBytesSnapshot","tensorsAdded","totalTensorsSnapshot","inputShapes","outputShapes","kernelTimeMs","gradConfig","inputTensorsToSave","inputsToSave","outputsToSave","saveAllInputs","outputTensorsToSave","backendVals","write","trackTensor","initialValue","incRef","has","track","removeDataId","varName","disposeVariable","disposeTensor","memory","unreliable","reasons","query","startBytes","startNumTensors","max","gradientsFunc","tapeNode","gradFunc","activeTape","scopeInfo","tensorsToTrackInParent","tensorsToTrackInParentSet","oldScope","scopeId","allowNoGradients","startTape","endTape","accumulatedGradientMap","ones","inputMap","gradRes","gradMap","grad","read","timingInfo","wallMs","reset","getOrMakeEngine","ns","_tfengine","environment","tensorToString","verbose","padPerCol","numCols","valuesOrTuples","createComplexTuples","row","offset","valToString","computeMaxSizePerColumn","valsLines","subTensorToString","lines","l","valStr","parseFloat","toFixed","boolNumToString","isLast","storagePerElement","complexTuple","firstValsSize","firstVals","lastVals","displayVals","subshape","substrides","sep","newLineSep","complexTuples","locs","locToIndex","loc","msg","trackerFn","setTensorTracker","setOpHandler","setDeprecationWarningFn","isDisposedInternal","rankType","throwIfDisposed","isDisposed","makeVariable","getGlobalTensorClass","tensorId","Function","_defineProperties","props","descriptor","enumerable","writable","_createClass","protoProps","staticProps","prototype","asyncGeneratorStep","gen","_next","_throw","_asyncToGenerator","args","apply","reshape","reshape_","_extends","source","call","shuffle","array","counter","random","swap","shuffleCombo","array2","clamp","min","nearestLargerEven","object","left","right","temp","sum","randUniform","distSquared","diff","assert","expr","assertShapesMatch","shapeA","shapeB","errorMessagePrefix","arraysEqual","assertNonNull","flatten","isTypedArray","sizeFromShape","isScalarShape","n1","n2","isInt","tanh","Infinity","e2x","exp","sizeToSquarishShape","createShuffledIndices","shuffledIndices","Uint32Array","rightPad","repeat","repeatedTry","checkFn","delayFn","maxCounter","tryCount","tryFn","nextBackoff","inferFromImplicitShape","shapeProd","implicitIdx","newShape","parseAxisParam","ax","squeezeShape","keptDims","isEmptyArray","axes","getTypedArrayFromDType","getArrayFromDType","checkConversionForErrors","isValidDtype","hasEncodingLoss","oldType","newType","bytesPerElement","bytesFromStringArray","isString","isBoolean","isNumber","inferDtype","isFunction","nearestDivisor","computeStrides","createNestedArray","isComplex","ret","rest","acc","makeOnesTypedArray","makeZerosTypedArray","makeZerosNestedTypedArray","prev","curr","assertNonNegativeIntegerDimensions","isInteger","indexToLoc","isPromise","_inherits","subClass","superClass","create","_typeof","obj","_possibleConstructorReturn","assertThisInitialized","_createSuper","Derived","hasNativeReflectConstruct","isNativeReflectConstruct","Super","getPrototypeOf","NewTarget","Reflect","construct","mul_","$a","$b","Long","hexToLong","hex","fromString","k0","k1","k2","shiftMix","xor","shru","fromBytes","fetch64","fetch32","rotate64","shift","or","shl","hashLen16","u","weakHashLen32WithSeedsStr","w","z","weakHashLen32WithSeeds","hashLen0to16","hashLen17to32","hashLen33to64","e","g","h","fingerPrint64","seed","fromNumber","UZERO","last64","and","createScalarValue","encodeString","toTypedArray","noConversionNeeded","bool","requestInits","decodeString","_createForOfIteratorHelper","allowArrayLike","it","F","normalCompletion","didErr","step","_e2","_toConsumableArray","arrayLikeToArray","iterableToArray","_objectWithoutProperties","excluded","getOwnPropertySymbols","sourceSymbolKeys","propertyIsEnumerable","cast_","$x","toVal","mix","str","tmp","_getPrototypeOf","setPrototypeOf","__proto__","add_","property","receiver","base","desc","getOwnPropertyDescriptor","sub_","div_","sum_","keepDims","getBroadcastDims","inShape","inRank","dims","unshift","getReductionAxes","inDim","outAxis","outDim","assertAndGetBroadcastShape","errMsg","withStyles","stylesOrCreator","options","Component","defaultTheme","_options$withTheme","withTheme","stylesOptions","classNamePrefix","useStyles","makeStyles","displayName","WithStyles","React","forwardRef","ref","classes","theme","innerRef","other","defaultProps","more","useTheme","getThemeProps","hoistNonReactStatics","withStylesWithoutDefault","zerosLike","zerosLike_","basicLSTMCell","basicLSTMCell_","forgetBias","lstmKernel","lstmBias","$forgetBias","$lstmKernel","$lstmBias","$data","$c","$h","combined","weighted","sliceCols","newC","sigmoid","batchNorm2d","batchNorm2d_","mean","variance","scale","varianceEpsilon","$scale","$offset","$mean","$variance","batchNorm3d","batchNorm3d_","batchNorm4d","batchNorm4d_","concat1d","concat1d_","concat2d","concat2d_","concat3d","concat3d_","concat4d","concat4d_","conv3dTranspose","conv3dTranspose_","$filter","diag","diag_","eye","eye_","numRows","numColumns","batchShape","buff","toTensor","tile","meshgrid","indexing","$y","moments","moments_","xMean","keepDimsShape","devSquared","multiRNNCell","multiRNNCell_","lstmCells","newStates","newH","outerProduct","outerProduct_","v1","v2","$v1","$v2","v12D","v22D","pad1d","pad1d_","paddings","constantValue","pad2d","pad2d_","pad3d","pad3d_","pad4d","pad4d_","rand","rand_","randFunction","randomGamma","randomGamma_","alpha","beta","rgamma","nextValue","randomNormal","randomNormal_","stdDev","randGauss","reverse1d","reverse1d_","reverse","reverse2d","reverse2d_","reverse3d","reverse3d_","reverse4d","reverse4d_","slice1d","slice1d_","begin","slice2d","slice2d_","slice3d","slice3d_","slice4d","slice4d_","tensor2d","tensor4d","tensor5d","tensor6d","mask","$tensor","$mask","axisFrom","maskDim","tensorShape","leadingSize","targetTensorShape","reshapedTensor","reshapedMask","positivePositions","squeeze","gather","booleanMaskAsync","movingAverage","movingAverage_","zeroDebias","$v","$decay","one","oneMinusDecay","update","$step","dropout","dropout_","rate","noiseShape","$noiseShape","newDimension","getNoiseShape","keepProb","enclosingPowerOfTwo","cosineWindow","windowLength","even","newValues","cosArg","tensor1d","predictions","targets","$predictions","$targets","lastDim","predictionsVals","targetsVals","batch","precision","subarray","valAndInd","inTopKAsync","fusedConv2d_","dataFormat","dilations","dimRoundingMode","bias","activation","preluActivationWeights","leakyreluAlpha","x4D","reshapedTo4D","conv_util","$bias","$preluActivationWeights","convInfo","broadcast_util","dyActivation","der","biasDer","customOp","customOpWithBias","depthwiseConv2d","fusedDepthwiseConv2d_","xDer","filterDer","matMul","fusedMatMul_","transposeA","transposeB","innerShapeA","innerShapeB","outerShapeA","outerShapeB","outerDimsA","outerDimsB","batchDimA","batchDimB","a3D","b3D","aDer","bDer","hammingWindow","hammingWindow_","hannWindow","hannWindow_","frame_","signal","frameLength","frameStep","padEnd","padValue","padLen","stft","stft_","fftLength","windowFn","framedSignal","windowedSignal","rfft","cropAndResize","cropAndResize_","image","boxes","boxInd","cropSize","extrapolationValue","$image","$boxes","$boxInd","numBoxes","flipLeftRight","flipLeftRight_","rotateWithOffset","rotateWithOffset_","radians","fillValue","nonMaxSuppSanityCheck","scores","maxOutputSize","iouThreshold","scoreThreshold","softNmsSigma","NEGATIVE_INFINITY","nonMaxSuppression","nonMaxSuppression_","$scores","boxesAndScores","boxesVals","scoresVals","selectedIndices","nonMaxSuppressionAsync","nonMaxSuppressionWithScore","nonMaxSuppressionWithScore_","params","selectedScores","nonMaxSuppressionWithScoreAsync","nonMaxSuppressionPadded","nonMaxSuppressionPadded_","padToMaxOutputSize","$maxOutputSize","$iouThreshold","$scoreThreshold","validOutputs","nonMaxSuppressionPaddedAsync","otsu","histogram","classFirst","classSecond","meanFirst","meanSec","weightForeground","weightBack","bestThresh","bestInBetVar","cInBetVar","meanFirstDivA","range","meanSecFill","meanSecAdd","meanSecMul","cInBetVarSubA","cInBetVarSubB","cInBetVarMul","condition","greater","where","threshold","threshold_","grayscale","inverted","threshValue","RED_INTENCITY_COEF","GREEN_INTENCITY_COEF","BLUE_INTENCITY_COEF","totalPixelsInImage","$threshold","$r","$g","$histogram","bincount","invCondition","transform","transform_","transforms","interpolation","fillMode","$transforms","bandPart","bandPart_","numLower","numUpper","M","N","ij","inBand","zero","zeros","unstack","mat","gramSchmidt","gramSchmidt_","inputIsTensor2D","ys","xs1d","proj","norm","qr2d","fullMatrices","q","one2D","iters","rTemp","wTemp","qTemp","rjEnd1","normX","rjj","u1","wPre","tau","neg","rjEndAll","tauTimesW","wT","transpose","rTimesTau","tawTimesWT","qAllJEnd","qTimesTau","qr","qr_","outerDimsProd","x2ds","q2ds","r2ds","x2d","q2d","r2d","computeWeightedLoss","computeWeightedLoss_","losses","reduction","SUM_BY_NONZERO_WEIGHTS","$losses","$weights","weightedLoss","NONE","SUM","MEAN","broadcastFactor","broadcastedWeights","numNonZeros","absoluteDifference","absoluteDifference_","labels","$labels","cosineDistance","cosineDistance_","hingeLoss","hingeLoss_","relu","huberLoss","huberLoss_","delta","deltaScalar","quadratic","minimum","linear","logLoss","logLoss_","epsilonScalar","l1","l2","meanSquaredError","meanSquaredError_","sigmoidCrossEntropyWithLogits_","logits","$logits","maxOutput","outputXTarget","sigmoidOutput","log1p","sigmoidCrossEntropy","sigmoidCrossEntropy_","multiClassLabels","labelSmoothing","$multiClassLabels","labelSmoothingScalar","half","softmaxCrossEntropyWithLogits_","lse","logResult","costVector","dyShape","softmaxCrossEntropy","softmaxCrossEntropy_","onehotLabels","$onehotLabels","numClasses","sparseFillEmptyRows","sparseFillEmptyRows_","denseShape","defaultValue","$indices","$values","$denseShape","$defaultValue","outputIndices","outputValues","emptyRowIndicator","reverseIndexMap","sparseReshape","sparseReshape_","inputIndices","$inputIndices","$inputShape","$newShape","sparseSegmentMean","sparseSegmentMean_","segmentIds","$segmentIds","sparseSegmentSum","sparseSegmentSum_","stringNGrams","stringNGrams_","dataSplits","separator","nGramWidths","leftPad","padWidth","preserveShortSequences","$dataSplits","nGrams","nGramsSplits","stringSplit","stringSplit_","delimiter","skipEmpty","$input","$delimiter","stringToHashBucketFast","stringToHashBucketFast_","numBuckets","spectral","fft","ifft","irfft","frame","resizeNearestNeighbor","resizeBilinear","linalg","sparse","string","TENSORFLOWJS_FLAGS_PREFIX","Environment","global","flags","flagRegistry","urlFlags","getQueryParams","populateURLFlags","platformName","flagName","evaluationFn","setHook","flagValue","evaluateFlag","location","search","urlParams","keyValue","toLowerCase","parseValue","queryString","decodeParam","decodeURIComponent","env","setEnvironmentGlobal","makeTypesMatch","assertTypesMatch","isTensorInList","tensorList","getTensorsInContainer","list","walkTensorContainer","container","seen","iterable","square_","matMul_","capitalize","_formatMuiErrorMessage","charAt","toUpperCase","slice_","engine","registerBackend","neg_","decomposeColor","color","substr","re","RegExp","colors","parseInt","hexToRgb","marker","recomposeColor","getContrastRatio","foreground","background","lumA","getLuminance","lumB","rgb","hslToRgb","emphasize","coefficient","darken","lighten","fade","computeDilation2DInfo","filterShape","inputChannels","$filterShape","$dataFormat","convertConv2DDataFormat","computeConv2DInfo","computePool2DInfo","filterSize","roundingMode","parseTupleParam","filterHeight","filterWidth","computePool3DInfo","parse3TupleParam","filterDepth","computeConv3DInfo","depthwise","inHeight","inWidth","inChannels","filterChannels","strideHeight","strideWidth","dilationHeight","dilationWidth","effectiveFilterHeight","getEffectiveFilterSize","effectiveFilterWidth","getPadAndOutInfo","padInfo","outHeight","outWidth","outChannels","inDepth","strideDepth","dilationDepth","effectiveFilterDepth","get3DPadAndOutInfo","outDepth","computeDefaultPad","fieldSize","dilation","effectiveFieldSize","param","top","bottom","zeroPad","inputRows","inputCols","computeOutputShape2D","padAlongHeight","padAlongWidth","front","back","inputDepth","computeOutputShape4D","padAlongDepth","trunc","tupleValuesAreOne","dimA","dimB","dimC","eitherStridesOrDilationsAreOne","concat_","$tensors","attr","useForkRef","refA","refB","refValue","setRef","where_","$condition","broadcastShape","encodeWeights","group","specs","dataPromises","names","spec","utf8bytes","totalNumBytes","p","bytesOfLength","tensorValues","concatenateTypedArrays","decodeWeights","float16Decode","quantizationSizeFactor","quantizedArray","Uint16Array","getFloat16Decoder","dtypeFactor","realTensor","imageTensor","totalByteLength","normalizedXs","useNodeBuffer","Buffer","atob","btoa","stringByteLength","arrayBufferToBase64String","buf","fromCharCode","base64StringToArrayBuffer","byteOffset","charCodeAt","concatenateArrayBuffers","basename","trim","getModelJSONForModelArtifacts","artifacts","getModelArtifactsForJSON","getModelArtifactsInfoForJSON","dateSaved","Date","mantisaTable","convertMantissa","computeFloat16MantisaTable","exponentTable","computeFloat16ExponentTable","offsetTable","computeFloat16OffsetTable","bufferUint32View","float16Bits","float32Bits","checkDCE","__REACT_DEVTOOLS_GLOBAL_HOOK__","absGradConfig","acosGradConfig","acoshGradConfig","addGradConfig","reduceAxes","addNGradConfig","ders","argMaxGradConfig","argMinGradConfig","asinGradConfig","asinhGradConfig","atan2GradConfig","atanGradConfig","atanhGradConfig","avgPool3dGrad","avgPool3dGrad_","$dy","dy5D","input5D","reshapedTo5D","avgPool3DGradConfig","avgPoolGrad","avgPoolGrad_","input4D","dy4D","avgPoolGradConfig","batchMatMulGradConfig","batchToSpaceNDGradConfig","broadcastToGradConfig","broadCastToAttrs","reps","castGradConfig","ceilGradConfig","clipByValueGradConfig","clipValueMin","clipValueMax","complexAbsGradConfig","concatGradConfig","$axis","sizeSplits","conv2DGradConfig","conv2DBackpropInputGradConfig","ddx","conv2d","conv3DBackpropFilter","conv3DBackpropFilter_","x5D","conv3DGradConfig","cosGradConfig","coshGradConfig","sinh","cumsumGradConfig","exclusive","permutation","cumsum","depthwiseConv2dNativeGradConfig","$dilations","dilation2dGradConfig","inputInputs","filterInputs","eluGradConfig","erfGradConfig","expGradConfig","expandDimsGradConfig","expm1GradConfig","floorGradConfig","floorDivGradConfig","fusedBatchNormGradConfig","scaleValue","reductionAxes","tileShape","xMinusMean","dyTimesScaleValue","oneOverSqrtVariance","rsqrt","minusHalfRCube","meanDer","varianceDer","xMinusMean2TimesRsqrt","scaleDer","offsetDer","gatherGradConfig","parsedAxis","paramsShape","indicesSize","outerShape","outerDims","innerShape","innerDims","outerAxesIndices","arrayRange","innerAxesIndices","valuesShape","arrayConcat","reshapedIndices","transposeDims","valuesTranspose","paramsGrad","invertTransposeDims","stop","arrays","greaterEqualGradConfig","identityGradConfig","isFiniteGradConfig","isInfGradConfig","isNanGradConfig","leakyReluGradConfig","log1pGradConfig","logGradConfig","logSoftmaxGradConfig","softmax","localResponseNormalizationBackprop","localResponseNormalizationBackprop_","depthRadius","lrnGradConfig","gradForMinAndMax","xOrig","origAxes","axis_util","equal","maxGradConfig","reductionIndices","maxGrad","maximumGradConfig","less","maxPool3dGrad","maxPool3dGrad_","$output","output5D","maxPool3DGradConfig","maxPoolGrad","maxPoolGrad_","maxPoolGradConfig","meanGradConfig","reduceShape","reduceSize","expandedDyShape","expandedDy","minGradConfig","minGrad","minimumGradConfig","mirrorPadGradConfig","modGradConfig","multiplyGradConfig","negGradConfig","oneHotGradConfig","onesLikeGradConfig","packGradConfig","padV2GradConfig","powGradConfig","expFloat","logBase","preluGradConfig","divGradConfig","reciprocalGradConfig","relu6GradConfig","reluGradConfig","reshapeGradConfig","resizeBilinearGradConfig","images","resizeNearestNeighborGradConfig","reverseGradConfig","roundGradConfig","rsqrtGradConfig","selectGradConfig","seluGradConfig","scaleAlpha","greaterThanZeroDer","lessEqualZeroDer","sigmoidGradConfig","signGradConfig","sinGradConfig","sinhGradConfig","cosh","sliceGradConfig","begin_","size_","softmaxGradConfig","dyTimesY","softplusGradConfig","spaceToBatchNDGradConfig","splitVGradConfig","sqrtGradConfig","squareGradConfig","squaredDifferenceGradConfig","two","stepGradConfig","subGradConfig","sumGradConfig","derX","tanGradConfig","tanhGradConfig","tileGradConfig","xGrad","transposeGradConfig","undoPerm","unpackGradConfig","unsortedSegmentSumGradConfig","zeroClippedIndices","gathered","isPositive","numIters","zeroSlice","gatherDropNegatives","zerosLikeGradConfig","gradientConfig","acos","acosh","any","argMax","argMin","asScalar","asType","as1D","as2D","rows","columns","as3D","as4D","depth2","as5D","depth3","asin","asinh","atan","atan2","atanh","avgPool","batchToSpaceND","batchNorm","broadcastTo","clipByValue","conv1d","conv2dTranspose","depthToSpace","blockSize","dilation2d","divNoNan","dot","elu","erf","expm1","floorDiv","greaterEqual","isInf","leakyRelu","lessEqual","localResponseNormalization","logSigmoid","logSoftmax","logSumExp","logicalAnd","logicalNot","logicalOr","logicalXor","maxPool","mirrorPad","mode","mod","ord","notEqual","oneHot","onValue","offValue","onesLike","pool","windowShape","poolingType","padding","dilationRate","prelu","reciprocal","relu6","reshapeAs","newShape2D","alignCorners","halfPixelCenters","halfFloatCenters","selu","separableConv2d","depthwiseFilter","pointwiseFilter","sign","softplus","spaceToBatchND","squaredDifference","tensorsToBeStacked","stridedSlice","beginMask","endMask","ellipsisMask","newAxisMask","shrinkAxisMask","tan","toBool","toFloat","toInt","topk","sorted","unique","unsortedSegmentSum","_epsilon","Parent","Class","bind","_cache","Map","Wrapper","AttributeError","RuntimeError","ValueError","NotImplementedError","AssertionError","pyListRepeat","numValues","newArray","refernce","singletonOrArray","toList","toSnakeCase","insecure","toCamelCase","identifier","p1","_GLOBAL_CUSTOM_OBJECTS","serializeKerasObject","dict","getConfig","convertNDArrayScalarsInConfig","configItem","field","deserializeKerasObject","moduleObjects","customObjects","printableModuleName","fastWeightInit","customObjectsCombined","nestedConfig","backupCustomObjects","returnObj","reverseNumberCompare","numberCompare","isObjectEmpty","checkStringTypeUnionValue","label","checkArrayTypeAndLength","expectedType","minLength","maxLength","assertPositiveInteger","formatAsFriendlyString","mapActivationToFusedKernel","activationName","calcL2Norms","Serializable","defaultMaxValue","defaultAxis","maxValue","norms","desired","defaultMinValue","defaultRate","minValue","CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP","serializeConstraint","constraint","deserializeConstraint","getConstraint","VALID_DATA_FORMAT_VALUES","VALID_INTERPOLATION_FORMAT_VALUES","VALID_PADDING_MODE_VALUES","VALID_POOL_MODE_VALUES","VALID_BIDIRECTIONAL_MERGE_MODES","nameMap","checkDataFormat","checkPaddingMode","checkPoolMode","_nameScopeStack","nameScope","getScopedTensorName","tensorName","isValidTensorName","getUniqueTensorName","scopedName","tensorNameRegex","arrayProd","NaN","POSITIVE_INFINITY","splice","sliceAlongFirstAxis","sliceAlongLastAxis","sliceAlongAxis","concatAlongFirstAxis","stddev","reshapeBias","aFirstDims","aLastDim","bShape","bLastDim","yOtherDims","reference","biasShape","biasAdd","level","inTrainPhase","alt","training","VALID_FAN_MODE_VALUES","VALID_DISTRIBUTION_VALUES","DEFAULT_MINVAL","DEFAULT_MAXVAL","minval","maxval","DEFAULT_MEAN","DEFAULT_STDDEV","gain","distribution","checkDistribution","fans","fanIn","fanOut","receptiveFieldSize","computeFans","limit","DEFAULT_GAIN","INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP","deserializeInitializer","serializeInitializer","initializer","getInitializer","_nextUniqueTensorId","getNextUniqueTensorId","_uidPrefixes","getUid","isArrayOfShapes","normalizeShapeList","getExactlyOneTensor","getExactlyOneShape","countParamsInWeights","weight","DEFAULT_VARIABLE_NAME_PREFIX","trainable_","assertNotDisposed","newVal","checkShapesMatch","batchGetValue","batchSetValue","variablesAndValues","variableAndValue","ndim","maxNDim","minNDim","sourceLayer","callArgs","outputTensorIndex","_nextNodeID","outboundLayer","inboundLayers","nodeIndices","tensorIndices","inputTensors","outputTensors","inputMasks","outputMasks","layer","outboundNodes","inboundNodes","inboundNames","_nextLayerID","_callHook","_addedWeightNames","_stateful","activityRegularizer","inputSpec","supportsMasking","_trainableWeights","_nonTrainableWeights","_losses","_updates","_built","batchInputShape","inputDType","initialWeights","_refCount","fastWeightInitDuringBuild","nodeIndex","attrName","getNodeAtIndex","lossFn","built","trainableWeights","nonTrainableWeights","stateful","inputIndex","xShape","xShapeAtAxis","specDim","kwargs","callHook","inputsList","allAreSymbolic","noneAreSymbolic","assertInputCompatibility","xElem","build","setWeights","outputList","outputListCopy","collectInputShape","computeOutputShape","outputDType","warnOnIncompatibleInputShape","addInboundNode","dimMismatch","dimension","allOutputShapes","shapeString","trainableOnly","weightValueTuples","paramValues","pv","regularizer","initValue","addLoss","maskElement","inputTensorList","tensorIndex","numDisposedVariables","disposeWeights","refCountAfterDispose","getSourceInputs","sourceTensors","previousSources","inputTensor","Input","ModelLoggingVerbosity","resolveScalarsInLogs","logs","scalarsToDispose","valueScalar","disposeTensorsInLogs","validationData","epoch","model","callbacks","queueLength","callback","setParams","setModel","onEpochBegin","onEpochEnd","onBatchBegin","onBatchEnd","onTrainBegin","onTrainEnd","totals","oldTotalsToDispose","history","valueArray","yieldEvery","currentEpoch","onYield","maybeWait","waitMs","lastResult","lastTime","trainBegin","trainEnd","epochBegin","epochEnd","batchBegin","batchEnd","yield","ps","standardizeCallbacks","callbackConfig","verbosityLevel","callbackConstructor","CallbackConstructorRegistry","checkForDuplicate","constructors","levelName","ctor","configureCallbacks","epochs","initialEpoch","numTrainSamples","stepsPerEpoch","doValidation","callbackMetrics","actualCallbacks","createCallbacks","callbackList","samples","metrics","deserialize","l2Normalize","squareSum","epsilonTensor","yTrue","yPred","meanAbsoluteError","meanAbsolutePercentageError","clippedTrue","MAX_VALUE","absResult","meanSquaredLogarithmicError","clippedPred","firstLog","secondLog","categoricalCrossentropy","fromLogits","outputSum","sparseCategoricalCrossentropy","flatTarget","binaryCrossentropy","reluLogits","negAbsLogits","sigmoidCrossEntropyWithLogits","kullbackLeiblerDivergence","cosineProximity","trueNormalized","predNormalized","trueXPred","lossesMap","squaredHinge","maxResult","hinge","categoricalHinge","pos","logcosh","log2","predictionDiff","logcoshResult","poisson","logPred","identifierOrFn","includes","binaryAccuracy","yPredThresholded","categoricalAccuracy","truePositives","tp","fp","falsePositives","denominator","sparseCategoricalAccuracy","metricsMap","mse","MSE","mae","MAE","mape","MAPE","cosine","getLossOrMetricName","fnName","MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH","checkUserDefinedMetadata","modelName","checkSize","plainObjectCheck","xType","printSummary","lineLength","positions","relevantNodes","printFn","sequentialLike","isModelSequentialLike","toDisplay","nodesByDepth","printRow","layers","printLayerSummary","printLayerSummaryWithConnections","checkTrainableWeightsConsistency","trainableCount","countTrainableParams","nonTrainableCount","collectedTrainableWeights","nodes","depthNodes","flag","fields","line","countParams","connections","inboundLayer","inboundLayerIndex","inboundTensorIndex","firstConnection","isArrayItemInputOrOutputName","convertPythonicToTs","pythonicConfig","tsArray","arrayLength","tsDict","pythonicKey","pythonicValue","tsKey","convertTsToPythonic","tsConfig","pyArray","pyDict","tsValue","pyKey","feeds","id2Value","id2Mask","name2Id","FeedDict","feed","assertFeedCompatibility","cachedSorted","cachedRecipientCounts","fetches","feedDict","probe","arrayFetches","fetchArray","outputNames","finalOutputs","feedNames","getValue","maxNumTensors","minNumTensors","recipientCounts","fetchAndFeedKey","finalSorted","finalRecipientMap","getTopologicalSortAndRecipientCountsForOneFetch","recipientMap","visited","symbolicTensor","recipient","recipientMap2Counts","getTopologicalSortAndRecipientCounts","internalFeedDict","symbolic","srcLayer","inputValues","tensorsToDispose","maskExists","getMask","hasKey","outputMask","computeMask","layerOutputs","getNodeOutputs","outputSymbolicTensors","disposeMasks","marks","topIsMarked","getOutputAt","standardizeSampleOrClassWeights","xWeight","weightType","numOutputs","standardizeClassWeights","classWeight","standardizeWeights","sampleWeight","sampleWeightMode","yClasses","yClassIndices","classSampleWeight","classIndex","sampleWeights","standardizeDataIteratorOutput","iteratorOut","iteratorOutObj","flattenedXs","flattenTensorOrArrayOrMap","flattenedYs","xIndex","yIndex","inputOrOutput","standardizeTensorValidationData","dataset","hasBatchesPerEpoch","batchesPerEpoch","optimizer","isTraining","isDatasetObject","validationBatches","valXs","valYs","trainFunction","makeTrainFunction","outLabels","getDedupedMetricsNames","getStepsPerEpoch","stopTraining_","dataIterator","epochLogs","stepsDone","batchIndex","batchLogs","standardClassWeights","ins","valOuts","evaluateDataset","batches","evaluate","validationBatchSize","metricsNames","syncData","isLazyIteratorObject","hasBatches","testFunction","numExamples","xsAndYs","batchOuts","batchOut","oldScalar","checkBatchSize","sliceArrays","sliceArraysByIndices","makeBatches","batchStart","fitLoop","valF","valIns","validationSteps","checkNumSamples","indexArray","epochIndexArray1D","batchIds","insBatch","testLoop","fitTensors","checkBatchAxis","standardizeUserData","standardizedOuts","inputValX","inputValY","valStandardized","valX","valY","validationSplit","splitAt","originalBatchSize","makeTestFunction","valFunction","disposeNewTensors","ensureTensorsRank2OrHigher","refTensors","oldTensorIds","oldTensor","isDataArray","isDataDict","isDataTensor","standardizeInputData","exceptionPrefix","gotUnexpectedData","refDim","checkArrayLengths","setX","setY","checkLossAndTargetCompatibility","lossFns","keyLosses","loss","slicedYShape","slicedShape","targetDim","checkInputData","optimizer_","optimizerMap","isOptimizerOwned","lossFunctions","theLosses","lossFunction","feedOutputNames","feedOutputShapes","feedLossFns","internalOutputShapes","skipTargetIndices","metricsTensors","nestedMetrics","wrappedMetrics","outputMetrics","collectMetrics","appendMetric","outputIndex","metricName","metricTensor","accFn","weightedMetricFn","metric","metricFn","metricResult","handleMetrics","standardizeUserDataXY","testOuts","numSamples","stepsName","outputsIsArray","retrieveSymbolicTensors","tensorValue","executeOutputs","symbolicTensorNames","outputsRemaining","layerOutputNames","remainingNames","outsBatches","xsRank2OrHigher","feedInputShapes","predictLoop","feedInputNames","standardXs","standardYs","standardSampleWeights","classWeights","dedupedOutLabels","newLabel","dupIndex","lossValues","metricsValues","totalLoss","meanLoss","weightedMetric","calculateLosses","regularizerLoss","valOutputs","meanMetric","standardizeOut","namedWeights","getWeights","numTensorsBeforeOptmizerDisposal","lossNames","metricsIdentifiers","getLossIdentifiers","getMetricIdentifiers","optimizer_config","class_name","weighted_metrics","loss_weights","sample_weight_mode","lossEntry","compile","handlerOrURL","handlers","getNamedWeights","weightDataAndSpecs","modelConfig","toJSON","includeOptimizer","getTrainingConfig","optimizerWeightData","optimizerWeightSpecs","containerNodes","inputLayers","inputLayersNodeIndices","inputLayersTensorIndices","outputLayers","outputLayersNodeIndices","outputLayersTensorIndices","internalContainerRefs","internalInputShapes","nodesDepths","nodeIDToNode","layersDepths","layerIDToLayer","layerIndices","nodesInDecreasingDepth","buildMapOfGraph","finishedNodes","nodesInProgress","Container","nodeKey","numInboundLayers","reversedNodesInDecreasingDepth","previousDepth","inboundNode","nodeID","layersByDepth","layerID","depthKeys","layersForDepth","aIndex","bIndex","computableTensors","layersWithCompleteInput","allNames","numOccurrences","strict","nameToWeight","totalWeightsCount","validatedName","tokens","shortenNameArray","unsetNames","theConfig","unused","returnString","updatedConfig","masks","runInternalGraph","layersToOutputShapes","outputShapeKeys","referenceInputTensors","referenceOutputTensors","computedData","computedTensors","computedMasks","computedTensor","computedMask","keptNodes","nodeConversionMap","originalNodeIndex","buildNodeConversionMap","layerConfigs","layerClassName","layerConfig","filteredInboundNodes","nodeData","modelInputs","newNodeIndex","modelOutputs","resetStates","createdLayers","unprocessedNodes","addUnprocessedNode","processNode","inputData","inboundLayerName","inboundNodeIndex","processLayer","layerData","layerName","setFastWeightInitDuringBuild","layersFromConfig","currentUnprocessedNodesForLayer","inputLayersFromConfig","layerOutputTensors","outputLayersFromConfig","modelLayer","isLayerModelInstance","Sequential","checkShape","outputTensor","lastLayerIndex","predict","predictOnBatch","fit","fitDataset","trainOnBatch","stopTraining","configArray","extraModelConfig","conf","serializeActivation","deserializeActivation","getActivation","assertObjectArgs","hasL1","hasL2","regularization","REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP","serializeRegularizer","deserializeRegularizer","getRegularizer","baseConfig","DEFAULT_ALPHA","DEFAULT_ALPHA_INITIALIZER","alphaInitializer","alphaRegularizer","alphaConstraint","sharedAxes","paramShape","addWeight","DEFAULT_THETA","theta","DEFAULT_AXIS","normalizeArray","singleValue","convOutputLength","inputLength","outputLength","dilatedFilterSize","deconvLength","strideSize","kernelSize","preprocessConv2DInput","preprocessConv3DInput","conv1dWithBias","conv2dWithBiasActivation","conv3dWithBias","DEFAULT_KERNEL_INITIALIZER","DEFAULT_BIAS_INITIALIZER","BaseConv","verifyArgs","useBias","biasInitializer","biasConstraint","biasRegularizer","Conv","filters","kernelInitializer","kernelConstraint","kernelRegularizer","channelAxis","inputDim","kernelShape","biasValue","fusedActivationName","newSpace","space","newDim","hAxis","wAxis","kernelH","kernelW","strideH","strideW","heightAxis","widthAxis","dAxis","kernelD","strideD","depthAxis","DEFAULT_DEPTHWISE_INITIALIZER","DEFAULT_POINTWISE_INITIALIZER","depthwiseKernel","pointwiseKernel","depthMultiplier","depthwiseInitializer","depthwiseRegularizer","depthwiseConstraint","pointwiseInitializer","pointwiseRegularizer","pointwiseConstraint","depthwiseKernelShape","pointwiseKernelShape","Conv1D","cropping","hSliced","DEFAULT_SIZE","resized","cols","outFilters","outRows","outCols","standardizeArgs","initialState","constants","numConstants","toListOrNull","rnn","stepFunction","initialStates","goBackwards","unroll","needPerStepOutputs","lastOutput","perStepMasks","perStepOutputs","states","timeSteps","perStepInputs","currentInput","stepOutputs","maskedOutputs","stepMask","negStepMask","cell","cells","stateSize","returnSequences","returnState","stateSpec","states_","keptStates","outputDim","stateShape","stateMask","numStates","stepInputShape","expectedShape","standardized","additionalInputs","additionalSpecs","fullInput","fullInputSpec","originalInputSpec","getInitialState","cellCallKwargs","rnnOutputs","cellConfig","RNN","DEFAULT_ACTIVATION","DEFAULT_RECURRENT_INITIALIZER","units","recurrentInitializer","recurrentRegularizer","recurrentConstraint","recurrentDropout","dropoutMask","recurrentDropoutMask","recurrentKernel","prevOutput","generateDropoutMask","dpMask","recDpMask","DEFAULT_RECURRENT_ACTIVATION","resetAfter","recurrentActivation","implementation","hTMinus1","hh","matrixX","recurrentKernelValue","rk1","rk2","matrixInner","xZ","xR","xH","recurrentZ","recurrentR","recurrentH","unitForgetBias","capturedBiasInit","capturedUnits","bI","bF","bCAndH","cTMinus1","z0","z1","z2","z3","nestedStates","callInputs","newNestedStates","cellStates","tuples","numParams","inputWeights","droppedInputs","createMask","computeSingleOutputShape","getStates","isChannelsFirst","hOut","wOut","recurrentKernelShape","applyDropout","xI","xF","xC","xO","recDropoutMask","hI","hF","hC","hO","kernelI","kernelF","kernelC","kernelO","biasI","biasF","biasC","biasO","inputConv","recKernelI","recKernelF","recKernelC","recKernelO","recurrentConv","invokeCallHook","inputLastDim","targetShape","isUnknown","errorMsg","finalShape","known","unknown","originalSize","anyUnknownDims","fixUnknownDimension","expectedSortedIndices","dimsIncludingBatch","maskValue","booleanMask","embeddings","DEFAULT_EMBEDDINGS_INITIALIZER","embeddingsInitializer","embeddingsRegularizer","embeddingsConstraint","maskZero","inLens","s1","s2","shape1","shape2","computeElementwiseOpOutputShape","batchSizes","allRanks","reshapeRequired","reshapedInputs","inputDims","xNDim","mergeFunction","transposed","xTransposed","yNDim","yShape","allNoneShape","shapeSet","shapeWithoutConcatAxis","exists","allNullMasks","concatenatedMasks","interpretAxis","normalize","interpretAxes","x1","x2","axesArray","diffShape","adjX","adjY","idx","squeezeAxes","batchDot","_getNoiseShape","alphaP","keptIdx","batchNormalization","gamma","regularNormalizeBatchInTraining","meanAndVariance","broadcastNormalizeBatchInTraining","broadcastMean","broadcastVariance","broadcastGamma","broadcastBeta","betaInitializer","gammaInitializer","movingMeanInitializer","movingVarianceInitializer","betaConstraint","gammaConstraint","betaRegularizer","gammaRegularizer","movingMean","movingVariance","sortedReductionAxes","needsBroadcasting","broadcastMovingMean","broadcastMovingVariance","normalizeInference","normalizeBatchInTraining","normedTraining","doMovingAverage","origValue","updateDelta","broadcast","momentsTiling","scaleOffsetTiling","heightPadding","widthPadding","pattern","pool2d","poolSize","poolMode","paddingString","pool3d","poolingFunction","depths","newConfig","childInputShape","childOutputShape","timesteps","forwDict","forwardLayer","backDict","backwardLayer","mergeMode","_trainable","numWeights","numeightsOver2","layerShapes","stateSpecs","isSymbolicTensor","yRev","forwardState","backwardState","rnnLayer","getInput","rawAttrs","getAttr","assertShapesMatchAllowUndefinedSize","dim0","dim1","fullDefinedShape","elementShape","inferElementShape","listElementShape","partialShape","mergeElementShape","notfullDefinedShape","elementShapeA","elementShapeB","maxSize","identicalElementShapes","dynamicSize","clearAfterRead","closed_","idTensor","keepIds","tensorWithState","cleared","written","readMany","maxIndex","writeMany","totalLength","cumulativeLengths","elementPerRow","sizes","elementDtype","maxNumElements","TensorList","numElements","outputElementShape","reshapedTensors","elementIndex","fromTensor","reserve","thenFunc","elseFunc","cond","functionMap","executeFunctionAsync","tensorArrayMap","tensorListMap","bodyFunc","condFunc","condResult","argIds","condValue","origResult","resultIds","pred","frameId","enterFrame","exitFrame","nextIteration","tensorArray","addTensorArray","writeTensor","writeTensorArray","getTensorArray","readId","readIndex","readTensorArray","gatherId","gatherIndices","gatherDtype","gatherTensorArray","scatterId","scatterIndices","scatterTensor","scatterTensorArray","scatter","concatId","concatTensorArray","concatDtype","splitId","splitTensor","lengths","splitTensorArray","sizeId","sizeTensorArray","closeId","closeTensorArray","clearAndClose","getTensorList","elementDType","addTensorList","numElementsParam","pushBack","popBack","fusedConvAndDepthWiseParams","extraOp","activationFunc","isBiasAdd","noBiasAdd","isPrelu","isBatchNorm","numArgs","biasArg","preluArg","nmsParams","keyDType","valueDType","handle","clear","checkKeyAndValueTensor","$keys","keysLength","valuesLength","findWithDefault","hashTable","addHashTable","getHashTableById","import","tensorSize","category","includeBatchInIndex","indexes","def","snapshot","summarize","binaryOutput","squeezedShape","mapped","sameShape","sparseValues","opMapper","customExecutor","weightMap","rootContext","frameName","iterationId","contexts","lastId","generateCurrentContextIds","_currentContextIds","contextIdforContexts","newFrame","getExecutionSubgraph","initNodes","usedNodes","missingInputs","dynamicNode","syncInputs","inputNodeNames","initNodeNames","frontier","isControlFlow","isDynamicShape","isHashTable","children","child","CONTROL_FLOW_OPS","DYNAMIC_SHAPE_OPS","HASH_TABLE_OPS","graph","parent","compiledMap","_weightMap","SEPERATOR","_functions","_functionExecutorMap","_outputs","_inputs","_initNodes","_signature","functions","GraphExecutor","weightIds","_weightIds","functionExecutorMap","_resourceManager","signatureKey","defaultOutput","sortedInputs","sortedOutputs","executionInfo","outNames","inNames","inputNodes","orderedNodes","getNodesInTopologicalOrder","mapInputs","checkInputs","checkInputShapeAndType","mapOutputs","checkOutputs","outputNodeNames","outputNodes","compilationKey","getCompilationKey","tensorsToKeep","getFrozenTensorIds","intermediateTensorConsumerCount","checkTensorForDisposal","ids","_executeAsync","isFunctionExecution","executeWithControlFlow","results","outputIds","inputIds","mappedInputs","currentContext","added","processStack","missingOutputs","alternativeMsg","processChildNodes","childNode","notInGraph","normalizedName","hashTableNameToHandle","hashTableMap","TFHUB_SEARCH_PARAM","DEFAULT_MODEL_NAME","modelUrl","executor","findIOHandler","loadSync","versions","producer","minConsumer","Instance","transformGraph","convertTensorMapToTensorsMap","executeAsync","execute","normalizeInputs","normalizeOutputs","newMap","loadGraphModel","fromTFHub","smallLastBatch","datasetFromIteratorFn","columnMajorBatch","deepBatchConcat","concatenate","predicate","forEachAsync","mapAsync","bufferSize","RangeError","prefetch","iteratorIterator","take","skip","reshuffleEachIteration","seedrandom","seed2","int32","toArray","toArrayForTest","iteratorFn","zip","datasets","ds","recurse","streams","SHORTEST","exampleRow","batchConcat","MAX_BUFFER_SIZE","inputIterator","utf8Iterator","decodeUTF8","lineIterator","CODE_QUOTE","STATE_OUT","STATE_FIELD","STATE_QUOTE","STATE_QUOTE_AFTER_QUOTE","STATE_WITHIN_QUOTE_IN_QUOTE","csvConfig","hasHeader","fullColumnNames","columnNamesValidated","columnConfigs","configuredColumnsOnly","delimWhitespace","columnNames","setColumnNames","maybeReadHeaderLine","columnNamesFromFile","counts","countAcc","duplicateNames","iter","firstElement","firstLine","headers","parseRow","makeDataElement","features","parsedValue","default","required","isLabel","valueAsNum","getBoolean","validateElementCount","readOffset","readLength","currentState","microphoneConfig","isClosed","fftSize","fftSizeLog2","numFrames","numFramesPerSpectrogram","sampleRateHz","columnTruncateLength","audioTrackConstraints","smoothingTimeConstant","includeSpectrogram","includeWaveform","navigator","mediaDevices","getUserMedia","audio","video","stream","ctxConstructor","AudioContext","webkitAudioContext","audioContext","sampleRate","streamSource","createMediaStreamSource","analyser","createAnalyser","connect","freqData","timeData","getAudioData","audioDataQueue","flattenQueue","freqDataQueue","spectrogramTensor","getTensorFromAudioDataArray","timeDataQueue","waveformTensor","currentFrames","intervalID","setInterval","getFloatFrequencyData","getFloatTimeDomainData","clearInterval","disconnect","getTracks","queue","frameSize","microphoneIterator","MicrophoneIterator","webcamVideoElement","webcamConfig","resize","needToResize","resizeHeight","resizeWidth","cropBoxInd","centerCrop","widthCroppingRatio","heightCroppingRatio","widthCropStart","heightCropStart","widthCropEnd","heightCropEnd","cropBox","facingMode","deviceId","srcObject","src","play","onloadedmetadata","cropAndResizeFrame","resizedImage","expandedImage","webcamIterator","WebcamIterator","File","chunkSize","chunk","fileReader","onabort","urlChunkIterator","urlString","getRequestInitFromRequest","uint8Array","statusText","request","credentials","cache","redirect","referrer","integrity","isLocalPath","fs","readFileSync","fileOptions","csv","generator","webcam","microphone","assertNotComplex","whereImpl","firstUse","MathBackendCPU","nextDataId","outId","encodedValues","complexTensorInfos","realValues","imagValues","decodedData","force","condVals","unaryKernelFunc","cpuBackend","xSize","$dtype","makeTensorInfo","unaryKernelFuncFromImpl","unaryImpl","identityConfig","createSimpleBinaryKernelImpl","aVals","bVals","resultRank","resultStrides","resultSize","aRank","bRank","aStrides","bStrides","aBroadcastDims","bBroadcastDims","aLoc","bLoc","sigmoidConfig","applyActivation","binaryKernelFunc","simpleImpl","complexImpl","decodedAVals","decodedBVals","resultData","$aComplex","$aComplexVals","aReal","aImag","aRealVals","aImagVals","$bComplex","$bComplexVals","bReal","bImag","bRealVals","bImagVals","resultRealData","resultImagData","resultReal","resultImag","disposeIntermediateTensorInfo","createComplexBinaryKernelImpl","resultRealVals","resultImagVals","aIdx","bIdx","opResult","addConfig","$shape","reshapeConfig","permutedAxes","getAxesPermutation","getInnerMostAxes","assertAxesAreInnerMostDims","computeOutAndReduceShapes","intermediateTensorInfos","xValues","poolType","padTop","padLeft","outputVals","outputBatchStrides","outputRowStrides","outputColStrides","outputBatchOffset","inputBatchOffset","yR","xRCorner","xRMin","xRMax","outputRowOffset","yC","xCCorner","xCMin","xCMax","minMaxValue","avgValue","xROffset","pixel","flattenPositions","maxPositions","xBuf","maxPosition","wR","wC","padFront","outputDepthStrides","yDepth","xDepthCorner","xDepthMin","xDepthMax","outputDepthOffset","yRow","xRowCorner","xRowMin","xRowMax","yCol","xColCorner","xColMin","xColMax","outputColOffset","xDepth","xDepthOffset","xRow","xRowOffset","xCol","bincountImpl","xVals","weightsVals","weightsDtype","weightsShape","weightsSize","outVals","bincountReduceImpl","weightsBuf","outBuf","bincountConfig","createSimpleUnaryImpl","clip","xi","clipAttrs","clipConfig","cumsumConfig","reverseTransposedResult","getUndoAxesPermutation","denseBincountConfig","bufferSync","dilation2dBackpropFilterConfig","gradients","hBeg","wBeg","curVal","MIN_SAFE_INTEGER","hMax","wMax","hIn","wIn","dilation2dBackpropInputConfig","hInMax","wInMax","$dim","expandDimsConfig","fftBatch","innerDim","inputVals","real2D","imag2D","fftImpl","$realInfo","$imagInfo","inputSize","realVals","imagVals","fftRadix2","realInfo","imagInfo","sizeInfo","sizeInfoCopy","divRealInfo","realDivConfig","divImagInfo","divRealVals","divImagVals","rawOutput","term","fourierTransformByMatmul","evenComplex","evenRealVals","evenImagVals","evenShape","evenRealInfo","evenImagInfo","evenTensorInfo","oddComplex","oddRealVals","oddImagVals","oddShape","oddRealInfo","oddImagInfo","oddTensorInfo","$evenComplex","$evenRealVals","$evenImagVals","$evenShape","$evenRealInfo","$evenImagInfo","$evenTensorInfo","$oddComplex","$oddRealVals","$oddImagVals","$oddShape","$oddRealInfo","$oddImagInfo","$oddTensorInfo","eShape","eRealInfo","eImagInfo","complexInfo","exponentInfo","addPart","subPart","addPartReal","subPartReal","addPartImag","subPartImag","$real","$imag","$realVals","$imagVals","gatherNdImpl","indicesData","paramsBuf","numSlices","paramsSize","flattenIndex","gatherV2Impl","indicesBuf","flattenOutputShape","originalLoc","batchIdx","indicesIdx","indicesIndex","originalIndex","isFiniteConfig","isInfConfig","isNaNConfig","linSpaceImpl","linSpaceConfig","logicalNotConfig","wDepth","wRow","wCol","maxPoolWithArgmaxConfig","nonMaxSuppressionV3Impl","nonMaxSuppressionV3Config","nonMaxSuppressionV5Impl","notEqualConfig","pack","expandedT","packConfig","rangeImpl","scatterImpl","outputSize","numUpdates","sumDupeIndices","flattenShape","updatesData","sparseFillEmptyRowsImpl","indicesDType","valuesDType","indicesCount","denseRows","rowsAreOrdered","lastIndicesRow","csrOffset","allRowsFull","rowEmpty","fullIndicesCount","filledCount","outputI","startingIndex","col","sparseReshapeImpl","inputIndicesShape","denseSize","nnz","outputRank","product","unknownIndex","missing","inputStrides","outputStrides","newIndices","sparseSegmentReductionImpl","isMean","numIndices","inputFlat","numCol","lastSegmentIdPlusOne","outputRows","uninitializedIndex","outIndex","nextIndex","stridedSliceImpl","newLoc","preserveShort","nGramWidth","getPadWidth","splitIndex","outputStartIndex","numNGrams","nGramIndex","leftPadding","rightPadding","numTokens","dataStartIndex","nGramSize","nGram","nextNGramIndex","appendToNGram","splits","inputDataSize","splitsSize","prevSplit","validSplits","numBatchItems","empty","getNumNGrams","outputStartIdx","createNGrams","dataLength","stringNGramsImpl","compute","delimiters","token","tokenStart","stringSplitImpl","maxNumEntries","nEntries","stringToHashBucketFastImpl","modulo","getLowBitsUnsigned","tileImpl","comparePair","valueDiff","sd","newLeft","newRight","topKImpl","xDtype","allTopKVals","allTopKIndices","outOffset","topKVals","topKIndices","uniqueImpl","uniqueElements","inputBuffer","uniqueIndices","is1DTensor","element","axisValues","uniqueIndex","outputTmpShape","outputBuffer","uniqueElementIndex","depthwiseConv2dNativeConfig","maximumConfig","PackingScheme","TextureUsage","PhysicalTextureType","WEBGL_ATTRIBUTES","antialias","premultipliedAlpha","preserveDrawingBuffer","stencil","failIfMajorPerformanceCaveat","getWebGLContext","webGLVersion","newCtx","OffscreenCanvas","createCanvas","addEventListener","ev","preventDefault","getWebGLRenderingContext","gl","isContextLost","disable","DEPTH_TEST","STENCIL_TEST","BLEND","DITHER","POLYGON_OFFSET_FILL","SAMPLE_COVERAGE","enable","SCISSOR_TEST","CULL_FACE","cullFace","BACK","getUnpackedMatrixTextureShapeWidthHeight","getDenseTexShape","texelsNeeded","getPackedMatrixTextureShapeWidthHeight","getTextureConfig","textureHalfFloatExtension","internalFormatFloat","internalFormatHalfFloat","internalFormatPackedHalfFloat","internalFormatPackedFloat","textureFormatFloat","downloadUnpackNumChannels","defaultNumChannels","textureTypeHalfFloat","textureTypeFloat","glany","getNumber","R32F","R16F","RGBA16F","RGBA32F","RED","HALF_FLOAT","FLOAT","RGBA","HALF_FLOAT_OES","downloadTextureFormat","callAndCheck","func","returnValue","getError","NO_ERROR","INVALID_ENUM","INVALID_VALUE","INVALID_OPERATION","INVALID_FRAMEBUFFER_OPERATION","OUT_OF_MEMORY","CONTEXT_LOST_WEBGL","getWebGLErrorMessage","checkWebGLError","canBeRepresented","getExtensionOrThrow","extensionName","throwIfNull","getExtension","createFragmentShader","fragmentShaderSource","fragmentShader","createShader","FRAGMENT_SHADER","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","shaderInfoLog","lineNumberRegexResult","lineNumberRegex","exec","lineNumber","shaderLines","linesWithLineNumbers","maxLineLength","beforeErrorLines","errorLine","afterErrorLines","logShaderSourceAndInfoLog","getShaderInfoLog","MAX_TEXTURE_SIZE","MAX_TEXTURES_IN_SHADER","validateProgram","program","getProgramParameter","VALIDATE_STATUS","getProgramInfoLog","bindVertexBufferToProgramAttribute","attribute","arrayEntriesPerItem","itemStrideInBytes","itemOffsetInBytes","getAttribLocation","bindBuffer","ARRAY_BUFFER","vertexAttribPointer","enableVertexAttribArray","getProgramUniformLocationOrThrow","uniformName","getUniformLocation","getProgramUniformLocation","bindTextureToProgramUniformSampler","texture","uniformSamplerLocation","textureUnit","validateTextureUnit","activeTexture","TEXTURE0","bindTexture","TEXTURE_2D","bindTextureUnit","uniform1i","bindColorTextureToFramebuffer","framebuffer","bindFramebuffer","FRAMEBUFFER","framebufferTexture2D","COLOR_ATTACHMENT0","unbindColorTextureFromFramebuffer","validateFramebuffer","checkFramebufferStatus","FRAMEBUFFER_COMPLETE","FRAMEBUFFER_INCOMPLETE_ATTACHMENT","FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT","FRAMEBUFFER_INCOMPLETE_DIMENSIONS","FRAMEBUFFER_UNSUPPORTED","getFramebufferErrorMessage","returnTOrNull","failureMessage","tOrNull","maxTextureUnit","MAX_COMBINED_TEXTURE_IMAGE_UNITS","glTextureUnit","textureUnitRange","getBatchDim","dimsToSkip","getRowsCols","getShapeAs3D","shapeAs3D","isEven","isReshapeFree","shape1Cols","shape2Cols","hasExtension","isWebGLVersionEnabled","isDownloadFloatTextureEnabled","createFloatTextureAndBindToFramebuffer","COLOR_BUFFER_HALF_FLOAT","texConfig","createTexture","texImage2D","frameBuffer","createFramebuffer","isFrameBufferComplete","deleteTexture","deleteFramebuffer","createHalfFloatTextureAndBindToFramebuffer","getGlslDifferences","varyingVs","varyingFs","texture2D","defineOutput","defineSpecialNaN","defineSpecialInf","defineRound","getLogicalCoordinatesFromFlatIndex","coords","line1","line2","getLogicalCoordinatesFromFlatIndexByUniform","getFlatIndexFrom3D","registerFlag","getParameter","getWebGLMaxTextureSize","MAX_TEXTURE_IMAGE_UNITS","getMaxTexturesInShader","getWebGLDisjointQueryTimerVersion","isMobile","isCapableOfRenderingToFloatTexture","fenceSync","ENCODE_FLOAT_SNIPPET","packedInputs","packedOutput","outPackingScheme","DENSE","texShape","glsl","userCode","outTexUsage","DOWNLOAD","inputIsUnsignedByte","mainLoop","vertexShaderSource","vertexShader","VERTEX_SHADER","createVertexBuffer","createBuffer","bufferData","STATIC_DRAW","createIndexBuffer","ELEMENT_ARRAY_BUFFER","createAndConfigureTexture","internalFormat","textureFormat","textureType","maxTextureSize","requested","tex2d","texParameteri","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","TEXTURE_MIN_FILTER","NEAREST","TEXTURE_MAG_FILTER","getInternalFormatForFloat32MatrixTexture","textureConfig","getInternalFormatForFloat16MatrixTexture","getInternalFormatForUnsignedBytesMatrixTexture","getInternalFormatForPackedMatrixTexture","getInternalFormatForFloat16PackedMatrixTexture","physicalRows","physicalCols","gl2","downloadTarget","PIXEL_PACK_BUFFER","getBufferSubData","outputTexture","disposed","vertexAttrsAreBound","itemsToPoll","glVersion","setWebGLContext","COLOR_BUFFER_FLOAT","TEXTURE_HALF_FLOAT","textureFloatExtension","colorBufferFloatExtension","colorBufferHalfFloatExtension","vertexBuffer","indexBuffer","finish","deleteBuffer","UNSIGNED_BYTE","dataForUpload","texelDataType","downloadMatrixDriver","readPixels","bindTextureToFrameBuffer","bufferSizeBytes","bytesPerFloat","STREAM_READ","unbindTextureToFrameBuffer","fenceContext","createFence","pollFence","isFencePassed","sync","SYNC_GPU_COMMANDS_COMPLETE","flush","clientWaitSync","ALREADY_SIGNALED","CONDITION_SATISFIED","beginQuery","endQuery","isQueryAvailable","packedRGBA","createProgram","attachShader","linkProgram","LINK_STATUS","debug","setProgram","deleteProgram","useProgram","shouldThrow","inputMatrixTexture","uniformLocation","throwIfNoProgram","outputMatrixTexture","setOutputMatrixTextureDriver","outputPackedMatrixTexture","startRow","startColumn","setOutputMatrixWriteRegionDriver","debugValidate","drawElements","TRIANGLES","UNSIGNED_SHORT","disjointQueryTimerExtension","getQueryTimerExtension","getQueryTimerExtensionWebGL2","createQuery","TIME_ELAPSED_EXT","ext","getQueryTimerExtensionWebGL1","createQueryEXT","beginQueryEXT","endQueryEXT","getQueryTime","queryTimerVersion","getQueryParameter","QUERY_RESULT","getQueryObjectEXT","QUERY_RESULT_EXT","available","QUERY_RESULT_AVAILABLE","disjoint","GPU_DISJOINT_EXT","QUERY_RESULT_AVAILABLE_EXT","addItemToPoll","linearSearchLastTrue","isDoneFn","resolveFn","pollItems","downloadAndDecode","outputMatrixTextureMaybePacked","viewport","scissor","makeShader","inputsInfo","prefixSnippets","shapeInfo","logicalShape","isUniform","enableShapeUniforms","getUniformInfoFromShape","uniformShape","customUniforms","arrayIndex","outputSamplingSnippet","floatTextureSetOutputSnippet","inputPrefixSnippet","inputSamplingSnippet","inInfo","outShapeInfo","usesPackedTextures","getPackedSamplerFromInInfo","getSamplerFromInInfo","getPackedSamplerAtOutputCoords","getSamplerAtOutputCoords","getInputSamplingSnippet","outTexShape","floatTextureSampleSnippet","getFloatTextureSampleSnippet","shaderPrefix","SAMPLE_1D_SNIPPET","SAMPLE_2D_SNIPPET","SAMPLE_3D_SNIPPET","getShaderPrefix","isPacked","packedTexShape","getOutputPacked1DCoords","texelsInLogicalRow","getOutputPacked2DCoords","texelsInBatch","getOutputPacked3DCoords","texelsInBatchN","getOutputPackedNDCoords","getPackedOutputSamplingSnippet","getFloatTextureSetRGBASnippet","getOutput1DCoords","getOutput2DCoords","coordsFromIndexSnippet","getOutput3DCoords","getOutput4DCoords","getOutput5DCoords","getOutput6DCoords","getOutputSamplingSnippet","getFloatTextureSetRSnippet","SHADER_PACKED_PREFIX","getSamplerScalar","getSampler1D","getSampler2D","getSampler3D","getSampler4D","getSampler5D","getSampler6D","inputInfo","texName","funcName","getPackedSamplerScalar","getPackedSampler1D","texNumR","texNumC","valuesPerRow","getPackedSampler2D","newInputInfo","squeezeInputInfo","getSqueezedParams","getPackedSampler3D","getPackedSamplerND","getFlatOffsetUniformName","tNumR","tNumC","getUniformSampler","stride0","stride1","flatOffset","stride2","stride2Str","stride1Str","stride0Str","stride3","stride4","coordsSnippet","texFuncSnippet","outRank","broadcastDims","getCoordsDataType","rankDiff","unpackedCoordsSnippet","isInputScalar","isOutputScalar","inTexShape","useSqueezePackedShape","useSqueezeShape","compileProgram","gpgpu","inputInfos","texData","inShapeInfos","webGLProgram","infLoc","nanLoc","outShapeLocation","outTexShapeLocation","outShapeStridesLocation","uniformLocations","inShapesLocations","inTexShapesLocations","customUniformLocations","validateBinaryAndProgram","shapeInfos","texShapeA","texShapeB","runProgram","binary","customUniformValues","outTex","setOutputPackedMatrixTexture","setOutputMatrixTexture","uniform1f","varLoc","varOffsetLoc","varShapeLoc","varTexShapeLoc","uniform1iv","uniform2iv","uniform3iv","uniform4iv","uniform2i","uniformValues","uniform1fv","setInputMatrixTexture","outShapeLoc","customLoc","customValue","uniform2fv","uniform3fv","uniform4fv","executeProgram","makeShaderKey","keyInputs","hasOffset","xTexShape","rank1","rank2","rank34","isLogicalShapTexShapeEqual","isScalar","isInOutTexShapeEqual","isTexShapeGreaterThanOne","keyUserCode","useShapeUniforms","addImplCPU","bincountImplCPU","bincountReduceImplCPU","ceilImplCPU","concatImplCPU","equalImplCPU","expImplCPU","expm1ImplCPU","floorImplCPU","gatherNdImplCPU","gatherV2ImplCPU","greaterImplCPU","greaterEqualImplCPU","lessImplCPU","lessEqualImplCPU","linSpaceImplCPU","logImplCPU","maxImplCPU","maximumImplCPU","minimumImplCPU","multiplyImplCPU","negImplCPU","notEqualImplCPU","prodImplCPU","rangeImplCPU","rsqrtImplCPU","simpleAbsImplCPU","sliceImplCPU","sparseFillEmptyRowsImplCPU","sparseReshapeImplCPU","sparseSegmentReductionImplCPU","stridedSliceImplCPU","stringNGramsImplCPU","stringSplitImplCPU","stringToHashBucketFastImplCPU","subImplCPU","tileImplCPU","topKImplCPU","transposeImplCPU","uniqueImplCPU","getVecChannels","getChannels","channels","outOfBoundsCondition","getOutOfBoundsCondition","setup","getSetup","sourceCoords","coord","getSourceCoordsArr","getOutput","thisRC","getReshapedInputCoords","numUsedTextures","numFreeTextures","_numBytesAllocated","_numBytesFree","freeTextures","logEnabled","usedTextures","shapeRC","usage","physicalTexType","getPhysicalFromLogicalTextureType","shapeKey","getKeyFromTextureShape","newTexture","texBytes","PACKED_2X2_FLOAT32","createPackedMatrixTexture","PACKED_2X2_FLOAT16","createFloat16PackedMatrixTexture","UNPACKED_FLOAT32","createFloat32MatrixTexture","UNPACKED_FLOAT16","createFloat16MatrixTexture","PACKED_4X1_UNSIGNED_BYTE","createUnsignedBytesMatrixTexture","logicalTexType","deleteTexThreshold","deleteMatrixTexture","texList","texIndex","freeRatio","tex","internalFormatForPhysicalTexType","numBytesForInternalFormat","UPLOAD","RENDER","getPhysicalTextureForRendering","PIXELS","shapeRowsCol","opSnippet","CHECK_NAN_SNIPPET","LINEAR","ABS","RELU","RELU6","CLONE","SIGMOID","getSourceCoords","binaryCaches","CPU_HANDOFF_SIZE_THRESHOLD","pendingRead","pendingDisposal","WeakSet","dataRefCount","numBytesInGPU","uploadWaitMs","downloadWaitMs","lastGlFlushTime","warnedAboutMemory","pendingDeletes","binaryCache","gpgpuCreatedLocally","textureManager","numMBBeforeWarning","screen","devicePixelRatio","MathBackendWebGL","checkNumericalProblems","runWebGLProgram","convertAndCacheOnCPU","shouldTimeProgram","activeTimers","getValuesFromTexture","tmpDownloadTarget","tmpData","createBufferFromTexture","createAndWaitForFence","downloadFloat32MatrixFromBuffer","dTypeVals","subscribers","tmpTarget","downloadMatrixFromPackedTexture","shouldUsePackedProgram","downloadByteEncodedFloatMatrixFromOutputTexture","oldActiveTimers","newActiveTimers","outerMostTime","programTimersStack","flattenedActiveTimerQueries","flattenedActiveTimerNames","ms","numBytesInGPUAllocated","numBytesAllocated","numBytesInGPUFree","numBytesFree","startMs","endMs","waitForQueryAndGetTime","timerQuery","releaseGPUData","origDataId","computeBytes","releaseTexture","uploadToGPU","sizeThreshold","compileAndRun","shouldExecuteOnCPU","outValues","makeOutput","packedUnaryOp","afterShape","input3DShape","input3D","afterShapeAs3D","outputDtype","preventEagerUnpackingOfOutput","outData","texelShape","dataToDispose","inputsData","unpackTensor","packTensor","savedInput","packedReshape","outputData","getAndSaveBinary","startTimer","endTimer","glFlushThreshold","unpacked","getBinary","HTMLCanvasElement","remove","floatPrecisionValue","debugFlag","underflowCheckValue","floatPrecision","logShape","maxTexSize","squeezeResult","batchDim","isByteArray","tempDenseInputHandle","uploadDenseMatrixToTexture","getTexture","encodedOutputTarget","outputTexData","acquireTexture","float32Values","float32ToTypedArray","texType","mb","isBrowser","checkOutOfBounds","supportsBroadcasting","checkOutOfBoundsString","realTensorInfo","imagTensorInfo","LEAKYRELU","LEAKYRELU_PACKED","$alpha","PRELU","PRELU_PACKED","packedOpSnippet","cpuKernelImpl","webglBackend","xData","supportsComplex","aData","bData","complexParts","aPart","bPart","aHandle","bHandle","complexOutput","mapActivationToShaderProgram","packed","addBias","hasPreluActivation","hasLeakyreluActivation","sharedDim","sharedDimensionPacked","aSample","bSample","aSwizzle","bSwizzle","activationSnippet","applyActivationSnippet","addBiasSnippet","batchASnippet","batchBSnippet","COMPLEX_MULTIPLY","MUL","upcastType","realProgram","imagProgram","realPart","imagPart","$xSize","xTexData","reduceInfo","divisor","windowSize","outSize","windowSizeNearestVec4","windowSizeVec4Remainder","updateSnippet","toPrecision","reduceType","initializationValue","compareOp","vecType","reductionType","reductionStages","stages","getReductionStages","previousResult","switched","originalOrder","switchedCoords","getSwitchedCoords","outputOrder","switchedOrder","nextColumn","getc","sumInputIsTransposed","sumInput","sumOutShape","expandShapeToKeepDim","reshapedInput","reduced","sumImpl","batchMatMulImpl","batchDimsCompatible","a3dShape","b3dShape","a3d","b3d","intermediates","hasBias","hasPreluActivationWeights","hasLeakyreluAlpha","fusedActivation","aVec","bVec","shouldReshapeB","aVec3d","bVec3d","$leakyreluAlpha","outReshaped","ADD","addKernelFunc","snippets","operation","midIndex","leftSide","rightSide","d1","d2","permutedX","a2D","firstPass","compOp","indexSnippet","sourceLocSetup","sourceRank","sourceLocDType","inChannel","intChannels","srcRCoords","srcGCoords","srcBCoords","srcACoords","fetchCandidateIdx","fetchValue","getBestIndicesAChannelSnippet","argReduce","bestIndicesA","argReducePacked","argMinMaxReduce","CHECK_NAN_SNIPPET_BINARY","computePositions","isAvgPool","batchFlattenPositionStr","flattenPositionStr","filterWidthNearestVec4","filterWidthVec4Remainder","avgPoolProgram","avgMultiplier","avgPoolGrad3DConfig","avgPoolBackpropProgram","meanShape","varianceShape","offsetShape","scaleShape","offsetSnippet","scaleSnippet","finalInputs","destSize","getCoords","coordSum","sourceLoc","getChannel","upperRow","lowerRow","parseSliceParams","$begin","$size","assertParamsValid","isContinous","isSliceContinous","customValues","newTexData","computeFlatOffset","shallowSlice","toDispose","reshapedIntermediate","transposedIntermediate","reshapedIntermediate2","sliced","zerosTensor","floatX","zerosTensorInfo","CEIL","clipByValueConfig","makeComplexComponentTensorInfo","complexTensor","complexPart","programInputs","offsets","lastIndex","lastShift","lastChannels","allChannels","getValueSnippet","shiftedChannels","channelIdx","reals","imags","realConcated","imagConcated","runOnCpu","innerSize","inputsValShapes","simplyConcat","finalOutShape","tensors2D","computeTensors2D","reshapedResult","$inputs","inputDepthNearestVec4","inputDepthVec4Remainder","isChannelsLast","rowDim","colDim","channelDim","itemsPerBlockRow","unrolled","conv2dByMatMul","sharedMatMulDim","outerShapeX","outerShapeFilter","batchMatMulWillBeUnpacked","reshapeWillBeExpensive","originalXTexDataShape","pointwiseConv","pointwiseConvTexData","xReshaped","filterReshaped","conv2dWithIm2Row","x2ColShape","xSqueezed","w2Row","im2ColProgram","im2Col","im2ColReshaped","matmulProgram","conv3DBackpropInputConfig","CHECK_NAN_SNIPPET_UNARY","imageShape","boxShape","cropHeight","cropWidth","methodId","inputHeightFloat","inputWidthFloat","heightRatio","heightScale","inY","widthRatio","widthScale","inX","idxString","getFinalCoord","permutedAxis","prevResult","getHeightCoordString","getWidthCoordString","getDepthCoordString","getOutputDepthSize","getInputSamplingString","inputHeight","inputWidth","outputHeight","outputWidth","outputDepth","hasLeakyReluAlpha","xNumRows","xNumCols","channelMul","texelsAcross","texelC","colIndex","nextTexelOffset","flat","dilation2DConfig","numDimsRemaining","idTerm","dimsToExpand","EXP","EXPM1","component","opString","exponentMultiplierSnippet","resultDenominator","innerDimensionSize","input2D","complexOutputReshaped","FLOOR","fromPixelsConfig","tempPixelHandle","uploadPixelDataToTexture","shouldPackDepthwiseConv","sliceDim","stridesType","strideString","flattenIndices","flattenX","outValue","currentCoords","segment_util","radius","powOperator","rad","maxD","basis","LRNConfig","LRNGradConfig","maxInputIsTransposed","maxInput","maxInputValues","maxOutShape","reshapedOutput","maxPoolProgram","maxPoolGrad3DConfig","maxPool3dPositionsProgram","maxPool3dPositions","maxPoolBackpropProgram","maxPoolPositionsProgram","maxPoolPositions","maxPoolBackPropProgram","poolOutput","meanInputIsTransposed","meanInput","meanInputValues","meanOutShape","meanImpl","unpackedCoords","cLimit","padSetup","numOutcomes","realDiv","SUB","maxLogit","expandedShape","maxLogitsReshaped","sumExp","sumExpReshaped","normalized","probs","NEG","nonMaxSuppressionV4Impl","componentSetup","paddingArea","outDtype","newHeight","newWidth","oldHeight","oldWidth","sourceFracIndexRC","effectiveInSize","effectiveOutSize","xHeight","xWidth","yHeight","yWidth","effectiveXSize","effectiveYSize","invHeightScale","invWidthScale","winHeight","winWidth","roundBase","inCoords","getInCoord","nextRow","inCoordsArray","channels1","getR","getG","getB","getA","$dims","fillSnippet","updateSize","updatesRank","indicesString","indicesSnippet","updatesString","updatesSnippet","calculateShapes","cRank","cCoords","abCoords","cCoordVars","abCoordVars","SELU_SCALEALPHA","SELU_SCALE","completePaddings","paddedX","reshapedPaddedShape","permutedReshapedPaddedPermutation","reshapedPaddedX","paddedXT","outputIndicesShape","outputDataShape","sparseIndices","sliceT","inputDtype","newCoords","outputAxis","sliceInfo","nonStrided","$strides","resultValues","resultReshaped","disposeIntermediateTensorInfoOrNull","roundUpToPow2","pow2","TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD","TOPK_K_CPU_HANDOFF_THRESHOLD","xtexData","xIsPacked","xUnPacked","x2D","kPow2","lastDimPow2","getInputs","runSwap","dir","inc","prevIndices","mergeProgram","prevValues","fillModeId","interpolationModeId","segOpInfo","segOpType","checkValueOutOfBounds","checkSegmentIdOutOfBounds","segOpCompute","rangeInfo","tileInfo","variableGrads","specifiedVarList","specifiedNonTrainable","originalVarCount","namedGrads","customGrad","Reduction","_defineProperty","sqrt_","historyContext","createContext","createNamedContext","Router","computeRootMatch","isExact","pathname","componentDidMount","_pendingLocation","componentWillUnmount","unlisten","render","RouterContext","staticContext","HistoryContext","Lifecycle","onMount","componentDidUpdate","onUpdate","prevProps","onUnmount","cacheCount","generatePath","pathToRegexp","compilePath","pretty","Redirect","computedMatch","to","createLocation","prevLocation","locationsAreEqual","matchPath","exact","sensitive","matched","cacheKey","pathCache","regexp","memo","Route","addLeadingSlash","stripBasename","createURL","createPath","staticHandler","methodName","invariant","noop","Switch","useContext","useHistory","useLocation","axesAreInnerMostDims","combineLocations","outputLoc","reduceLoc","outIdx","reduceIdx","numAxes","exp_","_assertThisInitialized","ReferenceError","_inheritsLoose","greater_","abs_","getFusedDyActivation","getFusedBiasGradient","shouldFuse","cloneIfTensor","capacity","doubledCapacity","isFull","wrap","isEmpty","relativeIndex","GrowingRingBuffer","INITIAL_CAPACITY","expand","newCapacity","newData","iteratorFromItems","iteratorFromFunction","iteratorFromConcatenated","baseIterators","baseErrorHandler","iteratorFromZipped","iterators","mismatchMode","ZipMismatchMode","FAIL","shouldContinue","serial","resolveFully","serialMapAsync","resolveWhile","zipFn","rowBatches","rowMajorBatch","trav","nextFn","upstream","lastRead","summary","serialNext","maxCount","skipped","enableSmallLastBatch","outputQueue","pump","mappedArray","pushAll","moreIterators","readFromChain","iteratorResult","handleErrors","itemResult","currentPromise","afterState","getNext","numIterators","iteratorsDone","LONGEST","nextState","refill","upstreamExhausted","randomInt","chosenIndex","chooseIndex","shuffleExcise","reverse_","providedSize","inferredSize","inferred","flatDimsDontMatch","ownerDocument","pow_","$base","$exp","_objectWithoutPropertiesLoose","sourceKeys","lessEqual_","pad_","transpose_","useEnhancedEffect","useEventCallback","current","OperationMapper","ops","mappersJson","opMappers","mapper","tfOpName","tfNodes","placeholders","mapNode","inputNodeNameToKey","outputNodeNameToKey","mapSignatureEntries","allNodes","inputNode","library","function","mapFunction","entries","newNode","getStringParam","tfName","tfDeprecatedName","getStringArrayParam","getNumberParam","getNumericArrayParam","getBoolParam","getBoolArrayParam","getTensorShapeParam","getTensorShapeArrayParam","getDtypeParam","getDtypeArrayParam","getFuncParam","functionDef","nodeDef","inputArg","parseDtypeParam","returnNodeMap","outputArg","mapArgsToSignature","mapArgToTensorInfo","_instance","parseStringParam","keepCase","decodeBase64","DT_FLOAT","DT_INT32","DT_INT64","DT_INT8","DT_UINT8","DT_BOOL","DT_DOUBLE","DT_STRING","parseTensorShapeParam","unknownRank","complex_","logicalAnd_","split_","stack_","kernelRegistry","gradRegistry","getKernel","makeKey","getGradient","getKernelsForBackend","registerKernel","registerGradient","expandDims_","SvgIcon","_props$color","_props$component","_props$fontSize","fontSize","htmlColor","titleAccess","_props$viewBox","viewBox","clsx","root","focusable","role","muiName","userSelect","display","flexShrink","typography","pxToRem","transition","transitions","duration","shorter","colorPrimary","palette","primary","main","colorSecondary","secondary","colorAction","action","active","colorError","colorDisabled","disabled","fontSizeInherit","fontSizeSmall","fontSizeLarge","createSvgIcon","conv2d_","greaterEqual_","clone_","sigmoid_","max_","deepMap","mapFn","deepMapInternal","containedIn","isIterable","mappedIterable","childResult","deepZip","zipToList","deepZipInternal","deepMapAndAwaitAll","mappedValue","isView","canTensorify","isAbsolute","spliceOne","resolvePathname","hasTrailingSlash","toParts","fromParts","isToAbs","isFromAbs","mustEndAbs","last","up","part","valueOf","valueEqual","aValue","bValue","stripLeadingSlash","hasBasename","stripTrailingSlash","hash","currentLocation","hashIndex","searchIndex","parsePath","decodeURI","URIError","createTransitionManager","prompt","listeners","setPrompt","nextPrompt","confirmTransitionTo","getUserConfirmation","appendListener","isActive","listener","notifyListeners","_len","_key","canUseDOM","getConfirmation","confirm","PopStateEvent","HashChangeEvent","getHistoryState","createBrowserHistory","globalHistory","canUseHistory","ua","userAgent","supportsHistory","needsHashChangeListener","_props","_props$forceRefresh","forceRefresh","_props$getUserConfirm","_props$keyLength","keyLength","getDOMLocation","historyState","_ref","_window$location","createKey","transitionManager","setState","handlePopState","isExtraneousPopstateEvent","handlePop","handleHashChange","forceNextPop","fromLocation","toLocation","toIndex","allKeys","fromIndex","go","revertPop","initialLocation","createHref","listenerCount","checkDOMListeners","removeEventListener","isBlocked","pushState","prevIndex","nextKeys","replaceState","goBack","goForward","block","unblock","listen","HashChangeEvent$1","HashPathCoders","hashbang","encodePath","decodePath","noslash","slash","stripHash","getHashPath","replaceHashPath","createHashHistory","_props$hashType","hashType","_HashPathCoders$hashT","ignorePath","encodedPath","allPaths","baseTag","querySelector","getAttribute","pushHashPath","nextPaths","lowerBound","upperBound","createMemoryHistory","_props$initialEntries","initialEntries","_props$initialIndex","initialIndex","nextEntries","canGo","log_","binaryInsert","comparator","middle","compareResult","binarySearch_","defaultComparator","binarySearch","insertionPoint","nonMaxSuppressionImpl_","returnScoresTensor","returnValidOutputs","candidates","score","boxIndex","suppressBeginIndex","ascendingComparator","candidate","originalScore","ignoreCandidate","iou","intersectionOverUnion","suppressWeight","elemsToPad","iCoord","jCoord","yminI","xminI","ymaxI","xmaxI","yminJ","xminJ","ymaxJ","xmaxJ","areaI","areaJ","intersectionYmin","intersectionXmin","intersectionYmax","intersectionXmax","intersectionArea","c1","c2","relu_","step_","unstack_","batchNorm_","xAs4D","tile_","useThemeWithoutDefault","alea","xor128","xorwow","xorshift7","xor4096","tychei","sr","DataType","SaverDef","CheckpointFormatVersion","warning","mean_","debounce","timeout","wait","debounced","that","later","clearTimeout","Rank","UpcastInt32AndMap","UpcastBoolAndMap","UpcastFloat32AndMap","UpcastComplex64AndMap","upcastTypeMap","typeA","typeB","sumOutType","batchToSpaceND_","depthwiseConv2d_","equal_","gather_","logicalNot_","maximum_","spaceToBatchND_","squeeze_","_unsupportedIterableToArray","minLen","test","broadcastTo_","MPRandGauss","stdDeviation","truncated","nextVal","upper","lower","seedValue","resultX","resultY","isValid","isValidTruncated","convertValue","RandGamma","randu","randn","v0","UniformRandom","canReturnFloat","merge","deepmerge","createBreakpoints","breakpoints","_breakpoints$values","sm","md","lg","xl","_breakpoints$unit","unit","_breakpoints$step","between","endIndex","down","upperbound","only","createMixins","spacing","mixins","_toolbar","gutters","styles","paddingLeft","paddingRight","toolbar","minHeight","common","black","white","grey","50","100","200","300","400","500","600","700","800","900","A100","A200","A400","A700","indigo","pink","red","orange","blue","green","light","hint","divider","paper","hover","hoverOpacity","selected","selectedOpacity","disabledBackground","disabledOpacity","focus","focusOpacity","activatedOpacity","dark","icon","addLightOrDark","intent","direction","shade","tonalOffset","tonalOffsetLight","tonalOffsetDark","createPalette","_palette$primary","_palette$secondary","_palette$error","_palette$warning","_palette$info","_palette$success","_palette$type","_palette$contrastThre","contrastThreshold","_palette$tonalOffset","getContrastText","augmentColor","mainShade","lightShade","darkShade","contrastText","types","caseAllCaps","textTransform","defaultFontFamily","createTypography","_ref$fontFamily","fontFamily","_ref$fontSize","_ref$fontWeightLight","fontWeightLight","_ref$fontWeightRegula","fontWeightRegular","_ref$fontWeightMedium","fontWeightMedium","_ref$fontWeightBold","fontWeightBold","_ref$htmlFontSize","htmlFontSize","allVariants","pxToRem2","coef","buildVariant","fontWeight","lineHeight","letterSpacing","casing","variants","h1","h2","h3","h4","h5","h6","subtitle1","subtitle2","body1","body2","button","caption","overline","createShadow","shadows","borderRadius","createSpacing","spacingInput","mui","createUnarySpacing","argument","easing","easeInOut","easeOut","easeIn","sharp","shortest","short","standard","enteringScreen","leavingScreen","formatMs","milliseconds","_options$duration","durationOption","_options$easing","easingOption","_options$delay","delay","animatedProp","getAutoHeightDuration","constant","createMuiTheme","_options$breakpoints","breakpointsInput","_options$mixins","mixinsInput","_options$palette","paletteInput","_options$typography","typographyInput","muiTheme","overrides","zIndex","CUSTOM_OPS","getRegisteredOp","min_","real_","ifft_","globalNameSpace","getGlobalNamespace","process","getGlobal","globalMap","_tfGlobals","getGlobalMap","singleton","webpackPolyfill","deprecate","__webpack_amd_options__","validateUpdateShape","shapeError","validateInput","totalNd","safeSliceDim","maskToAxes","stridesWithElidedDims","ellipsisInsertionIndex","numElidedAxes","newStrides","unnormalizeAxis","normalizedAxis","getElidedAxes","elidedAxes","getNormalizedAxes","ellipsisAxes","numInterpolatedAxes","normalizedBegin","normalizedEnd","normalizedStrides","fullIndex","startIndicesWithElidedDims","stopIndicesWithElidedDims","startForAxis","stopForAxis","stridesForAxis","originalBegin","originalAxis","originalValue","originalEnd","MAX_SAFE_INTEGER","axisSize","startIndices","stopIndices","firstNonOneAxis","$end","expandAxes","shrinkAxes","avgPool_","cos_","cumsum_","floorDiv_","elu_","floor_","imag_","leakyRelu_","less_","logSumExp_","xMax","logicalOr_","maxPool_","minimum_","notEqual_","prelu_","relu6_","fft_","rfft_","adjustedInput","zerosShape","zerosInput","complexInput","realComplexConjugate","imagComplexConjugate","squaredDifference_","unsortedSegmentSum_","normImpl","norm_","_setPrototypeOf","conv2DBackpropInput","conv2DBackpropInput_","xShape4D","testEpsilon","expectNumbersClose","areClose","conv2DBackpropFilter","conv2DBackpropFilter_","reactIs","REACT_STATICS","childContextTypes","contextType","contextTypes","getDefaultProps","getDerivedStateFromError","getDerivedStateFromProps","propTypes","KNOWN_STATICS","caller","callee","arity","MEMO_STATICS","compare","TYPE_STATICS","getStatics","isMemo","ForwardRef","Memo","getOwnPropertyNames","objectPrototype","targetComponent","sourceComponent","blacklist","inheritedComponent","targetStatics","sourceStatics","ownerWindow","defaultView","isMuiElement","muiNames","ListContext","debugValue","vendor","propIsEnumerable","toObject","test1","test2","test3","letter","shouldUseNative","symbols","DataStorage","dataMover","dataIdsCount","moveData","KernelBackend","notYetImplemented","tanh_","HashRouter","createHistory","resolveToLocation","normalizeToLocation","forwardRefShim","C","LinkAnchor","navigate","onClick","isModifiedEvent","forwardedRef","Link","ariaCurrent","activeClassName","activeStyle","classNameProp","isActiveProp","locationProp","styleProp","style","escapedPath","classnames","joinClassnames","_arrayLikeToArray","arr2","DTYPE_VALUE_SIZE_MAP","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","currentQueue","draining","queueIndex","cleanUpNextTick","drainQueue","run","runClearTimeout","Item","nextTick","title","browser","argv","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","binding","cwd","chdir","umask","nav","opera","WorkerGlobalScope","all_","any_","argMax_","argMin_","atan2_","bincount_","conv1d_","x3D","reshapedTo3D","filter4D","conv2dDataFormat","conv2dTranspose_","cosh_","depthToSpace_","dilation2d_","divNoNan_","divResult","bEqualsZero","dot_","t1","t2","$t1","$t2","t1Inner","t2Inner","t12D","t22D","t1t2","localResponseNormalization_","log1p_","softplus_","logicalXor_","mirrorPad_","shapeOffset","mod_","oneHot_","pool_","basePadding","padExtraShape","padExtraStart","padExtraEnd","withSpaceToBatchBasePaddings","isDilationOne","padStart","origPadEnd","fullInputShape","padEndExtra","requiredSpaceToBatchPaddings","adjustedPadding","adjustedCrops","convertedPad","convertedX","prod_","randomUniform","randomUniform_","round_","rsqrt_","selu_","separableConv2d_","$depthwiseFilter","$pointwiseFilter","channelMultiplier","pointwiseStride","sin_","sinh_","irfft_","realInput","imagInput","realConjugate","imagConjugate","topk_","unique_","whereAsync","condShape","inBuffer","_arrayWithHoles","_nonIterableRest","_iterableToArray","_isNativeReflectConstruct","sham","Proxy","conv3DBackpropInput","conv3DBackpropInput_","xShape5D","resizeNearestNeighbor_","$images","batchImages","_toArray","resizeBilinear_","depthwiseConv2dNativeBackpropInput","depthwiseConv2dNativeBackpropInput_","depthwiseConv2dNativeBackpropFilter","depthwiseConv2dNativeBackpropFilter_","ATTRIBUTE_NAMES","TAG_NAMES","BASE","BODY","HEAD","HTML","LINK","META","NOSCRIPT","SCRIPT","STYLE","TITLE","TAG_PROPERTIES","REACT_TAG_MAP","accesskey","charset","class","contenteditable","contextmenu","itemprop","tabindex","HELMET_PROPS","HTML_TAG_MAP","SELF_CLOSING_TAGS","HELMET_ATTRIBUTE","classCallCheck","createClass","defineProperties","objectWithoutProperties","possibleConstructorReturn","encodeSpecialCharacters","getTitleFromPropsList","propsList","innermostTitle","getInnermostProperty","innermostTemplate","innermostDefaultTitle","getOnChangeClientState","getAttributesFromPropsList","tagType","tagAttrs","getBaseTagFromPropsList","primaryAttributes","innermostBaseTag","tag","lowerCaseAttributeKey","getTagsFromPropsList","tagName","approvedSeenTags","approvedTags","instanceTags","instanceSeenTags","primaryAttributeKey","attributeKey","tagUnion","objectAssign","rafPolyfill","clock","currentTime","cafPolyfill","requestAnimationFrame","webkitRequestAnimationFrame","mozRequestAnimationFrame","cancelAnimationFrame","webkitCancelAnimationFrame","mozCancelAnimationFrame","_helmetCallback","commitTagChanges","newState","cb","bodyAttributes","htmlAttributes","linkTags","metaTags","noscriptTags","onChangeClientState","scriptTags","styleTags","titleAttributes","updateAttributes","updateTitle","tagUpdates","updateTags","addedTags","removedTags","_tagUpdates$tagType","newTags","oldTags","flattenArray","possibleArray","attributes","elementTag","getElementsByTagName","helmetAttributeString","helmetAttributes","attributesToRemove","attributeKeys","setAttribute","indexToSave","removeAttribute","tags","headElement","head","tagNodes","querySelectorAll","indexToDelete","newElement","innerHTML","styleSheet","cssText","appendChild","createTextNode","existingTag","isEqualNode","parentNode","removeChild","generateElementAttributesAsString","convertElementAttributestoReactProps","initProps","getMethodsForTag","toComponent","_initProps","generateTitleAsReactComponent","attributeString","flattenedTitle","generateTitleAsString","_mappedTag","mappedTag","mappedAttribute","content","dangerouslySetInnerHTML","__html","generateTagsAsReactComponent","attributeHtml","tagContent","isSelfClosing","generateTagsAsString","mapStateOnServer","_ref$title","link","meta","noscript","script","HelmetExport","_class","_temp","_React$Component","HelmetWrapper","inherits","shouldComponentUpdate","nextProps","isEqual","mapNestedChildrenToProps","nestedChildren","flattenArrayTypeChildren","_babelHelpers$extends","arrayTypeChildren","newChildProps","mapObjectTypeChildren","_ref2","_babelHelpers$extends2","_babelHelpers$extends3","newProps","mapArrayTypeChildrenToProps","newFlattenedProps","arrayChildName","_babelHelpers$extends4","warnOnInvalidChildren","mapChildrenToProps","_this2","Children","_child$props","initAttributes","convertReactPropstoHtmlAttributes","PropTypes","oneOfType","arrayOf","defaultTitle","titleTemplate","peek","rewind","mappedState","Helmet","withSideEffect","renderStatic","defaultBreakpoints","handleBreakpoints","propValue","styleFromPropValue","themeBreakpoints","_themeBreakpoints","breakpoint","mobileStepper","speedDial","appBar","drawer","modal","snackbar","tooltip","base64","ieee754","kMaxLength","TYPED_ARRAY_SUPPORT","encodingOrOffset","allocUnsafe","fromArrayLike","fromArrayBuffer","isEncoding","actual","isBuffer","checked","copy","fromObject","assertSize","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","bidirectionalIndexOf","arrayIndexOf","indexSize","arrLength","valLength","readUInt16BE","foundIndex","hexWrite","remaining","strLen","parsed","utf8Write","blitBuffer","asciiWrite","byteArray","asciiToBytes","latin1Write","base64Write","ucs2Write","hi","lo","utf16leToBytes","fromByteArray","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","MAX_ARGUMENTS_LENGTH","decodeCodePointsArray","SlowBuffer","alloc","INSPECT_MAX_BYTES","foo","typedArraySupport","_augment","species","allocUnsafeSlow","_isBuffer","swap16","swap32","swap64","equals","inspect","thisStart","thisEnd","thisCopy","targetCopy","toHex","checkOffset","checkInt","objectWriteUInt16","littleEndian","objectWriteUInt32","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","sliceLen","readUIntLE","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeUInt32LE","writeUInt32BE","writeIntLE","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","code","INVALID_BASE64_RE","leadSurrogate","toByteArray","stringtrim","base64clean","dst","wasm","WebAssembly","Module","low","high","unsigned","isLong","__isLong__","INT_CACHE","UINT_CACHE","fromInt","cachedObj","fromBits","ZERO","TWO_PWR_64_DBL","MAX_UNSIGNED_VALUE","TWO_PWR_63_DBL","MIN_VALUE","TWO_PWR_32_DBL","lowBits","highBits","pow_dbl","radix","radixToPower","power","fromValue","TWO_PWR_16_DBL","TWO_PWR_24","ONE","UONE","NEG_ONE","LongPrototype","toNumber","isZero","isNegative","eq","radixLong","rem1","rem","remDiv","digits","getHighBits","getHighBitsUnsigned","getLowBits","getNumBitsAbs","bit","eqz","isOdd","notEquals","neq","ne","lessThan","comp","lt","lessThanOrEqual","lte","le","greaterThan","gt","greaterThanOrEqual","gte","ge","thisNeg","otherNeg","negate","not","addend","a48","a32","a16","a00","b48","b32","b16","c48","c32","c16","c00","subtract","subtrahend","multiply","get_high","b00","divide","approx","div_u","div_s","toUnsigned","shr","LN2","approxRes","approxRem","rem_u","rem_s","shiftLeft","numBits","shiftRight","shiftRightUnsigned","shr_u","toSigned","toBytes","toBytesLE","toBytesBE","fromBytesLE","fromBytesBE","hasOwn","classNames","argType","inner","MAX_SIGNED_31_BIT_INT","commonjsGlobal","globalThis","createEventEmitter","changedBits","calculateChangedBits","_Provider$childContex","_Consumer$contextType","contextProp","getUniqueId","Provider","_Component","_this","emitter","_proto","getChildContext","componentWillReceiveProps","oldValue","isRequired","Consumer","_Component2","observedBits","_proto2","isarray","tokensToFunction","tokensToRegExp","PATH_REGEXP","defaultDelimiter","escaped","capture","modifier","asterisk","partial","optional","escapeGroup","escapeString","encodeURIComponentPretty","encodeURI","matches","opts","encodeURIComponent","segment","attachKeys","route","endsWithDelimiter","groups","regexpToRegexp","arrayToRegexp","stringToRegexp","acos_","acosh_","addN","addN_","firstTensor","asin_","asinh_","atan_","atanh_","avgPool3d","avgPool3d_","ceil_","clipByValue_","conv3d","conv3d_","denseBincount","denseBincount_","einsum","einsum_","erf_","expm1_","isFinite_","isInf_","isNaN_","linspace","logSigmoid_","logSoftmax_","shifted","maxPool3d","maxPool3d_","maxPoolWithArgmax","maxPoolWithArgmax_","multinomial","multinomial_","origRank","logits2D","onesLike_","reciprocal_","yVals","ySet","setdiff1dAsync","sign_","softmax_","stridedSlice_","tan_","truncatedNormal","truncatedNormal_","scatterND","scatterND_","$updates","gatherND","gatherND_","delayCallback","setImmediate","nextFrame","defaultValues","numElems","sparseToDense","sparseToDense_","$sparseIndices","$sparseValues","ByteChunkIterator","Utf8Iterator","impl","Utf8IteratorImpl","decoder","StringDecoder","chunkResult","StringIterator","SplitIterator","SplitIteratorImpl","carryover","React__default","reducePropsToState","handleStateChangeOnClient","WrappedComponent","mountedInstances","emitChange","SideEffect","_PureComponent","recordedState","UNSAFE_componentWillMount","PureComponent","getDisplayName","hasElementType","Element","hasMap","hasSet","hasArrayBuffer","$$typeof","formatMuiErrorMessage","hadKeyboardEvent","hadFocusVisibleRecently","hadFocusVisibleRecentlyTimeout","inputTypesWhitelist","tel","email","password","number","date","month","week","datetime","handleKeyDown","metaKey","altKey","ctrlKey","handlePointerDown","handleVisibilityChange","visibilityState","isFocusVisible","readOnly","isContentEditable","focusTriggersKeyboardModality","handleBlurVisible","useIsFocusVisible","onBlurVisible","doc","ReactDOM","getChildMapping","isValidElement","getProp","prop","getNextChildMapping","prevChildMapping","onExited","nextChildMapping","getValueForKey","nextKeysPending","pendingKeys","prevKey","childMapping","nextKey","pendingNextKey","mergeChildMappings","hasPrev","hasNext","prevChild","isLeaving","in","cloneElement","exit","enter","TransitionGroup","handleExited","contextValue","isMounting","firstRender","mounted","appear","currentChildMapping","_this$props","childFactory","TransitionGroupContext","Ripple","_props$pulsate","pulsate","rippleX","rippleY","rippleSize","inProp","_props$onExited","_React$useState","leaving","setLeaving","rippleClassName","ripple","rippleVisible","ripplePulsate","rippleStyles","childClassName","childLeaving","childPulsate","timeoutId","TouchRipple","_props$center","centerProp","ripples","setRipples","rippleCallback","ignoringMouseDown","startTimerCommit","startCommit","oldRipples","_options$pulsate","_options$center","_options$fakeElement","fakeElement","rect","getBoundingClientRect","clientX","clientY","touches","sizeX","clientWidth","sizeY","clientHeight","persist","overflow","pointerEvents","position","opacity","animation","animationDuration","backgroundColor","flip","ButtonBase","buttonRefProp","buttonRef","_props$centerRipple","centerRipple","_props$disabled","_props$disableRipple","disableRipple","_props$disableTouchRi","disableTouchRipple","_props$focusRipple","focusRipple","focusVisibleClassName","onBlur","onFocus","onFocusVisible","onKeyDown","onKeyUp","onMouseDown","onMouseLeave","onMouseUp","onTouchEnd","onTouchMove","onTouchStart","onDragLeave","_props$tabIndex","tabIndex","TouchRippleProps","_props$type","rippleRef","focusVisible","setFocusVisible","_useIsFocusVisible","focusVisibleRef","useRippleHandler","rippleAction","eventCallback","skipRippleAction","handleMouseDown","handleDragLeave","handleMouseUp","handleMouseLeave","handleTouchStart","handleTouchEnd","handleTouchMove","handleBlur","handleFocus","currentTarget","isNonNativeButton","keydownRef","handleKeyUp","defaultPrevented","ComponentProp","buttonProps","handleUserRef","handleOwnRef","handleRef","_React$useState2","mountedState","setMountedState","enableTouchRipple","alignItems","justifyContent","WebkitTapHighlightColor","outline","border","margin","cursor","verticalAlign","textDecoration","borderStyle","colorAdjust","Fragment","StrictMode","Profiler","Suspense","for","A","isMounted","enqueueForceUpdate","enqueueReplaceState","enqueueSetState","B","refs","updater","D","E","isReactComponent","forceUpdate","isPureReactComponent","G","H","I","__self","__source","J","_owner","L","escape","O","K","P","Q","_status","_result","R","S","T","ReactCurrentDispatcher","ReactCurrentBatchConfig","ReactCurrentOwner","IsSomeRendererActing","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","_calculateChangedBits","_currentValue","_currentValue2","_threadCount","_context","createFactory","createRef","lazy","_payload","_init","useCallback","useDebugValue","useEffect","useImperativeHandle","useLayoutEffect","useMemo","useReducer","useRef","useState","aa","ba","ca","da","ea","fa","ha","ia","ja","ka","acceptsBooleans","attributeName","attributeNamespace","mustUseProperty","propertyName","sanitizeURL","removeEmptyString","oa","pa","qa","ma","na","la","setAttributeNS","xlinkHref","ra","sa","ta","wa","xa","ya","za","Aa","Ba","Ca","Da","Ea","Fa","Ga","Ha","Ia","Ja","Ma","Ka","La","Na","Oa","Pa","prepareStackTrace","Qa","_render","Ra","Sa","Ta","Va","_valueTracker","setValue","stopTracking","Ua","Wa","Xa","activeElement","Ya","defaultChecked","_wrapperState","initialChecked","Za","controlled","ab","bb","eb","fb","defaultSelected","gb","hb","ib","jb","textContent","kb","lb","nb","ob","namespaceURI","firstChild","MSApp","execUnsafeLocalFunction","pb","lastChild","nodeType","nodeValue","qb","animationIterationCount","borderImageOutset","borderImageSlice","borderImageWidth","boxFlex","boxFlexGroup","boxOrdinalGroup","columnCount","flex","flexGrow","flexPositive","flexNegative","flexOrder","gridArea","gridRow","gridRowEnd","gridRowSpan","gridRowStart","gridColumn","gridColumnEnd","gridColumnSpan","gridColumnStart","lineClamp","order","orphans","tabSize","widows","zoom","fillOpacity","floodOpacity","stopOpacity","strokeDasharray","strokeDashoffset","strokeMiterlimit","strokeOpacity","strokeWidth","rb","sb","tb","setProperty","ub","menuitem","area","br","embed","hr","keygen","wbr","vb","wb","is","xb","srcElement","correspondingUseElement","yb","zb","Ab","Bb","Cb","stateNode","Db","Eb","Fb","Gb","Hb","Ib","Jb","Kb","Lb","Mb","Ob","Pb","Qb","Rb","onError","Sb","Tb","Ub","Vb","Wb","Xb","Zb","alternate","return","memoizedState","dehydrated","ac","cc","sibling","bc","dc","ec","fc","gc","hc","ic","jc","kc","lc","mc","nc","oc","pc","qc","rc","blockedOn","domEventName","eventSystemFlags","nativeEvent","targetContainers","sc","pointerId","tc","vc","wc","lanePriority","unstable_runWithPriority","hydrate","containerInfo","xc","yc","zc","Ac","Bc","unstable_scheduleCallback","unstable_NormalPriority","Cc","Dc","Ec","animationend","animationiteration","animationstart","transitionend","Fc","Gc","Hc","Ic","Jc","Kc","Lc","Mc","Nc","Oc","Pc","Qc","unstable_now","Rc","Uc","pendingLanes","expiredLanes","suspendedLanes","pingedLanes","Vc","entangledLanes","entanglements","Wc","Xc","Yc","Zc","eventTimes","clz32","bd","cd","dd","unstable_UserBlockingPriority","ed","fd","gd","hd","uc","jd","kd","ld","nd","od","keyCode","charCode","pd","qd","rd","_reactName","_targetInst","isDefaultPrevented","isPropagationStopped","stopPropagation","cancelBubble","isPersistent","wd","xd","yd","eventPhase","bubbles","cancelable","timeStamp","isTrusted","td","ud","view","detail","vd","Ad","screenX","screenY","pageX","pageY","shiftKey","getModifierState","zd","buttons","relatedTarget","fromElement","toElement","movementX","movementY","Bd","Dd","dataTransfer","Fd","Hd","animationName","elapsedTime","pseudoElement","Jd","clipboardData","Ld","Md","Esc","Spacebar","Left","Up","Right","Down","Del","Win","Menu","Apps","Scroll","MozPrintableKey","Nd","8","9","12","13","16","17","18","19","20","27","32","33","34","35","36","37","38","39","40","45","46","112","113","114","115","116","117","118","119","120","121","122","123","144","145","224","Od","Alt","Control","Meta","Shift","Pd","Rd","locale","which","Td","pressure","tangentialPressure","tiltX","tiltY","twist","pointerType","isPrimary","Vd","targetTouches","changedTouches","Xd","Zd","deltaX","wheelDeltaX","deltaY","wheelDeltaY","wheelDelta","deltaZ","deltaMode","$d","ae","be","documentMode","ce","de","ee","fe","he","ie","me","oe","pe","qe","se","te","ue","ve","we","xe","ye","ze","oninput","Ae","detachEvent","Be","Ce","attachEvent","De","Ee","Fe","He","Ie","Je","Ke","Le","nextSibling","Me","contains","compareDocumentPosition","Ne","HTMLIFrameElement","contentWindow","Oe","contentEditable","Pe","Qe","Re","Se","Te","Ue","selectionStart","selectionEnd","anchorNode","getSelection","anchorOffset","focusNode","focusOffset","Ve","We","Xe","Ye","Ze","Yb","$e","af","bf","cf","df","passive","Nb","ef","ff","parentWindow","gf","hf","je","char","ke","jf","kf","lf","mf","autoFocus","nf","of","pf","qf","rf","sf","previousSibling","tf","vf","wf","xf","yf","zf","Af","Bf","Cf","Df","Ef","__reactInternalMemoizedUnmaskedChildContext","__reactInternalMemoizedMaskedChildContext","Ff","Gf","Hf","If","Jf","__reactInternalMemoizedMergedChildContext","Kf","Lf","Mf","Nf","Of","Pf","unstable_cancelCallback","Qf","unstable_shouldYield","Rf","unstable_requestPaint","Sf","Tf","unstable_getCurrentPriorityLevel","Uf","unstable_ImmediatePriority","Vf","Wf","Xf","unstable_LowPriority","Yf","unstable_IdlePriority","Zf","$f","ag","bg","cg","dg","eg","fg","gg","hg","ig","jg","kg","mg","ng","og","pg","qg","rg","sg","childLanes","tg","dependencies","firstContext","lanes","ug","vg","responders","wg","xg","updateQueue","baseState","firstBaseUpdate","lastBaseUpdate","shared","pending","effects","yg","zg","eventTime","lane","payload","Ag","Bg","Cg","Dg","Eg","Fg","Gg","Kg","_reactInternals","Hg","Ig","Jg","Lg","Mg","Ng","UNSAFE_componentWillReceiveProps","Og","getSnapshotBeforeUpdate","componentWillMount","Pg","Qg","_stringRef","Rg","Sg","lastEffect","nextEffect","firstEffect","Tg","Ug","elementType","Vg","Wg","Xg","Yg","Zg","ah","bh","ch","dh","eh","documentElement","fh","gh","ih","memoizedProps","revealOrder","jh","kh","lh","mh","nh","oh","pendingProps","ph","qh","rh","sh","th","uh","_workInProgressVersionPrimary","vh","wh","xh","yh","zh","Ah","Bh","Ch","Dh","Eh","Fh","Gh","Hh","baseQueue","Ih","Jh","Kh","lastRenderedReducer","eagerReducer","eagerState","lastRenderedState","dispatch","Lh","Mh","_getVersion","_source","mutableReadLanes","Nh","U","getSnapshot","subscribe","setSnapshot","Oh","Ph","Qh","Rh","destroy","deps","Sh","Th","Uh","Vh","Wh","Xh","Yh","Zh","ai","bi","ci","di","readContext","useDeferredValue","useTransition","useMutableSource","useOpaqueIdentifier","unstable_isNewReconciler","uf","ei","fi","gi","ii","ji","ki","li","mi","baseLanes","ni","oi","pi","UNSAFE_componentWillUpdate","componentWillUpdate","qi","ri","pendingContext","Bi","Di","Ei","si","retryLane","ti","fallback","unstable_avoidThisFallback","ui","unstable_expectedLoadTime","vi","wi","yi","zi","isBackwards","rendering","renderingStartTime","tail","tailMode","Ai","Fi","Gi","wasMultiple","multiple","onclick","createElementNS","V","Hi","Ii","W","Ji","Ki","Li","Mi","Ni","Oi","Pi","Qi","Ri","Si","componentDidCatch","Ti","componentStack","Ui","Vi","Wi","Xi","__reactInternalSnapshotBeforeUpdate","Yi","Zi","$i","aj","bj","onCommitFiberUnmount","cj","dj","ej","fj","gj","hj","insertBefore","_reactRootContainer","jj","kj","lj","mj","nj","oj","pj","X","Y","qj","rj","sj","tj","uj","vj","wj","ck","Z","xj","yj","zj","Aj","Bj","Cj","Dj","Ej","Fj","Gj","Hj","Ij","Jj","Sc","Kj","Lj","Mj","callbackNode","expirationTimes","callbackPriority","Tc","Nj","Oj","Pj","Qj","Rj","Sj","Tj","finishedWork","finishedLanes","Uj","timeoutHandle","Wj","Xj","pingCache","Yj","Zj","va","ak","bk","dk","rangeCount","focusedElem","selectionRange","ek","extend","createRange","setStart","removeAllRanges","addRange","setEnd","scrollLeft","scrollTop","onCommitFiberRoot","fk","gk","ik","pendingChildren","jk","mutableSourceEagerHydrationData","kk","lk","mk","nk","qk","hydrationOptions","mutableSources","_internalRoot","rk","tk","hasAttribute","sk","uk","hk","unstable_observedBits","unmount","form","Vj","vk","Events","wk","findFiberByHostInstance","bundleType","rendererPackageName","xk","rendererConfig","overrideHookState","overrideHookStateDeletePath","overrideHookStateRenamePath","overrideProps","overridePropsDeletePath","overridePropsRenamePath","setSuspenseHandler","scheduleUpdate","currentDispatcherRef","findHostInstanceByFiber","findHostInstancesForRefresh","scheduleRefresh","scheduleRoot","setRefreshHandler","getCurrentFiber","yk","isDisabled","supportsFiber","inject","createPortal","findDOMNode","flushSync","unmountComponentAtNode","unstable_batchedUpdates","unstable_createPortal","unstable_renderSubtreeIntoContainer","MessageChannel","unstable_forceFrameRate","port2","port1","onmessage","postMessage","sortIndex","startTime","expirationTime","priorityLevel","unstable_Profiling","unstable_continueExecution","unstable_getFirstCallbackNode","unstable_next","unstable_pauseExecution","unstable_wrapCallback","runtime","Op","$Symbol","iteratorSymbol","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","innerFn","outerFn","tryLocsList","protoGenerator","Generator","Context","_invoke","GenStateSuspendedStart","GenStateExecuting","GenStateCompleted","doneResult","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","GenStateSuspendedYield","makeInvokeMethod","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","getProto","NativeIteratorPrototype","Gp","defineIteratorMethods","AsyncIterator","PromiseImpl","invoke","__await","unwrapped","previousPromise","callInvokeWithMethodAndArg","resultName","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","iteratorMethod","isGeneratorFunction","genFun","mark","awrap","async","skipTempReset","rootRecord","rval","exception","caught","hasCatch","hasFinally","finallyEntry","complete","thrown","delegateYield","regeneratorRuntime","accidentalStrictMode","b64","lens","getLens","validLen","placeHoldersLen","Arr","_byteLength","curByte","revLookup","uint8","extraBytes","maxChunkLength","len2","encodeChunk","lookup","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","rt","systemFetch","getNodeFetch","PlatformNode","hrtime","Alea","mash","Mash","s0","prng","double","quick","XorGen","strseed","math","nodecrypto","startdenom","significance","shortseed","mixkey","entropy","tostring","randomBytes","crypto","msCrypto","getRandomValues","plugins","autoseed","arc4","ARC4","pass","is_math_call","keylen","typ","smear","stringseed","scope","Timeout","clearFn","_id","_clearFn","unref","enroll","msecs","_idleTimeoutId","_idleTimeout","unenroll","_unrefActive","_onTimeout","clearImmediate","registerImmediate","nextHandle","tasksByHandle","currentlyRunningATask","attachTo","runIfPresent","importScripts","postMessageIsAsynchronous","oldOnMessage","canUsePostMessage","messagePrefix","onGlobalMessage","installPostMessageImplementation","installMessageChannelImplementation","html","onreadystatechange","installReadyStateChangeImplementation","task","ReactPropTypesSecret","emptyFunction","emptyFunctionWithReset","resetWarningCache","shim","propName","componentName","propFullName","secret","getShim","ReactPropTypes","symbol","instanceOf","objectOf","oneOf","checkPropTypes","jsx","jsxs","AsyncMode","ConcurrentMode","ContextConsumer","ContextProvider","Lazy","Portal","isAsyncMode","isConcurrentMode","isContextConsumer","isContextProvider","isElement","isForwardRef","isFragment","isLazy","isPortal","isProfiler","isStrictMode","isSuspense","isValidElementType","typeOf","isPlainObject","Paper","_props$square","_props$elevation","elevation","_props$variant","variant","outlined","rounded","elevations","shadow","boxShadow","plainObjectConstrurctor","cloneStyle","newStyle","createRule","decl","jss","declCopy","rule","onCreateRule","by","toCssValue","ignoreImportant","cssValue","indentStr","indent","toCss","selector","_options$indent","fallbacks","_prop","_value","_prop2","_value2","allowEmpty","escapeRegex","nativeEscape","CSS","BaseStyleRule","isProcessed","renderer","renderable","sheet","Renderer","onChangeValue","isDefined","removeProperty","attached","StyleRule","_BaseStyleRule","selectorText","scoped","generateId","applyTo","setSelector","replaceRule","pluginStyleRule","defaultToStringOptions","atRegExp","ConditionalRule","at","rules","atMatch","RuleList","getRule","addRule","onProcessRule","keyRegExp","pluginConditionalRule","defaultToStringOptions$1","nameRegExp","KeyframesRule","frames","nameMatch","keyRegExp$1","refRegExp","findReferencedKeyframe","keyframes","replaceRef","refKeyframe","plugin","onProcessStyle","KeyframeRule","pluginKeyframeRule","FontFaceRule","keyRegExp$2","pluginFontFaceRule","ViewportRule","pluginViewportRule","SimpleRule","keysMap","defaultUpdateOptions","forceUpdateOptions","raw","ruleOptions","_this$options","unregister","updateOne","_this$options2","styleRule","_nextValue","_prevValue","css","StyleSheet","deployed","attach","deploy","detach","insertRule","addRules","deleteRule","_this$rules","PluginsRegistry","internal","external","onProcessSheet","processedValue","use","newPlugin","SheetsRegistry","globalThis$1","moduleId","createGenerateId","ruleCounter","jssId","minify","memoize","getPropertyValue","cssRule","attributeStyleMap","getHead","findPrevNode","registry$1","findHigherSheet","findHighestSheet","comment","childNodes","findCommentNode","getNonce","_insertRule","appendRule","cssRules","getValidRuleInsertionIndex","DomRenderer","hasInsertedRules","media","el","createStyle","nonce","nextNode","insertionPointElement","insertStyle","Boolean","insertRules","nativeParent","latestNativeParent","_insertionIndex","refCssRule","ruleStr","insertionIndex","nativeRule","getRules","instanceCounter","Jss","isInBrowser","createStyleSheet","removeStyleSheet","getDynamicStyles","extracted","hasCSSTOMSupport","multiKeyStore","key1","key2","subCache","hasSymbol","pseudoClasses","fnValuesNs","fnRuleNs","functionPlugin","fnValues","fnRule","atPrefix","GlobalContainerRule","GlobalPrefixedRule","separatorRegExp","addScope","jssGlobal","handleNestedGlobalContainerRule","handlePrefixedGlobalRule","parentRegExp","jssNested","getReplaceRef","replaceParentRefs","nestedProp","parentProp","parentSelectors","nestedSelectors","nested","getOptions","prevOptions","nestingLevel","isNested","isNestedConditional","uppercasePattern","msPattern","toHyphenLower","hyphenateStyleName","hName","convertCase","converted","hyphenate","camelCase","hyphenatedProp","px","percent","addCamelCasedVersion","regExp","newObj","inset","motion","perspective","gap","grid","iterate","innerProp","_innerProp","defaultUnit","camelCasedOptions","js","isTouch","jsCssMap","Moz","Webkit","appearence","noPrefill","supportedProperty","toUpper","camelize","pascalize","longhand","textOrientation","writingMode","breakPropsOld","inlineLogicalOld","newProp","unprefixed","prefixed","pascalized","scrollSnap","overscrollBehavior","propMap","flex2012","propMap$1","propKeys","prefixCss","propertyDetectors","computed","getComputedStyle","key$1","el$1","cache$1","transitionProperties","transPropsRegExp","prefixTransitionCallback","p2","prefixedValue","supportedValue","jssVendorPrefixer","prefixStyle","changeProp","supportedProp","changeValue","supportedValue$1","atRule","jssPropsSort","prop0","prop1","jssPreset","vendorPrefixer","propsSort","defaultOptions","disableGeneration","generateClassName","_options$disableGloba","disableGlobal","_options$productionPr","productionPrefix","_options$seed","seedPrefix","getNextCounterId","createGenerateClassName","sheetsCache","sheetsManager","sheetsRegistry","StylesContext","indexCounter","increment","getStylesCreator","themingEnabled","stylesWithOverrides","noopTheme","getClasses","cacheClasses","lastProp","lastJSS","generate","mergeClasses","baseClasses","newClasses","stylesCreator","sheetManager","staticSheet","dynamicStyles","serverGenerateClassName","dynamicSheet","_ref3","_ref4","useSynchronousEffect","currentKey","classNamePrefixOption","_options$defaultTheme","stylesOptions2","shouldUpdate","ThemeContext","nextClasses","defaultVariantMapping","Typography","_props$align","align","_props$display","_props$gutterBottom","gutterBottom","_props$noWrap","noWrap","_props$paragraph","paragraph","_props$variantMapping","variantMapping","srOnly","alignLeft","textAlign","alignCenter","alignRight","alignJustify","textOverflow","whiteSpace","marginBottom","colorInherit","colorTextPrimary","colorTextSecondary","displayInline","displayBlock","LinearProgress","valueBuffer","rootProps","inlineStyles","bar1","bar2","_transform","determinate","indeterminate","dashed","bar","bar1Indeterminate","bar1Determinate","bar1Buffer","bar2Indeterminate","bar2Buffer","getColor","backgroundPrimary","backgroundSecondary","marginTop","dashedColorPrimary","backgroundImage","backgroundSize","backgroundPosition","dashedColorSecondary","transformOrigin","barColorPrimary","barColorSecondary","Button","_props$disableElevati","disableElevation","_props$disableFocusRi","disableFocusRipple","endIconProp","endIcon","_props$fullWidth","fullWidth","_props$size","startIconProp","startIcon","boxSizing","minWidth","textPrimary","textSecondary","outlinedPrimary","outlinedSecondary","contained","containedPrimary","containedSecondary","borderColor","textSizeSmall","textSizeLarge","outlinedSizeSmall","outlinedSizeLarge","containedSizeSmall","containedSizeLarge","sizeSmall","sizeLarge","marginRight","marginLeft","iconSizeSmall","iconSizeMedium","iconSizeLarge","makeStylesWithoutDefault","WebkitFontSmoothing","MozOsxFontSmoothing","_props$children","AppBar","_props$position","backgroundColorDefault","flexDirection","positionFixed","positionAbsolute","positionSticky","positionStatic","positionRelative","colorDefault","colorTransparent","Toolbar","_props$disableGutters","disableGutters","regular","dense","Tab","indicator","onChange","selectionFollowsFocus","_props$textColor","textColor","_props$wrapped","wrapped","labelIcon","wrapper","_extends2","maxWidth","paddingTop","textColorInherit","textColorPrimary","textColorSecondary","flexBasis","formControlState","muiFormControl","FormControlContext","getStyleValue","computedStyle","visibility","TextareaAutosize","rowsMax","_props$rowsMin","rowsMin","rowsMinProp","isControlled","inputRef","shadowRef","renders","syncHeight","inputShallow","placeholder","innerHeight","scrollHeight","singleRowHeight","outerHeight","outerHeightStyle","prevState","handleResize","hasValue","isFilled","SSR","InputBase","ariaDescribedby","autoComplete","endAdornment","_props$inputComponent","inputComponent","_props$inputProps","inputProps","inputPropsProp","inputRefProp","_props$multiline","multiline","renderSuffix","startAdornment","valueProp","handleInputRefWarning","handleInputPropsRefProp","handleInputRefProp","handleInputRef","focused","setFocused","fcs","onFilled","onEmpty","checkDirty","InputComponent","setAdornedStart","formControl","adornedStart","adornedEnd","marginDense","onAnimationStart","inputMultiline","hiddenLabel","inputHiddenLabel","inputAdornedStart","inputAdornedEnd","inputTypeSearch","inputMarginDense","placeholderHidden","placeholderVisible","font","disableUnderline","underline","bottomLineColor","borderBottomColor","borderBottom","borderBottomStyle","FilledInput","borderTopLeftRadius","borderTopRightRadius","paddingBottom","WebkitBoxShadow","WebkitTextFillColor","caretColor","NotchedOutline","labelWidthProp","labelWidth","notched","legendLabelled","legendNotched","legend","borderWidth","OutlinedInput","_props$labelWidth","notchedOutline","filled","useFormControl","FormLabel","InputLabel","_props$disableAnimati","disableAnimation","shrinkProp","shrink","animated","FormControl","_props$error","visuallyFocused","_props$hiddenLabel","_props$margin","_props$required","initialAdornedStart","initialFilled","setFilled","_React$useState3","_focused","childContext","registerEffect","marginNormal","FormHelperText","createChainedFunction","funcs","_len2","_key2","_props$disablePortal","disablePortal","onRendered","mountNode","setMountNode","getContainer","getScrollbarSize","scrollDiv","scrollbarSize","offsetWidth","ariaHidden","show","getPaddingRight","ariaHiddenSiblings","currentNode","nodesToExclude","blacklistTagNames","findIndexOf","handleContainer","fixedNodes","restoreStyle","restorePaddings","disableScrollLock","innerWidth","isOverflowing","parentElement","scrollContainer","ModalManager","modals","containers","modalIndex","modalRef","hiddenSiblingNodes","hiddenSiblings","getHiddenSiblings","containerIndex","restore","nextTop","Unstable_TrapFocus","_props$disableAutoFoc","disableAutoFocus","_props$disableEnforce","disableEnforceFocus","_props$disableRestore","disableRestoreFocus","getDoc","isEnabled","ignoreNextEnforceFocus","sentinelStart","sentinelEnd","nodeToRestore","rootRef","prevOpenRef","contain","hasFocus","loopFocus","interval","invisible","SimpleBackdrop","_props$invisible","defaultManager","Modal","inProps","_props$BackdropCompon","BackdropComponent","BackdropProps","_props$closeAfterTran","closeAfterTransition","_props$disableBackdro","disableBackdropClick","_props$disableEscapeK","disableEscapeKeyDown","_props$disableScrollL","_props$hideBackdrop","hideBackdrop","_props$keepMounted","keepMounted","_props$manager","onBackdropClick","onClose","onEscapeKeyDown","exited","setExited","mountNodeRef","hasTransition","getHasTransition","getModal","handleMounted","mount","handleOpen","resolvedContainer","isTopModal","handlePortalRef","handleClose","inlineStyle","hidden","childProps","onEnter","TrapFocus","UNMOUNTED","EXITED","ENTERING","ENTERED","EXITING","Transition","initialStatus","appearStatus","unmountOnExit","mountOnEnter","nextCallback","updateStatus","nextStatus","cancelNextCallback","getTimeouts","mounting","performEnter","performExit","appearing","nodeRef","maybeNode","maybeAppearing","timeouts","enterTimeout","safeSetState","onEntered","onEntering","onTransitionEnd","_this3","onExit","onExiting","cancel","setNextCallback","_this4","doesNotHaveTimeoutOrListener","addEndListener","maybeNextCallback","getTransitionProps","_props$style","transitionDuration","transitionDelay","getScale","entering","entered","Grow","_props$disableStrictM","disableStrictModeCompat","_props$timeout","_props$TransitionComp","TransitionComponent","autoTimeout","enableStrictModeCompat","unstable_strictMode","foreignRef","normalizedTransitionCallback","nodeOrAppearing","isAppearing","handleEntering","handleEnter","reflow","_getTransitionProps","handleEntered","handleExiting","handleExit","_getTransitionProps2","nodeOrNext","maybeNext","muiSupportAuto","getOffsetTop","vertical","getOffsetLeft","horizontal","getTransformOriginValue","getAnchorEl","anchorEl","Popover","_props$anchorOrigin","anchorOrigin","anchorPosition","_props$anchorReferenc","anchorReference","containerProp","getContentAnchorEl","_props$marginThreshol","marginThreshold","_props$PaperProps","PaperProps","_props$transformOrigi","_props$transitionDura","transitionDurationProp","_props$TransitionProp","TransitionProps","paperRef","getAnchorOffset","contentAnchorOffset","resolvedAnchorEl","anchorRect","anchorVertical","getContentAnchorOffset","contentAnchorEl","getScrollParent","offsetTop","getTransformOrigin","elemRect","getPositioningStyle","offsetHeight","elemTransformOrigin","containerWindow","heightThreshold","widthThreshold","_diff","_diff2","_diff3","setPositioningStyles","positioning","handlePaperRef","updatePosition","overflowY","overflowX","maxHeight","List","_props$dense","_props$disablePadding","disablePadding","subheader","listStyle","nextItem","disableListWrap","nextElementSibling","previousItem","previousElementSibling","textCriteriaMatches","nextFocus","textCriteria","innerText","repeating","moveFocus","currentFocus","disabledItemsFocusable","traversalFunction","wrappedOnce","nextFocusDisabled","MenuList","actions","_props$autoFocus","_props$autoFocusItem","autoFocusItem","_props$disabledItemsF","_props$disableListWra","listRef","textCriteriaRef","previousKeyMatched","adjustStyleForScrollbar","containerElement","noExplicitWidth","activeItemIndex","criteria","lowerKey","currTime","keepFocusOnCurrent","RTL_ORIGIN","LTR_ORIGIN","disableAutoFocusItem","_props$MenuListProps","MenuListProps","PopoverClasses","menuListActionsRef","contentAnchorRef","WebkitOverflowScrolling","areEqualValues","SelectInput","ariaLabel","autoWidth","displayEmpty","IconComponent","labelId","_props$MenuProps","MenuProps","onOpen","openProp","renderValue","_props$SelectDisplayP","SelectDisplayProps","tabIndexProp","_useControlled","defaultProp","valueState","useControlled","_useControlled2","displayNode","setDisplayNode","isOpenControlled","menuMinWidthState","setMenuMinWidthState","openState","setOpenState","getElementById","isCollapsed","displaySingle","childrenArray","handleItemClick","itemIndex","displayMultiple","computeDisplay","menuMinWidth","buttonId","select","selectMenu","nativeInput","iconOpen","NativeSelectInput","iconFilled","iconOutlined","defaultInput","NativeSelect","_props$IconComponent","ArrowDropDownIcon","_props$input","nativeSelectStyles","_props$autoWidth","_props$displayEmpty","_props$multiple","_props$native","native","variantProps","variantComponent","TextField","FormHelperTextProps","helperText","InputLabelProps","InputProps","_props$select","SelectProps","InputMore","_InputLabelProps$requ","displayRequired","helperTextId","inputLabelId","InputElement","htmlFor","styleFunction","newStyleFunction","omit","filterProps","compose","getPath","_options$cssProperty","cssProperty","themeKey","themeMapping","propValueFinal","getBorder","borders","flexbox","sizing","styled","componentCreator","StyledComponent","spread","FinalComponent","styledWithoutDefault","Box","cachedType","detectScrollType","dummy","getNormalizedScrollLeft","scrollWidth","easeInOutSin","ScrollbarSize","scrollbarHeight","setMeasurements","prevHeight","TabIndicator","orientation","KeyboardArrowLeft","KeyboardArrowRight","TabScrollButton","Tabs","ariaLabelledBy","_props$centered","childrenProp","_props$indicatorColor","indicatorColor","_props$orientation","_props$ScrollButtonCo","ScrollButtonComponent","_props$scrollButtons","scrollButtons","_props$TabIndicatorPr","TabIndicatorProps","TabScrollButtonProps","scrollable","isRtl","scrollStart","clientSize","setMounted","indicatorStyle","setIndicatorStyle","displayScroll","setDisplayScroll","_React$useState4","scrollerStyle","setScrollerStyle","valueToIndex","tabsRef","tabListRef","getTabsMeta","tabsMeta","tabMeta","tabsNode","scrollLeftNormalized","_children","tab","updateIndicatorState","_newIndicatorStyle","_getTabsMeta","startValue","correction","newIndicatorStyle","dStart","dSize","scroll","scrollValue","_options$ease","ease","cancelled","timestamp","animate","moveTabsScroll","handleStartScrollClick","handleEndScrollClick","handleScrollbarSizeChange","scrollSelectedIntoView","_getTabsMeta2","nextScrollStart","_nextScrollStart","updateScrollButtonState","showStartScroll","showEndScroll","_tabsRef$current","win","handleTabsScroll","updateIndicator","updateScrollButtons","childIndex","childValue","conditionalElements","scrollbarSizeListener","scrollButtonsActive","showScrollButtons","scrollButtonStart","scrollButtonsDesktop","scrollButtonEnd","getConditionalElements","scroller","fixed","onScroll","flexContainer","flexContainerVertical","newFocusTarget","previousItemKey","nextItemKey","scrollbarWidth","ListItem","_props$alignItems","_props$button","componentProp","_props$ContainerCompo","ContainerComponent","_props$ContainerProps","ContainerProps","ContainerClassName","_props$divider","_props$selected","listItemRef","hasSecondaryAction","componentProps","alignItemsFlexStart","secondaryAction","backgroundClip","MenuItem","ListItemClasses","_props$role","isDeleteKeyboardEvent","keyboardEvent","Chip","avatarProp","avatar","clickableProp","clickable","deleteIconProp","deleteIcon","iconProp","onDelete","chipRef","handleDeleteIconClick","small","moreProps","customClasses","deleteIconSmall","CancelIcon","avatarSmall","iconSmall","deletable","blur","labelSmall","deleteIconColor","clickableColorPrimary","clickableColorSecondary","deletableColorPrimary","deletableColorSecondary","avatarColorPrimary","avatarColorSecondary","iconColorPrimary","iconColorSecondary","deleteIconColorPrimary","deleteIconColorSecondary","deleteIconOutlinedColorPrimary","deleteIconOutlinedColorSecondary","Avatar","imgProps","srcSet","loaded","setLoaded","Image","useLoaded","hasImg","hasImgNotFailing","Person","system","circle","circular","objectFit","textIndent","properties","directions","aliases","marginX","marginY","paddingX","paddingY","getCssProperties","_prop$split","_prop$split2","spacingKeys","themeSpacing","getStyleFromPropValue","cssProperties","transformer","transformed"],"mappings":";0mgBAsBa,EAAb,WAOE,iCACEA,KAAKC,YAAc,GACnBD,KAAKE,YAAc,GATvB,oDAYU,WAIN,OAHiC,MAA7BC,EAAiBC,WACnBD,EAAiBC,SAAW,IAAID,GAE3BA,EAAiBC,WAhB5B,gCAyBE,SAA0BC,GACxBF,EAAiBG,cAAcL,YAAYM,KAAKF,KA1BpD,gCAmCE,SAA0BG,GACxBL,EAAiBG,cAAcJ,YAAYK,KAAKC,KApCpD,6BA+CE,SAAuBC,GACrB,OAAON,EAAiBO,YAAYD,EAAK,UAhD7C,6BA2DE,SAAuBA,EAAsBE,GAE3C,OAAOR,EAAiBO,YAAYD,EAAK,OAAQE,KA7DrD,yBAgEU,SACJF,EAAsBG,EACtBD,GACF,IAAME,EAA6B,GAUnC,OATgC,SAAhBD,EACZT,EAAiBG,cAAcJ,YAC/BC,EAAiBG,cAAcL,aAC3Ba,SAAQ,SAAAC,GACd,IAAMC,EAAUD,EAAON,EAAKE,GACZ,OAAZK,GACFH,EAAcN,KAAKS,MAGhBH,MA7EX,KAiFaI,EAAqB,SAACC,GAAD,OAC9B,EAAiBD,mBAAmBC,IAC3BC,EAAqB,SAACD,GAAD,OAC9B,EAAiBC,mBAAmBD,IAC3BE,EAAkB,SAACX,GAAD,OAC3B,EAAiBW,gBAAgBX,IACxBY,EACT,SAACZ,EAAsBE,GAAvB,OACI,EAAiBU,gBAAgBZ,EAAKE,ICtFxCW,EAAgB,eAMhBC,EAAmB,eAInBC,EAAkB,mBAexB,SAASC,IACP,IAAK,cAAMC,QAAQ,cAIjB,MAAM,IAAIC,M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EAAS,YAAUA,IAChDsrD,EAAW,aAAOrpD,EAAGopD,GACvBE,EAAa,YAAavrD,EAAS,OAAAhI,EAAA,GAAO,EAAG,UAC3CwzD,EAAWF,EAASv1D,KAAOw1D,EAAWx1D,KACnC1Q,EAAI,EAAGA,EAAImmE,IAAYnmE,EAC9BkmE,EAAa,aAAWA,EAAYlmE,EAAI,GAE1CkmE,EAAa,YAAWA,EAAY,aAAKD,EAASz8D,MAAO,SACzD,IAAM48D,EAAY,YAAUH,GAC5B,OAAO,YAAMC,EAAYD,EAAUG,GAnBxBC,CAAoB5uC,EAAIyzB,OC8LrC,IC7MO,IAAMob,GAAkC,CAC7C51C,WAAY,KACZ8K,SAAU,SAAC/D,GACT,MAAO,CAAC7a,EAAG,kBAAM,YAAU6a,O,SD0M/B,QA3GkC,CAChCiiC,EACAC,EACAC,EACAC,EACAE,EACAE,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAO,EACAK,EACAC,EACAC,EACAC,EACAG,EACAC,EACAC,EACAG,GACAC,GACAI,GACAD,GACAO,GACAC,GACAC,GACAE,GACAI,GACAE,GACAgG,GACA7F,GACAC,GACAC,GACAC,GACAC,GACAE,GACAD,GACAE,GACAc,GACAoB,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAK,GACAM,GACAA,GACAG,GACAM,GACAG,GACAC,GACAK,GACAE,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAC,GACAA,GACAC,GACAG,GACAE,GACAC,GACAC,GACAC,GACAC,GACAE,GACAC,GACAC,GACAC,GACAC,GACAC,GACAI,GACAC,GACAC,GACAC,GACAE,GACAG,GACAE,GACAC,GACAA,GACAC,GACAA,GACAC,GACAE,GACAD,GACAG,GACAC,GACAC,GACAE,GACAC,GACAC,GACAE,GACAE,GACAC,GACAO,IAGF,kBAA0C,CAArC,IAAMC,GAAc,OACvB,aAAiBA,I,sBExMnB,eAAuBjmC,UAAU7pB,IAAM,WAErC,OADA/e,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ACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACAC,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,kBAA0C,CAArC,IAAM,GAAY,OACrB,aAAe,IE9UjB,ICEYC,GAqCAC,GAOAC,GD9CNjoB,GAAmD,GAEnDkoB,GAA2C,CAC/C1sF,OAAO,EACP2sF,WAAW,EACXC,oBAAoB,EACpBC,uBAAuB,EACvB9wH,OAAO,EACP+wH,SAAS,EACTC,8BAA8B,GAY1B,SAAUC,GAAgBC,GAC9B,KAAMA,KAAgBzoB,IAAW,CAC/B,IAAM0oB,EAqCV,SAAkCD,GAChC,GAAqB,IAAjBA,GAAuC,IAAjBA,EACxB,MAAM,IAAIxoI,MAAM,0DAElB,IAAMkW,EAdR,SAAsBsyH,GACpB,GAA+B,qBAApBE,iBAAoD,IAAjBF,EAC5C,OAAO,IAAIE,gBAAgB,IAAK,KAC3B,GAAwB,qBAAbl+H,SAChB,OAAOA,SAASa,cAAc,UAE9B,MAAM,IAAIrL,MAAM,0CAQH2oI,CAAaH,GAM5B,GAJAtyH,EAAO0yH,iBAAiB,oBAAoB,SAACC,GAC3CA,EAAGC,wBACI/oB,GAASyoB,MACf,GACkB,IAAjBA,EACF,OAAQtyH,EAAOhB,WAAW,QAAS+yH,KAC3B/xH,EAAOhB,WAAW,qBA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QE,EAvCR,yDA0C6BF,EA1C7B,0BA2CsC,IAA5BC,EA3CV,qbA4DQC,EA5DR,gCA6D6C,IAA5BD,EA7DjB,2bA4EQC,EA5ER,gCA6E6C,IAA5BD,EA7EjB,sfA4FQC,EA5FR,0CA3BoB,WA2BpB,sBzG0RJ,IC5OO,ID4OP,QApKsC,CACpCgP,GACAC,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA9J,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACAmC,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACAqD,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACAsC,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACAc,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACAyB,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,GCvOoD,CACpDlvI,WAAY,KACZ7hB,YAAa,QACbupB,WArFI,SAA6BwI,GAKjC,IAAO9xB,EAA0B8xB,EAA1B9xB,OAAQyE,EAAkBqtB,EAAlBrtB,QAASxE,EAAS6xB,EAAT7xB,MACjB6N,EAAiB9N,EAAjB8N,EAAGsuC,EAAcp8C,EAAdo8C,WACHlrC,EAAejR,EAAfiR,Y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,OAAOD,KAAK8hC,GAAO/5B,KAAI,SAAUukN,GAGtC,IAAmC,IAA/Bg5E,EAAYhjS,QAAQgqN,GACtB,OAAO,KAGT,IACIta,EAAqBwzF,EADLL,EAAiB74E,GACyBo5E,GAC1D3zF,EAAYjwK,EAAMwqL,GACtB,OAAOxa,YAAkBhwK,EAAOiwK,EAAWC,MAC1C7lM,OAAO+8K,IAAO,IAGnBkB,EAAQ6P,UAGC,GACT7P,EAAQyuG,YAAcyM,EACPl7G","file":"static/js/2.e1845539.chunk.js","sourcesContent":["/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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/**\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 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 {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","/** @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 {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\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 */\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 */\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react.production.min.js');\n} else {\n module.exports = require('./cjs/react.development.js');\n}\n","module.exports = require(\"regenerator-runtime\");\n","import arrayWithHoles from \"@babel/runtime/helpers/esm/arrayWithHoles\";\nimport iterableToArrayLimit from \"@babel/runtime/helpers/esm/iterableToArrayLimit\";\nimport unsupportedIterableToArray from \"@babel/runtime/helpers/esm/unsupportedIterableToArray\";\nimport nonIterableRest from \"@babel/runtime/helpers/esm/nonIterableRest\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}","export default function _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a 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 */\nimport {ENGINE} from '../engine';\nimport {isPromise} from '../util';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op<T extends Function>(f: {[name: string]: T}): T {\n const keys = Object.keys(f);\n if (keys.length !== 1) {\n throw new Error(\n `Please provide an object with a single key ` +\n `(operation name) mapping to a function. Got an object with ` +\n `${keys.length} keys.`);\n }\n\n let opName = keys[0];\n const fn = f[opName];\n\n // Strip the underscore from the end of the function name.\n if (opName.endsWith('_')) {\n opName = opName.substring(0, opName.length - 1);\n }\n\n // add an __op suffix to distinguish ops from kernels in tf.profile\n opName = opName + OP_SCOPE_SUFFIX;\n\n // tslint:disable-next-line:no-any\n const f2 = (...args: any[]) => {\n ENGINE.startScope(opName);\n try {\n const result = fn(...args);\n if (isPromise(result)) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n ENGINE.endScope(result);\n return result;\n } catch (ex) {\n ENGINE.endScope(null);\n throw ex;\n }\n };\n Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n // tslint:disable-next-line:no-any\n return f2 as any as T;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}","function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\n\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\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","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nexport default function _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function _typeof(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}","import _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport assertThisInitialized from \"@babel/runtime/helpers/esm/assertThisInitialized\";\nexport default function _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n }\n\n return assertThisInitialized(self);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nimport possibleConstructorReturn from \"@babel/runtime/helpers/esm/possibleConstructorReturn\";\nexport default function _createSuper(Derived) {\n var hasNativeReflectConstruct = isNativeReflectConstruct();\n return function _createSuperInternal() {\n var Super = getPrototypeOf(Derived),\n result;\n\n if (hasNativeReflectConstruct) {\n var NewTarget = getPrototypeOf(this).constructor;\n result = Reflect.construct(Super, arguments, NewTarget);\n } else {\n result = Super.apply(this, arguments);\n }\n\n return possibleConstructorReturn(this, 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 {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 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Workaround for allowing cjs module to be included in bundle created by\n// rollup.\nimport * as LongExports from 'long';\n// tslint:disable-next-line\nconst Long: LongExports.LongConstructor =\n // tslint:disable-next-line\n (LongExports as any).default || LongExports;\n\nexport function hexToLong(hex: string): Long {\n return Long.fromString(hex, true, 16);\n}\n\n// Some primes between 2^63 and 2^64 for various uses.\n// Hex 0xc3a5c85c97cb3127\nconst k0: Long = hexToLong('c3a5c85c97cb3127');\n// Hex 0xb492b66fbe98f273\nconst k1: Long = hexToLong('b492b66fbe98f273');\n// Hex 0x9ae16a3b2f90404f\nconst k2: Long = hexToLong('9ae16a3b2f90404f');\n\nfunction shiftMix(val: Long): Long {\n return val.xor(val.shru(47));\n}\n\nfunction fetch(s: Uint8Array, offset: number, numBytes: number): Long {\n const bytes = s.slice(offset, offset + numBytes);\n return Long.fromBytes(Array.from(bytes), true, true);\n}\n\nfunction fetch64(s: Uint8Array, offset: number): Long {\n return fetch(s, offset, 8);\n}\n\nfunction fetch32(s: Uint8Array, offset: number): Long {\n return fetch(s, offset, 4);\n}\n\nfunction rotate64(val: Long, shift: number): Long {\n // Avoid shifting by 64: doing so yields an undefined result.\n return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift));\n}\n\nfunction hashLen16(u: Long, v: Long, mul = hexToLong('9ddfea08eb382d69')) {\n // Murmur-inspired hashing.\n let a = u.xor(v).mul(mul);\n a = a.xor(a.shru(47));\n let b = v.xor(a).mul(mul);\n b = b.xor(b.shru(47));\n b = b.mul(mul);\n return b;\n}\n\n// Return a 16-byte hash for 48 bytes. Quick and dirty.\n// Callers do best to use \"random-looking\" values for a and b.\nfunction weakHashLen32WithSeeds(\n w: Long, x: Long, y: Long, z: Long, a: Long, b: Long) {\n a = a.add(w);\n b = rotate64(b.add(a).add(z), 21);\n const c = a;\n a = a.add(x);\n a = a.add(y);\n b = b.add(rotate64(a, 44));\n return [a.add(z), b.add(c)];\n}\n\nfunction weakHashLen32WithSeedsStr(\n s: Uint8Array, offset: number, a: Long, b: Long) {\n return weakHashLen32WithSeeds(\n fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16),\n fetch64(s, offset + 24), a, b);\n}\n\nfunction hashLen0to16(s: Uint8Array, len = s.length): Long {\n if (len >= 8) {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).add(k2);\n const b = fetch64(s, len - 8);\n const c = rotate64(b, 37).mul(mul).add(a);\n const d = rotate64(a, 25).add(b).mul(mul);\n return hashLen16(c, d, mul);\n }\n if (len >= 4) {\n const mul = k2.add(len * 2);\n const a = fetch32(s, 0);\n return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul);\n }\n if (len > 0) {\n const a = s[0];\n const b = s[len >> 1];\n const c = s[len - 1];\n const y = a + (b << 8);\n const z = len + (c << 2);\n return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2);\n }\n return k2;\n}\n\nfunction hashLen17to32(s: Uint8Array, len = s.length): Long {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).mul(k1);\n const b = fetch64(s, 8);\n const c = fetch64(s, len - 8).mul(mul);\n const d = fetch64(s, len - 16).mul(k2);\n return hashLen16(\n rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d),\n a.add(rotate64(b.add(k2), 18)).add(c), mul);\n}\n\nfunction hashLen33to64(s: Uint8Array, len = s.length): Long {\n const mul = k2.add(len * 2);\n const a = fetch64(s, 0).mul(k2);\n const b = fetch64(s, 8);\n const c = fetch64(s, len - 8).mul(mul);\n const d = fetch64(s, len - 16).mul(k2);\n const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d);\n const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul);\n const e = fetch64(s, 16).mul(mul);\n const f = fetch64(s, 24);\n const g = y.add(fetch64(s, len - 32)).mul(mul);\n const h = z.add(fetch64(s, len - 24)).mul(mul);\n return hashLen16(\n rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h),\n e.add(rotate64(f.add(a), 18)).add(g), mul);\n}\n\nexport function fingerPrint64(s: Uint8Array, len = s.length): Long {\n const seed: Long = Long.fromNumber(81, true);\n if (len <= 32) {\n if (len <= 16) {\n return hashLen0to16(s, len);\n } else {\n return hashLen17to32(s, len);\n }\n } else if (len <= 64) {\n return hashLen33to64(s, len);\n }\n\n // For strings over 64 bytes we loop. Internal state consists of\n // 56 bytes: v, w, x, y, and z.\n let x = seed;\n let y = seed.mul(k1).add(113);\n\n let z = shiftMix(y.mul(k2).add(113)).mul(k2);\n let v = [Long.UZERO, Long.UZERO];\n let w = [Long.UZERO, Long.UZERO];\n x = x.mul(k2).add(fetch64(s, 0));\n\n let offset = 0;\n // Set end so that after the loop we have 1 to 64 bytes left to process.\n const end = ((len - 1) >> 6) * 64;\n const last64 = end + ((len - 1) & 63) - 63;\n\n do {\n x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1);\n y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1);\n x = x.xor(w[1]);\n y = y.add(v[0]).add(fetch64(s, offset + 40));\n z = rotate64(z.add(w[0]), 33).mul(k1);\n v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0]));\n w = weakHashLen32WithSeedsStr(\n s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n [z, x] = [x, z];\n offset += 64;\n } while (offset !== end);\n const mul = k1.add(z.and(0xff).shl(1));\n // Point to the last 64 bytes of input.\n offset = last64;\n\n w[0] = w[0].add((len - 1) & 63);\n v[0] = v[0].add(w[0]);\n w[0] = w[0].add(v[0]);\n\n x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul);\n y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul);\n x = x.xor(w[1].mul(9));\n y = y.add(v[0].mul(9).add(fetch64(s, offset + 40)));\n z = rotate64(z.add(w[0]), 33).mul(mul);\n v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul), x.add(w[0]));\n w = weakHashLen32WithSeedsStr(\n s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16)));\n\n [z, x] = [x, z];\n\n return hashLen16(\n hashLen16(v[0], w[0], mul).add(shiftMix(y).mul(k0)).add(z),\n hashLen16(v[1], w[1], mul).add(x), mul);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {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","import unsupportedIterableToArray from \"@babel/runtime/helpers/esm/unsupportedIterableToArray\";\nexport default function _createForOfIteratorHelper(o, allowArrayLike) {\n var it;\n\n if (typeof Symbol === \"undefined\" || o[Symbol.iterator] == null) {\n if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n\n var F = function F() {};\n\n return {\n s: F,\n n: function n() {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n },\n e: function e(_e) {\n throw _e;\n },\n f: F\n };\n }\n\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n\n var normalCompletion = true,\n didErr = false,\n err;\n return {\n s: function s() {\n it = o[Symbol.iterator]();\n },\n n: function n() {\n var step = it.next();\n normalCompletion = step.done;\n return step;\n },\n e: function e(_e2) {\n didErr = true;\n err = _e2;\n },\n f: function f() {\n try {\n if (!normalCompletion && it[\"return\"] != null) it[\"return\"]();\n } finally {\n if (didErr) throw err;\n }\n }\n };\n}","import arrayWithoutHoles from \"@babel/runtime/helpers/esm/arrayWithoutHoles\";\nimport iterableToArray from \"@babel/runtime/helpers/esm/iterableToArray\";\nimport unsupportedIterableToArray from \"@babel/runtime/helpers/esm/unsupportedIterableToArray\";\nimport nonIterableSpread from \"@babel/runtime/helpers/esm/nonIterableSpread\";\nexport default function _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();\n}","import arrayLikeToArray from \"@babel/runtime/helpers/esm/arrayLikeToArray\";\nexport default function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return arrayLikeToArray(arr);\n}","export default function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.min.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.js\";\nexport default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\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","function toVal(mix) {\n\tvar k, y, str='';\n\n\tif (typeof mix === 'string' || typeof mix === 'number') {\n\t\tstr += mix;\n\t} else if (typeof mix === 'object') {\n\t\tif (Array.isArray(mix)) {\n\t\t\tfor (k=0; k < mix.length; k++) {\n\t\t\t\tif (mix[k]) {\n\t\t\t\t\tif (y = toVal(mix[k])) {\n\t\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\t\tstr += y;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (k in mix) {\n\t\t\t\tif (mix[k]) {\n\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\tstr += k;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn str;\n}\n\nexport default function () {\n\tvar i=0, tmp, x, str='';\n\twhile (i < arguments.length) {\n\t\tif (tmp = arguments[i++]) {\n\t\t\tif (x = toVal(tmp)) {\n\t\t\t\tstr && (str += ' ');\n\t\t\t\tstr += x\n\t\t\t}\n\t\t}\n\t}\n\treturn str;\n}\n","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","import superPropBase from \"@babel/runtime/helpers/esm/superPropBase\";\nexport default function _get(target, property, receiver) {\n if (typeof Reflect !== \"undefined\" && Reflect.get) {\n _get = Reflect.get;\n } else {\n _get = function _get(target, property, receiver) {\n var base = superPropBase(target, property);\n if (!base) return;\n var desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.get) {\n return desc.get.call(receiver);\n }\n\n return desc.value;\n };\n }\n\n return _get(target, property, receiver || target);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nexport default function _superPropBase(object, property) {\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = getPrototypeOf(object);\n if (object === null) break;\n }\n\n return object;\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport { chainPropTypes, getDisplayName } from '@material-ui/utils';\nimport makeStyles from '../makeStyles';\nimport getThemeProps from '../getThemeProps';\nimport useTheme from '../useTheme'; // Link a style sheet with a component.\n// It does not modify the component passed to it;\n// instead, it returns a new component, with a `classes` property.\n\nvar withStyles = function withStyles(stylesOrCreator) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return function (Component) {\n var defaultTheme = options.defaultTheme,\n _options$withTheme = options.withTheme,\n withTheme = _options$withTheme === void 0 ? false : _options$withTheme,\n name = options.name,\n stylesOptions = _objectWithoutProperties(options, [\"defaultTheme\", \"withTheme\", \"name\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n if (Component === undefined) {\n throw new Error(['You are calling withStyles(styles)(Component) with an undefined component.', 'You may have forgotten to import it.'].join('\\n'));\n }\n }\n\n var classNamePrefix = name;\n\n if (process.env.NODE_ENV !== 'production') {\n if (!name) {\n // Provide a better DX outside production.\n var displayName = getDisplayName(Component);\n\n if (displayName !== undefined) {\n classNamePrefix = displayName;\n }\n }\n }\n\n var useStyles = makeStyles(stylesOrCreator, _extends({\n defaultTheme: defaultTheme,\n Component: Component,\n name: name || Component.displayName,\n classNamePrefix: classNamePrefix\n }, stylesOptions));\n var WithStyles = /*#__PURE__*/React.forwardRef(function WithStyles(props, ref) {\n var classesProp = props.classes,\n innerRef = props.innerRef,\n other = _objectWithoutProperties(props, [\"classes\", \"innerRef\"]); // The wrapper receives only user supplied props, which could be a subset of\n // the actual props Component might receive due to merging with defaultProps.\n // So copying it here would give us the same result in the wrapper as well.\n\n\n var classes = useStyles(_extends({}, Component.defaultProps, props));\n var theme;\n var more = other;\n\n if (typeof name === 'string' || withTheme) {\n // name and withTheme are invariant in the outer scope\n // eslint-disable-next-line react-hooks/rules-of-hooks\n theme = useTheme() || defaultTheme;\n\n if (name) {\n more = getThemeProps({\n theme: theme,\n name: name,\n props: other\n });\n } // Provide the theme to the wrapped component.\n // So we don't have to use the `withTheme()` Higher-order Component.\n\n\n if (withTheme && !more.theme) {\n more.theme = theme;\n }\n }\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n ref: innerRef || ref,\n classes: classes\n }, more));\n });\n process.env.NODE_ENV !== \"production\" ? WithStyles.propTypes = {\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n\n /**\n * Use that prop to pass a ref to the decorated component.\n * @deprecated\n */\n innerRef: chainPropTypes(PropTypes.oneOfType([PropTypes.func, PropTypes.object]), function (props) {\n if (props.innerRef == null) {\n return null;\n }\n\n return null; // return new Error(\n // 'Material-UI: The `innerRef` prop is deprecated and will be removed in v5. ' +\n // 'Refs are now automatically forwarded to the inner component.',\n // );\n })\n } : void 0;\n\n if (process.env.NODE_ENV !== 'production') {\n WithStyles.displayName = \"WithStyles(\".concat(getDisplayName(Component), \")\");\n }\n\n hoistNonReactStatics(WithStyles, Component);\n\n if (process.env.NODE_ENV !== 'production') {\n // Exposed for test purposes.\n WithStyles.Naked = Component;\n WithStyles.options = options;\n WithStyles.useStyles = useStyles;\n }\n\n return WithStyles;\n };\n};\n\nexport default withStyles;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport { withStyles as withStylesWithoutDefault } from '@material-ui/styles';\nimport defaultTheme from './defaultTheme';\n\nfunction withStyles(stylesOrCreator, options) {\n return withStylesWithoutDefault(stylesOrCreator, _extends({\n defaultTheme: defaultTheme\n }, options));\n}\n\nexport default withStyles;","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 */\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 */\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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {matMul} from './mat_mul';\nimport {ones} from './ones';\nimport {reshape} from './reshape';\nimport {Tensor} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {sizeFromShape} from '../util_base';\n\n/**\n * Broadcasts parameters for evaluation on an N-D grid.\n *\n * Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`\n * of N-D coordinate arrays for evaluating expressions on an N-D grid.\n *\n * Notes:\n * `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.\n * When the `indexing` argument is set to 'xy' (the default), the broadcasting\n * instructions for the first two dimensions are swapped.\n * Examples:\n * Calling `const [X, Y] = meshgrid(x, y)` with the tensors\n *\n * ```javascript\n * const x = [1, 2, 3];\n * const y = [4, 5, 6];\n * const [X, Y] = tf.meshgrid(x, y);\n * // X = [[1, 2, 3],\n * // [1, 2, 3],\n * // [1, 2, 3]]\n * // Y = [[4, 4, 4],\n * // [5, 5, 5],\n * // [6, 6, 6]]\n * ```\n *\n * @param x Tensor with rank geq 1.\n * @param y Tensor with rank geq 1.\n * @param indexing\n *\n * @doc {heading: 'Operations', subheading: 'Slicing and Joining'}\n */\nexport function meshgrid<T extends Tensor>(\n x?: T|TensorLike, y?: T|TensorLike, {indexing = 'xy'} = {}): T[] {\n if (indexing !== 'xy' && indexing !== 'ij') {\n throw new TypeError(\n `${indexing} is not a valid third argument to meshgrid`);\n }\n if (x === undefined) {\n return [];\n }\n let $x = convertToTensor(\n x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');\n\n if (y === undefined) {\n return [$x];\n }\n let $y = convertToTensor(\n y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');\n\n const w = sizeFromShape($x.shape);\n const h = sizeFromShape($y.shape);\n\n if (indexing === 'xy') {\n $x = reshape($x, [1, -1]) as T;\n $y = reshape($y, [-1, 1]) as T;\n return [\n matMul(ones([h, 1], $x.dtype), $x),\n matMul($y, ones([1, w], $y.dtype)),\n ];\n }\n\n $x = reshape($x, [-1, 1]) as T;\n $y = reshape($y, [1, -1]) as T;\n return [\n matMul($x, ones([1, h], $x.dtype)),\n matMul(ones([w, 1], $y.dtype), $y),\n ];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 */\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 */\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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 {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 {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 {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\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 {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 {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 {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 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 {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 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 */\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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 */\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","import { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\n// It should to be noted that this function isn't equivalent to `text-transform: capitalize`.\n//\n// A strict capitalization should uppercase the first letter of each word a the sentence.\n// We only handle the first word.\nexport default function capitalize(string) {\n if (typeof string !== 'string') {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: capitalize(string) expects a string argument.\" : _formatMuiErrorMessage(7));\n }\n\n return string.charAt(0).toUpperCase() + string.slice(1);\n}","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {KernelBackend} from './backends/backend';\nimport {ENGINE, Engine, MemoryInfo, ProfileInfo, ScopeFn, TimingInfo} from './engine';\nimport {env} from './environment';\n\nimport {Platform} from './platforms/platform';\nimport {setDeprecationWarningFn, Tensor} from './tensor';\nimport {TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\n\n/**\n * Enables production mode which disables correctness checks in favor of\n * performance.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableProdMode(): void {\n env().set('PROD', true);\n}\n\n/**\n * Enables debug mode which will log information about all executed kernels:\n * the elapsed time of the kernel execution, as well as the rank, shape, and\n * size of the output tensor.\n *\n * Debug mode will significantly slow down your application as it will\n * download the result of every operation to the CPU. This should not be used in\n * production. Debug mode does not affect the timing information of the kernel\n * execution as we do not measure download time in the kernel execution time.\n *\n * See also: `tf.profile`, `tf.memory`.\n *\n * @doc {heading: 'Environment'}\n */\nexport function enableDebugMode(): void {\n env().set('DEBUG', true);\n}\n\n/** Globally disables deprecation warnings */\nexport function disableDeprecationWarnings(): void {\n env().set('DEPRECATION_WARNINGS_ENABLED', false);\n console.warn(`TensorFlow.js deprecation warnings have been disabled.`);\n}\n\n/** Warn users about deprecated functionality. */\nexport function deprecationWarn(msg: string) {\n if (env().getBool('DEPRECATION_WARNINGS_ENABLED')) {\n console.warn(\n msg + ' You can disable deprecation warnings with ' +\n 'tf.disableDeprecationWarnings().');\n }\n}\nsetDeprecationWarningFn(deprecationWarn);\n\n/**\n * Dispose all variables kept in backend engine.\n *\n * @doc {heading: 'Environment'}\n */\nexport function disposeVariables(): void {\n ENGINE.disposeVariables();\n}\n\n/**\n * It returns the global engine that keeps track of all tensors and backends.\n *\n * @doc {heading: 'Environment'}\n */\nexport function engine(): Engine {\n return ENGINE;\n}\n\n/**\n * Returns memory info at the current time in the program. The result is an\n * object with the following properties:\n *\n * - `numBytes`: Number of bytes allocated (undisposed) at this time.\n * - `numTensors`: Number of unique tensors allocated.\n * - `numDataBuffers`: Number of unique data buffers allocated\n * (undisposed) at this time, which is ≤ the number of tensors\n * (e.g. `a.reshape(newShape)` makes a new Tensor that shares the same\n * data buffer with `a`).\n * - `unreliable`: True if the memory usage is unreliable. See `reasons` when\n * `unreliable` is true.\n * - `reasons`: `string[]`, reasons why the memory is unreliable, present if\n * `unreliable` is true.\n *\n * WebGL Properties:\n * - `numBytesInGPU`: Number of bytes allocated (undisposed) in the GPU only at\n * this time.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function memory(): MemoryInfo {\n return ENGINE.memory();\n}\n\n/**\n * Executes the provided function `f()` and returns a promise that resolves\n * with information about the function's memory use:\n * - `newBytes`: the number of new bytes allocated\n * - `newTensors`: the number of new tensors created\n * - `peakBytes`: the peak number of bytes allocated\n * - `kernels`: an array of objects for each kernel involved that reports\n * their input and output shapes, number of bytes used, and number of new\n * tensors created.\n * - `kernelNames`: an array of unique strings with just the names of the\n * kernels in the `kernels` array.\n *\n * ```js\n * const profile = await tf.profile(() => {\n * const x = tf.tensor1d([1, 2, 3]);\n * let x2 = x.square();\n * x2.dispose();\n * x2 = x.square();\n * x2.dispose();\n * return x;\n * });\n *\n * console.log(`newBytes: ${profile.newBytes}`);\n * console.log(`newTensors: ${profile.newTensors}`);\n * console.log(`byte usage over all kernels: ${profile.kernels.map(k =>\n * k.totalBytesSnapshot)}`);\n * ```\n *\n *\n * @doc {heading: 'Performance', subheading: 'Profile'}\n */\nexport function profile(f: () => (TensorContainer | Promise<TensorContainer>)):\n Promise<ProfileInfo> {\n return ENGINE.profile(f);\n}\n\n/**\n * Executes the provided function `fn` and after it is executed, cleans up all\n * intermediate tensors allocated by `fn` except those returned by `fn`.\n * `fn` must not return a Promise (async functions not allowed). The returned\n * result can be a complex object.\n *\n * Using this method helps avoid memory leaks. In general, wrap calls to\n * operations in `tf.tidy` for automatic memory cleanup.\n *\n * NOTE: Variables do *not* get cleaned up when inside a tidy(). If you want to\n * dispose variables, please use `tf.disposeVariables` or call dispose()\n * directly on variables.\n *\n * ```js\n * // y = 2 ^ 2 + 1\n * const y = tf.tidy(() => {\n * // a, b, and one will be cleaned up when the tidy ends.\n * const one = tf.scalar(1);\n * const a = tf.scalar(2);\n * const b = a.square();\n *\n * console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n * // The value returned inside the tidy function will return\n * // through the tidy, in this case to the variable y.\n * return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * y.print();\n * ```\n *\n * @param nameOrFn The name of the closure, or the function to execute.\n * If a name is provided, the 2nd argument should be the function.\n * If debug mode is on, the timing and the memory usage of the function\n * will be tracked and displayed on the console using the provided name.\n * @param fn The function to execute.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function tidy<T extends TensorContainer>(\n nameOrFn: string|ScopeFn<T>, fn?: ScopeFn<T>): T {\n return ENGINE.tidy(nameOrFn, fn);\n}\n\n/**\n * Disposes any `tf.Tensor`s found within the provided object.\n *\n * @param container an object that may be a `tf.Tensor` or may directly\n * contain `tf.Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. If\n * the object is not a `tf.Tensor` or does not contain `Tensors`, nothing\n * happens. In general it is safe to pass any object here, except that\n * `Promise`s are not supported.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function dispose(container: TensorContainer) {\n const tensors = getTensorsInContainer(container);\n tensors.forEach(tensor => tensor.dispose());\n}\n\n/**\n * Keeps a `tf.Tensor` generated inside a `tf.tidy` from being disposed\n * automatically.\n *\n * ```js\n * let b;\n * const y = tf.tidy(() => {\n * const one = tf.scalar(1);\n * const a = tf.scalar(2);\n *\n * // b will not be cleaned up by the tidy. a and one will be cleaned up\n * // when the tidy ends.\n * b = tf.keep(a.square());\n *\n * console.log('numTensors (in tidy): ' + tf.memory().numTensors);\n *\n * // The value returned inside the tidy function will return\n * // through the tidy, in this case to the variable y.\n * return b.add(one);\n * });\n *\n * console.log('numTensors (outside tidy): ' + tf.memory().numTensors);\n * console.log('y:');\n * y.print();\n * console.log('b:');\n * b.print();\n * ```\n *\n * @param result The tensor to keep from being disposed.\n *\n * @doc {heading: 'Performance', subheading: 'Memory'}\n */\nexport function keep<T extends Tensor>(result: T): T {\n return ENGINE.keep(result);\n}\n\n/**\n * Executes `f()` and returns a promise that resolves with timing\n * information.\n *\n * The result is an object with the following properties:\n *\n * - `wallMs`: Wall execution time.\n * - `kernelMs`: Kernel execution time, ignoring data transfer. If using the\n * WebGL backend and the query timer extension is not available, this will\n * return an error object.\n * - On `WebGL` The following additional properties exist:\n * - `uploadWaitMs`: CPU blocking time on texture uploads.\n * - `downloadWaitMs`: CPU blocking time on texture downloads (readPixels).\n *\n * ```js\n * const x = tf.randomNormal([20, 20]);\n * const time = await tf.time(() => x.matMul(x));\n *\n * console.log(`kernelMs: ${time.kernelMs}, wallTimeMs: ${time.wallMs}`);\n * ```\n *\n * @param f The function to execute and time.\n *\n * @doc {heading: 'Performance', subheading: 'Timing'}\n */\nexport function time(f: () => void): Promise<TimingInfo> {\n return ENGINE.time(f);\n}\n\n/**\n * Sets the backend (cpu, webgl, wasm, etc) responsible for creating tensors and\n * executing operations on those tensors. Returns a promise that resolves\n * to a boolean if the backend initialization was successful.\n *\n * Note this disposes the current backend, if any, as well as any tensors\n * associated with it. A new backend is initialized, even if it is of the\n * same type as the previous one.\n *\n * @param backendName The name of the backend. Currently supports\n * `'webgl'|'cpu'` in the browser, `'tensorflow'` under node.js\n * (requires tfjs-node), and `'wasm'` (requires tfjs-backend-wasm).\n *\n * @doc {heading: 'Backends'}\n */\nexport function setBackend(backendName: string): Promise<boolean> {\n return ENGINE.setBackend(backendName);\n}\n\n/**\n * Returns a promise that resolves when the currently selected backend (or the\n * highest priority one) has initialized. Await this promise when you are using\n * a backend that has async initialization.\n *\n * @doc {heading: 'Backends'}\n */\nexport function ready(): Promise<void> {\n return ENGINE.ready();\n}\n\n/**\n * Returns the current backend name (cpu, webgl, etc). The backend is\n * responsible for creating tensors and executing operations on those tensors.\n *\n * @doc {heading: 'Backends'}\n */\nexport function getBackend(): string {\n return ENGINE.backendName;\n}\n\n/**\n * Removes a backend and the registered factory.\n *\n * @doc {heading: 'Backends'}\n */\nexport function removeBackend(name: string): void {\n ENGINE.removeBackend(name);\n}\n\n/**\n * Finds the backend registered under the provided name. Returns null if the\n * name is not in the registry, or the registration hasn't finished yet.\n */\nexport function findBackend(name: string): KernelBackend {\n return ENGINE.findBackend(name);\n}\n\n/**\n * Finds the backend factory registered under the provided name. Returns a\n * function that produces a new backend when called. Returns null if the name\n * is not in the registry.\n */\nexport function findBackendFactory(name: string): () =>\n KernelBackend | Promise<KernelBackend> {\n return ENGINE.findBackendFactory(name);\n}\n\n/**\n * Registers a global backend. The registration should happen when importing\n * a module file (e.g. when importing `backend_webgl.ts`), and is used for\n * modular builds (e.g. custom tfjs bundle with only webgl support).\n *\n * @param factory The backend factory function. When called, it should\n * return a backend instance, or a promise of an instance.\n * @param priority The priority of the backend (higher = more important).\n * In case multiple backends are registered, the priority is used to find\n * the best backend. Defaults to 1.\n * @return False if there is already a registered backend under this name, true\n * if not.\n *\n * @doc {heading: 'Backends'}\n */\nexport function registerBackend(\n name: string, factory: () => KernelBackend | Promise<KernelBackend>,\n priority = 1): boolean {\n return ENGINE.registerBackend(name, factory, priority);\n}\n\n/**\n * Gets the current backend. If no backends have been initialized, this will\n * attempt to initialize the best backend. Will throw an error if the highest\n * priority backend has async initialization, in which case, you should call\n * 'await tf.ready()' before running other code.\n *\n * @doc {heading: 'Backends'}\n */\nexport function backend(): KernelBackend {\n return ENGINE.backend;\n}\n\n/**\n * Sets the global platform.\n *\n * @param platformName The name of this platform.\n * @param platform A platform implementation.\n */\nexport function setPlatform(platformName: string, platform: Platform) {\n env().setPlatform(platformName, platform);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {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","import { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Returns a number whose value is limited to the given range.\n *\n * @param {number} value The value to be clamped\n * @param {number} min The lower boundary of the output range\n * @param {number} max The upper boundary of the output range\n * @returns {number} A number in the range [min, max]\n */\nfunction clamp(value) {\n var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (value < min || value > max) {\n console.error(\"Material-UI: The value provided \".concat(value, \" is out of range [\").concat(min, \", \").concat(max, \"].\"));\n }\n }\n\n return Math.min(Math.max(min, value), max);\n}\n/**\n * Converts a color from CSS hex format to CSS rgb format.\n *\n * @param {string} color - Hex color, i.e. #nnn or #nnnnnn\n * @returns {string} A CSS rgb color string\n */\n\n\nexport function hexToRgb(color) {\n color = color.substr(1);\n var re = new RegExp(\".{1,\".concat(color.length >= 6 ? 2 : 1, \"}\"), 'g');\n var colors = color.match(re);\n\n if (colors && colors[0].length === 1) {\n colors = colors.map(function (n) {\n return n + n;\n });\n }\n\n return colors ? \"rgb\".concat(colors.length === 4 ? 'a' : '', \"(\").concat(colors.map(function (n, index) {\n return index < 3 ? parseInt(n, 16) : Math.round(parseInt(n, 16) / 255 * 1000) / 1000;\n }).join(', '), \")\") : '';\n}\n\nfunction intToHex(int) {\n var hex = int.toString(16);\n return hex.length === 1 ? \"0\".concat(hex) : hex;\n}\n/**\n * Converts a color from CSS rgb format to CSS hex format.\n *\n * @param {string} color - RGB color, i.e. rgb(n, n, n)\n * @returns {string} A CSS rgb color string, i.e. #nnnnnn\n */\n\n\nexport function rgbToHex(color) {\n // Idempotent\n if (color.indexOf('#') === 0) {\n return color;\n }\n\n var _decomposeColor = decomposeColor(color),\n values = _decomposeColor.values;\n\n return \"#\".concat(values.map(function (n) {\n return intToHex(n);\n }).join(''));\n}\n/**\n * Converts a color from hsl format to rgb format.\n *\n * @param {string} color - HSL color values\n * @returns {string} rgb color values\n */\n\nexport function hslToRgb(color) {\n color = decomposeColor(color);\n var _color = color,\n values = _color.values;\n var h = values[0];\n var s = values[1] / 100;\n var l = values[2] / 100;\n var a = s * Math.min(l, 1 - l);\n\n var f = function f(n) {\n var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12;\n return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);\n };\n\n var type = 'rgb';\n var rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];\n\n if (color.type === 'hsla') {\n type += 'a';\n rgb.push(values[3]);\n }\n\n return recomposeColor({\n type: type,\n values: rgb\n });\n}\n/**\n * Returns an object with the type and values of a color.\n *\n * Note: Does not support rgb % values.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {object} - A MUI color object: {type: string, values: number[]}\n */\n\nexport function decomposeColor(color) {\n // Idempotent\n if (color.type) {\n return color;\n }\n\n if (color.charAt(0) === '#') {\n return decomposeColor(hexToRgb(color));\n }\n\n var marker = color.indexOf('(');\n var type = color.substring(0, marker);\n\n if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: Unsupported `\".concat(color, \"` color.\\nWe support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().\") : _formatMuiErrorMessage(3, color));\n }\n\n var values = color.substring(marker + 1, color.length - 1).split(',');\n values = values.map(function (value) {\n return parseFloat(value);\n });\n return {\n type: type,\n values: values\n };\n}\n/**\n * Converts a color object with type and values to a string.\n *\n * @param {object} color - Decomposed color\n * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla'\n * @param {array} color.values - [n,n,n] or [n,n,n,n]\n * @returns {string} A CSS color string\n */\n\nexport function recomposeColor(color) {\n var type = color.type;\n var values = color.values;\n\n if (type.indexOf('rgb') !== -1) {\n // Only convert the first 3 values to int (i.e. not alpha)\n values = values.map(function (n, i) {\n return i < 3 ? parseInt(n, 10) : n;\n });\n } else if (type.indexOf('hsl') !== -1) {\n values[1] = \"\".concat(values[1], \"%\");\n values[2] = \"\".concat(values[2], \"%\");\n }\n\n return \"\".concat(type, \"(\").concat(values.join(', '), \")\");\n}\n/**\n * Calculates the contrast ratio between two colors.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} A contrast ratio value in the range 0 - 21.\n */\n\nexport function getContrastRatio(foreground, background) {\n var lumA = getLuminance(foreground);\n var lumB = getLuminance(background);\n return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);\n}\n/**\n * The relative brightness of any point in a color space,\n * normalized to 0 for darkest black and 1 for lightest white.\n *\n * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @returns {number} The relative brightness of the color in the range 0 - 1\n */\n\nexport function getLuminance(color) {\n color = decomposeColor(color);\n var rgb = color.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : color.values;\n rgb = rgb.map(function (val) {\n val /= 255; // normalized\n\n return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);\n }); // Truncate at 3 digits\n\n return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3));\n}\n/**\n * Darken or lighten a color, depending on its luminance.\n * Light colors are darkened, dark colors are lightened.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient=0.15 - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function emphasize(color) {\n var coefficient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.15;\n return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);\n}\n/**\n * Set the absolute transparency of a color.\n * Any existing alpha values are overwritten.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} value - value to set the alpha channel to in the range 0 -1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function fade(color, value) {\n color = decomposeColor(color);\n value = clamp(value);\n\n if (color.type === 'rgb' || color.type === 'hsl') {\n color.type += 'a';\n }\n\n color.values[3] = value;\n return recomposeColor(color);\n}\n/**\n * Darkens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function darken(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] *= 1 - coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] *= 1 - coefficient;\n }\n }\n\n return recomposeColor(color);\n}\n/**\n * Lightens a color.\n *\n * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()\n * @param {number} coefficient - multiplier in the range 0 - 1\n * @returns {string} A CSS color string. Hex input values are returned as rgb\n */\n\nexport function lighten(color, coefficient) {\n color = decomposeColor(color);\n coefficient = clamp(coefficient);\n\n if (color.type.indexOf('hsl') !== -1) {\n color.values[2] += (100 - color.values[2]) * coefficient;\n } else if (color.type.indexOf('rgb') !== -1) {\n for (var i = 0; i < 3; i += 1) {\n color.values[i] += (255 - color.values[i]) * coefficient;\n }\n }\n\n return recomposeColor(color);\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 */\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","import * as React from 'react';\nimport setRef from './setRef';\nexport default function useForkRef(refA, refB) {\n /**\n * This will create a new function if the ref props change and are defined.\n * This means react will call the old forkRef with `null` and the new forkRef\n * with the ref. Cleanup naturally emerges from this behavior\n */\n return React.useMemo(function () {\n if (refA == null && refB == null) {\n return null;\n }\n\n return function (refValue) {\n setRef(refA, refValue);\n setRef(refB, refValue);\n };\n }, [refA, refB]);\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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","'use strict';\n\nfunction checkDCE() {\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n if (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'\n ) {\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n // This branch is unreachable because this function is only called\n // in production, but the condition is true only in development.\n // Therefore if the branch is still here, dead code elimination wasn't\n // properly applied.\n // Don't change the message. React DevTools relies on it. Also make sure\n // this message doesn't occur elsewhere in this function, or it will cause\n // a false positive.\n throw new Error('^_^');\n }\n try {\n // Verify that the code above has been dead code eliminated (DCE'd).\n __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);\n } catch (err) {\n // DevTools shouldn't crash React, no matter what.\n // We should still report in case we break this code.\n console.error(err);\n }\n}\n\nif (process.env.NODE_ENV === 'production') {\n // DCE check should happen before ReactDOM bundle executes so that\n // DevTools can report bad minification during injection.\n checkDCE();\n module.exports = require('./cjs/react-dom.production.min.js');\n} else {\n module.exports = require('./cjs/react-dom.development.js');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 */\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 */\n\n// TODO update import path once op is modularized.\nimport {abs} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n abs<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.abs = function<T extends Tensor>(this: T) {\n this.throwIfDisposed();\n return abs(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {acos} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n acos<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.acos = function<T extends Tensor>(this: T) {\n this.throwIfDisposed();\n return acos(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {acosh} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n acosh<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.acosh = function<T extends Tensor>(this: T) {\n this.throwIfDisposed();\n return acosh(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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} from '../../ops/add';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n add<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.add = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return add(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {all} from '../../ops/all';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n all<T extends Tensor>(this: T, axis?: number|number[], keepDims?: boolean):\n T;\n }\n}\n\ngetGlobalTensorClass().prototype.all = function<T extends Tensor>(\n this: T, axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return all(this, axis, keepDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {any} from '../../ops/any';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n any<T extends Tensor>(this: T, axis?: number|number[], keepDims?: boolean):\n T;\n }\n}\n\ngetGlobalTensorClass().prototype.any = function<T extends Tensor>(\n this: T, axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return any(this, axis, keepDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {argMax} from '../../ops/arg_max';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n argMax<T extends Tensor>(axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.argMax = function<T extends Tensor>(\n axis?: number): T {\n this.throwIfDisposed();\n return argMax(this, axis);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {argMin} from '../../ops/arg_min';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n argMin<T extends Tensor>(axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.argMin = function<T extends Tensor>(\n axis: number): T {\n this.throwIfDisposed();\n return argMin(this, axis);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Scalar, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\nimport {assert} from '../../util';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n asScalar<T extends Tensor>(): Scalar;\n }\n}\n\n/**\n * Converts a size-1 `tf.Tensor` to a `tf.Scalar`.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.asScalar = function<T extends Tensor>(this: T):\n Scalar {\n this.throwIfDisposed();\n assert(this.size === 1, () => 'The array must have only 1 element.');\n return reshape(this, []);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {cast} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {DataType, Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n asType<T extends Tensor>(this: T, dtype: DataType): T;\n }\n}\n\n/**\n * Casts a `tf.Tensor` to a specified dtype.\n *\n * @param dtype Data-type to cast the tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.asType = function<T extends Tensor>(\n this: T, dtype: DataType): T {\n this.throwIfDisposed();\n return cast<T>(this, 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 {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n as1D<T extends Tensor>(): Tensor1D;\n }\n}\n\n/**\n * Converts a `tf.Tensor` to a `tf.Tensor1D`.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.as1D = function<T extends Tensor>(): T {\n this.throwIfDisposed();\n return reshape(this, [this.size]) 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 */\n\nimport {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n as2D<T extends Tensor>(rows: number, columns: number): Tensor2D;\n }\n}\n\n/**\n * Converts a `tf.Tensor` to a `tf.Tensor2D`.\n *\n * @param rows Number of rows in `tf.Tensor2D`.\n * @param columns Number of columns in `tf.Tensor2D`.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.as2D = function<T extends Tensor>(\n rows: number, columns: number): T {\n this.throwIfDisposed();\n return reshape(this, [rows, columns]) 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 */\n\nimport {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n as3D<T extends Tensor>(rows: number, columns: number, depth: number):\n Tensor3D;\n }\n}\n\n/**\n * Converts a `tf.Tensor` to a `tf.Tensor3D`.\n *\n * @param rows Number of rows in `tf.Tensor3D`.\n * @param columns Number of columns in `tf.Tensor3D`.\n * @param depth Depth of `tf.Tensor3D`.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.as3D = function<T extends Tensor>(\n rows: number, columns: number, depth: number): T {\n this.throwIfDisposed();\n return reshape(this, [rows, columns, depth]) 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 */\n\nimport {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n as4D<T extends Tensor>(\n rows: number, columns: number, depth: number, depth2: number): Tensor4D;\n }\n}\n\n/**\n * Converts a `tf.Tensor` to a `tf.Tensor4D`.\n *\n * @param rows Number of rows in `tf.Tensor4D`.\n * @param columns Number of columns in `tf.Tensor4D`.\n * @param depth Depth of `tf.Tensor4D`.\n * @param depth2 4th dimension of `tf.Tensor4D`.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.as4D = function<T extends Tensor>(\n rows: number, columns: number, depth: number, depth2: number): T {\n this.throwIfDisposed();\n return reshape(this, [rows, columns, depth, depth2]) 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 */\n\nimport {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n as5D<T extends Tensor>(\n rows: number, columns: number, depth: number, depth2: number,\n depth3: number): Tensor5D;\n }\n}\n\n/**\n * Converts a `tf.Tensor` to a `tf.Tensor5D`.\n *\n * @param rows Number of rows in `tf.Tensor5D`.\n * @param columns Number of columns in `tf.Tensor5D`.\n * @param depth Depth of `tf.Tensor5D`.\n * @param depth2 4th dimension of `tf.Tensor5D`.\n * @param depth3 5th dimension of 'tf.Tensor5D'\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.as5D = function<T extends Tensor>(\n rows: number, columns: number, depth: number, depth2: number,\n depth3: number): T {\n this.throwIfDisposed();\n return reshape(this, [rows, columns, depth, depth2, depth3]) 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 */\n\n// TODO update import path once op is modularized.\nimport {asin} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n asin<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.asin = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return asin(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {asinh} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n asinh<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.asinh = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return asinh(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {atan} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n atan<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.atan = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return atan(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {atan2} from '../../ops/atan2';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n atan2<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.atan2 = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return atan2(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {atanh} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n atanh<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.atanh = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return atanh(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ExplicitPadding} from '../../ops/conv_util';\nimport {avgPool} from '../../ops/avg_pool';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n avgPool<T extends Tensor3D|Tensor4D>(\n filterSize: [number, number]|number, strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.avgPool =\n function<T extends Tensor3D|Tensor4D>(\n this: T, filterSize: [number, number]|number,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n this.throwIfDisposed();\n return avgPool(this, filterSize, strides, pad, dimRoundingMode);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {batchToSpaceND} from '../../ops/batch_to_space_nd';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n batchToSpaceND<R extends Rank>(blockShape: number[], crops: number[][]):\n Tensor<R>;\n }\n}\n\ngetGlobalTensorClass().prototype.batchToSpaceND = function<R extends Rank>(\n blockShape: number[], crops: number[][]): Tensor<R> {\n this.throwIfDisposed();\n return batchToSpaceND(this, blockShape, crops);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {batchNorm} from '../../ops/batchnorm';\nimport {getGlobalTensorClass, Tensor, Tensor1D} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n batchNorm<T extends Tensor>(\n 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 }\n}\n\ngetGlobalTensorClass().prototype.batchNorm = function<R extends Rank>(\n 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 this.throwIfDisposed();\n return batchNorm(this, mean, variance, offset, scale, varianceEpsilon);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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} from '../../ops/broadcast_to';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, ShapeMap} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n broadcastTo<R extends Rank>(shape: ShapeMap[R]): Tensor<R>;\n }\n}\n\ngetGlobalTensorClass().prototype.broadcastTo = function<R extends Rank>(\n shape: ShapeMap[R]): Tensor<R> {\n this.throwIfDisposed();\n return broadcastTo(this, shape);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {cast} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {DataType, Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n cast<T extends Tensor>(dtype: DataType): T;\n }\n}\n\ngetGlobalTensorClass().prototype.cast = function<T extends Tensor>(\n dtype: DataType): T {\n this.throwIfDisposed();\n return cast(this, dtype) 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 */\n\n// TODO update import path once op is modularized.\nimport {ceil} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n ceil<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.ceil = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return ceil(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {clipByValue} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n clipByValue<T extends Tensor>(min: number, max: number): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.clipByValue = function<T extends Tensor>(\n min: number, max: number): T {\n this.throwIfDisposed();\n return clipByValue(this, min, max) 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 {concat} from '../../ops/concat';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n concat<T extends Tensor>(tensors: T|Array<T|TensorLike>, axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.concat = function<T extends Tensor>(\n x: T|Array<T|TensorLike>, axis?: number): T {\n this.throwIfDisposed();\n if (x instanceof Tensor) {\n x = [x];\n }\n return concat([this, ...x], axis) 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 {conv1d} from '../../ops/conv1d';\nimport {ExplicitPadding} from '../../ops/conv_util';\nimport {getGlobalTensorClass, Tensor2D, Tensor3D} from '../../tensor';\nimport {Rank, TensorLike3D} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n conv1d<T extends Tensor2D|Tensor3D>(\n filter: Tensor3D|TensorLike3D, stride: number,\n pad: 'valid'|'same'|number|ExplicitPadding, dataFormat?: 'NWC'|'NCW',\n dilation?: number, dimRoundingMode?: 'floor'|'round'|'ceil'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.conv1d = function<T extends Tensor2D|Tensor3D>(\n filter: Tensor3D|TensorLike3D, stride: number,\n pad: 'valid'|'same'|number|ExplicitPadding, dataFormat?: 'NWC'|'NCW',\n dilation?: number, dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n this.throwIfDisposed();\n return conv1d(\n this, filter, stride, pad, dataFormat, dilation,\n dimRoundingMode) 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 {conv2dTranspose} from '../../ops/conv2d_transpose';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank, TensorLike4D} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n conv2dTranspose<T extends Tensor3D|Tensor4D>(\n filter: Tensor4D|TensorLike4D,\n outputShape: [number, number, number, number]|[number, number, number],\n strides: [number, number]|number, pad: 'valid'|'same'|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.conv2dTranspose =\n function<T extends Tensor3D|Tensor4D>(\n filter: Tensor4D|TensorLike4D,\n outputShape: [number, number, number, number]|[number, number, number],\n strides: [number, number]|number, pad: 'valid'|'same'|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n this.throwIfDisposed();\n return conv2dTranspose(\n this, filter, outputShape, strides, pad, dimRoundingMode) 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 {conv2d} from '../../ops/conv2d';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank, TensorLike4D} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n conv2d<T extends Tensor3D|Tensor4D>(\n filter: Tensor4D|TensorLike4D, strides: [number, number]|number,\n pad: 'valid'|'same'|number, dataFormat?: 'NHWC'|'NCHW',\n dilations?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.conv2d = function<T extends Tensor3D|Tensor4D>(\n filter: Tensor4D|TensorLike4D, strides: [number, number]|number,\n pad: 'valid'|'same'|number, dataFormat?: 'NHWC'|'NCHW',\n dilations?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n this.throwIfDisposed();\n return conv2d(\n this, filter, strides, pad, dataFormat, dilations,\n dimRoundingMode) 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 */\n\n// TODO update import path once op is modularized.\nimport {cos} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n cos<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.cos = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return cos(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {cosh} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n cosh<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.cosh = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return cosh(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {cumsum} from '../../ops/cumsum';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n cumsum<R extends Rank>(\n axis?: number, exclusive?: boolean, reverse?: boolean): Tensor<R>;\n }\n}\n\ngetGlobalTensorClass().prototype.cumsum = function<R extends Rank>(\n axis?: number, exclusive?: boolean, reverse?: boolean): Tensor<R> {\n this.throwIfDisposed();\n return cumsum(this, axis, exclusive, reverse);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {depthToSpace} from '../../ops/depth_to_space';\nimport {getGlobalTensorClass, Tensor4D} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n depthToSpace<T extends Tensor4D>(\n blockSize: number, dataFormat: 'NHWC'|'NCHW'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.depthToSpace = function<T extends Tensor4D>(\n blockSize: number, dataFormat: 'NHWC'|'NCHW'): T {\n this.throwIfDisposed();\n return depthToSpace(this, blockSize, dataFormat) 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 {depthwiseConv2d} from '../../ops/depthwise_conv2d';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank, TensorLike4D} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n depthwiseConv2d<T extends Tensor3D|Tensor4D>(\n filter: Tensor4D|TensorLike4D, strides: [number, number]|number,\n pad: 'valid'|'same'|number, dataFormat?: 'NHWC'|'NCHW',\n dilations?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.depthwiseConv2d =\n function<T extends Tensor3D|Tensor4D>(\n filter: Tensor4D|TensorLike4D, strides: [number, number]|number,\n pad: 'valid'|'same'|number, dataFormat?: 'NHWC'|'NCHW',\n dilations?: [number, number]|number,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n this.throwIfDisposed();\n return depthwiseConv2d(\n this, filter, strides, pad, dataFormat, dilations,\n dimRoundingMode) 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 {dilation2d} from '../../ops/dilation2d';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank, TensorLike3D} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n dilation2d<T extends Tensor3D|Tensor4D>(\n filter: Tensor3D|TensorLike3D, strides: [number, number]|number,\n pad: 'valid'|'same', dilations?: [number, number]|number,\n dataFormat?: 'NHWC'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.dilation2d =\n function<T extends Tensor3D|Tensor4D>(\n filter: Tensor3D|TensorLike3D, strides: [number, number]|number,\n pad: 'valid'|'same', dilations?: [number, number]|number,\n dataFormat?: 'NHWC'): T {\n this.throwIfDisposed();\n return dilation2d(this, filter, strides, pad, dilations, dataFormat) 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 */\n\nimport {divNoNan} from '../../ops/div_no_nan';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n divNoNan<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.divNoNan = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return divNoNan(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {div} from '../../ops/div';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n div<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.div = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return div(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {dot} from '../../ops/dot';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n dot<T extends Tensor>(b: Tensor|TensorLike): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.dot = function<T extends Tensor>(\n b: T|TensorLike): Tensor {\n this.throwIfDisposed();\n return dot(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {elu} from '../../ops/elu';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n elu<T extends Tensor>(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.elu = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return elu(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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} from '../../ops/equal';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n equal<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.equal = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return equal(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {erf} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n erf<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.erf = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return erf(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {exp} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n exp<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.exp = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return exp(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {expandDims} from '../../ops/expand_dims';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n expandDims<T extends Tensor>(axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.expandDims = function<T extends Tensor>(\n axis?: number): T {\n this.throwIfDisposed();\n return expandDims(this, axis);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {expm1} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n expm1<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.expm1 = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return expm1(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {fft} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n fft<T extends Tensor>(this: Tensor): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.fft = function<T extends Tensor>(this: Tensor):\n T {\n this.throwIfDisposed();\n return fft(this) 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 */\n\nimport {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n flatten<T extends Tensor>(): Tensor1D;\n }\n}\n\n/**\n * Flatten a Tensor to a 1D array.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.flatten = function<T extends Tensor>(): T {\n this.throwIfDisposed();\n return reshape(this, [this.size]) 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 */\n\n// TODO update import path once op is modularized.\nimport {floor} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n floor<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.floor = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return floor(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {floorDiv} from '../../ops/floorDiv';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n floorDiv<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.floorDiv = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return floorDiv(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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} from '../../ops/gather';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n gather<T extends Tensor>(\n this: T, indices: Tensor|TensorLike, axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.gather = function<T extends Tensor>(\n this: T, indices: Tensor|TensorLike, axis?: number): T {\n this.throwIfDisposed();\n return gather(this, indices, axis);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 '../../ops/greater_equal';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n greaterEqual<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.greaterEqual = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return greaterEqual(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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} from '../../ops/greater';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n greater<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.greater = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return greater(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {ifft} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n ifft<T extends Tensor>(this: Tensor): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.ifft = function<T extends Tensor>(\n this: Tensor): T {\n this.throwIfDisposed();\n return ifft(this) 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 */\n\n// TODO update import path once op is modularized.\nimport {irfft} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n irfft<T extends Tensor>(this: Tensor): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.irfft = function<T extends Tensor>(\n this: Tensor): T {\n this.throwIfDisposed();\n return irfft(this) 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 */\n\n// TODO update import path once op is modularized.\nimport {isFinite} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n isFinite<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.isFinite = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return isFinite(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {isInf} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n isInf<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.isInf = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return isInf(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {isNaN} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n isNaN<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.isNaN = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return isNaN(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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} from '../../ops/leaky_relu';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n leakyRelu<T extends Tensor>(alpha: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.leakyRelu = function<T extends Tensor>(\n this: T, alpha: number): T {\n this.throwIfDisposed();\n return leakyRelu(this, alpha);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {lessEqual} from '../../ops/less_equal';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n lessEqual<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.lessEqual = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return lessEqual(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {less} from '../../ops/less';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n less<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.less = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return less(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {localResponseNormalization} from '../../ops/local_response_normalization';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n localResponseNormalization<T extends Tensor>(\n depthRadius?: number, bias?: number, alpha?: number, beta?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.localResponseNormalization =\n function<T extends Tensor>(\n depthRadius?: number, bias?: number, alpha?: number, beta?: number): T {\n this.throwIfDisposed();\n return localResponseNormalization(this, depthRadius, bias, alpha, beta) 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 */\n\n// TODO update import path once op is modularized.\nimport {logSigmoid} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n logSigmoid<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logSigmoid = function<T extends Tensor>(\n this: T): T {\n this.throwIfDisposed();\n return logSigmoid(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {logSoftmax} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n logSoftmax<T extends Tensor>(this: T, axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logSoftmax = function<T extends Tensor>(\n this: T, axis?: number): T {\n this.throwIfDisposed();\n return logSoftmax(this, axis);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {logSumExp} from '../../ops/log_sum_exp';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n logSumExp<T extends Tensor>(\n this: T, axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logSumExp = function<T extends Tensor>(\n this: T, axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return logSumExp(this, axis, keepDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {log} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n log<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.log = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return log(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {log1p} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n log1p<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.log1p = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return log1p(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {logicalAnd} from '../../ops/logical_and';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n logicalAnd<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logicalAnd = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return logicalAnd(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {logicalNot} from '../../ops/logical_not';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n logicalNot<T extends Tensor>(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logicalNot = function<T extends Tensor>(): T {\n this.throwIfDisposed();\n return logicalNot(this) 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 {logicalOr} from '../../ops/logical_or';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n logicalOr<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logicalOr = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return logicalOr(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {logicalXor} from '../../ops/logical_xor';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n logicalXor<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.logicalXor = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return logicalXor(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {matMul} from '../../ops/mat_mul';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n matMul<T extends Tensor>(\n b: Tensor|TensorLike, transposeA?: boolean,\n transposeB?: boolean): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.matMul = function<T extends Tensor>(\n this: T, b: Tensor|TensorLike, transposeA?: boolean,\n transposeB?: boolean): Tensor {\n this.throwIfDisposed();\n return matMul(this, b, transposeA, transposeB);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ExplicitPadding} from '../../ops/conv_util';\nimport {maxPool} from '../../ops/max_pool';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n maxPool<T extends Tensor3D|Tensor4D>(\n filterSize: [number, number]|number, strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.maxPool =\n function<T extends Tensor3D|Tensor4D>(\n this: T, filterSize: [number, number]|number,\n strides: [number, number]|number,\n pad: 'valid'|'same'|number|ExplicitPadding,\n dimRoundingMode?: 'floor'|'round'|'ceil'): T {\n this.throwIfDisposed();\n return maxPool(this, filterSize, strides, pad, dimRoundingMode);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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} from '../../ops/max';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n max<T extends Tensor>(axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.max = function<T extends Tensor>(\n axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return max(this, axis, keepDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {maximum} from '../../ops/maximum';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n maximum<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.maximum = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return maximum(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {mean} from '../../ops/mean';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n mean<T extends Tensor>(axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.mean = function<T extends Tensor>(\n axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return mean(this, axis, keepDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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} from '../../ops/min';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n min<T extends Tensor>(axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.min = function<T extends Tensor>(\n axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return min(this, axis, keepDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {minimum} from '../../ops/minimum';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n minimum<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.minimum = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return minimum(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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} from '../../ops/mirror_pad';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n mirrorPad<T extends Tensor>(\n paddings: Array<[number, number]>, mode: 'reflect'|'symmetric'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.mirrorPad = function<T extends Tensor>(\n this: T, paddings: Array<[number, number]>,\n mode: 'reflect'|'symmetric'): T {\n this.throwIfDisposed();\n return mirrorPad(this, paddings, mode);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {mod} from '../../ops/mod';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n mod<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.mod = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return mod(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {mul} from '../../ops/mul';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n mul<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.mul = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return mul(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {neg} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n neg<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.neg = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return neg(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {norm} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n norm<T extends Tensor>(\n ord?: number|'euclidean'|'fro', axis?: number|number[],\n keepDims?: boolean): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.norm = function<T extends Tensor>(\n ord?: number|'euclidean'|'fro', axis?: number|number[],\n keepDims?: boolean) {\n this.throwIfDisposed();\n return norm(this, ord, axis, keepDims) 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 {notEqual} from '../../ops/not_equal';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n notEqual<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.notEqual = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return notEqual(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 '../../ops/one_hot';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n oneHot(depth: number, onValue: number, offValue: number): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.oneHot = function(\n depth: number, onValue = 1, offValue = 0): Tensor {\n this.throwIfDisposed();\n return oneHot(this, depth, onValue, offValue);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {onesLike} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n onesLike<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.onesLike = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return onesLike(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {pad} from '../../ops/pad';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n pad<T extends Tensor>(\n paddings: Array<[number, number]>, constantValue?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.pad = function<T extends Tensor>(\n this: T, paddings: Array<[number, number]>, constantValue: number): T {\n this.throwIfDisposed();\n return pad(this, paddings, constantValue);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ExplicitPadding} from '../../ops/conv_util';\nimport {pool} from '../../ops/pool';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n pool<T extends Tensor3D|Tensor4D>(\n windowShape: [number, number]|number, poolingType: 'avg'|'max',\n padding: 'valid'|'same'|number|ExplicitPadding,\n diationRate?: [number, number]|number,\n strides?: [number, number]|number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.pool = function<T extends Tensor3D|Tensor4D>(\n this: T, windowShape: [number, number]|number, poolingType: 'max'|'avg',\n padding: 'valid'|'same'|number|ExplicitPadding,\n dilationRate?: [number, number]|number,\n strides?: [number, number]|number): T {\n this.throwIfDisposed();\n return pool(this, windowShape, poolingType, padding, dilationRate, strides);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 '../../ops/pow';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n pow<T extends Tensor>(exp: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.pow = function<T extends Tensor>(\n exp: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return pow(this, 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 */\nimport {prelu} from '../../ops/prelu';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n prelu<T extends Tensor>(alpha: T|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.prelu = function<T extends Tensor>(\n this: T, alpha: T|TensorLike): T {\n this.throwIfDisposed();\n return prelu(this, alpha);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {prod} from '../../ops/prod';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n prod<T extends Tensor>(this: T, axis?: number|number[], keepDims?: boolean):\n T;\n }\n}\n\ngetGlobalTensorClass().prototype.prod = function<T extends Tensor>(\n this: T, axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return prod(this, axis, keepDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {reciprocal} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n reciprocal<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.reciprocal = function<T extends Tensor>(\n this: T): T {\n this.throwIfDisposed();\n return reciprocal(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 '../../ops/relu';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n relu<T extends Tensor>(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.relu = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return relu(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 '../../ops/relu6';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n relu6<T extends Tensor>(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.relu6 = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return relu6(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n reshapeAs<T extends Tensor>(x: T): T;\n }\n}\n\n/**\n * Reshapes the tensor into the shape of the provided tensor.\n *\n * @param x The tensor of required shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.reshapeAs = function<T extends Tensor>(x: T):\n T {\n this.throwIfDisposed();\n return reshape(this, x.shape) 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 {reshape} from '../../ops/reshape';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n reshape<T extends Tensor>(shape: number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.reshape = function<T extends Tensor>(\n shape: number[]): T {\n this.throwIfDisposed();\n return reshape(this, shape) 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 {resizeBilinear} from '../../ops/image/resize_bilinear';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n resizeBilinear<T extends Tensor3D|Tensor4D>(\n newShape2D: [number, number], alignCorners?: boolean,\n halfPixelCenters?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.resizeBilinear =\n function<T extends Tensor3D|Tensor4D>(\n this: T, newShape2D: [number, number], alignCorners?: boolean,\n halfPixelCenters?: boolean): T {\n this.throwIfDisposed();\n return resizeBilinear(this, newShape2D, alignCorners, halfPixelCenters);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {resizeNearestNeighbor} from '../../ops/image/resize_nearest_neighbor';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n resizeNearestNeighbor<T extends Tensor3D|Tensor4D>(\n newShape2D: [number, number], alignCorners?: boolean,\n halfFloatCenters?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.resizeNearestNeighbor =\n function<T extends Tensor3D|Tensor4D>(\n this: T, newShape2D: [number, number], alignCorners?: boolean,\n halfFloatCenters?: boolean): T {\n this.throwIfDisposed();\n return resizeNearestNeighbor(\n this, newShape2D, alignCorners, halfFloatCenters);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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} from '../../ops/reverse';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n reverse<T extends Tensor>(this: T, axis?: number|number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.reverse = function<T extends Tensor>(\n this: T, axis?: number|number[]): T {\n this.throwIfDisposed();\n return reverse(this, axis);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {rfft} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n rfft<T extends Tensor>(this: Tensor): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.rfft = function<T extends Tensor>(\n this: Tensor): T {\n this.throwIfDisposed();\n return rfft(this) 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 */\n\n// TODO update import path once op is modularized.\nimport {round} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n round<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.round = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return round(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {rsqrt} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n rsqrt<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.rsqrt = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return rsqrt(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 '../../ops/selu';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n selu<T extends Tensor>(): T;\n }\n}\n\ngetGlobalTensorClass().prototype.selu = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return selu(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {separableConv2d} from '../../ops/separable_conv2d';\nimport {getGlobalTensorClass, Tensor3D, Tensor4D} from '../../tensor';\nimport {Rank, TensorLike, TensorLike4D} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n separableConv2d<T extends Tensor3D|Tensor4D>(\n depthwiseFilter: Tensor4D|TensorLike4D,\n pointwiseFilter: Tensor4D|TensorLike, strides: [number, number]|number,\n pad: 'valid'|'same', dilation?: [number, number]|number,\n dataFormat?: 'NHWC'|'NCHW'): T;\n }\n}\n\ngetGlobalTensorClass().prototype.separableConv2d =\n function<T extends Tensor3D|Tensor4D>(\n depthwiseFilter: Tensor4D|TensorLike4D,\n pointwiseFilter: Tensor4D|TensorLike, strides: [number, number]|number,\n pad: 'valid'|'same', dilation?: [number, number]|number,\n dataFormat?: 'NHWC'|'NCHW'): T {\n this.throwIfDisposed();\n return separableConv2d(\n this, depthwiseFilter, pointwiseFilter, strides, pad, dilation,\n dataFormat) 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 */\n\n// TODO update import path once op is modularized.\nimport {sigmoid} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n sigmoid<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sigmoid = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return sigmoid(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {sign} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n sign<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sign = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return sign(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {sin} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n sin<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sin = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return sin(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {sinh} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n sinh<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sinh = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return sinh(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {slice} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n slice<T extends Tensor>(\n this: T, begin: number|number[], size?: number|number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.slice = function<T extends Tensor>(\n this: T, begin: number|number[], size?: number|number[]): T {\n this.throwIfDisposed();\n return slice(this, begin, size);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {softmax} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n softmax<T extends Tensor>(this: T, dim?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.softmax = function<T extends Tensor>(\n this: T, dim: number): T {\n this.throwIfDisposed();\n return softmax(this, dim);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {softplus} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n softplus<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.softplus = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return softplus(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {spaceToBatchND} from '../../ops/space_to_batch_nd';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n spaceToBatchND<R extends Rank>(blockShape: number[], paddings: number[][]):\n Tensor<R>;\n }\n}\n\ngetGlobalTensorClass().prototype.spaceToBatchND = function<R extends Rank>(\n blockShape: number[], paddings: number[][]): Tensor<R> {\n this.throwIfDisposed();\n return spaceToBatchND(this, blockShape, paddings);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {split} from '../../ops/split';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n split<T extends Tensor>(numOrSizeSplits: number[]|number, axis?: number):\n T[];\n }\n}\n\ngetGlobalTensorClass().prototype.split = function<T extends Tensor>(\n numOrSizeSplits: number[]|number, axis?: number): T[] {\n this.throwIfDisposed();\n return split(this, numOrSizeSplits, axis);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {sqrt} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n sqrt<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sqrt = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return sqrt(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {square} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n square<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.square = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return square(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 '../../ops/squared_difference';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n squaredDifference<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.squaredDifference = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return squaredDifference(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {squeeze} from '../../ops/squeeze';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n squeeze<T extends Tensor>(axis?: number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.squeeze = function<T extends Tensor>(\n axis?: number[]): T {\n this.throwIfDisposed();\n return squeeze(this, axis);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {stack} from '../../ops/stack';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n stack<T extends Tensor>(x: Tensor|Tensor[], axis?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.stack = function<T extends Tensor>(\n x: Tensor|Tensor[], axis?: number): T {\n this.throwIfDisposed();\n const tensorsToBeStacked = x instanceof Tensor ? [this, x] : [this, ...x];\n return stack(tensorsToBeStacked, axis) 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 */\n\n// TODO update import path once op is modularized.\nimport {step} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n step<T extends Tensor>(this: T, alpha?: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.step = function<T extends Tensor>(\n this: T, alpha?: number) {\n this.throwIfDisposed();\n return step(this, alpha);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {stridedSlice} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n stridedSlice<T extends Tensor>(\n this: Tensor, begin: number[], end: number[], strides: number[],\n beginMask?: number, endMask?: number, ellipsisMask?: number,\n newAxisMask?: number, shrinkAxisMask?: number): Tensor;\n }\n}\n\ngetGlobalTensorClass().prototype.stridedSlice = function<T extends Tensor>(\n this: Tensor, begin: number[], end: number[], strides: number[],\n beginMask?: number, endMask?: number, ellipsisMask?: number,\n newAxisMask?: number, shrinkAxisMask?: number): T {\n this.throwIfDisposed();\n return stridedSlice(\n this, begin, end, strides, beginMask, endMask, ellipsisMask,\n newAxisMask, shrinkAxisMask) 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 {sub} from '../../ops/sub';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n sub<T extends Tensor>(b: Tensor|TensorLike): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sub = function<T extends Tensor>(\n b: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return sub(this, b);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {sum} from '../../ops/sum';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n sum<T extends Tensor>(axis?: number|number[], keepDims?: boolean): T;\n }\n}\n\ngetGlobalTensorClass().prototype.sum = function<T extends Tensor>(\n axis?: number|number[], keepDims?: boolean): T {\n this.throwIfDisposed();\n return sum(this, axis, keepDims);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {tan} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n tan<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.tan = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return tan(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {tanh} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n tanh<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.tanh = function<T extends Tensor>(this: T): T {\n this.throwIfDisposed();\n return tanh(this);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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} from '../../ops/tile';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n tile<T extends Tensor>(b: number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.tile = function<T extends Tensor>(\n reps: number[]): T {\n this.throwIfDisposed();\n return tile(this, reps) 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 */\n\n// TODO update import path once op is modularized.\nimport {cast} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n toBool<T extends Tensor>(this: T): T;\n }\n}\n\n/**\n * Casts the array to type `bool`\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.toBool = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return cast<T>(this, 'bool');\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {cast} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n toFloat<T extends Tensor>(this: T): T;\n }\n}\n\n/**\n * Casts the array to type `float32`\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.toFloat = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return cast<T>(this, 'float32');\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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// TODO update import path once op is modularized.\nimport {cast} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n toInt<T extends Tensor>(this: T): T;\n }\n}\n\n/**\n * Casts the array to type `int32`\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\ngetGlobalTensorClass().prototype.toInt = function<T extends Tensor>(this: T):\n T {\n this.throwIfDisposed();\n return cast<T>(this, 'int32');\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {topk} from '../../ops/topk';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n topk<T extends Tensor>(this: T, k?: number, sorted?: boolean):\n {values: T, indices: T};\n }\n}\n\ngetGlobalTensorClass().prototype.topk = function<T extends Tensor>(\n this: T, k?: number, sorted?: boolean): {values: T, indices: T} {\n this.throwIfDisposed();\n return topk(this, k, sorted) as {values: T, indices: 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 */\n\nimport {transpose} from '../../ops/transpose';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n transpose<T extends Tensor>(perm?: number[]): T;\n }\n}\n\ngetGlobalTensorClass().prototype.transpose = function<T extends Tensor>(\n this: T, perm?: number[]): T {\n this.throwIfDisposed();\n return transpose(this, perm);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {unique} from '../../ops/unique';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n unique<T extends Tensor>(this: T, axis?: number): {values: T, indices: T};\n }\n}\n\ngetGlobalTensorClass().prototype.unique = function<T extends Tensor>(\n this: T, axis?: number): {values: T, indices: T} {\n this.throwIfDisposed();\n return unique(this, axis) as {values: T, indices: 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 */\n\nimport {unsortedSegmentSum} from '../../ops/unsorted_segment_sum';\nimport {getGlobalTensorClass, Tensor, Tensor1D} from '../../tensor';\nimport {Rank, TensorLike1D} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n unsortedSegmentSum<T extends Tensor>(\n this: T, segmentIds: Tensor1D|TensorLike1D, numSegments: number): T;\n }\n}\n\ngetGlobalTensorClass().prototype.unsortedSegmentSum =\n function<T extends Tensor>(\n this: T, segmentIds: Tensor1D|TensorLike1D, numSegments: number): T {\n this.throwIfDisposed();\n return unsortedSegmentSum(this, segmentIds, numSegments);\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {unstack} from '../../ops/unstack';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n unstack<T extends Tensor>(axis?: number): T[];\n }\n}\n\ngetGlobalTensorClass().prototype.unstack = function<T extends Tensor>(\n axis?: number): T[] {\n this.throwIfDisposed();\n return unstack(this, axis) 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 */\n\nimport {where} from '../../ops/where';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank, TensorLike} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n where<T extends Tensor>(condition: Tensor|TensorLike, x: Tensor|TensorLike):\n T;\n }\n}\n\ngetGlobalTensorClass().prototype.where = function<T extends Tensor>(\n condition: Tensor|TensorLike, x: Tensor|TensorLike): T {\n this.throwIfDisposed();\n return where(condition, this, x) 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 */\n\n// TODO update import path once op is modularized.\nimport {zerosLike} from '../../ops/ops';\nimport {getGlobalTensorClass, Tensor} from '../../tensor';\nimport {Rank} from '../../types';\n\ndeclare module '../../tensor' {\n interface Tensor<R extends Rank = Rank> {\n zerosLike<T extends Tensor>(this: T): T;\n }\n}\n\ngetGlobalTensorClass().prototype.zerosLike = function<T extends Tensor>(\n this: T): T {\n this.throwIfDisposed();\n return zerosLike(this);\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","import setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeReflectConstruct from \"@babel/runtime/helpers/esm/isNativeReflectConstruct\";\nexport default function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n}","import getPrototypeOf from \"@babel/runtime/helpers/esm/getPrototypeOf\";\nimport setPrototypeOf from \"@babel/runtime/helpers/esm/setPrototypeOf\";\nimport isNativeFunction from \"@babel/runtime/helpers/esm/isNativeFunction\";\nimport construct from \"@babel/runtime/helpers/esm/construct\";\nexport default function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !isNativeFunction(Class)) return Class;\n\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return construct(Class, arguments, getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n}","export default function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\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\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\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\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\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 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 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","/**\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\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/**\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 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\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// 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 */\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 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/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 * 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 */\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 * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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} 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, 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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 */\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","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {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\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","/**\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 👋. 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\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 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 {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 {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 {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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {_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 {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 {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 {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 */\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 {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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 {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 {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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 {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 {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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, 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 {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 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, 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, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 {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, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {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 {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 {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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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, 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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, 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 {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 {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 {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 {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 {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 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, Rank, TensorBuffer} from '@tensorflow/tfjs-core';\n\nexport function stridedSliceImpl<R extends Rank>(\n outShape: number[], xBuf: TensorBuffer<R>, strides: number[],\n begin: number[]): TensorBuffer<R> {\n const outBuf = buffer(outShape, xBuf.dtype);\n\n for (let i = 0; i < outBuf.size; i++) {\n const loc = outBuf.indexToLoc(i);\n\n const newLoc: number[] = new Array(loc.length);\n for (let j = 0; j < newLoc.length; j++) {\n newLoc[j] = loc[j] * strides[j] + begin[j];\n }\n outBuf.set(xBuf.get(...newLoc), ...loc);\n }\n\n return outBuf as TensorBuffer<R>;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 {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 {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 {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 {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 {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 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 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {buffer, DataType, Rank, TensorBuffer} from '@tensorflow/tfjs-core';\n\n/**\n * An implementation of the tile kernel shared between webgl and cpu for string\n * tensors only.\n */\n\nexport function tileImpl<R extends Rank>(\n xBuf: TensorBuffer<R, DataType>,\n reps: number[]): TensorBuffer<R, DataType> {\n const newShape: number[] = new Array(xBuf.rank);\n for (let i = 0; i < newShape.length; i++) {\n newShape[i] = xBuf.shape[i] * reps[i];\n }\n const result = buffer(newShape, xBuf.dtype);\n for (let i = 0; i < result.values.length; ++i) {\n const newLoc = result.indexToLoc(i);\n\n const originalLoc: number[] = new Array(xBuf.rank);\n for (let j = 0; j < originalLoc.length; j++) {\n originalLoc[j] = newLoc[j] % xBuf.shape[j];\n }\n\n const originalIndex = xBuf.locToIndex(originalLoc);\n\n result.values[i] = xBuf.values[originalIndex];\n }\n return result as TensorBuffer<R, DataType>;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {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 {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 {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","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the License);\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an AS IS BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 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","/**\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 {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 {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 {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 {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 {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 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 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 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 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 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 * @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 {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 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 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 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 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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 */\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 {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 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 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 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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 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 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 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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\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// tslint:disable-next-line: no-imports-from-dist\nimport '@tensorflow/tfjs-core/dist/public/chained_ops/register_all_chained_ops';\n\nexport * from '@tensorflow/tfjs-core';\nexport * from '@tensorflow/tfjs-layers';\nexport * from '@tensorflow/tfjs-converter';\n\n// Export data api as tf.data\nimport * as data from '@tensorflow/tfjs-data';\nexport {data};\n\n// Import and register backends.\nimport '@tensorflow/tfjs-backend-cpu';\nimport '@tensorflow/tfjs-backend-webgl';\n\n// Import versions of all sub-packages.\nimport {version_core} from '@tensorflow/tfjs-core';\nimport {version_cpu} from '@tensorflow/tfjs-backend-cpu';\nimport {version_webgl} from '@tensorflow/tfjs-backend-webgl';\nimport {version_data} from '@tensorflow/tfjs-data';\nimport {version_layers} from '@tensorflow/tfjs-layers';\nimport {version_converter} from '@tensorflow/tfjs-converter';\nimport {version as version_union} from './version';\n\nexport const version = {\n 'tfjs-core': version_core,\n 'tfjs-backend-cpu': version_cpu,\n 'tfjs-backend-webgl': version_webgl,\n 'tfjs-data': version_data,\n 'tfjs-layers': version_layers,\n 'tfjs-converter': version_converter,\n 'tfjs': version_union\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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","import createNamedContext from \"./createNameContext\";\n\nconst historyContext = /*#__PURE__*/ createNamedContext(\"Router-History\");\nexport default historyContext;\n","// TODO: Replace with React.createContext once we can assume React 16+\nimport createContext from \"mini-create-react-context\";\n\nconst createNamedContext = name => {\n const context = createContext();\n context.displayName = name;\n\n return context;\n};\n\nexport default createNamedContext;\n","// TODO: Replace with React.createContext once we can assume React 16+\nimport createContext from \"mini-create-react-context\";\n\nconst createNamedContext = name => {\n const context = createContext();\n context.displayName = name;\n\n return context;\n};\n\nconst context = /*#__PURE__*/ createNamedContext(\"Router\");\nexport default context;\n","import React from \"react\";\nimport PropTypes from \"prop-types\";\nimport warning from \"tiny-warning\";\n\nimport HistoryContext from \"./HistoryContext.js\";\nimport RouterContext from \"./RouterContext.js\";\n\n/**\n * The public API for putting history on context.\n */\nclass Router extends React.Component {\n static computeRootMatch(pathname) {\n return { path: \"/\", url: \"/\", params: {}, isExact: pathname === \"/\" };\n }\n\n constructor(props) {\n super(props);\n\n this.state = {\n location: props.history.location\n };\n\n // This is a bit of a hack. We have to start listening for location\n // changes here in the constructor in case there are any <Redirect>s\n // on the initial render. If there are, they will replace/push when\n // they mount and since cDM fires in children before parents, we may\n // get a new location before the <Router> is mounted.\n this._isMounted = false;\n this._pendingLocation = null;\n\n if (!props.staticContext) {\n this.unlisten = props.history.listen(location => {\n if (this._isMounted) {\n this.setState({ location });\n } else {\n this._pendingLocation = location;\n }\n });\n }\n }\n\n componentDidMount() {\n this._isMounted = true;\n\n if (this._pendingLocation) {\n this.setState({ location: this._pendingLocation });\n }\n }\n\n componentWillUnmount() {\n if (this.unlisten) this.unlisten();\n }\n\n render() {\n return (\n <RouterContext.Provider\n value={{\n history: this.props.history,\n location: this.state.location,\n match: Router.computeRootMatch(this.state.location.pathname),\n staticContext: this.props.staticContext\n }}\n >\n <HistoryContext.Provider\n children={this.props.children || null}\n value={this.props.history}\n />\n </RouterContext.Provider>\n );\n }\n}\n\nif (__DEV__) {\n Router.propTypes = {\n children: PropTypes.node,\n history: PropTypes.object.isRequired,\n staticContext: PropTypes.object\n };\n\n Router.prototype.componentDidUpdate = function(prevProps) {\n warning(\n prevProps.history === this.props.history,\n \"You cannot change <Router history>\"\n );\n };\n}\n\nexport default Router;\n","import React from \"react\";\nimport PropTypes from \"prop-types\";\nimport { createMemoryHistory as createHistory } from \"history\";\nimport warning from \"tiny-warning\";\n\nimport Router from \"./Router.js\";\n\n/**\n * The public API for a <Router> that stores location in memory.\n */\nclass MemoryRouter extends React.Component {\n history = createHistory(this.props);\n\n render() {\n return <Router history={this.history} children={this.props.children} />;\n }\n}\n\nif (__DEV__) {\n MemoryRouter.propTypes = {\n initialEntries: PropTypes.array,\n initialIndex: PropTypes.number,\n getUserConfirmation: PropTypes.func,\n keyLength: PropTypes.number,\n children: PropTypes.node\n };\n\n MemoryRouter.prototype.componentDidMount = function() {\n warning(\n !this.props.history,\n \"<MemoryRouter> ignores the history prop. To use a custom history, \" +\n \"use `import { Router }` instead of `import { MemoryRouter as Router }`.\"\n );\n };\n}\n\nexport default MemoryRouter;\n","import React from \"react\";\n\nclass Lifecycle extends React.Component {\n componentDidMount() {\n if (this.props.onMount) this.props.onMount.call(this, this);\n }\n\n componentDidUpdate(prevProps) {\n if (this.props.onUpdate) this.props.onUpdate.call(this, this, prevProps);\n }\n\n componentWillUnmount() {\n if (this.props.onUnmount) this.props.onUnmount.call(this, this);\n }\n\n render() {\n return null;\n }\n}\n\nexport default Lifecycle;\n","import pathToRegexp from \"path-to-regexp\";\n\nconst cache = {};\nconst cacheLimit = 10000;\nlet cacheCount = 0;\n\nfunction compilePath(path) {\n if (cache[path]) return cache[path];\n\n const generator = pathToRegexp.compile(path);\n\n if (cacheCount < cacheLimit) {\n cache[path] = generator;\n cacheCount++;\n }\n\n return generator;\n}\n\n/**\n * Public API for generating a URL pathname from a path and parameters.\n */\nfunction generatePath(path = \"/\", params = {}) {\n return path === \"/\" ? path : compilePath(path)(params, { pretty: true });\n}\n\nexport default generatePath;\n","import React from \"react\";\nimport PropTypes from \"prop-types\";\nimport { createLocation, locationsAreEqual } from \"history\";\nimport invariant from \"tiny-invariant\";\n\nimport Lifecycle from \"./Lifecycle.js\";\nimport RouterContext from \"./RouterContext.js\";\nimport generatePath from \"./generatePath.js\";\n\n/**\n * The public API for navigating programmatically with a component.\n */\nfunction Redirect({ computedMatch, to, push = false }) {\n return (\n <RouterContext.Consumer>\n {context => {\n invariant(context, \"You should not use <Redirect> outside a <Router>\");\n\n const { history, staticContext } = context;\n\n const method = push ? history.push : history.replace;\n const location = createLocation(\n computedMatch\n ? typeof to === \"string\"\n ? generatePath(to, computedMatch.params)\n : {\n ...to,\n pathname: generatePath(to.pathname, computedMatch.params)\n }\n : to\n );\n\n // When rendering in a static context,\n // set the new location immediately.\n if (staticContext) {\n method(location);\n return null;\n }\n\n return (\n <Lifecycle\n onMount={() => {\n method(location);\n }}\n onUpdate={(self, prevProps) => {\n const prevLocation = createLocation(prevProps.to);\n if (\n !locationsAreEqual(prevLocation, {\n ...location,\n key: prevLocation.key\n })\n ) {\n method(location);\n }\n }}\n to={to}\n />\n );\n }}\n </RouterContext.Consumer>\n );\n}\n\nif (__DEV__) {\n Redirect.propTypes = {\n push: PropTypes.bool,\n from: PropTypes.string,\n to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired\n };\n}\n\nexport default Redirect;\n","import pathToRegexp from \"path-to-regexp\";\n\nconst cache = {};\nconst cacheLimit = 10000;\nlet cacheCount = 0;\n\nfunction compilePath(path, options) {\n const cacheKey = `${options.end}${options.strict}${options.sensitive}`;\n const pathCache = cache[cacheKey] || (cache[cacheKey] = {});\n\n if (pathCache[path]) return pathCache[path];\n\n const keys = [];\n const regexp = pathToRegexp(path, keys, options);\n const result = { regexp, keys };\n\n if (cacheCount < cacheLimit) {\n pathCache[path] = result;\n cacheCount++;\n }\n\n return result;\n}\n\n/**\n * Public API for matching a URL pathname to a path.\n */\nfunction matchPath(pathname, options = {}) {\n if (typeof options === \"string\" || Array.isArray(options)) {\n options = { path: options };\n }\n\n const { path, exact = false, strict = false, sensitive = false } = options;\n\n const paths = [].concat(path);\n\n return paths.reduce((matched, path) => {\n if (!path && path !== \"\") return null;\n if (matched) return matched;\n\n const { regexp, keys } = compilePath(path, {\n end: exact,\n strict,\n sensitive\n });\n const match = regexp.exec(pathname);\n\n if (!match) return null;\n\n const [url, ...values] = match;\n const isExact = pathname === url;\n\n if (exact && !isExact) return null;\n\n return {\n path, // the path used to match\n url: path === \"/\" && url === \"\" ? \"/\" : url, // the matched portion of the URL\n isExact, // whether or not we matched exactly\n params: keys.reduce((memo, key, index) => {\n memo[key.name] = values[index];\n return memo;\n }, {})\n };\n }, null);\n}\n\nexport default matchPath;\n","import React from \"react\";\nimport { isValidElementType } from \"react-is\";\nimport PropTypes from \"prop-types\";\nimport invariant from \"tiny-invariant\";\nimport warning from \"tiny-warning\";\n\nimport RouterContext from \"./RouterContext.js\";\nimport matchPath from \"./matchPath.js\";\n\nfunction isEmptyChildren(children) {\n return React.Children.count(children) === 0;\n}\n\nfunction evalChildrenDev(children, props, path) {\n const value = children(props);\n\n warning(\n value !== undefined,\n \"You returned `undefined` from the `children` function of \" +\n `<Route${path ? ` path=\"${path}\"` : \"\"}>, but you ` +\n \"should have returned a React element or `null`\"\n );\n\n return value || null;\n}\n\n/**\n * The public API for matching a single path and rendering.\n */\nclass Route extends React.Component {\n render() {\n return (\n <RouterContext.Consumer>\n {context => {\n invariant(context, \"You should not use <Route> outside a <Router>\");\n\n const location = this.props.location || context.location;\n const match = this.props.computedMatch\n ? this.props.computedMatch // <Switch> already computed the match for us\n : this.props.path\n ? matchPath(location.pathname, this.props)\n : context.match;\n\n const props = { ...context, location, match };\n\n let { children, component, render } = this.props;\n\n // Preact uses an empty array as children by\n // default, so use null if that's the case.\n if (Array.isArray(children) && children.length === 0) {\n children = null;\n }\n\n return (\n <RouterContext.Provider value={props}>\n {props.match\n ? children\n ? typeof children === \"function\"\n ? __DEV__\n ? evalChildrenDev(children, props, this.props.path)\n : children(props)\n : children\n : component\n ? React.createElement(component, props)\n : render\n ? render(props)\n : null\n : typeof children === \"function\"\n ? __DEV__\n ? evalChildrenDev(children, props, this.props.path)\n : children(props)\n : null}\n </RouterContext.Provider>\n );\n }}\n </RouterContext.Consumer>\n );\n }\n}\n\nif (__DEV__) {\n Route.propTypes = {\n children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),\n component: (props, propName) => {\n if (props[propName] && !isValidElementType(props[propName])) {\n return new Error(\n `Invalid prop 'component' supplied to 'Route': the prop is not a valid React component`\n );\n }\n },\n exact: PropTypes.bool,\n location: PropTypes.object,\n path: PropTypes.oneOfType([\n PropTypes.string,\n PropTypes.arrayOf(PropTypes.string)\n ]),\n render: PropTypes.func,\n sensitive: PropTypes.bool,\n strict: PropTypes.bool\n };\n\n Route.prototype.componentDidMount = function() {\n warning(\n !(\n this.props.children &&\n !isEmptyChildren(this.props.children) &&\n this.props.component\n ),\n \"You should not use <Route component> and <Route children> in the same route; <Route component> will be ignored\"\n );\n\n warning(\n !(\n this.props.children &&\n !isEmptyChildren(this.props.children) &&\n this.props.render\n ),\n \"You should not use <Route render> and <Route children> in the same route; <Route render> will be ignored\"\n );\n\n warning(\n !(this.props.component && this.props.render),\n \"You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored\"\n );\n };\n\n Route.prototype.componentDidUpdate = function(prevProps) {\n warning(\n !(this.props.location && !prevProps.location),\n '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no \"location\" prop and then provided one on a subsequent render.'\n );\n\n warning(\n !(!this.props.location && prevProps.location),\n '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a \"location\" prop initially but omitted it on a subsequent render.'\n );\n };\n}\n\nexport default Route;\n","import React from \"react\";\nimport PropTypes from \"prop-types\";\nimport { createLocation, createPath } from \"history\";\nimport invariant from \"tiny-invariant\";\nimport warning from \"tiny-warning\";\n\nimport Router from \"./Router.js\";\n\nfunction addLeadingSlash(path) {\n return path.charAt(0) === \"/\" ? path : \"/\" + path;\n}\n\nfunction addBasename(basename, location) {\n if (!basename) return location;\n\n return {\n ...location,\n pathname: addLeadingSlash(basename) + location.pathname\n };\n}\n\nfunction stripBasename(basename, location) {\n if (!basename) return location;\n\n const base = addLeadingSlash(basename);\n\n if (location.pathname.indexOf(base) !== 0) return location;\n\n return {\n ...location,\n pathname: location.pathname.substr(base.length)\n };\n}\n\nfunction createURL(location) {\n return typeof location === \"string\" ? location : createPath(location);\n}\n\nfunction staticHandler(methodName) {\n return () => {\n invariant(false, \"You cannot %s with <StaticRouter>\", methodName);\n };\n}\n\nfunction noop() {}\n\n/**\n * The public top-level API for a \"static\" <Router>, so-called because it\n * can't actually change the current location. Instead, it just records\n * location changes in a context object. Useful mainly in testing and\n * server-rendering scenarios.\n */\nclass StaticRouter extends React.Component {\n navigateTo(location, action) {\n const { basename = \"\", context = {} } = this.props;\n context.action = action;\n context.location = addBasename(basename, createLocation(location));\n context.url = createURL(context.location);\n }\n\n handlePush = location => this.navigateTo(location, \"PUSH\");\n handleReplace = location => this.navigateTo(location, \"REPLACE\");\n handleListen = () => noop;\n handleBlock = () => noop;\n\n render() {\n const { basename = \"\", context = {}, location = \"/\", ...rest } = this.props;\n\n const history = {\n createHref: path => addLeadingSlash(basename + createURL(path)),\n action: \"POP\",\n location: stripBasename(basename, createLocation(location)),\n push: this.handlePush,\n replace: this.handleReplace,\n go: staticHandler(\"go\"),\n goBack: staticHandler(\"goBack\"),\n goForward: staticHandler(\"goForward\"),\n listen: this.handleListen,\n block: this.handleBlock\n };\n\n return <Router {...rest} history={history} staticContext={context} />;\n }\n}\n\nif (__DEV__) {\n StaticRouter.propTypes = {\n basename: PropTypes.string,\n context: PropTypes.object,\n location: PropTypes.oneOfType([PropTypes.string, PropTypes.object])\n };\n\n StaticRouter.prototype.componentDidMount = function() {\n warning(\n !this.props.history,\n \"<StaticRouter> ignores the history prop. To use a custom history, \" +\n \"use `import { Router }` instead of `import { StaticRouter as Router }`.\"\n );\n };\n}\n\nexport default StaticRouter;\n","import React from \"react\";\nimport PropTypes from \"prop-types\";\nimport invariant from \"tiny-invariant\";\nimport warning from \"tiny-warning\";\n\nimport RouterContext from \"./RouterContext.js\";\nimport matchPath from \"./matchPath.js\";\n\n/**\n * The public API for rendering the first <Route> that matches.\n */\nclass Switch extends React.Component {\n render() {\n return (\n <RouterContext.Consumer>\n {context => {\n invariant(context, \"You should not use <Switch> outside a <Router>\");\n\n const location = this.props.location || context.location;\n\n let element, match;\n\n // We use React.Children.forEach instead of React.Children.toArray().find()\n // here because toArray adds keys to all child elements and we do not want\n // to trigger an unmount/remount for two <Route>s that render the same\n // component at different URLs.\n React.Children.forEach(this.props.children, child => {\n if (match == null && React.isValidElement(child)) {\n element = child;\n\n const path = child.props.path || child.props.from;\n\n match = path\n ? matchPath(location.pathname, { ...child.props, path })\n : context.match;\n }\n });\n\n return match\n ? React.cloneElement(element, { location, computedMatch: match })\n : null;\n }}\n </RouterContext.Consumer>\n );\n }\n}\n\nif (__DEV__) {\n Switch.propTypes = {\n children: PropTypes.node,\n location: PropTypes.object\n };\n\n Switch.prototype.componentDidUpdate = function(prevProps) {\n warning(\n !(this.props.location && !prevProps.location),\n '<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no \"location\" prop and then provided one on a subsequent render.'\n );\n\n warning(\n !(!this.props.location && prevProps.location),\n '<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a \"location\" prop initially but omitted it on a subsequent render.'\n );\n };\n}\n\nexport default Switch;\n","import React from \"react\";\nimport invariant from \"tiny-invariant\";\n\nimport Context from \"./RouterContext.js\";\nimport HistoryContext from \"./HistoryContext.js\";\nimport matchPath from \"./matchPath.js\";\n\nconst useContext = React.useContext;\n\nexport function useHistory() {\n if (__DEV__) {\n invariant(\n typeof useContext === \"function\",\n \"You must use React >= 16.8 in order to use useHistory()\"\n );\n }\n\n return useContext(HistoryContext);\n}\n\nexport function useLocation() {\n if (__DEV__) {\n invariant(\n typeof useContext === \"function\",\n \"You must use React >= 16.8 in order to use useLocation()\"\n );\n }\n\n return useContext(Context).location;\n}\n\nexport function useParams() {\n if (__DEV__) {\n invariant(\n typeof useContext === \"function\",\n \"You must use React >= 16.8 in order to use useParams()\"\n );\n }\n\n const match = useContext(Context).match;\n return match ? match.params : {};\n}\n\nexport function useRouteMatch(path) {\n if (__DEV__) {\n invariant(\n typeof useContext === \"function\",\n \"You must use React >= 16.8 in order to use useRouteMatch()\"\n );\n }\n\n const location = useLocation();\n const match = useContext(Context).match;\n\n return path ? matchPath(location.pathname, path) : match;\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\n/**\n * Returns true if the axis specifies the inner most dimensions of the\n * array.\n */\nexport function axesAreInnerMostDims(axes: number[], rank: number): boolean {\n for (let i = 0; i < axes.length; ++i) {\n if (axes[axes.length - i - 1] !== rank - 1 - i) {\n return false;\n }\n }\n return true;\n}\n\nexport function combineLocations(\n outputLoc: number[], reduceLoc: number[], axes: number[]): number[] {\n const rank = outputLoc.length + reduceLoc.length;\n const loc = [];\n let outIdx = 0;\n let reduceIdx = 0;\n   for (let dim = 0; dim < rank; dim++) {\n if (axes.indexOf(dim) === -1) {\n loc.push(outputLoc[outIdx++]);\n } else {\n loc.push(reduceLoc[reduceIdx++]);\n }\n }\n return loc;\n}\n\nexport function computeOutAndReduceShapes(\n aShape: number[], axes: number[]): [number[], number[]] {\n const outShape = [];\n const rank = aShape.length;\n for (let dim = 0; dim < rank; dim++) {\n if (axes.indexOf(dim) === -1) {\n outShape.push(aShape[dim]);\n }\n }\n const reduceShape = axes.map(dim => aShape[dim]);\n return [outShape, reduceShape];\n}\n\nexport function expandShapeToKeepDim(\n shape: number[], axes: number[]): number[] {\n const reduceSubShape = axes.map(x => 1);\n return combineLocations(shape, reduceSubShape, axes);\n}\n\nexport function assertAxesAreInnerMostDims(\n msg: string, axes: number[], rank: number): void {\n util.assert(\n axesAreInnerMostDims(axes, rank),\n () => `${msg} supports only inner-most axes for now. ` +\n `Got axes ${axes} and rank-${rank} input.`);\n}\n\n/**\n * Returns the axes permutation to be used with `tf.transpose`, if such\n * permutation is necessary. Otherwise it returns null. This method is used by\n * operations that operate only on inner-most axes.\n */\nexport function getAxesPermutation(axes: number[], rank: number): number[]|\n null {\n if (axesAreInnerMostDims(axes, rank)) {\n return null;\n }\n const result: number[] = [];\n for (let i = 0; i < rank; ++i) {\n if (axes.indexOf(i) === -1) {\n result.push(i);\n }\n }\n axes.forEach(axis => result.push(axis));\n return result;\n}\n\n/** Returns the axes permutation that undoes the original permutation. */\nexport function getUndoAxesPermutation(axes: number[]): number[] {\n return axes.map((axis, i) => [i, axis])\n .sort((a, b) => a[1] - b[1])\n .map(x => x[0]);\n}\n\nexport function getInnerMostAxes(numAxes: number, rank: number): number[] {\n const res: number[] = [];\n for (let i = rank - numAxes; i < rank; ++i) {\n res.push(i);\n }\n return res;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n setPrototypeOf(subClass, superClass);\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 * 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 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer<R extends Rank, D extends DataType = 'float32'>(\n shape: ShapeMap[R], dtype: D = 'float32' as D,\n values?: DataTypeMap[D]): TensorBuffer<R, D> {\n dtype = dtype || 'float32' as D;\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer<R, D>(shape, dtype, values);\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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","export default function ownerDocument(node) {\n return node && node.ownerDocument || document;\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","import * as React from 'react';\nvar useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n/**\n * https://github.com/facebook/react/issues/14099#issuecomment-440013892\n *\n * @param {function} fn\n */\n\nexport default function useEventCallback(fn) {\n var ref = React.useRef(fn);\n useEnhancedEffect(function () {\n ref.current = fn;\n });\n return React.useCallback(function () {\n return (0, ref.current).apply(void 0, arguments);\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 */\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n userSelect: 'none',\n width: '1em',\n height: '1em',\n display: 'inline-block',\n fill: 'currentColor',\n flexShrink: 0,\n fontSize: theme.typography.pxToRem(24),\n transition: theme.transitions.create('fill', {\n duration: theme.transitions.duration.shorter\n })\n },\n\n /* Styles applied to the root element if `color=\"primary\"`. */\n colorPrimary: {\n color: theme.palette.primary.main\n },\n\n /* Styles applied to the root element if `color=\"secondary\"`. */\n colorSecondary: {\n color: theme.palette.secondary.main\n },\n\n /* Styles applied to the root element if `color=\"action\"`. */\n colorAction: {\n color: theme.palette.action.active\n },\n\n /* Styles applied to the root element if `color=\"error\"`. */\n colorError: {\n color: theme.palette.error.main\n },\n\n /* Styles applied to the root element if `color=\"disabled\"`. */\n colorDisabled: {\n color: theme.palette.action.disabled\n },\n\n /* Styles applied to the root element if `fontSize=\"inherit\"`. */\n fontSizeInherit: {\n fontSize: 'inherit'\n },\n\n /* Styles applied to the root element if `fontSize=\"small\"`. */\n fontSizeSmall: {\n fontSize: theme.typography.pxToRem(20)\n },\n\n /* Styles applied to the root element if `fontSize=\"large\"`. */\n fontSizeLarge: {\n fontSize: theme.typography.pxToRem(35)\n }\n };\n};\nvar SvgIcon = /*#__PURE__*/React.forwardRef(function SvgIcon(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'inherit' : _props$color,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'svg' : _props$component,\n _props$fontSize = props.fontSize,\n fontSize = _props$fontSize === void 0 ? 'default' : _props$fontSize,\n htmlColor = props.htmlColor,\n titleAccess = props.titleAccess,\n _props$viewBox = props.viewBox,\n viewBox = _props$viewBox === void 0 ? '0 0 24 24' : _props$viewBox,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"color\", \"component\", \"fontSize\", \"htmlColor\", \"titleAccess\", \"viewBox\"]);\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, color !== 'inherit' && classes[\"color\".concat(capitalize(color))], fontSize !== 'default' && classes[\"fontSize\".concat(capitalize(fontSize))]),\n focusable: \"false\",\n viewBox: viewBox,\n color: htmlColor,\n \"aria-hidden\": titleAccess ? undefined : true,\n role: titleAccess ? 'img' : undefined,\n ref: ref\n }, other), children, titleAccess ? /*#__PURE__*/React.createElement(\"title\", null, titleAccess) : null);\n});\nprocess.env.NODE_ENV !== \"production\" ? SvgIcon.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * Node passed into the SVG element.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n * You can use the `htmlColor` prop to apply a color attribute to the SVG element.\n */\n color: PropTypes.oneOf(['action', 'disabled', 'error', 'inherit', 'primary', 'secondary']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * The fontSize applied to the icon. Defaults to 24px, but can be configure to inherit font size.\n */\n fontSize: PropTypes.oneOf(['default', 'inherit', 'large', 'small']),\n\n /**\n * Applies a color attribute to the SVG element.\n */\n htmlColor: PropTypes.string,\n\n /**\n * The shape-rendering attribute. The behavior of the different options is described on the\n * [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering).\n * If you are having issues with blurry icons you should investigate this property.\n */\n shapeRendering: PropTypes.string,\n\n /**\n * Provides a human-readable title for the element that contains it.\n * https://www.w3.org/TR/SVG-access/#Equivalent\n */\n titleAccess: PropTypes.string,\n\n /**\n * Allows you to redefine what the coordinates without units mean inside an SVG element.\n * For example, if the SVG element is 500 (width) by 200 (height),\n * and you pass viewBox=\"0 0 50 20\",\n * this means that the coordinates inside the SVG will go from the top left corner (0,0)\n * to bottom right (50,20) and each unit will be worth 10px.\n */\n viewBox: PropTypes.string\n} : void 0;\nSvgIcon.muiName = 'SvgIcon';\nexport default withStyles(styles, {\n name: 'MuiSvgIcon'\n})(SvgIcon);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport React from 'react';\nimport SvgIcon from '../SvgIcon';\n/**\n * Private module reserved for @material-ui/x packages.\n */\n\nexport default function createSvgIcon(path, displayName) {\n var Component = function Component(props, ref) {\n return /*#__PURE__*/React.createElement(SvgIcon, _extends({\n ref: ref\n }, props), path);\n };\n\n if (process.env.NODE_ENV !== 'production') {\n // Need to set `displayName` on the inner component for React.memo.\n // React prior to 16.14 ignores `displayName` on the wrapper.\n Component.displayName = \"\".concat(displayName, \"Icon\");\n }\n\n Component.muiName = SvgIcon.muiName;\n return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));\n}","var isProduction = process.env.NODE_ENV === 'production';\nvar prefix = 'Invariant failed';\nfunction invariant(condition, message) {\n if (condition) {\n return;\n }\n if (isProduction) {\n throw new Error(prefix);\n }\n throw new Error(prefix + \": \" + (message || ''));\n}\n\nexport default invariant;\n","module.exports = function() {\n\tthrow new Error(\"define cannot be used indirect\");\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","function isAbsolute(pathname) {\n return pathname.charAt(0) === '/';\n}\n\n// About 1.5x faster than the two-arg version of Array#splice()\nfunction spliceOne(list, index) {\n for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {\n list[i] = list[k];\n }\n\n list.pop();\n}\n\n// This implementation is based heavily on node's url.parse\nfunction resolvePathname(to, from) {\n if (from === undefined) from = '';\n\n var toParts = (to && to.split('/')) || [];\n var fromParts = (from && from.split('/')) || [];\n\n var isToAbs = to && isAbsolute(to);\n var isFromAbs = from && isAbsolute(from);\n var mustEndAbs = isToAbs || isFromAbs;\n\n if (to && isAbsolute(to)) {\n // to is absolute\n fromParts = toParts;\n } else if (toParts.length) {\n // to is relative, drop the filename\n fromParts.pop();\n fromParts = fromParts.concat(toParts);\n }\n\n if (!fromParts.length) return '/';\n\n var hasTrailingSlash;\n if (fromParts.length) {\n var last = fromParts[fromParts.length - 1];\n hasTrailingSlash = last === '.' || last === '..' || last === '';\n } else {\n hasTrailingSlash = false;\n }\n\n var up = 0;\n for (var i = fromParts.length; i >= 0; i--) {\n var part = fromParts[i];\n\n if (part === '.') {\n spliceOne(fromParts, i);\n } else if (part === '..') {\n spliceOne(fromParts, i);\n up++;\n } else if (up) {\n spliceOne(fromParts, i);\n up--;\n }\n }\n\n if (!mustEndAbs) for (; up--; up) fromParts.unshift('..');\n\n if (\n mustEndAbs &&\n fromParts[0] !== '' &&\n (!fromParts[0] || !isAbsolute(fromParts[0]))\n )\n fromParts.unshift('');\n\n var result = fromParts.join('/');\n\n if (hasTrailingSlash && result.substr(-1) !== '/') result += '/';\n\n return result;\n}\n\nexport default resolvePathname;\n","function valueOf(obj) {\n return obj.valueOf ? obj.valueOf() : Object.prototype.valueOf.call(obj);\n}\n\nfunction valueEqual(a, b) {\n // Test for strict equality first.\n if (a === b) return true;\n\n // Otherwise, if either of them == null they are not equal.\n if (a == null || b == null) return false;\n\n if (Array.isArray(a)) {\n return (\n Array.isArray(b) &&\n a.length === b.length &&\n a.every(function(item, index) {\n return valueEqual(item, b[index]);\n })\n );\n }\n\n if (typeof a === 'object' || typeof b === 'object') {\n var aValue = valueOf(a);\n var bValue = valueOf(b);\n\n if (aValue !== a || bValue !== b) return valueEqual(aValue, bValue);\n\n return Object.keys(Object.assign({}, a, b)).every(function(key) {\n return valueEqual(a[key], b[key]);\n });\n }\n\n return false;\n}\n\nexport default valueEqual;\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport resolvePathname from 'resolve-pathname';\nimport valueEqual from 'value-equal';\nimport warning from 'tiny-warning';\nimport invariant from 'tiny-invariant';\n\nfunction addLeadingSlash(path) {\n return path.charAt(0) === '/' ? path : '/' + path;\n}\nfunction stripLeadingSlash(path) {\n return path.charAt(0) === '/' ? path.substr(1) : path;\n}\nfunction hasBasename(path, prefix) {\n return path.toLowerCase().indexOf(prefix.toLowerCase()) === 0 && '/?#'.indexOf(path.charAt(prefix.length)) !== -1;\n}\nfunction stripBasename(path, prefix) {\n return hasBasename(path, prefix) ? path.substr(prefix.length) : path;\n}\nfunction stripTrailingSlash(path) {\n return path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path;\n}\nfunction parsePath(path) {\n var pathname = path || '/';\n var search = '';\n var hash = '';\n var hashIndex = pathname.indexOf('#');\n\n if (hashIndex !== -1) {\n hash = pathname.substr(hashIndex);\n pathname = pathname.substr(0, hashIndex);\n }\n\n var searchIndex = pathname.indexOf('?');\n\n if (searchIndex !== -1) {\n search = pathname.substr(searchIndex);\n pathname = pathname.substr(0, searchIndex);\n }\n\n return {\n pathname: pathname,\n search: search === '?' ? '' : search,\n hash: hash === '#' ? '' : hash\n };\n}\nfunction createPath(location) {\n var pathname = location.pathname,\n search = location.search,\n hash = location.hash;\n var path = pathname || '/';\n if (search && search !== '?') path += search.charAt(0) === '?' ? search : \"?\" + search;\n if (hash && hash !== '#') path += hash.charAt(0) === '#' ? hash : \"#\" + hash;\n return path;\n}\n\nfunction createLocation(path, state, key, currentLocation) {\n var location;\n\n if (typeof path === 'string') {\n // Two-arg form: push(path, state)\n location = parsePath(path);\n location.state = state;\n } else {\n // One-arg form: push(location)\n location = _extends({}, path);\n if (location.pathname === undefined) location.pathname = '';\n\n if (location.search) {\n if (location.search.charAt(0) !== '?') location.search = '?' + location.search;\n } else {\n location.search = '';\n }\n\n if (location.hash) {\n if (location.hash.charAt(0) !== '#') location.hash = '#' + location.hash;\n } else {\n location.hash = '';\n }\n\n if (state !== undefined && location.state === undefined) location.state = state;\n }\n\n try {\n location.pathname = decodeURI(location.pathname);\n } catch (e) {\n if (e instanceof URIError) {\n throw new URIError('Pathname \"' + location.pathname + '\" could not be decoded. ' + 'This is likely caused by an invalid percent-encoding.');\n } else {\n throw e;\n }\n }\n\n if (key) location.key = key;\n\n if (currentLocation) {\n // Resolve incomplete/relative pathname relative to current location.\n if (!location.pathname) {\n location.pathname = currentLocation.pathname;\n } else if (location.pathname.charAt(0) !== '/') {\n location.pathname = resolvePathname(location.pathname, currentLocation.pathname);\n }\n } else {\n // When there is no prior location and pathname is empty, set it to /\n if (!location.pathname) {\n location.pathname = '/';\n }\n }\n\n return location;\n}\nfunction locationsAreEqual(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && a.key === b.key && valueEqual(a.state, b.state);\n}\n\nfunction createTransitionManager() {\n var prompt = null;\n\n function setPrompt(nextPrompt) {\n process.env.NODE_ENV !== \"production\" ? warning(prompt == null, 'A history supports only one prompt at a time') : void 0;\n prompt = nextPrompt;\n return function () {\n if (prompt === nextPrompt) prompt = null;\n };\n }\n\n function confirmTransitionTo(location, action, getUserConfirmation, callback) {\n // TODO: If another transition starts while we're still confirming\n // the previous one, we may end up in a weird state. Figure out the\n // best way to handle this.\n if (prompt != null) {\n var result = typeof prompt === 'function' ? prompt(location, action) : prompt;\n\n if (typeof result === 'string') {\n if (typeof getUserConfirmation === 'function') {\n getUserConfirmation(result, callback);\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'A history needs a getUserConfirmation function in order to use a prompt message') : void 0;\n callback(true);\n }\n } else {\n // Return false from a transition hook to cancel the transition.\n callback(result !== false);\n }\n } else {\n callback(true);\n }\n }\n\n var listeners = [];\n\n function appendListener(fn) {\n var isActive = true;\n\n function listener() {\n if (isActive) fn.apply(void 0, arguments);\n }\n\n listeners.push(listener);\n return function () {\n isActive = false;\n listeners = listeners.filter(function (item) {\n return item !== listener;\n });\n };\n }\n\n function notifyListeners() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n listeners.forEach(function (listener) {\n return listener.apply(void 0, args);\n });\n }\n\n return {\n setPrompt: setPrompt,\n confirmTransitionTo: confirmTransitionTo,\n appendListener: appendListener,\n notifyListeners: notifyListeners\n };\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\nfunction getConfirmation(message, callback) {\n callback(window.confirm(message)); // eslint-disable-line no-alert\n}\n/**\n * Returns true if the HTML5 history API is supported. Taken from Modernizr.\n *\n * https://github.com/Modernizr/Modernizr/blob/master/LICENSE\n * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js\n * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586\n */\n\nfunction supportsHistory() {\n var ua = window.navigator.userAgent;\n if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false;\n return window.history && 'pushState' in window.history;\n}\n/**\n * Returns true if browser fires popstate on hash change.\n * IE10 and IE11 do not.\n */\n\nfunction supportsPopStateOnHashChange() {\n return window.navigator.userAgent.indexOf('Trident') === -1;\n}\n/**\n * Returns false if using go(n) with hash history causes a full page reload.\n */\n\nfunction supportsGoWithoutReloadUsingHash() {\n return window.navigator.userAgent.indexOf('Firefox') === -1;\n}\n/**\n * Returns true if a given popstate event is an extraneous WebKit event.\n * Accounts for the fact that Chrome on iOS fires real popstate events\n * containing undefined state when pressing the back button.\n */\n\nfunction isExtraneousPopstateEvent(event) {\n return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1;\n}\n\nvar PopStateEvent = 'popstate';\nvar HashChangeEvent = 'hashchange';\n\nfunction getHistoryState() {\n try {\n return window.history.state || {};\n } catch (e) {\n // IE 11 sometimes throws when accessing window.history.state\n // See https://github.com/ReactTraining/history/pull/289\n return {};\n }\n}\n/**\n * Creates a history object that uses the HTML5 history API including\n * pushState, replaceState, and the popstate event.\n */\n\n\nfunction createBrowserHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n !canUseDOM ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Browser history needs a DOM') : invariant(false) : void 0;\n var globalHistory = window.history;\n var canUseHistory = supportsHistory();\n var needsHashChangeListener = !supportsPopStateOnHashChange();\n var _props = props,\n _props$forceRefresh = _props.forceRefresh,\n forceRefresh = _props$forceRefresh === void 0 ? false : _props$forceRefresh,\n _props$getUserConfirm = _props.getUserConfirmation,\n getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm,\n _props$keyLength = _props.keyLength,\n keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;\n var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';\n\n function getDOMLocation(historyState) {\n var _ref = historyState || {},\n key = _ref.key,\n state = _ref.state;\n\n var _window$location = window.location,\n pathname = _window$location.pathname,\n search = _window$location.search,\n hash = _window$location.hash;\n var path = pathname + search + hash;\n process.env.NODE_ENV !== \"production\" ? warning(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path \"' + path + '\" to begin with \"' + basename + '\".') : void 0;\n if (basename) path = stripBasename(path, basename);\n return createLocation(path, state, key);\n }\n\n function createKey() {\n return Math.random().toString(36).substr(2, keyLength);\n }\n\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n _extends(history, nextState);\n\n history.length = globalHistory.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n function handlePopState(event) {\n // Ignore extraneous popstate events in WebKit.\n if (isExtraneousPopstateEvent(event)) return;\n handlePop(getDOMLocation(event.state));\n }\n\n function handleHashChange() {\n handlePop(getDOMLocation(getHistoryState()));\n }\n\n var forceNextPop = false;\n\n function handlePop(location) {\n if (forceNextPop) {\n forceNextPop = false;\n setState();\n } else {\n var action = 'POP';\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location\n });\n } else {\n revertPop(location);\n }\n });\n }\n }\n\n function revertPop(fromLocation) {\n var toLocation = history.location; // TODO: We could probably make this more reliable by\n // keeping a list of keys we've seen in sessionStorage.\n // Instead, we just default to 0 for keys we don't know.\n\n var toIndex = allKeys.indexOf(toLocation.key);\n if (toIndex === -1) toIndex = 0;\n var fromIndex = allKeys.indexOf(fromLocation.key);\n if (fromIndex === -1) fromIndex = 0;\n var delta = toIndex - fromIndex;\n\n if (delta) {\n forceNextPop = true;\n go(delta);\n }\n }\n\n var initialLocation = getDOMLocation(getHistoryState());\n var allKeys = [initialLocation.key]; // Public interface\n\n function createHref(location) {\n return basename + createPath(location);\n }\n\n function push(path, state) {\n process.env.NODE_ENV !== \"production\" ? warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : void 0;\n var action = 'PUSH';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var href = createHref(location);\n var key = location.key,\n state = location.state;\n\n if (canUseHistory) {\n globalHistory.pushState({\n key: key,\n state: state\n }, null, href);\n\n if (forceRefresh) {\n window.location.href = href;\n } else {\n var prevIndex = allKeys.indexOf(history.location.key);\n var nextKeys = allKeys.slice(0, prevIndex + 1);\n nextKeys.push(location.key);\n allKeys = nextKeys;\n setState({\n action: action,\n location: location\n });\n }\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(state === undefined, 'Browser history cannot push state in browsers that do not support HTML5 history') : void 0;\n window.location.href = href;\n }\n });\n }\n\n function replace(path, state) {\n process.env.NODE_ENV !== \"production\" ? warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : void 0;\n var action = 'REPLACE';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var href = createHref(location);\n var key = location.key,\n state = location.state;\n\n if (canUseHistory) {\n globalHistory.replaceState({\n key: key,\n state: state\n }, null, href);\n\n if (forceRefresh) {\n window.location.replace(href);\n } else {\n var prevIndex = allKeys.indexOf(history.location.key);\n if (prevIndex !== -1) allKeys[prevIndex] = location.key;\n setState({\n action: action,\n location: location\n });\n }\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(state === undefined, 'Browser history cannot replace state in browsers that do not support HTML5 history') : void 0;\n window.location.replace(href);\n }\n });\n }\n\n function go(n) {\n globalHistory.go(n);\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n var listenerCount = 0;\n\n function checkDOMListeners(delta) {\n listenerCount += delta;\n\n if (listenerCount === 1 && delta === 1) {\n window.addEventListener(PopStateEvent, handlePopState);\n if (needsHashChangeListener) window.addEventListener(HashChangeEvent, handleHashChange);\n } else if (listenerCount === 0) {\n window.removeEventListener(PopStateEvent, handlePopState);\n if (needsHashChangeListener) window.removeEventListener(HashChangeEvent, handleHashChange);\n }\n }\n\n var isBlocked = false;\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n var unblock = transitionManager.setPrompt(prompt);\n\n if (!isBlocked) {\n checkDOMListeners(1);\n isBlocked = true;\n }\n\n return function () {\n if (isBlocked) {\n isBlocked = false;\n checkDOMListeners(-1);\n }\n\n return unblock();\n };\n }\n\n function listen(listener) {\n var unlisten = transitionManager.appendListener(listener);\n checkDOMListeners(1);\n return function () {\n checkDOMListeners(-1);\n unlisten();\n };\n }\n\n var history = {\n length: globalHistory.length,\n action: 'POP',\n location: initialLocation,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n block: block,\n listen: listen\n };\n return history;\n}\n\nvar HashChangeEvent$1 = 'hashchange';\nvar HashPathCoders = {\n hashbang: {\n encodePath: function encodePath(path) {\n return path.charAt(0) === '!' ? path : '!/' + stripLeadingSlash(path);\n },\n decodePath: function decodePath(path) {\n return path.charAt(0) === '!' ? path.substr(1) : path;\n }\n },\n noslash: {\n encodePath: stripLeadingSlash,\n decodePath: addLeadingSlash\n },\n slash: {\n encodePath: addLeadingSlash,\n decodePath: addLeadingSlash\n }\n};\n\nfunction stripHash(url) {\n var hashIndex = url.indexOf('#');\n return hashIndex === -1 ? url : url.slice(0, hashIndex);\n}\n\nfunction getHashPath() {\n // We can't use window.location.hash here because it's not\n // consistent across browsers - Firefox will pre-decode it!\n var href = window.location.href;\n var hashIndex = href.indexOf('#');\n return hashIndex === -1 ? '' : href.substring(hashIndex + 1);\n}\n\nfunction pushHashPath(path) {\n window.location.hash = path;\n}\n\nfunction replaceHashPath(path) {\n window.location.replace(stripHash(window.location.href) + '#' + path);\n}\n\nfunction createHashHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n !canUseDOM ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Hash history needs a DOM') : invariant(false) : void 0;\n var globalHistory = window.history;\n var canGoWithoutReload = supportsGoWithoutReloadUsingHash();\n var _props = props,\n _props$getUserConfirm = _props.getUserConfirmation,\n getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm,\n _props$hashType = _props.hashType,\n hashType = _props$hashType === void 0 ? 'slash' : _props$hashType;\n var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';\n var _HashPathCoders$hashT = HashPathCoders[hashType],\n encodePath = _HashPathCoders$hashT.encodePath,\n decodePath = _HashPathCoders$hashT.decodePath;\n\n function getDOMLocation() {\n var path = decodePath(getHashPath());\n process.env.NODE_ENV !== \"production\" ? warning(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path \"' + path + '\" to begin with \"' + basename + '\".') : void 0;\n if (basename) path = stripBasename(path, basename);\n return createLocation(path);\n }\n\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n _extends(history, nextState);\n\n history.length = globalHistory.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n var forceNextPop = false;\n var ignorePath = null;\n\n function locationsAreEqual$$1(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash;\n }\n\n function handleHashChange() {\n var path = getHashPath();\n var encodedPath = encodePath(path);\n\n if (path !== encodedPath) {\n // Ensure we always have a properly-encoded hash.\n replaceHashPath(encodedPath);\n } else {\n var location = getDOMLocation();\n var prevLocation = history.location;\n if (!forceNextPop && locationsAreEqual$$1(prevLocation, location)) return; // A hashchange doesn't always == location change.\n\n if (ignorePath === createPath(location)) return; // Ignore this change; we already setState in push/replace.\n\n ignorePath = null;\n handlePop(location);\n }\n }\n\n function handlePop(location) {\n if (forceNextPop) {\n forceNextPop = false;\n setState();\n } else {\n var action = 'POP';\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location\n });\n } else {\n revertPop(location);\n }\n });\n }\n }\n\n function revertPop(fromLocation) {\n var toLocation = history.location; // TODO: We could probably make this more reliable by\n // keeping a list of paths we've seen in sessionStorage.\n // Instead, we just default to 0 for paths we don't know.\n\n var toIndex = allPaths.lastIndexOf(createPath(toLocation));\n if (toIndex === -1) toIndex = 0;\n var fromIndex = allPaths.lastIndexOf(createPath(fromLocation));\n if (fromIndex === -1) fromIndex = 0;\n var delta = toIndex - fromIndex;\n\n if (delta) {\n forceNextPop = true;\n go(delta);\n }\n } // Ensure the hash is encoded properly before doing anything else.\n\n\n var path = getHashPath();\n var encodedPath = encodePath(path);\n if (path !== encodedPath) replaceHashPath(encodedPath);\n var initialLocation = getDOMLocation();\n var allPaths = [createPath(initialLocation)]; // Public interface\n\n function createHref(location) {\n var baseTag = document.querySelector('base');\n var href = '';\n\n if (baseTag && baseTag.getAttribute('href')) {\n href = stripHash(window.location.href);\n }\n\n return href + '#' + encodePath(basename + createPath(location));\n }\n\n function push(path, state) {\n process.env.NODE_ENV !== \"production\" ? warning(state === undefined, 'Hash history cannot push state; it is ignored') : void 0;\n var action = 'PUSH';\n var location = createLocation(path, undefined, undefined, history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var path = createPath(location);\n var encodedPath = encodePath(basename + path);\n var hashChanged = getHashPath() !== encodedPath;\n\n if (hashChanged) {\n // We cannot tell if a hashchange was caused by a PUSH, so we'd\n // rather setState here and ignore the hashchange. The caveat here\n // is that other hash histories in the page will consider it a POP.\n ignorePath = path;\n pushHashPath(encodedPath);\n var prevIndex = allPaths.lastIndexOf(createPath(history.location));\n var nextPaths = allPaths.slice(0, prevIndex + 1);\n nextPaths.push(path);\n allPaths = nextPaths;\n setState({\n action: action,\n location: location\n });\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(false, 'Hash history cannot PUSH the same path; a new entry will not be added to the history stack') : void 0;\n setState();\n }\n });\n }\n\n function replace(path, state) {\n process.env.NODE_ENV !== \"production\" ? warning(state === undefined, 'Hash history cannot replace state; it is ignored') : void 0;\n var action = 'REPLACE';\n var location = createLocation(path, undefined, undefined, history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var path = createPath(location);\n var encodedPath = encodePath(basename + path);\n var hashChanged = getHashPath() !== encodedPath;\n\n if (hashChanged) {\n // We cannot tell if a hashchange was caused by a REPLACE, so we'd\n // rather setState here and ignore the hashchange. The caveat here\n // is that other hash histories in the page will consider it a POP.\n ignorePath = path;\n replaceHashPath(encodedPath);\n }\n\n var prevIndex = allPaths.indexOf(createPath(history.location));\n if (prevIndex !== -1) allPaths[prevIndex] = path;\n setState({\n action: action,\n location: location\n });\n });\n }\n\n function go(n) {\n process.env.NODE_ENV !== \"production\" ? warning(canGoWithoutReload, 'Hash history go(n) causes a full page reload in this browser') : void 0;\n globalHistory.go(n);\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n var listenerCount = 0;\n\n function checkDOMListeners(delta) {\n listenerCount += delta;\n\n if (listenerCount === 1 && delta === 1) {\n window.addEventListener(HashChangeEvent$1, handleHashChange);\n } else if (listenerCount === 0) {\n window.removeEventListener(HashChangeEvent$1, handleHashChange);\n }\n }\n\n var isBlocked = false;\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n var unblock = transitionManager.setPrompt(prompt);\n\n if (!isBlocked) {\n checkDOMListeners(1);\n isBlocked = true;\n }\n\n return function () {\n if (isBlocked) {\n isBlocked = false;\n checkDOMListeners(-1);\n }\n\n return unblock();\n };\n }\n\n function listen(listener) {\n var unlisten = transitionManager.appendListener(listener);\n checkDOMListeners(1);\n return function () {\n checkDOMListeners(-1);\n unlisten();\n };\n }\n\n var history = {\n length: globalHistory.length,\n action: 'POP',\n location: initialLocation,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n block: block,\n listen: listen\n };\n return history;\n}\n\nfunction clamp(n, lowerBound, upperBound) {\n return Math.min(Math.max(n, lowerBound), upperBound);\n}\n/**\n * Creates a history object that stores locations in memory.\n */\n\n\nfunction createMemoryHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n var _props = props,\n getUserConfirmation = _props.getUserConfirmation,\n _props$initialEntries = _props.initialEntries,\n initialEntries = _props$initialEntries === void 0 ? ['/'] : _props$initialEntries,\n _props$initialIndex = _props.initialIndex,\n initialIndex = _props$initialIndex === void 0 ? 0 : _props$initialIndex,\n _props$keyLength = _props.keyLength,\n keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n _extends(history, nextState);\n\n history.length = history.entries.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n function createKey() {\n return Math.random().toString(36).substr(2, keyLength);\n }\n\n var index = clamp(initialIndex, 0, initialEntries.length - 1);\n var entries = initialEntries.map(function (entry) {\n return typeof entry === 'string' ? createLocation(entry, undefined, createKey()) : createLocation(entry, undefined, entry.key || createKey());\n }); // Public interface\n\n var createHref = createPath;\n\n function push(path, state) {\n process.env.NODE_ENV !== \"production\" ? warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : void 0;\n var action = 'PUSH';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var prevIndex = history.index;\n var nextIndex = prevIndex + 1;\n var nextEntries = history.entries.slice(0);\n\n if (nextEntries.length > nextIndex) {\n nextEntries.splice(nextIndex, nextEntries.length - nextIndex, location);\n } else {\n nextEntries.push(location);\n }\n\n setState({\n action: action,\n location: location,\n index: nextIndex,\n entries: nextEntries\n });\n });\n }\n\n function replace(path, state) {\n process.env.NODE_ENV !== \"production\" ? warning(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : void 0;\n var action = 'REPLACE';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n history.entries[history.index] = location;\n setState({\n action: action,\n location: location\n });\n });\n }\n\n function go(n) {\n var nextIndex = clamp(history.index + n, 0, history.entries.length - 1);\n var action = 'POP';\n var location = history.entries[nextIndex];\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location,\n index: nextIndex\n });\n } else {\n // Mimic the behavior of DOM histories by\n // causing a render after a cancelled POP.\n setState();\n }\n });\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n function canGo(n) {\n var nextIndex = history.index + n;\n return nextIndex >= 0 && nextIndex < history.entries.length;\n }\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n return transitionManager.setPrompt(prompt);\n }\n\n function listen(listener) {\n return transitionManager.appendListener(listener);\n }\n\n var history = {\n length: entries.length,\n action: 'POP',\n location: entries[index],\n index: index,\n entries: entries,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n canGo: canGo,\n block: block,\n listen: listen\n };\n return history;\n}\n\nexport { createBrowserHistory, createHashHistory, createMemoryHistory, createLocation, locationsAreEqual, parsePath, createPath };\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","import { useTheme as useThemeWithoutDefault } from '@material-ui/styles';\nimport React from 'react';\nimport defaultTheme from './defaultTheme';\nexport default function useTheme() {\n var theme = useThemeWithoutDefault() || defaultTheme;\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(theme);\n }\n\n return theme;\n}","import arrayWithoutHoles from \"./arrayWithoutHoles.js\";\nimport iterableToArray from \"./iterableToArray.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableSpread from \"./nonIterableSpread.js\";\nexport default function _toConsumableArray(arr) {\n return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return arrayLikeToArray(arr);\n}","export default function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","// A library of seedable RNGs implemented in Javascript.\n//\n// Usage:\n//\n// var seedrandom = require('seedrandom');\n// var random = seedrandom(1); // or any seed.\n// var x = random(); // 0 <= x < 1. Every bit is random.\n// var x = random.quick(); // 0 <= x < 1. 32 bits of randomness.\n\n// alea, a 53-bit multiply-with-carry generator by Johannes Baagøe.\n// Period: ~2^116\n// Reported to pass all BigCrush tests.\nvar alea = require('./lib/alea');\n\n// xor128, a pure xor-shift generator by George Marsaglia.\n// Period: 2^128-1.\n// Reported to fail: MatrixRank and LinearComp.\nvar xor128 = require('./lib/xor128');\n\n// xorwow, George Marsaglia's 160-bit xor-shift combined plus weyl.\n// Period: 2^192-2^32\n// Reported to fail: CollisionOver, SimpPoker, and LinearComp.\nvar xorwow = require('./lib/xorwow');\n\n// xorshift7, by François Panneton and Pierre L'ecuyer, takes\n// a different approach: it adds robustness by allowing more shifts\n// than Marsaglia's original three. It is a 7-shift generator\n// with 256 bits, that passes BigCrush with no systmatic failures.\n// Period 2^256-1.\n// No systematic BigCrush failures reported.\nvar xorshift7 = require('./lib/xorshift7');\n\n// xor4096, by Richard Brent, is a 4096-bit xor-shift with a\n// very long period that also adds a Weyl generator. It also passes\n// BigCrush with no systematic failures. Its long period may\n// be useful if you have many generators and need to avoid\n// collisions.\n// Period: 2^4128-2^32.\n// No systematic BigCrush failures reported.\nvar xor4096 = require('./lib/xor4096');\n\n// Tyche-i, by Samuel Neves and Filipe Araujo, is a bit-shifting random\n// number generator derived from ChaCha, a modern stream cipher.\n// https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n// Period: ~2^127\n// No systematic BigCrush failures reported.\nvar tychei = require('./lib/tychei');\n\n// The original ARC4-based prng included in this library.\n// Period: ~2^1600\nvar sr = require('./seedrandom');\n\nsr.alea = alea;\nsr.xor128 = xor128;\nsr.xorwow = xorwow;\nsr.xorshift7 = xorshift7;\nsr.xor4096 = xor4096;\nsr.tychei = tychei;\n\nmodule.exports = sr;\n","/**\n * @license\n * Copyright 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","var isProduction = process.env.NODE_ENV === 'production';\nfunction warning(condition, message) {\n if (!isProduction) {\n if (condition) {\n return;\n }\n\n var text = \"Warning: \" + message;\n\n if (typeof console !== 'undefined') {\n console.warn(text);\n }\n\n try {\n throw Error(text);\n } catch (x) {}\n }\n}\n\nexport default warning;\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","// Corresponds to 10 frames at 60 Hz.\n// A few bytes payload overhead when lodash/debounce is ~3 kB and debounce ~300 B.\nexport default function debounce(func) {\n var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 166;\n var timeout;\n\n function debounced() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n // eslint-disable-next-line consistent-this\n var that = this;\n\n var later = function later() {\n func.apply(that, args);\n };\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n }\n\n debounced.clear = function () {\n clearTimeout(timeout);\n };\n\n return debounced;\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 */\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 {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 */\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 */\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 {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 LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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","import arrayLikeToArray from \"@babel/runtime/helpers/esm/arrayLikeToArray\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 * 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","import { deepmerge } from '@material-ui/utils';\n\nfunction merge(acc, item) {\n if (!item) {\n return acc;\n }\n\n return deepmerge(acc, item, {\n clone: false // No need to clone deep, it's way faster.\n\n });\n}\n\nexport default merge;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\n// Sorted ASC by size. That's important.\n// It can't be configured as it's used statically for propTypes.\nexport var keys = ['xs', 'sm', 'md', 'lg', 'xl']; // Keep in mind that @media is inclusive by the CSS specification.\n\nexport default function createBreakpoints(breakpoints) {\n var _breakpoints$values = breakpoints.values,\n values = _breakpoints$values === void 0 ? {\n xs: 0,\n sm: 600,\n md: 960,\n lg: 1280,\n xl: 1920\n } : _breakpoints$values,\n _breakpoints$unit = breakpoints.unit,\n unit = _breakpoints$unit === void 0 ? 'px' : _breakpoints$unit,\n _breakpoints$step = breakpoints.step,\n step = _breakpoints$step === void 0 ? 5 : _breakpoints$step,\n other = _objectWithoutProperties(breakpoints, [\"values\", \"unit\", \"step\"]);\n\n function up(key) {\n var value = typeof values[key] === 'number' ? values[key] : key;\n return \"@media (min-width:\".concat(value).concat(unit, \")\");\n }\n\n function down(key) {\n var endIndex = keys.indexOf(key) + 1;\n var upperbound = values[keys[endIndex]];\n\n if (endIndex === keys.length) {\n // xl down applies to all sizes\n return up('xs');\n }\n\n var value = typeof upperbound === 'number' && endIndex > 0 ? upperbound : key;\n return \"@media (max-width:\".concat(value - step / 100).concat(unit, \")\");\n }\n\n function between(start, end) {\n var endIndex = keys.indexOf(end);\n\n if (endIndex === keys.length - 1) {\n return up(start);\n }\n\n return \"@media (min-width:\".concat(typeof values[start] === 'number' ? values[start] : start).concat(unit, \") and \") + \"(max-width:\".concat((endIndex !== -1 && typeof values[keys[endIndex + 1]] === 'number' ? values[keys[endIndex + 1]] : end) - step / 100).concat(unit, \")\");\n }\n\n function only(key) {\n return between(key, key);\n }\n\n function width(key) {\n return values[key];\n }\n\n return _extends({\n keys: keys,\n values: values,\n up: up,\n down: down,\n between: between,\n only: only,\n width: width\n }, other);\n}","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nexport default function createMixins(breakpoints, spacing, mixins) {\n var _toolbar;\n\n return _extends({\n gutters: function gutters() {\n var styles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n // To deprecate in v4.1\n // warning(\n // false,\n // [\n // 'Material-UI: Theme.mixins.gutters() is deprecated.',\n // 'You can use the source of the mixin directly:',\n // `\n // paddingLeft: theme.spacing(2),\n // paddingRight: theme.spacing(2),\n // [theme.breakpoints.up('sm')]: {\n // paddingLeft: theme.spacing(3),\n // paddingRight: theme.spacing(3),\n // },\n // `,\n // ].join('\\n'),\n // );\n return _extends({\n paddingLeft: spacing(2),\n paddingRight: spacing(2)\n }, styles, _defineProperty({}, breakpoints.up('sm'), _extends({\n paddingLeft: spacing(3),\n paddingRight: spacing(3)\n }, styles[breakpoints.up('sm')])));\n },\n toolbar: (_toolbar = {\n minHeight: 56\n }, _defineProperty(_toolbar, \"\".concat(breakpoints.up('xs'), \" and (orientation: landscape)\"), {\n minHeight: 48\n }), _defineProperty(_toolbar, breakpoints.up('sm'), {\n minHeight: 64\n }), _toolbar)\n }, mixins);\n}","var common = {\n black: '#000',\n white: '#fff'\n};\nexport default common;","var grey = {\n 50: '#fafafa',\n 100: '#f5f5f5',\n 200: '#eeeeee',\n 300: '#e0e0e0',\n 400: '#bdbdbd',\n 500: '#9e9e9e',\n 600: '#757575',\n 700: '#616161',\n 800: '#424242',\n 900: '#212121',\n A100: '#d5d5d5',\n A200: '#aaaaaa',\n A400: '#303030',\n A700: '#616161'\n};\nexport default grey;","var indigo = {\n 50: '#e8eaf6',\n 100: '#c5cae9',\n 200: '#9fa8da',\n 300: '#7986cb',\n 400: '#5c6bc0',\n 500: '#3f51b5',\n 600: '#3949ab',\n 700: '#303f9f',\n 800: '#283593',\n 900: '#1a237e',\n A100: '#8c9eff',\n A200: '#536dfe',\n A400: '#3d5afe',\n A700: '#304ffe'\n};\nexport default indigo;","var pink = {\n 50: '#fce4ec',\n 100: '#f8bbd0',\n 200: '#f48fb1',\n 300: '#f06292',\n 400: '#ec407a',\n 500: '#e91e63',\n 600: '#d81b60',\n 700: '#c2185b',\n 800: '#ad1457',\n 900: '#880e4f',\n A100: '#ff80ab',\n A200: '#ff4081',\n A400: '#f50057',\n A700: '#c51162'\n};\nexport default pink;","var red = {\n 50: '#ffebee',\n 100: '#ffcdd2',\n 200: '#ef9a9a',\n 300: '#e57373',\n 400: '#ef5350',\n 500: '#f44336',\n 600: '#e53935',\n 700: '#d32f2f',\n 800: '#c62828',\n 900: '#b71c1c',\n A100: '#ff8a80',\n A200: '#ff5252',\n A400: '#ff1744',\n A700: '#d50000'\n};\nexport default red;","var orange = {\n 50: '#fff3e0',\n 100: '#ffe0b2',\n 200: '#ffcc80',\n 300: '#ffb74d',\n 400: '#ffa726',\n 500: '#ff9800',\n 600: '#fb8c00',\n 700: '#f57c00',\n 800: '#ef6c00',\n 900: '#e65100',\n A100: '#ffd180',\n A200: '#ffab40',\n A400: '#ff9100',\n A700: '#ff6d00'\n};\nexport default orange;","var blue = {\n 50: '#e3f2fd',\n 100: '#bbdefb',\n 200: '#90caf9',\n 300: '#64b5f6',\n 400: '#42a5f5',\n 500: '#2196f3',\n 600: '#1e88e5',\n 700: '#1976d2',\n 800: '#1565c0',\n 900: '#0d47a1',\n A100: '#82b1ff',\n A200: '#448aff',\n A400: '#2979ff',\n A700: '#2962ff'\n};\nexport default blue;","var green = {\n 50: '#e8f5e9',\n 100: '#c8e6c9',\n 200: '#a5d6a7',\n 300: '#81c784',\n 400: '#66bb6a',\n 500: '#4caf50',\n 600: '#43a047',\n 700: '#388e3c',\n 800: '#2e7d32',\n 900: '#1b5e20',\n A100: '#b9f6ca',\n A200: '#69f0ae',\n A400: '#00e676',\n A700: '#00c853'\n};\nexport default green;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\nimport { deepmerge } from '@material-ui/utils';\nimport common from '../colors/common';\nimport grey from '../colors/grey';\nimport indigo from '../colors/indigo';\nimport pink from '../colors/pink';\nimport red from '../colors/red';\nimport orange from '../colors/orange';\nimport blue from '../colors/blue';\nimport green from '../colors/green';\nimport { darken, getContrastRatio, lighten } from './colorManipulator';\nexport var light = {\n // The colors used to style the text.\n text: {\n // The most important text.\n primary: 'rgba(0, 0, 0, 0.87)',\n // Secondary text.\n secondary: 'rgba(0, 0, 0, 0.54)',\n // Disabled text have even lower visual prominence.\n disabled: 'rgba(0, 0, 0, 0.38)',\n // Text hints.\n hint: 'rgba(0, 0, 0, 0.38)'\n },\n // The color used to divide different elements.\n divider: 'rgba(0, 0, 0, 0.12)',\n // The background colors used to style the surfaces.\n // Consistency between these values is important.\n background: {\n paper: common.white,\n default: grey[50]\n },\n // The colors used to style the action elements.\n action: {\n // The color of an active action like an icon button.\n active: 'rgba(0, 0, 0, 0.54)',\n // The color of an hovered action.\n hover: 'rgba(0, 0, 0, 0.04)',\n hoverOpacity: 0.04,\n // The color of a selected action.\n selected: 'rgba(0, 0, 0, 0.08)',\n selectedOpacity: 0.08,\n // The color of a disabled action.\n disabled: 'rgba(0, 0, 0, 0.26)',\n // The background color of a disabled action.\n disabledBackground: 'rgba(0, 0, 0, 0.12)',\n disabledOpacity: 0.38,\n focus: 'rgba(0, 0, 0, 0.12)',\n focusOpacity: 0.12,\n activatedOpacity: 0.12\n }\n};\nexport var dark = {\n text: {\n primary: common.white,\n secondary: 'rgba(255, 255, 255, 0.7)',\n disabled: 'rgba(255, 255, 255, 0.5)',\n hint: 'rgba(255, 255, 255, 0.5)',\n icon: 'rgba(255, 255, 255, 0.5)'\n },\n divider: 'rgba(255, 255, 255, 0.12)',\n background: {\n paper: grey[800],\n default: '#303030'\n },\n action: {\n active: common.white,\n hover: 'rgba(255, 255, 255, 0.08)',\n hoverOpacity: 0.08,\n selected: 'rgba(255, 255, 255, 0.16)',\n selectedOpacity: 0.16,\n disabled: 'rgba(255, 255, 255, 0.3)',\n disabledBackground: 'rgba(255, 255, 255, 0.12)',\n disabledOpacity: 0.38,\n focus: 'rgba(255, 255, 255, 0.12)',\n focusOpacity: 0.12,\n activatedOpacity: 0.24\n }\n};\n\nfunction addLightOrDark(intent, direction, shade, tonalOffset) {\n var tonalOffsetLight = tonalOffset.light || tonalOffset;\n var tonalOffsetDark = tonalOffset.dark || tonalOffset * 1.5;\n\n if (!intent[direction]) {\n if (intent.hasOwnProperty(shade)) {\n intent[direction] = intent[shade];\n } else if (direction === 'light') {\n intent.light = lighten(intent.main, tonalOffsetLight);\n } else if (direction === 'dark') {\n intent.dark = darken(intent.main, tonalOffsetDark);\n }\n }\n}\n\nexport default function createPalette(palette) {\n var _palette$primary = palette.primary,\n primary = _palette$primary === void 0 ? {\n light: indigo[300],\n main: indigo[500],\n dark: indigo[700]\n } : _palette$primary,\n _palette$secondary = palette.secondary,\n secondary = _palette$secondary === void 0 ? {\n light: pink.A200,\n main: pink.A400,\n dark: pink.A700\n } : _palette$secondary,\n _palette$error = palette.error,\n error = _palette$error === void 0 ? {\n light: red[300],\n main: red[500],\n dark: red[700]\n } : _palette$error,\n _palette$warning = palette.warning,\n warning = _palette$warning === void 0 ? {\n light: orange[300],\n main: orange[500],\n dark: orange[700]\n } : _palette$warning,\n _palette$info = palette.info,\n info = _palette$info === void 0 ? {\n light: blue[300],\n main: blue[500],\n dark: blue[700]\n } : _palette$info,\n _palette$success = palette.success,\n success = _palette$success === void 0 ? {\n light: green[300],\n main: green[500],\n dark: green[700]\n } : _palette$success,\n _palette$type = palette.type,\n type = _palette$type === void 0 ? 'light' : _palette$type,\n _palette$contrastThre = palette.contrastThreshold,\n contrastThreshold = _palette$contrastThre === void 0 ? 3 : _palette$contrastThre,\n _palette$tonalOffset = palette.tonalOffset,\n tonalOffset = _palette$tonalOffset === void 0 ? 0.2 : _palette$tonalOffset,\n other = _objectWithoutProperties(palette, [\"primary\", \"secondary\", \"error\", \"warning\", \"info\", \"success\", \"type\", \"contrastThreshold\", \"tonalOffset\"]); // Use the same logic as\n // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59\n // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54\n\n\n function getContrastText(background) {\n var contrastText = getContrastRatio(background, dark.text.primary) >= contrastThreshold ? dark.text.primary : light.text.primary;\n\n if (process.env.NODE_ENV !== 'production') {\n var contrast = getContrastRatio(background, contrastText);\n\n if (contrast < 3) {\n console.error([\"Material-UI: The contrast ratio of \".concat(contrast, \":1 for \").concat(contrastText, \" on \").concat(background), 'falls below the WCAG recommended absolute minimum contrast ratio of 3:1.', 'https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast'].join('\\n'));\n }\n }\n\n return contrastText;\n }\n\n var augmentColor = function augmentColor(color) {\n var mainShade = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500;\n var lightShade = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300;\n var darkShade = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 700;\n color = _extends({}, color);\n\n if (!color.main && color[mainShade]) {\n color.main = color[mainShade];\n }\n\n if (!color.main) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: The color provided to augmentColor(color) is invalid.\\nThe color object needs to have a `main` property or a `\".concat(mainShade, \"` property.\") : _formatMuiErrorMessage(4, mainShade));\n }\n\n if (typeof color.main !== 'string') {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: The color provided to augmentColor(color) is invalid.\\n`color.main` should be a string, but `\".concat(JSON.stringify(color.main), \"` was provided instead.\\n\\nDid you intend to use one of the following approaches?\\n\\nimport {\\xA0green } from \\\"@material-ui/core/colors\\\";\\n\\nconst theme1 = createMuiTheme({ palette: {\\n primary: green,\\n} });\\n\\nconst theme2 = createMuiTheme({ palette: {\\n primary: { main: green[500] },\\n} });\") : _formatMuiErrorMessage(5, JSON.stringify(color.main)));\n }\n\n addLightOrDark(color, 'light', lightShade, tonalOffset);\n addLightOrDark(color, 'dark', darkShade, tonalOffset);\n\n if (!color.contrastText) {\n color.contrastText = getContrastText(color.main);\n }\n\n return color;\n };\n\n var types = {\n dark: dark,\n light: light\n };\n\n if (process.env.NODE_ENV !== 'production') {\n if (!types[type]) {\n console.error(\"Material-UI: The palette type `\".concat(type, \"` is not supported.\"));\n }\n }\n\n var paletteOutput = deepmerge(_extends({\n // A collection of common colors.\n common: common,\n // The palette type, can be light or dark.\n type: type,\n // The colors used to represent primary interface elements for a user.\n primary: augmentColor(primary),\n // The colors used to represent secondary interface elements for a user.\n secondary: augmentColor(secondary, 'A400', 'A200', 'A700'),\n // The colors used to represent interface elements that the user should be made aware of.\n error: augmentColor(error),\n // The colors used to represent potentially dangerous actions or important messages.\n warning: augmentColor(warning),\n // The colors used to present information to the user that is neutral and not necessarily important.\n info: augmentColor(info),\n // The colors used to indicate the successful completion of an action that user triggered.\n success: augmentColor(success),\n // The grey colors.\n grey: grey,\n // Used by `getContrastText()` to maximize the contrast between\n // the background and the text.\n contrastThreshold: contrastThreshold,\n // Takes a background color and returns the text color that maximizes the contrast.\n getContrastText: getContrastText,\n // Generate a rich color object.\n augmentColor: augmentColor,\n // Used by the functions below to shift a color's luminance by approximately\n // two indexes within its tonal palette.\n // E.g., shift from Red 500 to Red 300 or Red 700.\n tonalOffset: tonalOffset\n }, types[type]), other);\n return paletteOutput;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport { deepmerge } from '@material-ui/utils';\n\nfunction round(value) {\n return Math.round(value * 1e5) / 1e5;\n}\n\nvar caseAllCaps = {\n textTransform: 'uppercase'\n};\nvar defaultFontFamily = '\"Roboto\", \"Helvetica\", \"Arial\", sans-serif';\n/**\n * @see @link{https://material.io/design/typography/the-type-system.html}\n * @see @link{https://material.io/design/typography/understanding-typography.html}\n */\n\nexport default function createTypography(palette, typography) {\n var _ref = typeof typography === 'function' ? typography(palette) : typography,\n _ref$fontFamily = _ref.fontFamily,\n fontFamily = _ref$fontFamily === void 0 ? defaultFontFamily : _ref$fontFamily,\n _ref$fontSize = _ref.fontSize,\n fontSize = _ref$fontSize === void 0 ? 14 : _ref$fontSize,\n _ref$fontWeightLight = _ref.fontWeightLight,\n fontWeightLight = _ref$fontWeightLight === void 0 ? 300 : _ref$fontWeightLight,\n _ref$fontWeightRegula = _ref.fontWeightRegular,\n fontWeightRegular = _ref$fontWeightRegula === void 0 ? 400 : _ref$fontWeightRegula,\n _ref$fontWeightMedium = _ref.fontWeightMedium,\n fontWeightMedium = _ref$fontWeightMedium === void 0 ? 500 : _ref$fontWeightMedium,\n _ref$fontWeightBold = _ref.fontWeightBold,\n fontWeightBold = _ref$fontWeightBold === void 0 ? 700 : _ref$fontWeightBold,\n _ref$htmlFontSize = _ref.htmlFontSize,\n htmlFontSize = _ref$htmlFontSize === void 0 ? 16 : _ref$htmlFontSize,\n allVariants = _ref.allVariants,\n pxToRem2 = _ref.pxToRem,\n other = _objectWithoutProperties(_ref, [\"fontFamily\", \"fontSize\", \"fontWeightLight\", \"fontWeightRegular\", \"fontWeightMedium\", \"fontWeightBold\", \"htmlFontSize\", \"allVariants\", \"pxToRem\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof fontSize !== 'number') {\n console.error('Material-UI: `fontSize` is required to be a number.');\n }\n\n if (typeof htmlFontSize !== 'number') {\n console.error('Material-UI: `htmlFontSize` is required to be a number.');\n }\n }\n\n var coef = fontSize / 14;\n\n var pxToRem = pxToRem2 || function (size) {\n return \"\".concat(size / htmlFontSize * coef, \"rem\");\n };\n\n var buildVariant = function buildVariant(fontWeight, size, lineHeight, letterSpacing, casing) {\n return _extends({\n fontFamily: fontFamily,\n fontWeight: fontWeight,\n fontSize: pxToRem(size),\n // Unitless following https://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/\n lineHeight: lineHeight\n }, fontFamily === defaultFontFamily ? {\n letterSpacing: \"\".concat(round(letterSpacing / size), \"em\")\n } : {}, casing, allVariants);\n };\n\n var variants = {\n h1: buildVariant(fontWeightLight, 96, 1.167, -1.5),\n h2: buildVariant(fontWeightLight, 60, 1.2, -0.5),\n h3: buildVariant(fontWeightRegular, 48, 1.167, 0),\n h4: buildVariant(fontWeightRegular, 34, 1.235, 0.25),\n h5: buildVariant(fontWeightRegular, 24, 1.334, 0),\n h6: buildVariant(fontWeightMedium, 20, 1.6, 0.15),\n subtitle1: buildVariant(fontWeightRegular, 16, 1.75, 0.15),\n subtitle2: buildVariant(fontWeightMedium, 14, 1.57, 0.1),\n body1: buildVariant(fontWeightRegular, 16, 1.5, 0.15),\n body2: buildVariant(fontWeightRegular, 14, 1.43, 0.15),\n button: buildVariant(fontWeightMedium, 14, 1.75, 0.4, caseAllCaps),\n caption: buildVariant(fontWeightRegular, 12, 1.66, 0.4),\n overline: buildVariant(fontWeightRegular, 12, 2.66, 1, caseAllCaps)\n };\n return deepmerge(_extends({\n htmlFontSize: htmlFontSize,\n pxToRem: pxToRem,\n round: round,\n // TODO v5: remove\n fontFamily: fontFamily,\n fontSize: fontSize,\n fontWeightLight: fontWeightLight,\n fontWeightRegular: fontWeightRegular,\n fontWeightMedium: fontWeightMedium,\n fontWeightBold: fontWeightBold\n }, variants), other, {\n clone: false // No need to clone deep\n\n });\n}","var shadowKeyUmbraOpacity = 0.2;\nvar shadowKeyPenumbraOpacity = 0.14;\nvar shadowAmbientShadowOpacity = 0.12;\n\nfunction createShadow() {\n return [\"\".concat(arguments.length <= 0 ? undefined : arguments[0], \"px \").concat(arguments.length <= 1 ? undefined : arguments[1], \"px \").concat(arguments.length <= 2 ? undefined : arguments[2], \"px \").concat(arguments.length <= 3 ? undefined : arguments[3], \"px rgba(0,0,0,\").concat(shadowKeyUmbraOpacity, \")\"), \"\".concat(arguments.length <= 4 ? undefined : arguments[4], \"px \").concat(arguments.length <= 5 ? undefined : arguments[5], \"px \").concat(arguments.length <= 6 ? undefined : arguments[6], \"px \").concat(arguments.length <= 7 ? undefined : arguments[7], \"px rgba(0,0,0,\").concat(shadowKeyPenumbraOpacity, \")\"), \"\".concat(arguments.length <= 8 ? undefined : arguments[8], \"px \").concat(arguments.length <= 9 ? undefined : arguments[9], \"px \").concat(arguments.length <= 10 ? undefined : arguments[10], \"px \").concat(arguments.length <= 11 ? undefined : arguments[11], \"px rgba(0,0,0,\").concat(shadowAmbientShadowOpacity, \")\")].join(',');\n} // Values from https://github.com/material-components/material-components-web/blob/be8747f94574669cb5e7add1a7c54fa41a89cec7/packages/mdc-elevation/_variables.scss\n\n\nvar shadows = ['none', createShadow(0, 2, 1, -1, 0, 1, 1, 0, 0, 1, 3, 0), createShadow(0, 3, 1, -2, 0, 2, 2, 0, 0, 1, 5, 0), createShadow(0, 3, 3, -2, 0, 3, 4, 0, 0, 1, 8, 0), createShadow(0, 2, 4, -1, 0, 4, 5, 0, 0, 1, 10, 0), createShadow(0, 3, 5, -1, 0, 5, 8, 0, 0, 1, 14, 0), createShadow(0, 3, 5, -1, 0, 6, 10, 0, 0, 1, 18, 0), createShadow(0, 4, 5, -2, 0, 7, 10, 1, 0, 2, 16, 1), createShadow(0, 5, 5, -3, 0, 8, 10, 1, 0, 3, 14, 2), createShadow(0, 5, 6, -3, 0, 9, 12, 1, 0, 3, 16, 2), createShadow(0, 6, 6, -3, 0, 10, 14, 1, 0, 4, 18, 3), createShadow(0, 6, 7, -4, 0, 11, 15, 1, 0, 4, 20, 3), createShadow(0, 7, 8, -4, 0, 12, 17, 2, 0, 5, 22, 4), createShadow(0, 7, 8, -4, 0, 13, 19, 2, 0, 5, 24, 4), createShadow(0, 7, 9, -4, 0, 14, 21, 2, 0, 5, 26, 4), createShadow(0, 8, 9, -5, 0, 15, 22, 2, 0, 6, 28, 5), createShadow(0, 8, 10, -5, 0, 16, 24, 2, 0, 6, 30, 5), createShadow(0, 8, 11, -5, 0, 17, 26, 2, 0, 6, 32, 5), createShadow(0, 9, 11, -5, 0, 18, 28, 2, 0, 7, 34, 6), createShadow(0, 9, 12, -6, 0, 19, 29, 2, 0, 7, 36, 6), createShadow(0, 10, 13, -6, 0, 20, 31, 3, 0, 8, 38, 7), createShadow(0, 10, 13, -6, 0, 21, 33, 3, 0, 8, 40, 7), createShadow(0, 10, 14, -6, 0, 22, 35, 3, 0, 8, 42, 7), createShadow(0, 11, 14, -7, 0, 23, 36, 3, 0, 9, 44, 8), createShadow(0, 11, 15, -7, 0, 24, 38, 3, 0, 9, 46, 8)];\nexport default shadows;","var shape = {\n borderRadius: 4\n};\nexport default shape;","import { createUnarySpacing } from '@material-ui/system';\nvar warnOnce;\nexport default function createSpacing() {\n var spacingInput = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8;\n\n // Already transformed.\n if (spacingInput.mui) {\n return spacingInput;\n } // Material Design layouts are visually balanced. Most measurements align to an 8dp grid applied, which aligns both spacing and the overall layout.\n // Smaller components, such as icons and type, can align to a 4dp grid.\n // https://material.io/design/layout/understanding-layout.html#usage\n\n\n var transform = createUnarySpacing({\n spacing: spacingInput\n });\n\n var spacing = function spacing() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!(args.length <= 4)) {\n console.error(\"Material-UI: Too many arguments provided, expected between 0 and 4, got \".concat(args.length));\n }\n }\n\n if (args.length === 0) {\n return transform(1);\n }\n\n if (args.length === 1) {\n return transform(args[0]);\n }\n\n return args.map(function (argument) {\n if (typeof argument === 'string') {\n return argument;\n }\n\n var output = transform(argument);\n return typeof output === 'number' ? \"\".concat(output, \"px\") : output;\n }).join(' ');\n }; // Backward compatibility, to remove in v5.\n\n\n Object.defineProperty(spacing, 'unit', {\n get: function get() {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnOnce || process.env.NODE_ENV === 'test') {\n console.error(['Material-UI: theme.spacing.unit usage has been deprecated.', 'It will be removed in v5.', 'You can replace `theme.spacing.unit * y` with `theme.spacing(y)`.', '', 'You can use the `https://github.com/mui-org/material-ui/tree/master/packages/material-ui-codemod/README.md#theme-spacing-api` migration helper to make the process smoother.'].join('\\n'));\n }\n\n warnOnce = true;\n }\n\n return spacingInput;\n }\n });\n spacing.mui = true;\n return spacing;\n}","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\n// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves\n// to learn the context in which each easing should be used.\nexport var easing = {\n // This is the most common easing curve.\n easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',\n // Objects enter the screen at full velocity from off-screen and\n // slowly decelerate to a resting point.\n easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)',\n // Objects leave the screen at full velocity. They do not decelerate when off-screen.\n easeIn: 'cubic-bezier(0.4, 0, 1, 1)',\n // The sharp curve is used by objects that may return to the screen at any time.\n sharp: 'cubic-bezier(0.4, 0, 0.6, 1)'\n}; // Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations\n// to learn when use what timing\n\nexport var duration = {\n shortest: 150,\n shorter: 200,\n short: 250,\n // most basic recommended timing\n standard: 300,\n // this is to be used in complex animations\n complex: 375,\n // recommended when something is entering screen\n enteringScreen: 225,\n // recommended when something is leaving screen\n leavingScreen: 195\n};\n\nfunction formatMs(milliseconds) {\n return \"\".concat(Math.round(milliseconds), \"ms\");\n}\n/**\n * @param {string|Array} props\n * @param {object} param\n * @param {string} param.prop\n * @param {number} param.duration\n * @param {string} param.easing\n * @param {number} param.delay\n */\n\n\nexport default {\n easing: easing,\n duration: duration,\n create: function create() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['all'];\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n var _options$duration = options.duration,\n durationOption = _options$duration === void 0 ? duration.standard : _options$duration,\n _options$easing = options.easing,\n easingOption = _options$easing === void 0 ? easing.easeInOut : _options$easing,\n _options$delay = options.delay,\n delay = _options$delay === void 0 ? 0 : _options$delay,\n other = _objectWithoutProperties(options, [\"duration\", \"easing\", \"delay\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n var isString = function isString(value) {\n return typeof value === 'string';\n };\n\n var isNumber = function isNumber(value) {\n return !isNaN(parseFloat(value));\n };\n\n if (!isString(props) && !Array.isArray(props)) {\n console.error('Material-UI: Argument \"props\" must be a string or Array.');\n }\n\n if (!isNumber(durationOption) && !isString(durationOption)) {\n console.error(\"Material-UI: Argument \\\"duration\\\" must be a number or a string but found \".concat(durationOption, \".\"));\n }\n\n if (!isString(easingOption)) {\n console.error('Material-UI: Argument \"easing\" must be a string.');\n }\n\n if (!isNumber(delay) && !isString(delay)) {\n console.error('Material-UI: Argument \"delay\" must be a number or a string.');\n }\n\n if (Object.keys(other).length !== 0) {\n console.error(\"Material-UI: Unrecognized argument(s) [\".concat(Object.keys(other).join(','), \"].\"));\n }\n }\n\n return (Array.isArray(props) ? props : [props]).map(function (animatedProp) {\n return \"\".concat(animatedProp, \" \").concat(typeof durationOption === 'string' ? durationOption : formatMs(durationOption), \" \").concat(easingOption, \" \").concat(typeof delay === 'string' ? delay : formatMs(delay));\n }).join(',');\n },\n getAutoHeightDuration: function getAutoHeightDuration(height) {\n if (!height) {\n return 0;\n }\n\n var constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10\n\n return Math.round((4 + 15 * Math.pow(constant, 0.25) + constant / 5) * 10);\n }\n};","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport { deepmerge } from '@material-ui/utils';\nimport createBreakpoints from './createBreakpoints';\nimport createMixins from './createMixins';\nimport createPalette from './createPalette';\nimport createTypography from './createTypography';\nimport shadows from './shadows';\nimport shape from './shape';\nimport createSpacing from './createSpacing';\nimport transitions from './transitions';\nimport zIndex from './zIndex';\n\nfunction createMuiTheme() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n var _options$breakpoints = options.breakpoints,\n breakpointsInput = _options$breakpoints === void 0 ? {} : _options$breakpoints,\n _options$mixins = options.mixins,\n mixinsInput = _options$mixins === void 0 ? {} : _options$mixins,\n _options$palette = options.palette,\n paletteInput = _options$palette === void 0 ? {} : _options$palette,\n spacingInput = options.spacing,\n _options$typography = options.typography,\n typographyInput = _options$typography === void 0 ? {} : _options$typography,\n other = _objectWithoutProperties(options, [\"breakpoints\", \"mixins\", \"palette\", \"spacing\", \"typography\"]);\n\n var palette = createPalette(paletteInput);\n var breakpoints = createBreakpoints(breakpointsInput);\n var spacing = createSpacing(spacingInput);\n var muiTheme = deepmerge({\n breakpoints: breakpoints,\n direction: 'ltr',\n mixins: createMixins(breakpoints, spacing, mixinsInput),\n overrides: {},\n // Inject custom styles\n palette: palette,\n props: {},\n // Provide default props\n shadows: shadows,\n typography: createTypography(palette, typographyInput),\n spacing: spacing,\n shape: shape,\n transitions: transitions,\n zIndex: zIndex\n }, other);\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n muiTheme = args.reduce(function (acc, argument) {\n return deepmerge(acc, argument);\n }, muiTheme);\n\n if (process.env.NODE_ENV !== 'production') {\n var pseudoClasses = ['checked', 'disabled', 'error', 'focused', 'focusVisible', 'required', 'expanded', 'selected'];\n\n var traverse = function traverse(node, parentKey) {\n var depth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n var key; // eslint-disable-next-line guard-for-in, no-restricted-syntax\n\n for (key in node) {\n var child = node[key];\n\n if (depth === 1) {\n if (key.indexOf('Mui') === 0 && child) {\n traverse(child, key, depth + 1);\n }\n } else if (pseudoClasses.indexOf(key) !== -1 && Object.keys(child).length > 0) {\n if (process.env.NODE_ENV !== 'production') {\n console.error([\"Material-UI: The `\".concat(parentKey, \"` component increases \") + \"the CSS specificity of the `\".concat(key, \"` internal state.\"), 'You can not override it like this: ', JSON.stringify(node, null, 2), '', 'Instead, you need to use the $ruleName syntax:', JSON.stringify({\n root: _defineProperty({}, \"&$\".concat(key), child)\n }, null, 2), '', 'https://material-ui.com/r/pseudo-classes-guide'].join('\\n'));\n } // Remove the style to prevent global conflicts.\n\n\n node[key] = {};\n }\n }\n };\n\n traverse(muiTheme.overrides);\n }\n\n return muiTheme;\n}\n\nexport default createMuiTheme;","import createMuiTheme from './createMuiTheme';\nvar defaultTheme = createMuiTheme();\nexport default defaultTheme;","// TODO v5: consider to make it private\nexport default function setRef(ref, value) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n ref.current = value;\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 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function _typeof(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function _typeof(obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n","module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","/* globals __webpack_amd_options__ */\nmodule.exports = __webpack_amd_options__;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 {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 {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 */\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 */\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 */\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 {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 {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 */\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","import ownerDocument from './ownerDocument';\nexport default function ownerWindow(node) {\n var doc = ownerDocument(node);\n return doc.defaultView || window;\n}","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}","export default function _iterableToArrayLimit(arr, i) {\n var _i = arr && (typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"]);\n\n if (_i == null) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n\n var _s, _e;\n\n try {\n for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}","import * as React from 'react';\nexport default function isMuiElement(element, muiNames) {\n return /*#__PURE__*/React.isValidElement(element) && muiNames.indexOf(element.type.muiName) !== -1;\n}","import React from 'react';\nexport default React.createContext(null);","import * as React from 'react';\n/**\n * @ignore - internal component.\n */\n\nvar ListContext = React.createContext({});\n\nif (process.env.NODE_ENV !== 'production') {\n ListContext.displayName = 'ListContext';\n}\n\nexport default ListContext;","/**\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","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","import React from \"react\";\nimport { Router } from \"react-router\";\nimport { createBrowserHistory as createHistory } from \"history\";\nimport PropTypes from \"prop-types\";\nimport warning from \"tiny-warning\";\n\n/**\n * The public API for a <Router> that uses HTML5 history.\n */\nclass BrowserRouter extends React.Component {\n history = createHistory(this.props);\n\n render() {\n return <Router history={this.history} children={this.props.children} />;\n }\n}\n\nif (__DEV__) {\n BrowserRouter.propTypes = {\n basename: PropTypes.string,\n children: PropTypes.node,\n forceRefresh: PropTypes.bool,\n getUserConfirmation: PropTypes.func,\n keyLength: PropTypes.number\n };\n\n BrowserRouter.prototype.componentDidMount = function() {\n warning(\n !this.props.history,\n \"<BrowserRouter> ignores the history prop. To use a custom history, \" +\n \"use `import { Router }` instead of `import { BrowserRouter as Router }`.\"\n );\n };\n}\n\nexport default BrowserRouter;\n","import React from \"react\";\nimport { Router } from \"react-router\";\nimport { createHashHistory as createHistory } from \"history\";\nimport PropTypes from \"prop-types\";\nimport warning from \"tiny-warning\";\n\n/**\n * The public API for a <Router> that uses window.location.hash.\n */\nclass HashRouter extends React.Component {\n history = createHistory(this.props);\n\n render() {\n return <Router history={this.history} children={this.props.children} />;\n }\n}\n\nif (__DEV__) {\n HashRouter.propTypes = {\n basename: PropTypes.string,\n children: PropTypes.node,\n getUserConfirmation: PropTypes.func,\n hashType: PropTypes.oneOf([\"hashbang\", \"noslash\", \"slash\"])\n };\n\n HashRouter.prototype.componentDidMount = function() {\n warning(\n !this.props.history,\n \"<HashRouter> ignores the history prop. To use a custom history, \" +\n \"use `import { Router }` instead of `import { HashRouter as Router }`.\"\n );\n };\n}\n\nexport default HashRouter;\n","import { createLocation } from \"history\";\n\nexport const resolveToLocation = (to, currentLocation) =>\n typeof to === \"function\" ? to(currentLocation) : to;\n\nexport const normalizeToLocation = (to, currentLocation) => {\n return typeof to === \"string\"\n ? createLocation(to, null, null, currentLocation)\n : to;\n};\n","import React from \"react\";\nimport { __RouterContext as RouterContext } from \"react-router\";\nimport PropTypes from \"prop-types\";\nimport invariant from \"tiny-invariant\";\nimport {\n resolveToLocation,\n normalizeToLocation\n} from \"./utils/locationUtils.js\";\n\n// React 15 compat\nconst forwardRefShim = C => C;\nlet { forwardRef } = React;\nif (typeof forwardRef === \"undefined\") {\n forwardRef = forwardRefShim;\n}\n\nfunction isModifiedEvent(event) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nconst LinkAnchor = forwardRef(\n (\n {\n innerRef, // TODO: deprecate\n navigate,\n onClick,\n ...rest\n },\n forwardedRef\n ) => {\n const { target } = rest;\n\n let props = {\n ...rest,\n onClick: event => {\n try {\n if (onClick) onClick(event);\n } catch (ex) {\n event.preventDefault();\n throw ex;\n }\n\n if (\n !event.defaultPrevented && // onClick prevented default\n event.button === 0 && // ignore everything but left clicks\n (!target || target === \"_self\") && // let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // ignore clicks with modifier keys\n ) {\n event.preventDefault();\n navigate();\n }\n }\n };\n\n // React 15 compat\n if (forwardRefShim !== forwardRef) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.ref = innerRef;\n }\n\n /* eslint-disable-next-line jsx-a11y/anchor-has-content */\n return <a {...props} />;\n }\n);\n\nif (__DEV__) {\n LinkAnchor.displayName = \"LinkAnchor\";\n}\n\n/**\n * The public API for rendering a history-aware <a>.\n */\nconst Link = forwardRef(\n (\n {\n component = LinkAnchor,\n replace,\n to,\n innerRef, // TODO: deprecate\n ...rest\n },\n forwardedRef\n ) => {\n return (\n <RouterContext.Consumer>\n {context => {\n invariant(context, \"You should not use <Link> outside a <Router>\");\n\n const { history } = context;\n\n const location = normalizeToLocation(\n resolveToLocation(to, context.location),\n context.location\n );\n\n const href = location ? history.createHref(location) : \"\";\n const props = {\n ...rest,\n href,\n navigate() {\n const location = resolveToLocation(to, context.location);\n const method = replace ? history.replace : history.push;\n\n method(location);\n }\n };\n\n // React 15 compat\n if (forwardRefShim !== forwardRef) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.innerRef = innerRef;\n }\n\n return React.createElement(component, props);\n }}\n </RouterContext.Consumer>\n );\n }\n);\n\nif (__DEV__) {\n const toType = PropTypes.oneOfType([\n PropTypes.string,\n PropTypes.object,\n PropTypes.func\n ]);\n const refType = PropTypes.oneOfType([\n PropTypes.string,\n PropTypes.func,\n PropTypes.shape({ current: PropTypes.any })\n ]);\n\n Link.displayName = \"Link\";\n\n Link.propTypes = {\n innerRef: refType,\n onClick: PropTypes.func,\n replace: PropTypes.bool,\n target: PropTypes.string,\n to: toType.isRequired\n };\n}\n\nexport default Link;\n","import React from \"react\";\nimport { __RouterContext as RouterContext, matchPath } from \"react-router\";\nimport PropTypes from \"prop-types\";\nimport invariant from \"tiny-invariant\";\nimport Link from \"./Link.js\";\nimport {\n resolveToLocation,\n normalizeToLocation\n} from \"./utils/locationUtils.js\";\n\n// React 15 compat\nconst forwardRefShim = C => C;\nlet { forwardRef } = React;\nif (typeof forwardRef === \"undefined\") {\n forwardRef = forwardRefShim;\n}\n\nfunction joinClassnames(...classnames) {\n return classnames.filter(i => i).join(\" \");\n}\n\n/**\n * A <Link> wrapper that knows if it's \"active\" or not.\n */\nconst NavLink = forwardRef(\n (\n {\n \"aria-current\": ariaCurrent = \"page\",\n activeClassName = \"active\",\n activeStyle,\n className: classNameProp,\n exact,\n isActive: isActiveProp,\n location: locationProp,\n sensitive,\n strict,\n style: styleProp,\n to,\n innerRef, // TODO: deprecate\n ...rest\n },\n forwardedRef\n ) => {\n return (\n <RouterContext.Consumer>\n {context => {\n invariant(context, \"You should not use <NavLink> outside a <Router>\");\n\n const currentLocation = locationProp || context.location;\n const toLocation = normalizeToLocation(\n resolveToLocation(to, currentLocation),\n currentLocation\n );\n const { pathname: path } = toLocation;\n // Regex taken from: https://github.com/pillarjs/path-to-regexp/blob/master/index.js#L202\n const escapedPath =\n path && path.replace(/([.+*?=^!:${}()[\\]|/\\\\])/g, \"\\\\$1\");\n\n const match = escapedPath\n ? matchPath(currentLocation.pathname, {\n path: escapedPath,\n exact,\n sensitive,\n strict\n })\n : null;\n const isActive = !!(isActiveProp\n ? isActiveProp(match, currentLocation)\n : match);\n\n const className = isActive\n ? joinClassnames(classNameProp, activeClassName)\n : classNameProp;\n const style = isActive ? { ...styleProp, ...activeStyle } : styleProp;\n\n const props = {\n \"aria-current\": (isActive && ariaCurrent) || null,\n className,\n style,\n to: toLocation,\n ...rest\n };\n\n // React 15 compat\n if (forwardRefShim !== forwardRef) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.innerRef = innerRef;\n }\n\n return <Link {...props} />;\n }}\n </RouterContext.Consumer>\n );\n }\n);\n\nif (__DEV__) {\n NavLink.displayName = \"NavLink\";\n\n const ariaCurrentType = PropTypes.oneOf([\n \"page\",\n \"step\",\n \"location\",\n \"date\",\n \"time\",\n \"true\"\n ]);\n\n NavLink.propTypes = {\n ...Link.propTypes,\n \"aria-current\": ariaCurrentType,\n activeClassName: PropTypes.string,\n activeStyle: PropTypes.object,\n className: PropTypes.string,\n exact: PropTypes.bool,\n isActive: PropTypes.func,\n location: PropTypes.object,\n sensitive: PropTypes.bool,\n strict: PropTypes.bool,\n style: PropTypes.object\n };\n}\n\nexport default NavLink;\n","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\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 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print<T extends Tensor>(x: T, verbose = false): void {\n console.log(x.toString(verbose));\n}\n","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 */\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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 */\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 */\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 {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 {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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike3D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor3d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor3d([[[1], [2]], [[3], [4]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n * `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor3d(\n values: TensorLike3D, shape?: [number, number, number],\n dtype?: DataType): Tensor3D {\n assertNonNull(values);\n if (shape != null && shape.length !== 3) {\n throw new Error('tensor3d() requires shape to have three numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 3 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor3d() requires values to be number[][][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor3d() requires shape to be provided when `values` ' +\n 'are a flat array');\n }\n return makeTensor(values, shape, inferredShape, dtype) as Tensor3D;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {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 {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 */\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\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","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","export default function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter);\n}","export default function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 */\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","import arrayWithHoles from \"@babel/runtime/helpers/esm/arrayWithHoles\";\nimport iterableToArray from \"@babel/runtime/helpers/esm/iterableToArray\";\nimport unsupportedIterableToArray from \"@babel/runtime/helpers/esm/unsupportedIterableToArray\";\nimport nonIterableRest from \"@babel/runtime/helpers/esm/nonIterableRest\";\nexport default function _toArray(arr) {\n return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();\n}","/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 */\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","import PropTypes from 'prop-types';\nimport withSideEffect from 'react-side-effect';\nimport isEqual from 'react-fast-compare';\nimport React from 'react';\nimport objectAssign from 'object-assign';\n\nvar ATTRIBUTE_NAMES = {\n BODY: \"bodyAttributes\",\n HTML: \"htmlAttributes\",\n TITLE: \"titleAttributes\"\n};\n\nvar TAG_NAMES = {\n BASE: \"base\",\n BODY: \"body\",\n HEAD: \"head\",\n HTML: \"html\",\n LINK: \"link\",\n META: \"meta\",\n NOSCRIPT: \"noscript\",\n SCRIPT: \"script\",\n STYLE: \"style\",\n TITLE: \"title\"\n};\n\nvar VALID_TAG_NAMES = Object.keys(TAG_NAMES).map(function (name) {\n return TAG_NAMES[name];\n});\n\nvar TAG_PROPERTIES = {\n CHARSET: \"charset\",\n CSS_TEXT: \"cssText\",\n HREF: \"href\",\n HTTPEQUIV: \"http-equiv\",\n INNER_HTML: \"innerHTML\",\n ITEM_PROP: \"itemprop\",\n NAME: \"name\",\n PROPERTY: \"property\",\n REL: \"rel\",\n SRC: \"src\",\n TARGET: \"target\"\n};\n\nvar REACT_TAG_MAP = {\n accesskey: \"accessKey\",\n charset: \"charSet\",\n class: \"className\",\n contenteditable: \"contentEditable\",\n contextmenu: \"contextMenu\",\n \"http-equiv\": \"httpEquiv\",\n itemprop: \"itemProp\",\n tabindex: \"tabIndex\"\n};\n\nvar HELMET_PROPS = {\n DEFAULT_TITLE: \"defaultTitle\",\n DEFER: \"defer\",\n ENCODE_SPECIAL_CHARACTERS: \"encodeSpecialCharacters\",\n ON_CHANGE_CLIENT_STATE: \"onChangeClientState\",\n TITLE_TEMPLATE: \"titleTemplate\"\n};\n\nvar HTML_TAG_MAP = Object.keys(REACT_TAG_MAP).reduce(function (obj, key) {\n obj[REACT_TAG_MAP[key]] = key;\n return obj;\n}, {});\n\nvar SELF_CLOSING_TAGS = [TAG_NAMES.NOSCRIPT, TAG_NAMES.SCRIPT, TAG_NAMES.STYLE];\n\nvar HELMET_ATTRIBUTE = \"data-react-helmet\";\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n} : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\nvar classCallCheck = function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n};\n\nvar createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n}();\n\nvar _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nvar inherits = function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n};\n\nvar objectWithoutProperties = function (obj, keys) {\n var target = {};\n\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n\n return target;\n};\n\nvar possibleConstructorReturn = function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n};\n\nvar encodeSpecialCharacters = function encodeSpecialCharacters(str) {\n var encode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\n if (encode === false) {\n return String(str);\n }\n\n return String(str).replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\").replace(/'/g, \"&#x27;\");\n};\n\nvar getTitleFromPropsList = function getTitleFromPropsList(propsList) {\n var innermostTitle = getInnermostProperty(propsList, TAG_NAMES.TITLE);\n var innermostTemplate = getInnermostProperty(propsList, HELMET_PROPS.TITLE_TEMPLATE);\n\n if (innermostTemplate && innermostTitle) {\n // use function arg to avoid need to escape $ characters\n return innermostTemplate.replace(/%s/g, function () {\n return Array.isArray(innermostTitle) ? innermostTitle.join(\"\") : innermostTitle;\n });\n }\n\n var innermostDefaultTitle = getInnermostProperty(propsList, HELMET_PROPS.DEFAULT_TITLE);\n\n return innermostTitle || innermostDefaultTitle || undefined;\n};\n\nvar getOnChangeClientState = function getOnChangeClientState(propsList) {\n return getInnermostProperty(propsList, HELMET_PROPS.ON_CHANGE_CLIENT_STATE) || function () {};\n};\n\nvar getAttributesFromPropsList = function getAttributesFromPropsList(tagType, propsList) {\n return propsList.filter(function (props) {\n return typeof props[tagType] !== \"undefined\";\n }).map(function (props) {\n return props[tagType];\n }).reduce(function (tagAttrs, current) {\n return _extends({}, tagAttrs, current);\n }, {});\n};\n\nvar getBaseTagFromPropsList = function getBaseTagFromPropsList(primaryAttributes, propsList) {\n return propsList.filter(function (props) {\n return typeof props[TAG_NAMES.BASE] !== \"undefined\";\n }).map(function (props) {\n return props[TAG_NAMES.BASE];\n }).reverse().reduce(function (innermostBaseTag, tag) {\n if (!innermostBaseTag.length) {\n var keys = Object.keys(tag);\n\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var lowerCaseAttributeKey = attributeKey.toLowerCase();\n\n if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && tag[lowerCaseAttributeKey]) {\n return innermostBaseTag.concat(tag);\n }\n }\n }\n\n return innermostBaseTag;\n }, []);\n};\n\nvar getTagsFromPropsList = function getTagsFromPropsList(tagName, primaryAttributes, propsList) {\n // Calculate list of tags, giving priority innermost component (end of the propslist)\n var approvedSeenTags = {};\n\n return propsList.filter(function (props) {\n if (Array.isArray(props[tagName])) {\n return true;\n }\n if (typeof props[tagName] !== \"undefined\") {\n warn(\"Helmet: \" + tagName + \" should be of type \\\"Array\\\". Instead found type \\\"\" + _typeof(props[tagName]) + \"\\\"\");\n }\n return false;\n }).map(function (props) {\n return props[tagName];\n }).reverse().reduce(function (approvedTags, instanceTags) {\n var instanceSeenTags = {};\n\n instanceTags.filter(function (tag) {\n var primaryAttributeKey = void 0;\n var keys = Object.keys(tag);\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var lowerCaseAttributeKey = attributeKey.toLowerCase();\n\n // Special rule with link tags, since rel and href are both primary tags, rel takes priority\n if (primaryAttributes.indexOf(lowerCaseAttributeKey) !== -1 && !(primaryAttributeKey === TAG_PROPERTIES.REL && tag[primaryAttributeKey].toLowerCase() === \"canonical\") && !(lowerCaseAttributeKey === TAG_PROPERTIES.REL && tag[lowerCaseAttributeKey].toLowerCase() === \"stylesheet\")) {\n primaryAttributeKey = lowerCaseAttributeKey;\n }\n // Special case for innerHTML which doesn't work lowercased\n if (primaryAttributes.indexOf(attributeKey) !== -1 && (attributeKey === TAG_PROPERTIES.INNER_HTML || attributeKey === TAG_PROPERTIES.CSS_TEXT || attributeKey === TAG_PROPERTIES.ITEM_PROP)) {\n primaryAttributeKey = attributeKey;\n }\n }\n\n if (!primaryAttributeKey || !tag[primaryAttributeKey]) {\n return false;\n }\n\n var value = tag[primaryAttributeKey].toLowerCase();\n\n if (!approvedSeenTags[primaryAttributeKey]) {\n approvedSeenTags[primaryAttributeKey] = {};\n }\n\n if (!instanceSeenTags[primaryAttributeKey]) {\n instanceSeenTags[primaryAttributeKey] = {};\n }\n\n if (!approvedSeenTags[primaryAttributeKey][value]) {\n instanceSeenTags[primaryAttributeKey][value] = true;\n return true;\n }\n\n return false;\n }).reverse().forEach(function (tag) {\n return approvedTags.push(tag);\n });\n\n // Update seen tags with tags from this instance\n var keys = Object.keys(instanceSeenTags);\n for (var i = 0; i < keys.length; i++) {\n var attributeKey = keys[i];\n var tagUnion = objectAssign({}, approvedSeenTags[attributeKey], instanceSeenTags[attributeKey]);\n\n approvedSeenTags[attributeKey] = tagUnion;\n }\n\n return approvedTags;\n }, []).reverse();\n};\n\nvar getInnermostProperty = function getInnermostProperty(propsList, property) {\n for (var i = propsList.length - 1; i >= 0; i--) {\n var props = propsList[i];\n\n if (props.hasOwnProperty(property)) {\n return props[property];\n }\n }\n\n return null;\n};\n\nvar reducePropsToState = function reducePropsToState(propsList) {\n return {\n baseTag: getBaseTagFromPropsList([TAG_PROPERTIES.HREF, TAG_PROPERTIES.TARGET], propsList),\n bodyAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.BODY, propsList),\n defer: getInnermostProperty(propsList, HELMET_PROPS.DEFER),\n encode: getInnermostProperty(propsList, HELMET_PROPS.ENCODE_SPECIAL_CHARACTERS),\n htmlAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.HTML, propsList),\n linkTags: getTagsFromPropsList(TAG_NAMES.LINK, [TAG_PROPERTIES.REL, TAG_PROPERTIES.HREF], propsList),\n metaTags: getTagsFromPropsList(TAG_NAMES.META, [TAG_PROPERTIES.NAME, TAG_PROPERTIES.CHARSET, TAG_PROPERTIES.HTTPEQUIV, TAG_PROPERTIES.PROPERTY, TAG_PROPERTIES.ITEM_PROP], propsList),\n noscriptTags: getTagsFromPropsList(TAG_NAMES.NOSCRIPT, [TAG_PROPERTIES.INNER_HTML], propsList),\n onChangeClientState: getOnChangeClientState(propsList),\n scriptTags: getTagsFromPropsList(TAG_NAMES.SCRIPT, [TAG_PROPERTIES.SRC, TAG_PROPERTIES.INNER_HTML], propsList),\n styleTags: getTagsFromPropsList(TAG_NAMES.STYLE, [TAG_PROPERTIES.CSS_TEXT], propsList),\n title: getTitleFromPropsList(propsList),\n titleAttributes: getAttributesFromPropsList(ATTRIBUTE_NAMES.TITLE, propsList)\n };\n};\n\nvar rafPolyfill = function () {\n var clock = Date.now();\n\n return function (callback) {\n var currentTime = Date.now();\n\n if (currentTime - clock > 16) {\n clock = currentTime;\n callback(currentTime);\n } else {\n setTimeout(function () {\n rafPolyfill(callback);\n }, 0);\n }\n };\n}();\n\nvar cafPolyfill = function cafPolyfill(id) {\n return clearTimeout(id);\n};\n\nvar requestAnimationFrame = typeof window !== \"undefined\" ? window.requestAnimationFrame && window.requestAnimationFrame.bind(window) || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || rafPolyfill : global.requestAnimationFrame || rafPolyfill;\n\nvar cancelAnimationFrame = typeof window !== \"undefined\" ? window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || cafPolyfill : global.cancelAnimationFrame || cafPolyfill;\n\nvar warn = function warn(msg) {\n return console && typeof console.warn === \"function\" && console.warn(msg);\n};\n\nvar _helmetCallback = null;\n\nvar handleClientStateChange = function handleClientStateChange(newState) {\n if (_helmetCallback) {\n cancelAnimationFrame(_helmetCallback);\n }\n\n if (newState.defer) {\n _helmetCallback = requestAnimationFrame(function () {\n commitTagChanges(newState, function () {\n _helmetCallback = null;\n });\n });\n } else {\n commitTagChanges(newState);\n _helmetCallback = null;\n }\n};\n\nvar commitTagChanges = function commitTagChanges(newState, cb) {\n var baseTag = newState.baseTag,\n bodyAttributes = newState.bodyAttributes,\n htmlAttributes = newState.htmlAttributes,\n linkTags = newState.linkTags,\n metaTags = newState.metaTags,\n noscriptTags = newState.noscriptTags,\n onChangeClientState = newState.onChangeClientState,\n scriptTags = newState.scriptTags,\n styleTags = newState.styleTags,\n title = newState.title,\n titleAttributes = newState.titleAttributes;\n\n updateAttributes(TAG_NAMES.BODY, bodyAttributes);\n updateAttributes(TAG_NAMES.HTML, htmlAttributes);\n\n updateTitle(title, titleAttributes);\n\n var tagUpdates = {\n baseTag: updateTags(TAG_NAMES.BASE, baseTag),\n linkTags: updateTags(TAG_NAMES.LINK, linkTags),\n metaTags: updateTags(TAG_NAMES.META, metaTags),\n noscriptTags: updateTags(TAG_NAMES.NOSCRIPT, noscriptTags),\n scriptTags: updateTags(TAG_NAMES.SCRIPT, scriptTags),\n styleTags: updateTags(TAG_NAMES.STYLE, styleTags)\n };\n\n var addedTags = {};\n var removedTags = {};\n\n Object.keys(tagUpdates).forEach(function (tagType) {\n var _tagUpdates$tagType = tagUpdates[tagType],\n newTags = _tagUpdates$tagType.newTags,\n oldTags = _tagUpdates$tagType.oldTags;\n\n\n if (newTags.length) {\n addedTags[tagType] = newTags;\n }\n if (oldTags.length) {\n removedTags[tagType] = tagUpdates[tagType].oldTags;\n }\n });\n\n cb && cb();\n\n onChangeClientState(newState, addedTags, removedTags);\n};\n\nvar flattenArray = function flattenArray(possibleArray) {\n return Array.isArray(possibleArray) ? possibleArray.join(\"\") : possibleArray;\n};\n\nvar updateTitle = function updateTitle(title, attributes) {\n if (typeof title !== \"undefined\" && document.title !== title) {\n document.title = flattenArray(title);\n }\n\n updateAttributes(TAG_NAMES.TITLE, attributes);\n};\n\nvar updateAttributes = function updateAttributes(tagName, attributes) {\n var elementTag = document.getElementsByTagName(tagName)[0];\n\n if (!elementTag) {\n return;\n }\n\n var helmetAttributeString = elementTag.getAttribute(HELMET_ATTRIBUTE);\n var helmetAttributes = helmetAttributeString ? helmetAttributeString.split(\",\") : [];\n var attributesToRemove = [].concat(helmetAttributes);\n var attributeKeys = Object.keys(attributes);\n\n for (var i = 0; i < attributeKeys.length; i++) {\n var attribute = attributeKeys[i];\n var value = attributes[attribute] || \"\";\n\n if (elementTag.getAttribute(attribute) !== value) {\n elementTag.setAttribute(attribute, value);\n }\n\n if (helmetAttributes.indexOf(attribute) === -1) {\n helmetAttributes.push(attribute);\n }\n\n var indexToSave = attributesToRemove.indexOf(attribute);\n if (indexToSave !== -1) {\n attributesToRemove.splice(indexToSave, 1);\n }\n }\n\n for (var _i = attributesToRemove.length - 1; _i >= 0; _i--) {\n elementTag.removeAttribute(attributesToRemove[_i]);\n }\n\n if (helmetAttributes.length === attributesToRemove.length) {\n elementTag.removeAttribute(HELMET_ATTRIBUTE);\n } else if (elementTag.getAttribute(HELMET_ATTRIBUTE) !== attributeKeys.join(\",\")) {\n elementTag.setAttribute(HELMET_ATTRIBUTE, attributeKeys.join(\",\"));\n }\n};\n\nvar updateTags = function updateTags(type, tags) {\n var headElement = document.head || document.querySelector(TAG_NAMES.HEAD);\n var tagNodes = headElement.querySelectorAll(type + \"[\" + HELMET_ATTRIBUTE + \"]\");\n var oldTags = Array.prototype.slice.call(tagNodes);\n var newTags = [];\n var indexToDelete = void 0;\n\n if (tags && tags.length) {\n tags.forEach(function (tag) {\n var newElement = document.createElement(type);\n\n for (var attribute in tag) {\n if (tag.hasOwnProperty(attribute)) {\n if (attribute === TAG_PROPERTIES.INNER_HTML) {\n newElement.innerHTML = tag.innerHTML;\n } else if (attribute === TAG_PROPERTIES.CSS_TEXT) {\n if (newElement.styleSheet) {\n newElement.styleSheet.cssText = tag.cssText;\n } else {\n newElement.appendChild(document.createTextNode(tag.cssText));\n }\n } else {\n var value = typeof tag[attribute] === \"undefined\" ? \"\" : tag[attribute];\n newElement.setAttribute(attribute, value);\n }\n }\n }\n\n newElement.setAttribute(HELMET_ATTRIBUTE, \"true\");\n\n // Remove a duplicate tag from domTagstoRemove, so it isn't cleared.\n if (oldTags.some(function (existingTag, index) {\n indexToDelete = index;\n return newElement.isEqualNode(existingTag);\n })) {\n oldTags.splice(indexToDelete, 1);\n } else {\n newTags.push(newElement);\n }\n });\n }\n\n oldTags.forEach(function (tag) {\n return tag.parentNode.removeChild(tag);\n });\n newTags.forEach(function (tag) {\n return headElement.appendChild(tag);\n });\n\n return {\n oldTags: oldTags,\n newTags: newTags\n };\n};\n\nvar generateElementAttributesAsString = function generateElementAttributesAsString(attributes) {\n return Object.keys(attributes).reduce(function (str, key) {\n var attr = typeof attributes[key] !== \"undefined\" ? key + \"=\\\"\" + attributes[key] + \"\\\"\" : \"\" + key;\n return str ? str + \" \" + attr : attr;\n }, \"\");\n};\n\nvar generateTitleAsString = function generateTitleAsString(type, title, attributes, encode) {\n var attributeString = generateElementAttributesAsString(attributes);\n var flattenedTitle = flattenArray(title);\n return attributeString ? \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\" \" + attributeString + \">\" + encodeSpecialCharacters(flattenedTitle, encode) + \"</\" + type + \">\" : \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\">\" + encodeSpecialCharacters(flattenedTitle, encode) + \"</\" + type + \">\";\n};\n\nvar generateTagsAsString = function generateTagsAsString(type, tags, encode) {\n return tags.reduce(function (str, tag) {\n var attributeHtml = Object.keys(tag).filter(function (attribute) {\n return !(attribute === TAG_PROPERTIES.INNER_HTML || attribute === TAG_PROPERTIES.CSS_TEXT);\n }).reduce(function (string, attribute) {\n var attr = typeof tag[attribute] === \"undefined\" ? attribute : attribute + \"=\\\"\" + encodeSpecialCharacters(tag[attribute], encode) + \"\\\"\";\n return string ? string + \" \" + attr : attr;\n }, \"\");\n\n var tagContent = tag.innerHTML || tag.cssText || \"\";\n\n var isSelfClosing = SELF_CLOSING_TAGS.indexOf(type) === -1;\n\n return str + \"<\" + type + \" \" + HELMET_ATTRIBUTE + \"=\\\"true\\\" \" + attributeHtml + (isSelfClosing ? \"/>\" : \">\" + tagContent + \"</\" + type + \">\");\n }, \"\");\n};\n\nvar convertElementAttributestoReactProps = function convertElementAttributestoReactProps(attributes) {\n var initProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n return Object.keys(attributes).reduce(function (obj, key) {\n obj[REACT_TAG_MAP[key] || key] = attributes[key];\n return obj;\n }, initProps);\n};\n\nvar convertReactPropstoHtmlAttributes = function convertReactPropstoHtmlAttributes(props) {\n var initAttributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n return Object.keys(props).reduce(function (obj, key) {\n obj[HTML_TAG_MAP[key] || key] = props[key];\n return obj;\n }, initAttributes);\n};\n\nvar generateTitleAsReactComponent = function generateTitleAsReactComponent(type, title, attributes) {\n var _initProps;\n\n // assigning into an array to define toString function on it\n var initProps = (_initProps = {\n key: title\n }, _initProps[HELMET_ATTRIBUTE] = true, _initProps);\n var props = convertElementAttributestoReactProps(attributes, initProps);\n\n return [React.createElement(TAG_NAMES.TITLE, props, title)];\n};\n\nvar generateTagsAsReactComponent = function generateTagsAsReactComponent(type, tags) {\n return tags.map(function (tag, i) {\n var _mappedTag;\n\n var mappedTag = (_mappedTag = {\n key: i\n }, _mappedTag[HELMET_ATTRIBUTE] = true, _mappedTag);\n\n Object.keys(tag).forEach(function (attribute) {\n var mappedAttribute = REACT_TAG_MAP[attribute] || attribute;\n\n if (mappedAttribute === TAG_PROPERTIES.INNER_HTML || mappedAttribute === TAG_PROPERTIES.CSS_TEXT) {\n var content = tag.innerHTML || tag.cssText;\n mappedTag.dangerouslySetInnerHTML = { __html: content };\n } else {\n mappedTag[mappedAttribute] = tag[attribute];\n }\n });\n\n return React.createElement(type, mappedTag);\n });\n};\n\nvar getMethodsForTag = function getMethodsForTag(type, tags, encode) {\n switch (type) {\n case TAG_NAMES.TITLE:\n return {\n toComponent: function toComponent() {\n return generateTitleAsReactComponent(type, tags.title, tags.titleAttributes, encode);\n },\n toString: function toString() {\n return generateTitleAsString(type, tags.title, tags.titleAttributes, encode);\n }\n };\n case ATTRIBUTE_NAMES.BODY:\n case ATTRIBUTE_NAMES.HTML:\n return {\n toComponent: function toComponent() {\n return convertElementAttributestoReactProps(tags);\n },\n toString: function toString() {\n return generateElementAttributesAsString(tags);\n }\n };\n default:\n return {\n toComponent: function toComponent() {\n return generateTagsAsReactComponent(type, tags);\n },\n toString: function toString() {\n return generateTagsAsString(type, tags, encode);\n }\n };\n }\n};\n\nvar mapStateOnServer = function mapStateOnServer(_ref) {\n var baseTag = _ref.baseTag,\n bodyAttributes = _ref.bodyAttributes,\n encode = _ref.encode,\n htmlAttributes = _ref.htmlAttributes,\n linkTags = _ref.linkTags,\n metaTags = _ref.metaTags,\n noscriptTags = _ref.noscriptTags,\n scriptTags = _ref.scriptTags,\n styleTags = _ref.styleTags,\n _ref$title = _ref.title,\n title = _ref$title === undefined ? \"\" : _ref$title,\n titleAttributes = _ref.titleAttributes;\n return {\n base: getMethodsForTag(TAG_NAMES.BASE, baseTag, encode),\n bodyAttributes: getMethodsForTag(ATTRIBUTE_NAMES.BODY, bodyAttributes, encode),\n htmlAttributes: getMethodsForTag(ATTRIBUTE_NAMES.HTML, htmlAttributes, encode),\n link: getMethodsForTag(TAG_NAMES.LINK, linkTags, encode),\n meta: getMethodsForTag(TAG_NAMES.META, metaTags, encode),\n noscript: getMethodsForTag(TAG_NAMES.NOSCRIPT, noscriptTags, encode),\n script: getMethodsForTag(TAG_NAMES.SCRIPT, scriptTags, encode),\n style: getMethodsForTag(TAG_NAMES.STYLE, styleTags, encode),\n title: getMethodsForTag(TAG_NAMES.TITLE, { title: title, titleAttributes: titleAttributes }, encode)\n };\n};\n\nvar Helmet = function Helmet(Component) {\n var _class, _temp;\n\n return _temp = _class = function (_React$Component) {\n inherits(HelmetWrapper, _React$Component);\n\n function HelmetWrapper() {\n classCallCheck(this, HelmetWrapper);\n return possibleConstructorReturn(this, _React$Component.apply(this, arguments));\n }\n\n HelmetWrapper.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {\n return !isEqual(this.props, nextProps);\n };\n\n HelmetWrapper.prototype.mapNestedChildrenToProps = function mapNestedChildrenToProps(child, nestedChildren) {\n if (!nestedChildren) {\n return null;\n }\n\n switch (child.type) {\n case TAG_NAMES.SCRIPT:\n case TAG_NAMES.NOSCRIPT:\n return {\n innerHTML: nestedChildren\n };\n\n case TAG_NAMES.STYLE:\n return {\n cssText: nestedChildren\n };\n }\n\n throw new Error(\"<\" + child.type + \" /> elements are self-closing and can not contain children. Refer to our API for more information.\");\n };\n\n HelmetWrapper.prototype.flattenArrayTypeChildren = function flattenArrayTypeChildren(_ref) {\n var _babelHelpers$extends;\n\n var child = _ref.child,\n arrayTypeChildren = _ref.arrayTypeChildren,\n newChildProps = _ref.newChildProps,\n nestedChildren = _ref.nestedChildren;\n\n return _extends({}, arrayTypeChildren, (_babelHelpers$extends = {}, _babelHelpers$extends[child.type] = [].concat(arrayTypeChildren[child.type] || [], [_extends({}, newChildProps, this.mapNestedChildrenToProps(child, nestedChildren))]), _babelHelpers$extends));\n };\n\n HelmetWrapper.prototype.mapObjectTypeChildren = function mapObjectTypeChildren(_ref2) {\n var _babelHelpers$extends2, _babelHelpers$extends3;\n\n var child = _ref2.child,\n newProps = _ref2.newProps,\n newChildProps = _ref2.newChildProps,\n nestedChildren = _ref2.nestedChildren;\n\n switch (child.type) {\n case TAG_NAMES.TITLE:\n return _extends({}, newProps, (_babelHelpers$extends2 = {}, _babelHelpers$extends2[child.type] = nestedChildren, _babelHelpers$extends2.titleAttributes = _extends({}, newChildProps), _babelHelpers$extends2));\n\n case TAG_NAMES.BODY:\n return _extends({}, newProps, {\n bodyAttributes: _extends({}, newChildProps)\n });\n\n case TAG_NAMES.HTML:\n return _extends({}, newProps, {\n htmlAttributes: _extends({}, newChildProps)\n });\n }\n\n return _extends({}, newProps, (_babelHelpers$extends3 = {}, _babelHelpers$extends3[child.type] = _extends({}, newChildProps), _babelHelpers$extends3));\n };\n\n HelmetWrapper.prototype.mapArrayTypeChildrenToProps = function mapArrayTypeChildrenToProps(arrayTypeChildren, newProps) {\n var newFlattenedProps = _extends({}, newProps);\n\n Object.keys(arrayTypeChildren).forEach(function (arrayChildName) {\n var _babelHelpers$extends4;\n\n newFlattenedProps = _extends({}, newFlattenedProps, (_babelHelpers$extends4 = {}, _babelHelpers$extends4[arrayChildName] = arrayTypeChildren[arrayChildName], _babelHelpers$extends4));\n });\n\n return newFlattenedProps;\n };\n\n HelmetWrapper.prototype.warnOnInvalidChildren = function warnOnInvalidChildren(child, nestedChildren) {\n if (process.env.NODE_ENV !== \"production\") {\n if (!VALID_TAG_NAMES.some(function (name) {\n return child.type === name;\n })) {\n if (typeof child.type === \"function\") {\n return warn(\"You may be attempting to nest <Helmet> components within each other, which is not allowed. Refer to our API for more information.\");\n }\n\n return warn(\"Only elements types \" + VALID_TAG_NAMES.join(\", \") + \" are allowed. Helmet does not support rendering <\" + child.type + \"> elements. Refer to our API for more information.\");\n }\n\n if (nestedChildren && typeof nestedChildren !== \"string\" && (!Array.isArray(nestedChildren) || nestedChildren.some(function (nestedChild) {\n return typeof nestedChild !== \"string\";\n }))) {\n throw new Error(\"Helmet expects a string as a child of <\" + child.type + \">. Did you forget to wrap your children in braces? ( <\" + child.type + \">{``}</\" + child.type + \"> ) Refer to our API for more information.\");\n }\n }\n\n return true;\n };\n\n HelmetWrapper.prototype.mapChildrenToProps = function mapChildrenToProps(children, newProps) {\n var _this2 = this;\n\n var arrayTypeChildren = {};\n\n React.Children.forEach(children, function (child) {\n if (!child || !child.props) {\n return;\n }\n\n var _child$props = child.props,\n nestedChildren = _child$props.children,\n childProps = objectWithoutProperties(_child$props, [\"children\"]);\n\n var newChildProps = convertReactPropstoHtmlAttributes(childProps);\n\n _this2.warnOnInvalidChildren(child, nestedChildren);\n\n switch (child.type) {\n case TAG_NAMES.LINK:\n case TAG_NAMES.META:\n case TAG_NAMES.NOSCRIPT:\n case TAG_NAMES.SCRIPT:\n case TAG_NAMES.STYLE:\n arrayTypeChildren = _this2.flattenArrayTypeChildren({\n child: child,\n arrayTypeChildren: arrayTypeChildren,\n newChildProps: newChildProps,\n nestedChildren: nestedChildren\n });\n break;\n\n default:\n newProps = _this2.mapObjectTypeChildren({\n child: child,\n newProps: newProps,\n newChildProps: newChildProps,\n nestedChildren: nestedChildren\n });\n break;\n }\n });\n\n newProps = this.mapArrayTypeChildrenToProps(arrayTypeChildren, newProps);\n return newProps;\n };\n\n HelmetWrapper.prototype.render = function render() {\n var _props = this.props,\n children = _props.children,\n props = objectWithoutProperties(_props, [\"children\"]);\n\n var newProps = _extends({}, props);\n\n if (children) {\n newProps = this.mapChildrenToProps(children, newProps);\n }\n\n return React.createElement(Component, newProps);\n };\n\n createClass(HelmetWrapper, null, [{\n key: \"canUseDOM\",\n\n\n // Component.peek comes from react-side-effect:\n // For testing, you may use a static peek() method available on the returned component.\n // It lets you get the current state without resetting the mounted instance stack.\n // Don’t use it for anything other than testing.\n\n /**\n * @param {Object} base: {\"target\": \"_blank\", \"href\": \"http://mysite.com/\"}\n * @param {Object} bodyAttributes: {\"className\": \"root\"}\n * @param {String} defaultTitle: \"Default Title\"\n * @param {Boolean} defer: true\n * @param {Boolean} encodeSpecialCharacters: true\n * @param {Object} htmlAttributes: {\"lang\": \"en\", \"amp\": undefined}\n * @param {Array} link: [{\"rel\": \"canonical\", \"href\": \"http://mysite.com/example\"}]\n * @param {Array} meta: [{\"name\": \"description\", \"content\": \"Test description\"}]\n * @param {Array} noscript: [{\"innerHTML\": \"<img src='http://mysite.com/js/test.js'\"}]\n * @param {Function} onChangeClientState: \"(newState) => console.log(newState)\"\n * @param {Array} script: [{\"type\": \"text/javascript\", \"src\": \"http://mysite.com/js/test.js\"}]\n * @param {Array} style: [{\"type\": \"text/css\", \"cssText\": \"div { display: block; color: blue; }\"}]\n * @param {String} title: \"Title\"\n * @param {Object} titleAttributes: {\"itemprop\": \"name\"}\n * @param {String} titleTemplate: \"MySite.com - %s\"\n */\n set: function set$$1(canUseDOM) {\n Component.canUseDOM = canUseDOM;\n }\n }]);\n return HelmetWrapper;\n }(React.Component), _class.propTypes = {\n base: PropTypes.object,\n bodyAttributes: PropTypes.object,\n children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),\n defaultTitle: PropTypes.string,\n defer: PropTypes.bool,\n encodeSpecialCharacters: PropTypes.bool,\n htmlAttributes: PropTypes.object,\n link: PropTypes.arrayOf(PropTypes.object),\n meta: PropTypes.arrayOf(PropTypes.object),\n noscript: PropTypes.arrayOf(PropTypes.object),\n onChangeClientState: PropTypes.func,\n script: PropTypes.arrayOf(PropTypes.object),\n style: PropTypes.arrayOf(PropTypes.object),\n title: PropTypes.string,\n titleAttributes: PropTypes.object,\n titleTemplate: PropTypes.string\n }, _class.defaultProps = {\n defer: true,\n encodeSpecialCharacters: true\n }, _class.peek = Component.peek, _class.rewind = function () {\n var mappedState = Component.rewind();\n if (!mappedState) {\n // provide fallback if mappedState is undefined\n mappedState = mapStateOnServer({\n baseTag: [],\n bodyAttributes: {},\n encodeSpecialCharacters: true,\n htmlAttributes: {},\n linkTags: [],\n metaTags: [],\n noscriptTags: [],\n scriptTags: [],\n styleTags: [],\n title: \"\",\n titleAttributes: {}\n });\n }\n\n return mappedState;\n }, _temp;\n};\n\nvar NullComponent = function NullComponent() {\n return null;\n};\n\nvar HelmetSideEffects = withSideEffect(reducePropsToState, handleClientStateChange, mapStateOnServer)(NullComponent);\n\nvar HelmetExport = Helmet(HelmetSideEffects);\nHelmetExport.renderStatic = HelmetExport.rewind;\n\nexport default HelmetExport;\nexport { HelmetExport as Helmet };\n","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport PropTypes from 'prop-types';\nimport merge from './merge'; // The breakpoint **start** at this value.\n// For instance with the first breakpoint xs: [xs, sm[.\n\nvar values = {\n xs: 0,\n sm: 600,\n md: 960,\n lg: 1280,\n xl: 1920\n};\nvar defaultBreakpoints = {\n // Sorted ASC by size. That's important.\n // It can't be configured as it's used statically for propTypes.\n keys: ['xs', 'sm', 'md', 'lg', 'xl'],\n up: function up(key) {\n return \"@media (min-width:\".concat(values[key], \"px)\");\n }\n};\nexport function handleBreakpoints(props, propValue, styleFromPropValue) {\n if (process.env.NODE_ENV !== 'production') {\n if (!props.theme) {\n console.error('Material-UI: You are calling a style function without a theme value.');\n }\n }\n\n if (Array.isArray(propValue)) {\n var themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n return propValue.reduce(function (acc, item, index) {\n acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);\n return acc;\n }, {});\n }\n\n if (_typeof(propValue) === 'object') {\n var _themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n\n return Object.keys(propValue).reduce(function (acc, breakpoint) {\n acc[_themeBreakpoints.up(breakpoint)] = styleFromPropValue(propValue[breakpoint]);\n return acc;\n }, {});\n }\n\n var output = styleFromPropValue(propValue);\n return output;\n}\n\nfunction breakpoints(styleFunction) {\n var newStyleFunction = function newStyleFunction(props) {\n var base = styleFunction(props);\n var themeBreakpoints = props.theme.breakpoints || defaultBreakpoints;\n var extended = themeBreakpoints.keys.reduce(function (acc, key) {\n if (props[key]) {\n acc = acc || {};\n acc[themeBreakpoints.up(key)] = styleFunction(_extends({\n theme: props.theme\n }, props[key]));\n }\n\n return acc;\n }, null);\n return merge(base, extended);\n };\n\n newStyleFunction.propTypes = process.env.NODE_ENV !== 'production' ? _extends({}, styleFunction.propTypes, {\n xs: PropTypes.object,\n sm: PropTypes.object,\n md: PropTypes.object,\n lg: PropTypes.object,\n xl: PropTypes.object\n }) : {};\n newStyleFunction.filterProps = ['xs', 'sm', 'md', 'lg', 'xl'].concat(_toConsumableArray(styleFunction.filterProps));\n return newStyleFunction;\n}\n\nexport default breakpoints;","// We need to centralize the zIndex definitions as they work\n// like global values in the browser.\nvar zIndex = {\n mobileStepper: 1000,\n speedDial: 1050,\n appBar: 1100,\n drawer: 1200,\n modal: 1300,\n snackbar: 1400,\n tooltip: 1500\n};\nexport default zIndex;","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <http://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return '<Buffer ' + str + '>'\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n","module.exports = Long;\r\n\r\n/**\r\n * wasm optimizations, to do native i64 multiplication and divide\r\n */\r\nvar wasm = null;\r\n\r\ntry {\r\n wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([\r\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11\r\n ])), {}).exports;\r\n} catch (e) {\r\n // no wasm support :(\r\n}\r\n\r\n/**\r\n * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.\r\n * See the from* functions below for more convenient ways of constructing Longs.\r\n * @exports Long\r\n * @class A Long class for representing a 64 bit two's-complement integer value.\r\n * @param {number} low The low (signed) 32 bits of the long\r\n * @param {number} high The high (signed) 32 bits of the long\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @constructor\r\n */\r\nfunction Long(low, high, unsigned) {\r\n\r\n /**\r\n * The low 32 bits as a signed value.\r\n * @type {number}\r\n */\r\n this.low = low | 0;\r\n\r\n /**\r\n * The high 32 bits as a signed value.\r\n * @type {number}\r\n */\r\n this.high = high | 0;\r\n\r\n /**\r\n * Whether unsigned or not.\r\n * @type {boolean}\r\n */\r\n this.unsigned = !!unsigned;\r\n}\r\n\r\n// The internal representation of a long is the two given signed, 32-bit values.\r\n// We use 32-bit pieces because these are the size of integers on which\r\n// Javascript performs bit-operations. For operations like addition and\r\n// multiplication, we split each number into 16 bit pieces, which can easily be\r\n// multiplied within Javascript's floating-point representation without overflow\r\n// or change in sign.\r\n//\r\n// In the algorithms below, we frequently reduce the negative case to the\r\n// positive case by negating the input(s) and then post-processing the result.\r\n// Note that we must ALWAYS check specially whether those values are MIN_VALUE\r\n// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as\r\n// a positive number, it overflows back into a negative). Not handling this\r\n// case would often result in infinite recursion.\r\n//\r\n// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*\r\n// methods on which they depend.\r\n\r\n/**\r\n * An indicator used to reliably determine if an object is a Long or not.\r\n * @type {boolean}\r\n * @const\r\n * @private\r\n */\r\nLong.prototype.__isLong__;\r\n\r\nObject.defineProperty(Long.prototype, \"__isLong__\", { value: true });\r\n\r\n/**\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n * @inner\r\n */\r\nfunction isLong(obj) {\r\n return (obj && obj[\"__isLong__\"]) === true;\r\n}\r\n\r\n/**\r\n * Tests if the specified object is a Long.\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n */\r\nLong.isLong = isLong;\r\n\r\n/**\r\n * A cache of the Long representations of small integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar INT_CACHE = {};\r\n\r\n/**\r\n * A cache of the Long representations of small unsigned integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar UINT_CACHE = {};\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromInt(value, unsigned) {\r\n var obj, cachedObj, cache;\r\n if (unsigned) {\r\n value >>>= 0;\r\n if (cache = (0 <= value && value < 256)) {\r\n cachedObj = UINT_CACHE[value];\r\n if (cachedObj)\r\n return cachedObj;\r\n }\r\n obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);\r\n if (cache)\r\n UINT_CACHE[value] = obj;\r\n return obj;\r\n } else {\r\n value |= 0;\r\n if (cache = (-128 <= value && value < 128)) {\r\n cachedObj = INT_CACHE[value];\r\n if (cachedObj)\r\n return cachedObj;\r\n }\r\n obj = fromBits(value, value < 0 ? -1 : 0, false);\r\n if (cache)\r\n INT_CACHE[value] = obj;\r\n return obj;\r\n }\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given 32 bit integer value.\r\n * @function\r\n * @param {number} value The 32 bit integer in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromInt = fromInt;\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromNumber(value, unsigned) {\r\n if (isNaN(value))\r\n return unsigned ? UZERO : ZERO;\r\n if (unsigned) {\r\n if (value < 0)\r\n return UZERO;\r\n if (value >= TWO_PWR_64_DBL)\r\n return MAX_UNSIGNED_VALUE;\r\n } else {\r\n if (value <= -TWO_PWR_63_DBL)\r\n return MIN_VALUE;\r\n if (value + 1 >= TWO_PWR_63_DBL)\r\n return MAX_VALUE;\r\n }\r\n if (value < 0)\r\n return fromNumber(-value, unsigned).neg();\r\n return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.\r\n * @function\r\n * @param {number} value The number in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromNumber = fromNumber;\r\n\r\n/**\r\n * @param {number} lowBits\r\n * @param {number} highBits\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromBits(lowBits, highBits, unsigned) {\r\n return new Long(lowBits, highBits, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is\r\n * assumed to use 32 bits.\r\n * @function\r\n * @param {number} lowBits The low 32 bits\r\n * @param {number} highBits The high 32 bits\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromBits = fromBits;\r\n\r\n/**\r\n * @function\r\n * @param {number} base\r\n * @param {number} exponent\r\n * @returns {number}\r\n * @inner\r\n */\r\nvar pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)\r\n\r\n/**\r\n * @param {string} str\r\n * @param {(boolean|number)=} unsigned\r\n * @param {number=} radix\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromString(str, unsigned, radix) {\r\n if (str.length === 0)\r\n throw Error('empty string');\r\n if (str === \"NaN\" || str === \"Infinity\" || str === \"+Infinity\" || str === \"-Infinity\")\r\n return ZERO;\r\n if (typeof unsigned === 'number') {\r\n // For goog.math.long compatibility\r\n radix = unsigned,\r\n unsigned = false;\r\n } else {\r\n unsigned = !! unsigned;\r\n }\r\n radix = radix || 10;\r\n if (radix < 2 || 36 < radix)\r\n throw RangeError('radix');\r\n\r\n var p;\r\n if ((p = str.indexOf('-')) > 0)\r\n throw Error('interior hyphen');\r\n else if (p === 0) {\r\n return fromString(str.substring(1), unsigned, radix).neg();\r\n }\r\n\r\n // Do several (8) digits each time through the loop, so as to\r\n // minimize the calls to the very expensive emulated div.\r\n var radixToPower = fromNumber(pow_dbl(radix, 8));\r\n\r\n var result = ZERO;\r\n for (var i = 0; i < str.length; i += 8) {\r\n var size = Math.min(8, str.length - i),\r\n value = parseInt(str.substring(i, i + size), radix);\r\n if (size < 8) {\r\n var power = fromNumber(pow_dbl(radix, size));\r\n result = result.mul(power).add(fromNumber(value));\r\n } else {\r\n result = result.mul(radixToPower);\r\n result = result.add(fromNumber(value));\r\n }\r\n }\r\n result.unsigned = unsigned;\r\n return result;\r\n}\r\n\r\n/**\r\n * Returns a Long representation of the given string, written using the specified radix.\r\n * @function\r\n * @param {string} str The textual representation of the Long\r\n * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {number=} radix The radix in which the text is written (2-36), defaults to 10\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromString = fromString;\r\n\r\n/**\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromValue(val, unsigned) {\r\n if (typeof val === 'number')\r\n return fromNumber(val, unsigned);\r\n if (typeof val === 'string')\r\n return fromString(val, unsigned);\r\n // Throws for non-objects, converts non-instanceof Long:\r\n return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);\r\n}\r\n\r\n/**\r\n * Converts the specified value to a Long using the appropriate from* function for its type.\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long}\r\n */\r\nLong.fromValue = fromValue;\r\n\r\n// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be\r\n// no runtime penalty for these.\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_16_DBL = 1 << 16;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24_DBL = 1 << 24;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;\r\n\r\n/**\r\n * @type {!Long}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ZERO = fromInt(0);\r\n\r\n/**\r\n * Signed zero.\r\n * @type {!Long}\r\n */\r\nLong.ZERO = ZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UZERO = fromInt(0, true);\r\n\r\n/**\r\n * Unsigned zero.\r\n * @type {!Long}\r\n */\r\nLong.UZERO = UZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ONE = fromInt(1);\r\n\r\n/**\r\n * Signed one.\r\n * @type {!Long}\r\n */\r\nLong.ONE = ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UONE = fromInt(1, true);\r\n\r\n/**\r\n * Unsigned one.\r\n * @type {!Long}\r\n */\r\nLong.UONE = UONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar NEG_ONE = fromInt(-1);\r\n\r\n/**\r\n * Signed negative one.\r\n * @type {!Long}\r\n */\r\nLong.NEG_ONE = NEG_ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);\r\n\r\n/**\r\n * Maximum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_VALUE = MAX_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);\r\n\r\n/**\r\n * Maximum unsigned value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MIN_VALUE = fromBits(0, 0x80000000|0, false);\r\n\r\n/**\r\n * Minimum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MIN_VALUE = MIN_VALUE;\r\n\r\n/**\r\n * @alias Long.prototype\r\n * @inner\r\n */\r\nvar LongPrototype = Long.prototype;\r\n\r\n/**\r\n * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.\r\n * @returns {number}\r\n */\r\nLongPrototype.toInt = function toInt() {\r\n return this.unsigned ? this.low >>> 0 : this.low;\r\n};\r\n\r\n/**\r\n * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).\r\n * @returns {number}\r\n */\r\nLongPrototype.toNumber = function toNumber() {\r\n if (this.unsigned)\r\n return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);\r\n return this.high * TWO_PWR_32_DBL + (this.low >>> 0);\r\n};\r\n\r\n/**\r\n * Converts the Long to a string written in the specified radix.\r\n * @param {number=} radix Radix (2-36), defaults to 10\r\n * @returns {string}\r\n * @override\r\n * @throws {RangeError} If `radix` is out of range\r\n */\r\nLongPrototype.toString = function toString(radix) {\r\n radix = radix || 10;\r\n if (radix < 2 || 36 < radix)\r\n throw RangeError('radix');\r\n if (this.isZero())\r\n return '0';\r\n if (this.isNegative()) { // Unsigned Longs are never negative\r\n if (this.eq(MIN_VALUE)) {\r\n // We need to change the Long value before it can be negated, so we remove\r\n // the bottom-most digit in this base and then recurse to do the rest.\r\n var radixLong = fromNumber(radix),\r\n div = this.div(radixLong),\r\n rem1 = div.mul(radixLong).sub(this);\r\n return div.toString(radix) + rem1.toInt().toString(radix);\r\n } else\r\n return '-' + this.neg().toString(radix);\r\n }\r\n\r\n // Do several (6) digits each time through the loop, so as to\r\n // minimize the calls to the very expensive emulated div.\r\n var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),\r\n rem = this;\r\n var result = '';\r\n while (true) {\r\n var remDiv = rem.div(radixToPower),\r\n intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,\r\n digits = intval.toString(radix);\r\n rem = remDiv;\r\n if (rem.isZero())\r\n return digits + result;\r\n else {\r\n while (digits.length < 6)\r\n digits = '0' + digits;\r\n result = '' + digits + result;\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as a signed integer.\r\n * @returns {number} Signed high bits\r\n */\r\nLongPrototype.getHighBits = function getHighBits() {\r\n return this.high;\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned high bits\r\n */\r\nLongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {\r\n return this.high >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as a signed integer.\r\n * @returns {number} Signed low bits\r\n */\r\nLongPrototype.getLowBits = function getLowBits() {\r\n return this.low;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned low bits\r\n */\r\nLongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {\r\n return this.low >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the number of bits needed to represent the absolute value of this Long.\r\n * @returns {number}\r\n */\r\nLongPrototype.getNumBitsAbs = function getNumBitsAbs() {\r\n if (this.isNegative()) // Unsigned Longs are never negative\r\n return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();\r\n var val = this.high != 0 ? this.high : this.low;\r\n for (var bit = 31; bit > 0; bit--)\r\n if ((val & (1 << bit)) != 0)\r\n break;\r\n return this.high != 0 ? bit + 33 : bit + 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isZero = function isZero() {\r\n return this.high === 0 && this.low === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eqz = LongPrototype.isZero;\r\n\r\n/**\r\n * Tests if this Long's value is negative.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isNegative = function isNegative() {\r\n return !this.unsigned && this.high < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is positive.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isPositive = function isPositive() {\r\n return this.unsigned || this.high >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is odd.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isOdd = function isOdd() {\r\n return (this.low & 1) === 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is even.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isEven = function isEven() {\r\n return (this.low & 1) === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.equals = function equals(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)\r\n return false;\r\n return this.high === other.high && this.low === other.low;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eq = LongPrototype.equals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.notEquals = function notEquals(other) {\r\n return !this.eq(/* validates */ other);\r\n};\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.neq = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ne = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThan = function lessThan(other) {\r\n return this.comp(/* validates */ other) < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lt = LongPrototype.lessThan;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {\r\n return this.comp(/* validates */ other) <= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lte = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.le = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThan = function greaterThan(other) {\r\n return this.comp(/* validates */ other) > 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gt = LongPrototype.greaterThan;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {\r\n return this.comp(/* validates */ other) >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gte = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ge = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Compares this Long's value with the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n * if the given one is greater\r\n */\r\nLongPrototype.compare = function compare(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n if (this.eq(other))\r\n return 0;\r\n var thisNeg = this.isNegative(),\r\n otherNeg = other.isNegative();\r\n if (thisNeg && !otherNeg)\r\n return -1;\r\n if (!thisNeg && otherNeg)\r\n return 1;\r\n // At this point the sign bits are the same\r\n if (!this.unsigned)\r\n return this.sub(other).isNegative() ? -1 : 1;\r\n // Both are positive if at least one is unsigned\r\n return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;\r\n};\r\n\r\n/**\r\n * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n * if the given one is greater\r\n */\r\nLongPrototype.comp = LongPrototype.compare;\r\n\r\n/**\r\n * Negates this Long's value.\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.negate = function negate() {\r\n if (!this.unsigned && this.eq(MIN_VALUE))\r\n return MIN_VALUE;\r\n return this.not().add(ONE);\r\n};\r\n\r\n/**\r\n * Negates this Long's value. This is an alias of {@link Long#negate}.\r\n * @function\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.neg = LongPrototype.negate;\r\n\r\n/**\r\n * Returns the sum of this and the specified Long.\r\n * @param {!Long|number|string} addend Addend\r\n * @returns {!Long} Sum\r\n */\r\nLongPrototype.add = function add(addend) {\r\n if (!isLong(addend))\r\n addend = fromValue(addend);\r\n\r\n // Divide each number into 4 chunks of 16 bits, and then sum the chunks.\r\n\r\n var a48 = this.high >>> 16;\r\n var a32 = this.high & 0xFFFF;\r\n var a16 = this.low >>> 16;\r\n var a00 = this.low & 0xFFFF;\r\n\r\n var b48 = addend.high >>> 16;\r\n var b32 = addend.high & 0xFFFF;\r\n var b16 = addend.low >>> 16;\r\n var b00 = addend.low & 0xFFFF;\r\n\r\n var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n c00 += a00 + b00;\r\n c16 += c00 >>> 16;\r\n c00 &= 0xFFFF;\r\n c16 += a16 + b16;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c32 += a32 + b32;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c48 += a48 + b48;\r\n c48 &= 0xFFFF;\r\n return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long.\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.subtract = function subtract(subtrahend) {\r\n if (!isLong(subtrahend))\r\n subtrahend = fromValue(subtrahend);\r\n return this.add(subtrahend.neg());\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.\r\n * @function\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.sub = LongPrototype.subtract;\r\n\r\n/**\r\n * Returns the product of this and the specified Long.\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.multiply = function multiply(multiplier) {\r\n if (this.isZero())\r\n return ZERO;\r\n if (!isLong(multiplier))\r\n multiplier = fromValue(multiplier);\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n var low = wasm.mul(this.low,\r\n this.high,\r\n multiplier.low,\r\n multiplier.high);\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n if (multiplier.isZero())\r\n return ZERO;\r\n if (this.eq(MIN_VALUE))\r\n return multiplier.isOdd() ? MIN_VALUE : ZERO;\r\n if (multiplier.eq(MIN_VALUE))\r\n return this.isOdd() ? MIN_VALUE : ZERO;\r\n\r\n if (this.isNegative()) {\r\n if (multiplier.isNegative())\r\n return this.neg().mul(multiplier.neg());\r\n else\r\n return this.neg().mul(multiplier).neg();\r\n } else if (multiplier.isNegative())\r\n return this.mul(multiplier.neg()).neg();\r\n\r\n // If both longs are small, use float multiplication\r\n if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))\r\n return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);\r\n\r\n // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.\r\n // We can skip products that would overflow.\r\n\r\n var a48 = this.high >>> 16;\r\n var a32 = this.high & 0xFFFF;\r\n var a16 = this.low >>> 16;\r\n var a00 = this.low & 0xFFFF;\r\n\r\n var b48 = multiplier.high >>> 16;\r\n var b32 = multiplier.high & 0xFFFF;\r\n var b16 = multiplier.low >>> 16;\r\n var b00 = multiplier.low & 0xFFFF;\r\n\r\n var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n c00 += a00 * b00;\r\n c16 += c00 >>> 16;\r\n c00 &= 0xFFFF;\r\n c16 += a16 * b00;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c16 += a00 * b16;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c32 += a32 * b00;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c32 += a16 * b16;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c32 += a00 * b32;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;\r\n c48 &= 0xFFFF;\r\n return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.\r\n * @function\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.mul = LongPrototype.multiply;\r\n\r\n/**\r\n * Returns this Long divided by the specified. The result is signed if this Long is signed or\r\n * unsigned if this Long is unsigned.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.divide = function divide(divisor) {\r\n if (!isLong(divisor))\r\n divisor = fromValue(divisor);\r\n if (divisor.isZero())\r\n throw Error('division by zero');\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n // guard against signed division overflow: the largest\r\n // negative number / -1 would be 1 larger than the largest\r\n // positive number, due to two's complement.\r\n if (!this.unsigned &&\r\n this.high === -0x80000000 &&\r\n divisor.low === -1 && divisor.high === -1) {\r\n // be consistent with non-wasm code path\r\n return this;\r\n }\r\n var low = (this.unsigned ? wasm.div_u : wasm.div_s)(\r\n this.low,\r\n this.high,\r\n divisor.low,\r\n divisor.high\r\n );\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n if (this.isZero())\r\n return this.unsigned ? UZERO : ZERO;\r\n var approx, rem, res;\r\n if (!this.unsigned) {\r\n // This section is only relevant for signed longs and is derived from the\r\n // closure library as a whole.\r\n if (this.eq(MIN_VALUE)) {\r\n if (divisor.eq(ONE) || divisor.eq(NEG_ONE))\r\n return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE\r\n else if (divisor.eq(MIN_VALUE))\r\n return ONE;\r\n else {\r\n // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.\r\n var halfThis = this.shr(1);\r\n approx = halfThis.div(divisor).shl(1);\r\n if (approx.eq(ZERO)) {\r\n return divisor.isNegative() ? ONE : NEG_ONE;\r\n } else {\r\n rem = this.sub(divisor.mul(approx));\r\n res = approx.add(rem.div(divisor));\r\n return res;\r\n }\r\n }\r\n } else if (divisor.eq(MIN_VALUE))\r\n return this.unsigned ? UZERO : ZERO;\r\n if (this.isNegative()) {\r\n if (divisor.isNegative())\r\n return this.neg().div(divisor.neg());\r\n return this.neg().div(divisor).neg();\r\n } else if (divisor.isNegative())\r\n return this.div(divisor.neg()).neg();\r\n res = ZERO;\r\n } else {\r\n // The algorithm below has not been made for unsigned longs. It's therefore\r\n // required to take special care of the MSB prior to running it.\r\n if (!divisor.unsigned)\r\n divisor = divisor.toUnsigned();\r\n if (divisor.gt(this))\r\n return UZERO;\r\n if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true\r\n return UONE;\r\n res = UZERO;\r\n }\r\n\r\n // Repeat the following until the remainder is less than other: find a\r\n // floating-point that approximates remainder / other *from below*, add this\r\n // into the result, and subtract it from the remainder. It is critical that\r\n // the approximate value is less than or equal to the real value so that the\r\n // remainder never becomes negative.\r\n rem = this;\r\n while (rem.gte(divisor)) {\r\n // Approximate the result of division. This may be a little greater or\r\n // smaller than the actual value.\r\n approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));\r\n\r\n // We will tweak the approximate result by changing it in the 48-th digit or\r\n // the smallest non-fractional digit, whichever is larger.\r\n var log2 = Math.ceil(Math.log(approx) / Math.LN2),\r\n delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),\r\n\r\n // Decrease the approximation until it is smaller than the remainder. Note\r\n // that if it is too large, the product overflows and is negative.\r\n approxRes = fromNumber(approx),\r\n approxRem = approxRes.mul(divisor);\r\n while (approxRem.isNegative() || approxRem.gt(rem)) {\r\n approx -= delta;\r\n approxRes = fromNumber(approx, this.unsigned);\r\n approxRem = approxRes.mul(divisor);\r\n }\r\n\r\n // We know the answer can't be zero... and actually, zero would cause\r\n // infinite recursion since we would make no progress.\r\n if (approxRes.isZero())\r\n approxRes = ONE;\r\n\r\n res = res.add(approxRes);\r\n rem = rem.sub(approxRem);\r\n }\r\n return res;\r\n};\r\n\r\n/**\r\n * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.div = LongPrototype.divide;\r\n\r\n/**\r\n * Returns this Long modulo the specified.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.modulo = function modulo(divisor) {\r\n if (!isLong(divisor))\r\n divisor = fromValue(divisor);\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(\r\n this.low,\r\n this.high,\r\n divisor.low,\r\n divisor.high\r\n );\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n return this.sub(this.div(divisor).mul(divisor));\r\n};\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.mod = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.rem = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns the bitwise NOT of this Long.\r\n * @returns {!Long}\r\n */\r\nLongPrototype.not = function not() {\r\n return fromBits(~this.low, ~this.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise AND of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.and = function and(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low & other.low, this.high & other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise OR of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.or = function or(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low | other.low, this.high | other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise XOR of this Long and the given one.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.xor = function xor(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftLeft = function shiftLeft(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n if ((numBits &= 63) === 0)\r\n return this;\r\n else if (numBits < 32)\r\n return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);\r\n else\r\n return fromBits(0, this.low << (numBits - 32), this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shl = LongPrototype.shiftLeft;\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRight = function shiftRight(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n if ((numBits &= 63) === 0)\r\n return this;\r\n else if (numBits < 32)\r\n return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);\r\n else\r\n return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr = LongPrototype.shiftRight;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n numBits &= 63;\r\n if (numBits === 0)\r\n return this;\r\n else {\r\n var high = this.high;\r\n if (numBits < 32) {\r\n var low = this.low;\r\n return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);\r\n } else if (numBits === 32)\r\n return fromBits(high, 0, this.unsigned);\r\n else\r\n return fromBits(high >>> (numBits - 32), 0, this.unsigned);\r\n }\r\n};\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shru = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr_u = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Converts this Long to signed.\r\n * @returns {!Long} Signed long\r\n */\r\nLongPrototype.toSigned = function toSigned() {\r\n if (!this.unsigned)\r\n return this;\r\n return fromBits(this.low, this.high, false);\r\n};\r\n\r\n/**\r\n * Converts this Long to unsigned.\r\n * @returns {!Long} Unsigned long\r\n */\r\nLongPrototype.toUnsigned = function toUnsigned() {\r\n if (this.unsigned)\r\n return this;\r\n return fromBits(this.low, this.high, true);\r\n};\r\n\r\n/**\r\n * Converts this Long to its byte representation.\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {!Array.<number>} Byte representation\r\n */\r\nLongPrototype.toBytes = function toBytes(le) {\r\n return le ? this.toBytesLE() : this.toBytesBE();\r\n};\r\n\r\n/**\r\n * Converts this Long to its little endian byte representation.\r\n * @returns {!Array.<number>} Little endian byte representation\r\n */\r\nLongPrototype.toBytesLE = function toBytesLE() {\r\n var hi = this.high,\r\n lo = this.low;\r\n return [\r\n lo & 0xff,\r\n lo >>> 8 & 0xff,\r\n lo >>> 16 & 0xff,\r\n lo >>> 24 ,\r\n hi & 0xff,\r\n hi >>> 8 & 0xff,\r\n hi >>> 16 & 0xff,\r\n hi >>> 24\r\n ];\r\n};\r\n\r\n/**\r\n * Converts this Long to its big endian byte representation.\r\n * @returns {!Array.<number>} Big endian byte representation\r\n */\r\nLongPrototype.toBytesBE = function toBytesBE() {\r\n var hi = this.high,\r\n lo = this.low;\r\n return [\r\n hi >>> 24 ,\r\n hi >>> 16 & 0xff,\r\n hi >>> 8 & 0xff,\r\n hi & 0xff,\r\n lo >>> 24 ,\r\n lo >>> 16 & 0xff,\r\n lo >>> 8 & 0xff,\r\n lo & 0xff\r\n ];\r\n};\r\n\r\n/**\r\n * Creates a Long from its byte representation.\r\n * @param {!Array.<number>} bytes Byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytes = function fromBytes(bytes, unsigned, le) {\r\n return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);\r\n};\r\n\r\n/**\r\n * Creates a Long from its little endian byte representation.\r\n * @param {!Array.<number>} bytes Little endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesLE = function fromBytesLE(bytes, unsigned) {\r\n return new Long(\r\n bytes[0] |\r\n bytes[1] << 8 |\r\n bytes[2] << 16 |\r\n bytes[3] << 24,\r\n bytes[4] |\r\n bytes[5] << 8 |\r\n bytes[6] << 16 |\r\n bytes[7] << 24,\r\n unsigned\r\n );\r\n};\r\n\r\n/**\r\n * Creates a Long from its big endian byte representation.\r\n * @param {!Array.<number>} bytes Big endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesBE = function fromBytesBE(bytes, unsigned) {\r\n return new Long(\r\n bytes[4] << 24 |\r\n bytes[5] << 16 |\r\n bytes[6] << 8 |\r\n bytes[7],\r\n bytes[0] << 24 |\r\n bytes[1] << 16 |\r\n bytes[2] << 8 |\r\n bytes[3],\r\n unsigned\r\n );\r\n};\r\n","/*!\n Copyright (c) 2018 Jed Watson.\n Licensed under the MIT License (MIT), see\n http://jedwatson.github.io/classnames\n*/\n/* global define */\n\n(function () {\n\t'use strict';\n\n\tvar hasOwn = {}.hasOwnProperty;\n\n\tfunction classNames() {\n\t\tvar classes = [];\n\n\t\tfor (var i = 0; i < arguments.length; i++) {\n\t\t\tvar arg = arguments[i];\n\t\t\tif (!arg) continue;\n\n\t\t\tvar argType = typeof arg;\n\n\t\t\tif (argType === 'string' || argType === 'number') {\n\t\t\t\tclasses.push(arg);\n\t\t\t} else if (Array.isArray(arg)) {\n\t\t\t\tif (arg.length) {\n\t\t\t\t\tvar inner = classNames.apply(null, arg);\n\t\t\t\t\tif (inner) {\n\t\t\t\t\t\tclasses.push(inner);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (argType === 'object') {\n\t\t\t\tif (arg.toString === Object.prototype.toString) {\n\t\t\t\t\tfor (var key in arg) {\n\t\t\t\t\t\tif (hasOwn.call(arg, key) && arg[key]) {\n\t\t\t\t\t\t\tclasses.push(key);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tclasses.push(arg.toString());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn classes.join(' ');\n\t}\n\n\tif (typeof module !== 'undefined' && module.exports) {\n\t\tclassNames.default = classNames;\n\t\tmodule.exports = classNames;\n\t} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {\n\t\t// register as 'classnames', consistent with npm package name\n\t\tdefine('classnames', [], function () {\n\t\t\treturn classNames;\n\t\t});\n\t} else {\n\t\twindow.classNames = classNames;\n\t}\n}());\n","import React, { Component } from 'react';\nimport _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose';\nimport PropTypes from 'prop-types';\nimport warning from 'tiny-warning';\n\nvar MAX_SIGNED_31_BIT_INT = 1073741823;\nvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {};\n\nfunction getUniqueId() {\n var key = '__global_unique_id__';\n return commonjsGlobal[key] = (commonjsGlobal[key] || 0) + 1;\n}\n\nfunction objectIs(x, y) {\n if (x === y) {\n return x !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\n\nfunction createEventEmitter(value) {\n var handlers = [];\n return {\n on: function on(handler) {\n handlers.push(handler);\n },\n off: function off(handler) {\n handlers = handlers.filter(function (h) {\n return h !== handler;\n });\n },\n get: function get() {\n return value;\n },\n set: function set(newValue, changedBits) {\n value = newValue;\n handlers.forEach(function (handler) {\n return handler(value, changedBits);\n });\n }\n };\n}\n\nfunction onlyChild(children) {\n return Array.isArray(children) ? children[0] : children;\n}\n\nfunction createReactContext(defaultValue, calculateChangedBits) {\n var _Provider$childContex, _Consumer$contextType;\n\n var contextProp = '__create-react-context-' + getUniqueId() + '__';\n\n var Provider = /*#__PURE__*/function (_Component) {\n _inheritsLoose(Provider, _Component);\n\n function Provider() {\n var _this;\n\n _this = _Component.apply(this, arguments) || this;\n _this.emitter = createEventEmitter(_this.props.value);\n return _this;\n }\n\n var _proto = Provider.prototype;\n\n _proto.getChildContext = function getChildContext() {\n var _ref;\n\n return _ref = {}, _ref[contextProp] = this.emitter, _ref;\n };\n\n _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n if (this.props.value !== nextProps.value) {\n var oldValue = this.props.value;\n var newValue = nextProps.value;\n var changedBits;\n\n if (objectIs(oldValue, newValue)) {\n changedBits = 0;\n } else {\n changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;\n\n if (process.env.NODE_ENV !== 'production') {\n warning((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: ' + changedBits);\n }\n\n changedBits |= 0;\n\n if (changedBits !== 0) {\n this.emitter.set(nextProps.value, changedBits);\n }\n }\n }\n };\n\n _proto.render = function render() {\n return this.props.children;\n };\n\n return Provider;\n }(Component);\n\n Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = PropTypes.object.isRequired, _Provider$childContex);\n\n var Consumer = /*#__PURE__*/function (_Component2) {\n _inheritsLoose(Consumer, _Component2);\n\n function Consumer() {\n var _this2;\n\n _this2 = _Component2.apply(this, arguments) || this;\n _this2.state = {\n value: _this2.getValue()\n };\n\n _this2.onUpdate = function (newValue, changedBits) {\n var observedBits = _this2.observedBits | 0;\n\n if ((observedBits & changedBits) !== 0) {\n _this2.setState({\n value: _this2.getValue()\n });\n }\n };\n\n return _this2;\n }\n\n var _proto2 = Consumer.prototype;\n\n _proto2.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n var observedBits = nextProps.observedBits;\n this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;\n };\n\n _proto2.componentDidMount = function componentDidMount() {\n if (this.context[contextProp]) {\n this.context[contextProp].on(this.onUpdate);\n }\n\n var observedBits = this.props.observedBits;\n this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;\n };\n\n _proto2.componentWillUnmount = function componentWillUnmount() {\n if (this.context[contextProp]) {\n this.context[contextProp].off(this.onUpdate);\n }\n };\n\n _proto2.getValue = function getValue() {\n if (this.context[contextProp]) {\n return this.context[contextProp].get();\n } else {\n return defaultValue;\n }\n };\n\n _proto2.render = function render() {\n return onlyChild(this.props.children)(this.state.value);\n };\n\n return Consumer;\n }(Component);\n\n Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = PropTypes.object, _Consumer$contextType);\n return {\n Provider: Provider,\n Consumer: Consumer\n };\n}\n\nvar index = React.createContext || createReactContext;\n\nexport default index;\n","var isarray = require('isarray')\n\n/**\n * Expose `pathToRegexp`.\n */\nmodule.exports = pathToRegexp\nmodule.exports.parse = parse\nmodule.exports.compile = compile\nmodule.exports.tokensToFunction = tokensToFunction\nmodule.exports.tokensToRegExp = tokensToRegExp\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n // Match escaped characters that would otherwise appear in future matches.\n // This allows the user to escape special characters that won't transform.\n '(\\\\\\\\.)',\n // Match Express-style parameters and un-named parameters with a prefix\n // and optional suffixes. Matches appear as:\n //\n // \"/:test(\\\\d+)?\" => [\"/\", \"test\", \"\\d+\", undefined, \"?\", undefined]\n // \"/route(\\\\d+)\" => [undefined, undefined, undefined, \"\\d+\", undefined, undefined]\n // \"/*\" => [\"/\", undefined, undefined, undefined, undefined, \"*\"]\n '([\\\\/.])?(?:(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))([+*?])?|(\\\\*))'\n].join('|'), 'g')\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param {string} str\n * @param {Object=} options\n * @return {!Array}\n */\nfunction parse (str, options) {\n var tokens = []\n var key = 0\n var index = 0\n var path = ''\n var defaultDelimiter = options && options.delimiter || '/'\n var res\n\n while ((res = PATH_REGEXP.exec(str)) != null) {\n var m = res[0]\n var escaped = res[1]\n var offset = res.index\n path += str.slice(index, offset)\n index = offset + m.length\n\n // Ignore already escaped sequences.\n if (escaped) {\n path += escaped[1]\n continue\n }\n\n var next = str[index]\n var prefix = res[2]\n var name = res[3]\n var capture = res[4]\n var group = res[5]\n var modifier = res[6]\n var asterisk = res[7]\n\n // Push the current path onto the tokens.\n if (path) {\n tokens.push(path)\n path = ''\n }\n\n var partial = prefix != null && next != null && next !== prefix\n var repeat = modifier === '+' || modifier === '*'\n var optional = modifier === '?' || modifier === '*'\n var delimiter = res[2] || defaultDelimiter\n var pattern = capture || group\n\n tokens.push({\n name: name || key++,\n prefix: prefix || '',\n delimiter: delimiter,\n optional: optional,\n repeat: repeat,\n partial: partial,\n asterisk: !!asterisk,\n pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')\n })\n }\n\n // Match any characters still remaining.\n if (index < str.length) {\n path += str.substr(index)\n }\n\n // If the path exists, push it onto the end.\n if (path) {\n tokens.push(path)\n }\n\n return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param {string} str\n * @param {Object=} options\n * @return {!function(Object=, Object=)}\n */\nfunction compile (str, options) {\n return tokensToFunction(parse(str, options), options)\n}\n\n/**\n * Prettier encoding of URI path segments.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeURIComponentPretty (str) {\n return encodeURI(str).replace(/[\\/?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeAsterisk (str) {\n return encodeURI(str).replace(/[?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens, options) {\n // Compile all the tokens into regexps.\n var matches = new Array(tokens.length)\n\n // Compile all the patterns before compilation.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] === 'object') {\n matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options))\n }\n }\n\n return function (obj, opts) {\n var path = ''\n var data = obj || {}\n var options = opts || {}\n var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent\n\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n path += token\n\n continue\n }\n\n var value = data[token.name]\n var segment\n\n if (value == null) {\n if (token.optional) {\n // Prepend partial segment prefixes.\n if (token.partial) {\n path += token.prefix\n }\n\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to be defined')\n }\n }\n\n if (isarray(value)) {\n if (!token.repeat) {\n throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received `' + JSON.stringify(value) + '`')\n }\n\n if (value.length === 0) {\n if (token.optional) {\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n }\n }\n\n for (var j = 0; j < value.length; j++) {\n segment = encode(value[j])\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received `' + JSON.stringify(segment) + '`')\n }\n\n path += (j === 0 ? token.prefix : token.delimiter) + segment\n }\n\n continue\n }\n\n segment = token.asterisk ? encodeAsterisk(value) : encode(value)\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n }\n\n path += token.prefix + segment\n }\n\n return path\n }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param {string} str\n * @return {string}\n */\nfunction escapeString (str) {\n return str.replace(/([.+*?=^!:${}()[\\]|\\/\\\\])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param {string} group\n * @return {string}\n */\nfunction escapeGroup (group) {\n return group.replace(/([=!:$\\/()])/g, '\\\\$1')\n}\n\n/**\n * Attach the keys as a property of the regexp.\n *\n * @param {!RegExp} re\n * @param {Array} keys\n * @return {!RegExp}\n */\nfunction attachKeys (re, keys) {\n re.keys = keys\n return re\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param {Object} options\n * @return {string}\n */\nfunction flags (options) {\n return options && options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param {!RegExp} path\n * @param {!Array} keys\n * @return {!RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n // Use a negative lookahead to match only capturing groups.\n var groups = path.source.match(/\\((?!\\?)/g)\n\n if (groups) {\n for (var i = 0; i < groups.length; i++) {\n keys.push({\n name: i,\n prefix: null,\n delimiter: null,\n optional: false,\n repeat: false,\n partial: false,\n asterisk: false,\n pattern: null\n })\n }\n }\n\n return attachKeys(path, keys)\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param {!Array} path\n * @param {Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n var parts = []\n\n for (var i = 0; i < path.length; i++) {\n parts.push(pathToRegexp(path[i], keys, options).source)\n }\n\n var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options))\n\n return attachKeys(regexp, keys)\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param {string} path\n * @param {!Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n return tokensToRegExp(parse(path, options), keys, options)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param {!Array} tokens\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction tokensToRegExp (tokens, keys, options) {\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys || options)\n keys = []\n }\n\n options = options || {}\n\n var strict = options.strict\n var end = options.end !== false\n var route = ''\n\n // Iterate over the tokens and create our regexp string.\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n route += escapeString(token)\n } else {\n var prefix = escapeString(token.prefix)\n var capture = '(?:' + token.pattern + ')'\n\n keys.push(token)\n\n if (token.repeat) {\n capture += '(?:' + prefix + capture + ')*'\n }\n\n if (token.optional) {\n if (!token.partial) {\n capture = '(?:' + prefix + '(' + capture + '))?'\n } else {\n capture = prefix + '(' + capture + ')?'\n }\n } else {\n capture = prefix + '(' + capture + ')'\n }\n\n route += capture\n }\n }\n\n var delimiter = escapeString(options.delimiter || '/')\n var endsWithDelimiter = route.slice(-delimiter.length) === delimiter\n\n // In non-strict mode we allow a slash at the end of match. If the path to\n // match already ends with a slash, we remove it for consistency. The slash\n // is valid at the end of a path match, not in the middle. This is important\n // in non-ending mode, where \"/test/\" shouldn't match \"/test//route\".\n if (!strict) {\n route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?'\n }\n\n if (end) {\n route += '$'\n } else {\n // In non-ending mode, we need the capturing groups to match as much as\n // possible by using a positive lookahead to the end or next path segment.\n route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)'\n }\n\n return attachKeys(new RegExp('^' + route, flags(options)), keys)\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param {(string|RegExp|Array)} path\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction pathToRegexp (path, keys, options) {\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys || options)\n keys = []\n }\n\n options = options || {}\n\n if (path instanceof RegExp) {\n return regexpToRegexp(path, /** @type {!Array} */ (keys))\n }\n\n if (isarray(path)) {\n return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)\n }\n\n return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)\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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 */\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 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 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 {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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\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 {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 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 */\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 */\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 */\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\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","'use strict';\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar React = require('react');\nvar React__default = _interopDefault(React);\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\nfunction withSideEffect(reducePropsToState, handleStateChangeOnClient, mapStateOnServer) {\n if (typeof reducePropsToState !== 'function') {\n throw new Error('Expected reducePropsToState to be a function.');\n }\n\n if (typeof handleStateChangeOnClient !== 'function') {\n throw new Error('Expected handleStateChangeOnClient to be a function.');\n }\n\n if (typeof mapStateOnServer !== 'undefined' && typeof mapStateOnServer !== 'function') {\n throw new Error('Expected mapStateOnServer to either be undefined or a function.');\n }\n\n function getDisplayName(WrappedComponent) {\n return WrappedComponent.displayName || WrappedComponent.name || 'Component';\n }\n\n return function wrap(WrappedComponent) {\n if (typeof WrappedComponent !== 'function') {\n throw new Error('Expected WrappedComponent to be a React component.');\n }\n\n var mountedInstances = [];\n var state;\n\n function emitChange() {\n state = reducePropsToState(mountedInstances.map(function (instance) {\n return instance.props;\n }));\n\n if (SideEffect.canUseDOM) {\n handleStateChangeOnClient(state);\n } else if (mapStateOnServer) {\n state = mapStateOnServer(state);\n }\n }\n\n var SideEffect = /*#__PURE__*/function (_PureComponent) {\n _inheritsLoose(SideEffect, _PureComponent);\n\n function SideEffect() {\n return _PureComponent.apply(this, arguments) || this;\n }\n\n // Try to use displayName of wrapped component\n // Expose canUseDOM so tests can monkeypatch it\n SideEffect.peek = function peek() {\n return state;\n };\n\n SideEffect.rewind = function rewind() {\n if (SideEffect.canUseDOM) {\n throw new Error('You may only call rewind() on the server. Call peek() to read the current state.');\n }\n\n var recordedState = state;\n state = undefined;\n mountedInstances = [];\n return recordedState;\n };\n\n var _proto = SideEffect.prototype;\n\n _proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() {\n mountedInstances.push(this);\n emitChange();\n };\n\n _proto.componentDidUpdate = function componentDidUpdate() {\n emitChange();\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n var index = mountedInstances.indexOf(this);\n mountedInstances.splice(index, 1);\n emitChange();\n };\n\n _proto.render = function render() {\n return /*#__PURE__*/React__default.createElement(WrappedComponent, this.props);\n };\n\n return SideEffect;\n }(React.PureComponent);\n\n _defineProperty(SideEffect, \"displayName\", \"SideEffect(\" + getDisplayName(WrappedComponent) + \")\");\n\n _defineProperty(SideEffect, \"canUseDOM\", canUseDOM);\n\n return SideEffect;\n };\n}\n\nmodule.exports = withSideEffect;\n","/* global Map:readonly, Set:readonly, ArrayBuffer:readonly */\n\nvar hasElementType = typeof Element !== 'undefined';\nvar hasMap = typeof Map === 'function';\nvar hasSet = typeof Set === 'function';\nvar hasArrayBuffer = typeof ArrayBuffer === 'function' && !!ArrayBuffer.isView;\n\n// Note: We **don't** need `envHasBigInt64Array` in fde es6/index.js\n\nfunction equal(a, b) {\n // START: fast-deep-equal es6/index.js 3.1.1\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n // START: Modifications:\n // 1. Extra `has<Type> &&` helpers in initial condition allow es6 code\n // to co-exist with es5.\n // 2. Replace `for of` with es5 compliant iteration using `for`.\n // Basically, take:\n //\n // ```js\n // for (i of a.entries())\n // if (!b.has(i[0])) return false;\n // ```\n //\n // ... and convert to:\n //\n // ```js\n // it = a.entries();\n // while (!(i = it.next()).done)\n // if (!b.has(i.value[0])) return false;\n // ```\n //\n // **Note**: `i` access switches to `i.value`.\n var it;\n if (hasMap && (a instanceof Map) && (b instanceof Map)) {\n if (a.size !== b.size) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!b.has(i.value[0])) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!equal(i.value[1], b.get(i.value[0]))) return false;\n return true;\n }\n\n if (hasSet && (a instanceof Set) && (b instanceof Set)) {\n if (a.size !== b.size) return false;\n it = a.entries();\n while (!(i = it.next()).done)\n if (!b.has(i.value[0])) return false;\n return true;\n }\n // END: Modifications\n\n if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (a[i] !== b[i]) return false;\n return true;\n }\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n // END: fast-deep-equal\n\n // START: react-fast-compare\n // custom handling for DOM elements\n if (hasElementType && a instanceof Element) return false;\n\n // custom handling for React/Preact\n for (i = length; i-- !== 0;) {\n if ((keys[i] === '_owner' || keys[i] === '__v' || keys[i] === '__o') && a.$$typeof) {\n // React-specific: avoid traversing React elements' _owner\n // Preact-specific: avoid traversing Preact elements' __v and __o\n // __v = $_original / $_vnode\n // __o = $_owner\n // These properties contain circular references and are not needed when\n // comparing the actual elements (and not their owners)\n // .$$typeof and ._store on just reasonable markers of elements\n\n continue;\n }\n\n // all other properties should be traversed as usual\n if (!equal(a[keys[i]], b[keys[i]])) return false;\n }\n // END: react-fast-compare\n\n // START: fast-deep-equal\n return true;\n }\n\n return a !== a && b !== b;\n}\n// end fast-deep-equal\n\nmodule.exports = function isEqual(a, b) {\n try {\n return equal(a, b);\n } catch (error) {\n if (((error.message || '').match(/stack|recursion/i))) {\n // warn on circular references, don't crash\n // browsers give this different errors name and messages:\n // chrome/safari: \"RangeError\", \"Maximum call stack size exceeded\"\n // firefox: \"InternalError\", too much recursion\"\n // edge: \"Error\", \"Out of stack space\"\n console.warn('react-fast-compare cannot handle circular refs');\n return false;\n }\n // some other error. we should definitely know about these\n throw error;\n }\n};\n","export default function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter);\n}","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n}","/**\n * WARNING: Don't import this directly.\n * Use `MuiError` from `@material-ui/utils/macros/MuiError.macro` instead.\n * @param {number} code\n */\nexport default function formatMuiErrorMessage(code) {\n // Apply babel-plugin-transform-template-literals in loose mode\n // loose mode is safe iff we're concatenating primitives\n // see https://babeljs.io/docs/en/babel-plugin-transform-template-literals#loose\n\n /* eslint-disable prefer-template */\n var url = 'https://material-ui.com/production-error/?code=' + code;\n\n for (var i = 1; i < arguments.length; i += 1) {\n // rest params over-transpile for this case\n // eslint-disable-next-line prefer-rest-params\n url += '&args[]=' + encodeURIComponent(arguments[i]);\n }\n\n return 'Minified Material-UI error #' + code + '; visit ' + url + ' for the full message.';\n /* eslint-enable prefer-template */\n}","// based on https://github.com/WICG/focus-visible/blob/v4.1.5/src/focus-visible.js\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nvar hadKeyboardEvent = true;\nvar hadFocusVisibleRecently = false;\nvar hadFocusVisibleRecentlyTimeout = null;\nvar inputTypesWhitelist = {\n text: true,\n search: true,\n url: true,\n tel: true,\n email: true,\n password: true,\n number: true,\n date: true,\n month: true,\n week: true,\n time: true,\n datetime: true,\n 'datetime-local': true\n};\n/**\n * Computes whether the given element should automatically trigger the\n * `focus-visible` class being added, i.e. whether it should always match\n * `:focus-visible` when focused.\n * @param {Element} node\n * @return {boolean}\n */\n\nfunction focusTriggersKeyboardModality(node) {\n var type = node.type,\n tagName = node.tagName;\n\n if (tagName === 'INPUT' && inputTypesWhitelist[type] && !node.readOnly) {\n return true;\n }\n\n if (tagName === 'TEXTAREA' && !node.readOnly) {\n return true;\n }\n\n if (node.isContentEditable) {\n return true;\n }\n\n return false;\n}\n/**\n * Keep track of our keyboard modality state with `hadKeyboardEvent`.\n * If the most recent user interaction was via the keyboard;\n * and the key press did not include a meta, alt/option, or control key;\n * then the modality is keyboard. Otherwise, the modality is not keyboard.\n * @param {KeyboardEvent} event\n */\n\n\nfunction handleKeyDown(event) {\n if (event.metaKey || event.altKey || event.ctrlKey) {\n return;\n }\n\n hadKeyboardEvent = true;\n}\n/**\n * If at any point a user clicks with a pointing device, ensure that we change\n * the modality away from keyboard.\n * This avoids the situation where a user presses a key on an already focused\n * element, and then clicks on a different element, focusing it with a\n * pointing device, while we still think we're in keyboard modality.\n */\n\n\nfunction handlePointerDown() {\n hadKeyboardEvent = false;\n}\n\nfunction handleVisibilityChange() {\n if (this.visibilityState === 'hidden') {\n // If the tab becomes active again, the browser will handle calling focus\n // on the element (Safari actually calls it twice).\n // If this tab change caused a blur on an element with focus-visible,\n // re-apply the class when the user switches back to the tab.\n if (hadFocusVisibleRecently) {\n hadKeyboardEvent = true;\n }\n }\n}\n\nfunction prepare(doc) {\n doc.addEventListener('keydown', handleKeyDown, true);\n doc.addEventListener('mousedown', handlePointerDown, true);\n doc.addEventListener('pointerdown', handlePointerDown, true);\n doc.addEventListener('touchstart', handlePointerDown, true);\n doc.addEventListener('visibilitychange', handleVisibilityChange, true);\n}\n\nexport function teardown(doc) {\n doc.removeEventListener('keydown', handleKeyDown, true);\n doc.removeEventListener('mousedown', handlePointerDown, true);\n doc.removeEventListener('pointerdown', handlePointerDown, true);\n doc.removeEventListener('touchstart', handlePointerDown, true);\n doc.removeEventListener('visibilitychange', handleVisibilityChange, true);\n}\n\nfunction isFocusVisible(event) {\n var target = event.target;\n\n try {\n return target.matches(':focus-visible');\n } catch (error) {} // browsers not implementing :focus-visible will throw a SyntaxError\n // we use our own heuristic for those browsers\n // rethrow might be better if it's not the expected error but do we really\n // want to crash if focus-visible malfunctioned?\n // no need for validFocusTarget check. the user does that by attaching it to\n // focusable events only\n\n\n return hadKeyboardEvent || focusTriggersKeyboardModality(target);\n}\n/**\n * Should be called if a blur event is fired on a focus-visible element\n */\n\n\nfunction handleBlurVisible() {\n // To detect a tab/window switch, we look for a blur event followed\n // rapidly by a visibility change.\n // If we don't see a visibility change within 100ms, it's probably a\n // regular focus change.\n hadFocusVisibleRecently = true;\n window.clearTimeout(hadFocusVisibleRecentlyTimeout);\n hadFocusVisibleRecentlyTimeout = window.setTimeout(function () {\n hadFocusVisibleRecently = false;\n }, 100);\n}\n\nexport default function useIsFocusVisible() {\n var ref = React.useCallback(function (instance) {\n var node = ReactDOM.findDOMNode(instance);\n\n if (node != null) {\n prepare(node.ownerDocument);\n }\n }, []);\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(isFocusVisible);\n }\n\n return {\n isFocusVisible: isFocusVisible,\n onBlurVisible: handleBlurVisible,\n ref: ref\n };\n}","import { Children, cloneElement, isValidElement } from 'react';\n/**\n * Given `this.props.children`, return an object mapping key to child.\n *\n * @param {*} children `this.props.children`\n * @return {object} Mapping of key to child\n */\n\nexport function getChildMapping(children, mapFn) {\n var mapper = function mapper(child) {\n return mapFn && isValidElement(child) ? mapFn(child) : child;\n };\n\n var result = Object.create(null);\n if (children) Children.map(children, function (c) {\n return c;\n }).forEach(function (child) {\n // run the map function here instead so that the key is the computed one\n result[child.key] = mapper(child);\n });\n return result;\n}\n/**\n * When you're adding or removing children some may be added or removed in the\n * same render pass. We want to show *both* since we want to simultaneously\n * animate elements in and out. This function takes a previous set of keys\n * and a new set of keys and merges them with its best guess of the correct\n * ordering. In the future we may expose some of the utilities in\n * ReactMultiChild to make this easy, but for now React itself does not\n * directly have this concept of the union of prevChildren and nextChildren\n * so we implement it here.\n *\n * @param {object} prev prev children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @param {object} next next children as returned from\n * `ReactTransitionChildMapping.getChildMapping()`.\n * @return {object} a key set that contains all keys in `prev` and all keys\n * in `next` in a reasonable order.\n */\n\nexport function mergeChildMappings(prev, next) {\n prev = prev || {};\n next = next || {};\n\n function getValueForKey(key) {\n return key in next ? next[key] : prev[key];\n } // For each key of `next`, the list of keys to insert before that key in\n // the combined list\n\n\n var nextKeysPending = Object.create(null);\n var pendingKeys = [];\n\n for (var prevKey in prev) {\n if (prevKey in next) {\n if (pendingKeys.length) {\n nextKeysPending[prevKey] = pendingKeys;\n pendingKeys = [];\n }\n } else {\n pendingKeys.push(prevKey);\n }\n }\n\n var i;\n var childMapping = {};\n\n for (var nextKey in next) {\n if (nextKeysPending[nextKey]) {\n for (i = 0; i < nextKeysPending[nextKey].length; i++) {\n var pendingNextKey = nextKeysPending[nextKey][i];\n childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);\n }\n }\n\n childMapping[nextKey] = getValueForKey(nextKey);\n } // Finally, add the keys which didn't appear before any key in `next`\n\n\n for (i = 0; i < pendingKeys.length; i++) {\n childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);\n }\n\n return childMapping;\n}\n\nfunction getProp(child, prop, props) {\n return props[prop] != null ? props[prop] : child.props[prop];\n}\n\nexport function getInitialChildMapping(props, onExited) {\n return getChildMapping(props.children, function (child) {\n return cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: true,\n appear: getProp(child, 'appear', props),\n enter: getProp(child, 'enter', props),\n exit: getProp(child, 'exit', props)\n });\n });\n}\nexport function getNextChildMapping(nextProps, prevChildMapping, onExited) {\n var nextChildMapping = getChildMapping(nextProps.children);\n var children = mergeChildMappings(prevChildMapping, nextChildMapping);\n Object.keys(children).forEach(function (key) {\n var child = children[key];\n if (!isValidElement(child)) return;\n var hasPrev = (key in prevChildMapping);\n var hasNext = (key in nextChildMapping);\n var prevChild = prevChildMapping[key];\n var isLeaving = isValidElement(prevChild) && !prevChild.props.in; // item is new (entering)\n\n if (hasNext && (!hasPrev || isLeaving)) {\n // console.log('entering', key)\n children[key] = cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: true,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n } else if (!hasNext && hasPrev && !isLeaving) {\n // item is old (exiting)\n // console.log('leaving', key)\n children[key] = cloneElement(child, {\n in: false\n });\n } else if (hasNext && hasPrev && isValidElement(prevChild)) {\n // item hasn't changed transition states\n // copy over the last transition props;\n // console.log('unchanged', key)\n children[key] = cloneElement(child, {\n onExited: onExited.bind(null, child),\n in: prevChild.props.in,\n exit: getProp(child, 'exit', nextProps),\n enter: getProp(child, 'enter', nextProps)\n });\n }\n });\n return children;\n}","import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _assertThisInitialized from \"@babel/runtime/helpers/esm/assertThisInitialized\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport TransitionGroupContext from './TransitionGroupContext';\nimport { getChildMapping, getInitialChildMapping, getNextChildMapping } from './utils/ChildMapping';\n\nvar values = Object.values || function (obj) {\n return Object.keys(obj).map(function (k) {\n return obj[k];\n });\n};\n\nvar defaultProps = {\n component: 'div',\n childFactory: function childFactory(child) {\n return child;\n }\n};\n/**\n * The `<TransitionGroup>` component manages a set of transition components\n * (`<Transition>` and `<CSSTransition>`) in a list. Like with the transition\n * components, `<TransitionGroup>` is a state machine for managing the mounting\n * and unmounting of components over time.\n *\n * Consider the example below. As items are removed or added to the TodoList the\n * `in` prop is toggled automatically by the `<TransitionGroup>`.\n *\n * Note that `<TransitionGroup>` does not define any animation behavior!\n * Exactly _how_ a list item animates is up to the individual transition\n * component. This means you can mix and match animations across different list\n * items.\n */\n\nvar TransitionGroup = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(TransitionGroup, _React$Component);\n\n function TransitionGroup(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n\n var handleExited = _this.handleExited.bind(_assertThisInitialized(_this)); // Initial children should all be entering, dependent on appear\n\n\n _this.state = {\n contextValue: {\n isMounting: true\n },\n handleExited: handleExited,\n firstRender: true\n };\n return _this;\n }\n\n var _proto = TransitionGroup.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.mounted = true;\n this.setState({\n contextValue: {\n isMounting: false\n }\n });\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.mounted = false;\n };\n\n TransitionGroup.getDerivedStateFromProps = function getDerivedStateFromProps(nextProps, _ref) {\n var prevChildMapping = _ref.children,\n handleExited = _ref.handleExited,\n firstRender = _ref.firstRender;\n return {\n children: firstRender ? getInitialChildMapping(nextProps, handleExited) : getNextChildMapping(nextProps, prevChildMapping, handleExited),\n firstRender: false\n };\n } // node is `undefined` when user provided `nodeRef` prop\n ;\n\n _proto.handleExited = function handleExited(child, node) {\n var currentChildMapping = getChildMapping(this.props.children);\n if (child.key in currentChildMapping) return;\n\n if (child.props.onExited) {\n child.props.onExited(node);\n }\n\n if (this.mounted) {\n this.setState(function (state) {\n var children = _extends({}, state.children);\n\n delete children[child.key];\n return {\n children: children\n };\n });\n }\n };\n\n _proto.render = function render() {\n var _this$props = this.props,\n Component = _this$props.component,\n childFactory = _this$props.childFactory,\n props = _objectWithoutPropertiesLoose(_this$props, [\"component\", \"childFactory\"]);\n\n var contextValue = this.state.contextValue;\n var children = values(this.state.children).map(childFactory);\n delete props.appear;\n delete props.enter;\n delete props.exit;\n\n if (Component === null) {\n return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {\n value: contextValue\n }, children);\n }\n\n return /*#__PURE__*/React.createElement(TransitionGroupContext.Provider, {\n value: contextValue\n }, /*#__PURE__*/React.createElement(Component, props, children));\n };\n\n return TransitionGroup;\n}(React.Component);\n\nTransitionGroup.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * `<TransitionGroup>` renders a `<div>` by default. You can change this\n * behavior by providing a `component` prop.\n * If you use React v16+ and would like to avoid a wrapping `<div>` element\n * you can pass in `component={null}`. This is useful if the wrapping div\n * borks your css styles.\n */\n component: PropTypes.any,\n\n /**\n * A set of `<Transition>` components, that are toggled `in` and out as they\n * leave. the `<TransitionGroup>` will inject specific transition props, so\n * remember to spread them through if you are wrapping the `<Transition>` as\n * with our `<Fade>` example.\n *\n * While this component is meant for multiple `Transition` or `CSSTransition`\n * children, sometimes you may want to have a single transition child with\n * content that you want to be transitioned out and in when you change it\n * (e.g. routes, images etc.) In that case you can change the `key` prop of\n * the transition child as you change its content, this will cause\n * `TransitionGroup` to transition the child out and back in.\n */\n children: PropTypes.node,\n\n /**\n * A convenience prop that enables or disables appear animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n appear: PropTypes.bool,\n\n /**\n * A convenience prop that enables or disables enter animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * A convenience prop that enables or disables exit animations\n * for all children. Note that specifying this will override any defaults set\n * on individual children Transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * You may need to apply reactive updates to a child as it is exiting.\n * This is generally done by using `cloneElement` however in the case of an exiting\n * child the element has already been removed and not accessible to the consumer.\n *\n * If you do need to update a child as it leaves you can provide a `childFactory`\n * to wrap every child, even the ones that are leaving.\n *\n * @type Function(child: ReactElement) -> ReactElement\n */\n childFactory: PropTypes.func\n} : {};\nTransitionGroup.defaultProps = defaultProps;\nexport default TransitionGroup;","import * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport useEventCallback from '../utils/useEventCallback';\nvar useEnhancedEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;\n/**\n * @ignore - internal component.\n */\n\nfunction Ripple(props) {\n var classes = props.classes,\n _props$pulsate = props.pulsate,\n pulsate = _props$pulsate === void 0 ? false : _props$pulsate,\n rippleX = props.rippleX,\n rippleY = props.rippleY,\n rippleSize = props.rippleSize,\n inProp = props.in,\n _props$onExited = props.onExited,\n onExited = _props$onExited === void 0 ? function () {} : _props$onExited,\n timeout = props.timeout;\n\n var _React$useState = React.useState(false),\n leaving = _React$useState[0],\n setLeaving = _React$useState[1];\n\n var rippleClassName = clsx(classes.ripple, classes.rippleVisible, pulsate && classes.ripplePulsate);\n var rippleStyles = {\n width: rippleSize,\n height: rippleSize,\n top: -(rippleSize / 2) + rippleY,\n left: -(rippleSize / 2) + rippleX\n };\n var childClassName = clsx(classes.child, leaving && classes.childLeaving, pulsate && classes.childPulsate);\n var handleExited = useEventCallback(onExited); // Ripple is used for user feedback (e.g. click or press) so we want to apply styles with the highest priority\n\n useEnhancedEffect(function () {\n if (!inProp) {\n // react-transition-group#onExit\n setLeaving(true); // react-transition-group#onExited\n\n var timeoutId = setTimeout(handleExited, timeout);\n return function () {\n clearTimeout(timeoutId);\n };\n }\n\n return undefined;\n }, [handleExited, inProp, timeout]);\n return /*#__PURE__*/React.createElement(\"span\", {\n className: rippleClassName,\n style: rippleStyles\n }, /*#__PURE__*/React.createElement(\"span\", {\n className: childClassName\n }));\n}\n\nprocess.env.NODE_ENV !== \"production\" ? Ripple.propTypes = {\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore - injected from TransitionGroup\n */\n in: PropTypes.bool,\n\n /**\n * @ignore - injected from TransitionGroup\n */\n onExited: PropTypes.func,\n\n /**\n * If `true`, the ripple pulsates, typically indicating the keyboard focus state of an element.\n */\n pulsate: PropTypes.bool,\n\n /**\n * Diameter of the ripple.\n */\n rippleSize: PropTypes.number,\n\n /**\n * Horizontal position of the ripple center.\n */\n rippleX: PropTypes.number,\n\n /**\n * Vertical position of the ripple center.\n */\n rippleY: PropTypes.number,\n\n /**\n * exit delay\n */\n timeout: PropTypes.number.isRequired\n} : void 0;\nexport default Ripple;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { TransitionGroup } from 'react-transition-group';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport Ripple from './Ripple';\nvar DURATION = 550;\nexport var DELAY_RIPPLE = 80;\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n overflow: 'hidden',\n pointerEvents: 'none',\n position: 'absolute',\n zIndex: 0,\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n borderRadius: 'inherit'\n },\n\n /* Styles applied to the internal `Ripple` components `ripple` class. */\n ripple: {\n opacity: 0,\n position: 'absolute'\n },\n\n /* Styles applied to the internal `Ripple` components `rippleVisible` class. */\n rippleVisible: {\n opacity: 0.3,\n transform: 'scale(1)',\n animation: \"$enter \".concat(DURATION, \"ms \").concat(theme.transitions.easing.easeInOut)\n },\n\n /* Styles applied to the internal `Ripple` components `ripplePulsate` class. */\n ripplePulsate: {\n animationDuration: \"\".concat(theme.transitions.duration.shorter, \"ms\")\n },\n\n /* Styles applied to the internal `Ripple` components `child` class. */\n child: {\n opacity: 1,\n display: 'block',\n width: '100%',\n height: '100%',\n borderRadius: '50%',\n backgroundColor: 'currentColor'\n },\n\n /* Styles applied to the internal `Ripple` components `childLeaving` class. */\n childLeaving: {\n opacity: 0,\n animation: \"$exit \".concat(DURATION, \"ms \").concat(theme.transitions.easing.easeInOut)\n },\n\n /* Styles applied to the internal `Ripple` components `childPulsate` class. */\n childPulsate: {\n position: 'absolute',\n left: 0,\n top: 0,\n animation: \"$pulsate 2500ms \".concat(theme.transitions.easing.easeInOut, \" 200ms infinite\")\n },\n '@keyframes enter': {\n '0%': {\n transform: 'scale(0)',\n opacity: 0.1\n },\n '100%': {\n transform: 'scale(1)',\n opacity: 0.3\n }\n },\n '@keyframes exit': {\n '0%': {\n opacity: 1\n },\n '100%': {\n opacity: 0\n }\n },\n '@keyframes pulsate': {\n '0%': {\n transform: 'scale(1)'\n },\n '50%': {\n transform: 'scale(0.92)'\n },\n '100%': {\n transform: 'scale(1)'\n }\n }\n };\n};\n/**\n * @ignore - internal component.\n *\n * TODO v5: Make private\n */\n\nvar TouchRipple = /*#__PURE__*/React.forwardRef(function TouchRipple(props, ref) {\n var _props$center = props.center,\n centerProp = _props$center === void 0 ? false : _props$center,\n classes = props.classes,\n className = props.className,\n other = _objectWithoutProperties(props, [\"center\", \"classes\", \"className\"]);\n\n var _React$useState = React.useState([]),\n ripples = _React$useState[0],\n setRipples = _React$useState[1];\n\n var nextKey = React.useRef(0);\n var rippleCallback = React.useRef(null);\n React.useEffect(function () {\n if (rippleCallback.current) {\n rippleCallback.current();\n rippleCallback.current = null;\n }\n }, [ripples]); // Used to filter out mouse emulated events on mobile.\n\n var ignoringMouseDown = React.useRef(false); // We use a timer in order to only show the ripples for touch \"click\" like events.\n // We don't want to display the ripple for touch scroll events.\n\n var startTimer = React.useRef(null); // This is the hook called once the previous timeout is ready.\n\n var startTimerCommit = React.useRef(null);\n var container = React.useRef(null);\n React.useEffect(function () {\n return function () {\n clearTimeout(startTimer.current);\n };\n }, []);\n var startCommit = React.useCallback(function (params) {\n var pulsate = params.pulsate,\n rippleX = params.rippleX,\n rippleY = params.rippleY,\n rippleSize = params.rippleSize,\n cb = params.cb;\n setRipples(function (oldRipples) {\n return [].concat(_toConsumableArray(oldRipples), [/*#__PURE__*/React.createElement(Ripple, {\n key: nextKey.current,\n classes: classes,\n timeout: DURATION,\n pulsate: pulsate,\n rippleX: rippleX,\n rippleY: rippleY,\n rippleSize: rippleSize\n })]);\n });\n nextKey.current += 1;\n rippleCallback.current = cb;\n }, [classes]);\n var start = React.useCallback(function () {\n var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var cb = arguments.length > 2 ? arguments[2] : undefined;\n var _options$pulsate = options.pulsate,\n pulsate = _options$pulsate === void 0 ? false : _options$pulsate,\n _options$center = options.center,\n center = _options$center === void 0 ? centerProp || options.pulsate : _options$center,\n _options$fakeElement = options.fakeElement,\n fakeElement = _options$fakeElement === void 0 ? false : _options$fakeElement;\n\n if (event.type === 'mousedown' && ignoringMouseDown.current) {\n ignoringMouseDown.current = false;\n return;\n }\n\n if (event.type === 'touchstart') {\n ignoringMouseDown.current = true;\n }\n\n var element = fakeElement ? null : container.current;\n var rect = element ? element.getBoundingClientRect() : {\n width: 0,\n height: 0,\n left: 0,\n top: 0\n }; // Get the size of the ripple\n\n var rippleX;\n var rippleY;\n var rippleSize;\n\n if (center || event.clientX === 0 && event.clientY === 0 || !event.clientX && !event.touches) {\n rippleX = Math.round(rect.width / 2);\n rippleY = Math.round(rect.height / 2);\n } else {\n var _ref = event.touches ? event.touches[0] : event,\n clientX = _ref.clientX,\n clientY = _ref.clientY;\n\n rippleX = Math.round(clientX - rect.left);\n rippleY = Math.round(clientY - rect.top);\n }\n\n if (center) {\n rippleSize = Math.sqrt((2 * Math.pow(rect.width, 2) + Math.pow(rect.height, 2)) / 3); // For some reason the animation is broken on Mobile Chrome if the size if even.\n\n if (rippleSize % 2 === 0) {\n rippleSize += 1;\n }\n } else {\n var sizeX = Math.max(Math.abs((element ? element.clientWidth : 0) - rippleX), rippleX) * 2 + 2;\n var sizeY = Math.max(Math.abs((element ? element.clientHeight : 0) - rippleY), rippleY) * 2 + 2;\n rippleSize = Math.sqrt(Math.pow(sizeX, 2) + Math.pow(sizeY, 2));\n } // Touche devices\n\n\n if (event.touches) {\n // check that this isn't another touchstart due to multitouch\n // otherwise we will only clear a single timer when unmounting while two\n // are running\n if (startTimerCommit.current === null) {\n // Prepare the ripple effect.\n startTimerCommit.current = function () {\n startCommit({\n pulsate: pulsate,\n rippleX: rippleX,\n rippleY: rippleY,\n rippleSize: rippleSize,\n cb: cb\n });\n }; // Delay the execution of the ripple effect.\n\n\n startTimer.current = setTimeout(function () {\n if (startTimerCommit.current) {\n startTimerCommit.current();\n startTimerCommit.current = null;\n }\n }, DELAY_RIPPLE); // We have to make a tradeoff with this value.\n }\n } else {\n startCommit({\n pulsate: pulsate,\n rippleX: rippleX,\n rippleY: rippleY,\n rippleSize: rippleSize,\n cb: cb\n });\n }\n }, [centerProp, startCommit]);\n var pulsate = React.useCallback(function () {\n start({}, {\n pulsate: true\n });\n }, [start]);\n var stop = React.useCallback(function (event, cb) {\n clearTimeout(startTimer.current); // The touch interaction occurs too quickly.\n // We still want to show ripple effect.\n\n if (event.type === 'touchend' && startTimerCommit.current) {\n event.persist();\n startTimerCommit.current();\n startTimerCommit.current = null;\n startTimer.current = setTimeout(function () {\n stop(event, cb);\n });\n return;\n }\n\n startTimerCommit.current = null;\n setRipples(function (oldRipples) {\n if (oldRipples.length > 0) {\n return oldRipples.slice(1);\n }\n\n return oldRipples;\n });\n rippleCallback.current = cb;\n }, []);\n React.useImperativeHandle(ref, function () {\n return {\n pulsate: pulsate,\n start: start,\n stop: stop\n };\n }, [pulsate, start, stop]);\n return /*#__PURE__*/React.createElement(\"span\", _extends({\n className: clsx(classes.root, className),\n ref: container\n }, other), /*#__PURE__*/React.createElement(TransitionGroup, {\n component: null,\n exit: true\n }, ripples));\n});\nprocess.env.NODE_ENV !== \"production\" ? TouchRipple.propTypes = {\n /**\n * If `true`, the ripple starts at the center of the component\n * rather than at the point of interaction.\n */\n center: PropTypes.bool,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string\n} : void 0;\nexport default withStyles(styles, {\n flip: false,\n name: 'MuiTouchRipple'\n})( /*#__PURE__*/React.memo(TouchRipple));","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport * as ReactDOM from 'react-dom';\nimport clsx from 'clsx';\nimport { elementTypeAcceptingRef, refType } from '@material-ui/utils';\nimport useForkRef from '../utils/useForkRef';\nimport useEventCallback from '../utils/useEventCallback';\nimport withStyles from '../styles/withStyles';\nimport useIsFocusVisible from '../utils/useIsFocusVisible';\nimport TouchRipple from './TouchRipple';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n position: 'relative',\n WebkitTapHighlightColor: 'transparent',\n backgroundColor: 'transparent',\n // Reset default value\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0,\n border: 0,\n margin: 0,\n // Remove the margin in Safari\n borderRadius: 0,\n padding: 0,\n // Remove the padding in Firefox\n cursor: 'pointer',\n userSelect: 'none',\n verticalAlign: 'middle',\n '-moz-appearance': 'none',\n // Reset\n '-webkit-appearance': 'none',\n // Reset\n textDecoration: 'none',\n // So we take precedent over the style of a native <a /> element.\n color: 'inherit',\n '&::-moz-focus-inner': {\n borderStyle: 'none' // Remove Firefox dotted outline.\n\n },\n '&$disabled': {\n pointerEvents: 'none',\n // Disable link interactions\n cursor: 'default'\n },\n '@media print': {\n colorAdjust: 'exact'\n }\n },\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Pseudo-class applied to the root element if keyboard focused. */\n focusVisible: {}\n};\n/**\n * `ButtonBase` contains as few styles as possible.\n * It aims to be a simple building block for creating a button.\n * It contains a load of style reset and some focus/ripple logic.\n */\n\nvar ButtonBase = /*#__PURE__*/React.forwardRef(function ButtonBase(props, ref) {\n var action = props.action,\n buttonRefProp = props.buttonRef,\n _props$centerRipple = props.centerRipple,\n centerRipple = _props$centerRipple === void 0 ? false : _props$centerRipple,\n children = props.children,\n classes = props.classes,\n className = props.className,\n _props$component = props.component,\n component = _props$component === void 0 ? 'button' : _props$component,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$disableRipple = props.disableRipple,\n disableRipple = _props$disableRipple === void 0 ? false : _props$disableRipple,\n _props$disableTouchRi = props.disableTouchRipple,\n disableTouchRipple = _props$disableTouchRi === void 0 ? false : _props$disableTouchRi,\n _props$focusRipple = props.focusRipple,\n focusRipple = _props$focusRipple === void 0 ? false : _props$focusRipple,\n focusVisibleClassName = props.focusVisibleClassName,\n onBlur = props.onBlur,\n onClick = props.onClick,\n onFocus = props.onFocus,\n onFocusVisible = props.onFocusVisible,\n onKeyDown = props.onKeyDown,\n onKeyUp = props.onKeyUp,\n onMouseDown = props.onMouseDown,\n onMouseLeave = props.onMouseLeave,\n onMouseUp = props.onMouseUp,\n onTouchEnd = props.onTouchEnd,\n onTouchMove = props.onTouchMove,\n onTouchStart = props.onTouchStart,\n onDragLeave = props.onDragLeave,\n _props$tabIndex = props.tabIndex,\n tabIndex = _props$tabIndex === void 0 ? 0 : _props$tabIndex,\n TouchRippleProps = props.TouchRippleProps,\n _props$type = props.type,\n type = _props$type === void 0 ? 'button' : _props$type,\n other = _objectWithoutProperties(props, [\"action\", \"buttonRef\", \"centerRipple\", \"children\", \"classes\", \"className\", \"component\", \"disabled\", \"disableRipple\", \"disableTouchRipple\", \"focusRipple\", \"focusVisibleClassName\", \"onBlur\", \"onClick\", \"onFocus\", \"onFocusVisible\", \"onKeyDown\", \"onKeyUp\", \"onMouseDown\", \"onMouseLeave\", \"onMouseUp\", \"onTouchEnd\", \"onTouchMove\", \"onTouchStart\", \"onDragLeave\", \"tabIndex\", \"TouchRippleProps\", \"type\"]);\n\n var buttonRef = React.useRef(null);\n\n function getButtonNode() {\n // #StrictMode ready\n return ReactDOM.findDOMNode(buttonRef.current);\n }\n\n var rippleRef = React.useRef(null);\n\n var _React$useState = React.useState(false),\n focusVisible = _React$useState[0],\n setFocusVisible = _React$useState[1];\n\n if (disabled && focusVisible) {\n setFocusVisible(false);\n }\n\n var _useIsFocusVisible = useIsFocusVisible(),\n isFocusVisible = _useIsFocusVisible.isFocusVisible,\n onBlurVisible = _useIsFocusVisible.onBlurVisible,\n focusVisibleRef = _useIsFocusVisible.ref;\n\n React.useImperativeHandle(action, function () {\n return {\n focusVisible: function focusVisible() {\n setFocusVisible(true);\n buttonRef.current.focus();\n }\n };\n }, []);\n React.useEffect(function () {\n if (focusVisible && focusRipple && !disableRipple) {\n rippleRef.current.pulsate();\n }\n }, [disableRipple, focusRipple, focusVisible]);\n\n function useRippleHandler(rippleAction, eventCallback) {\n var skipRippleAction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : disableTouchRipple;\n return useEventCallback(function (event) {\n if (eventCallback) {\n eventCallback(event);\n }\n\n var ignore = skipRippleAction;\n\n if (!ignore && rippleRef.current) {\n rippleRef.current[rippleAction](event);\n }\n\n return true;\n });\n }\n\n var handleMouseDown = useRippleHandler('start', onMouseDown);\n var handleDragLeave = useRippleHandler('stop', onDragLeave);\n var handleMouseUp = useRippleHandler('stop', onMouseUp);\n var handleMouseLeave = useRippleHandler('stop', function (event) {\n if (focusVisible) {\n event.preventDefault();\n }\n\n if (onMouseLeave) {\n onMouseLeave(event);\n }\n });\n var handleTouchStart = useRippleHandler('start', onTouchStart);\n var handleTouchEnd = useRippleHandler('stop', onTouchEnd);\n var handleTouchMove = useRippleHandler('stop', onTouchMove);\n var handleBlur = useRippleHandler('stop', function (event) {\n if (focusVisible) {\n onBlurVisible(event);\n setFocusVisible(false);\n }\n\n if (onBlur) {\n onBlur(event);\n }\n }, false);\n var handleFocus = useEventCallback(function (event) {\n // Fix for https://github.com/facebook/react/issues/7769\n if (!buttonRef.current) {\n buttonRef.current = event.currentTarget;\n }\n\n if (isFocusVisible(event)) {\n setFocusVisible(true);\n\n if (onFocusVisible) {\n onFocusVisible(event);\n }\n }\n\n if (onFocus) {\n onFocus(event);\n }\n });\n\n var isNonNativeButton = function isNonNativeButton() {\n var button = getButtonNode();\n return component && component !== 'button' && !(button.tagName === 'A' && button.href);\n };\n /**\n * IE 11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat\n */\n\n\n var keydownRef = React.useRef(false);\n var handleKeyDown = useEventCallback(function (event) {\n // Check if key is already down to avoid repeats being counted as multiple activations\n if (focusRipple && !keydownRef.current && focusVisible && rippleRef.current && event.key === ' ') {\n keydownRef.current = true;\n event.persist();\n rippleRef.current.stop(event, function () {\n rippleRef.current.start(event);\n });\n }\n\n if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') {\n event.preventDefault();\n }\n\n if (onKeyDown) {\n onKeyDown(event);\n } // Keyboard accessibility for non interactive elements\n\n\n if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter' && !disabled) {\n event.preventDefault();\n\n if (onClick) {\n onClick(event);\n }\n }\n });\n var handleKeyUp = useEventCallback(function (event) {\n // calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed\n // https://codesandbox.io/s/button-keyup-preventdefault-dn7f0\n if (focusRipple && event.key === ' ' && rippleRef.current && focusVisible && !event.defaultPrevented) {\n keydownRef.current = false;\n event.persist();\n rippleRef.current.stop(event, function () {\n rippleRef.current.pulsate(event);\n });\n }\n\n if (onKeyUp) {\n onKeyUp(event);\n } // Keyboard accessibility for non interactive elements\n\n\n if (onClick && event.target === event.currentTarget && isNonNativeButton() && event.key === ' ' && !event.defaultPrevented) {\n onClick(event);\n }\n });\n var ComponentProp = component;\n\n if (ComponentProp === 'button' && other.href) {\n ComponentProp = 'a';\n }\n\n var buttonProps = {};\n\n if (ComponentProp === 'button') {\n buttonProps.type = type;\n buttonProps.disabled = disabled;\n } else {\n if (ComponentProp !== 'a' || !other.href) {\n buttonProps.role = 'button';\n }\n\n buttonProps['aria-disabled'] = disabled;\n }\n\n var handleUserRef = useForkRef(buttonRefProp, ref);\n var handleOwnRef = useForkRef(focusVisibleRef, buttonRef);\n var handleRef = useForkRef(handleUserRef, handleOwnRef);\n\n var _React$useState2 = React.useState(false),\n mountedState = _React$useState2[0],\n setMountedState = _React$useState2[1];\n\n React.useEffect(function () {\n setMountedState(true);\n }, []);\n var enableTouchRipple = mountedState && !disableRipple && !disabled;\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(function () {\n if (enableTouchRipple && !rippleRef.current) {\n console.error(['Material-UI: The `component` prop provided to ButtonBase is invalid.', 'Please make sure the children prop is rendered in this custom component.'].join('\\n'));\n }\n }, [enableTouchRipple]);\n }\n\n return /*#__PURE__*/React.createElement(ComponentProp, _extends({\n className: clsx(classes.root, className, focusVisible && [classes.focusVisible, focusVisibleClassName], disabled && classes.disabled),\n onBlur: handleBlur,\n onClick: onClick,\n onFocus: handleFocus,\n onKeyDown: handleKeyDown,\n onKeyUp: handleKeyUp,\n onMouseDown: handleMouseDown,\n onMouseLeave: handleMouseLeave,\n onMouseUp: handleMouseUp,\n onDragLeave: handleDragLeave,\n onTouchEnd: handleTouchEnd,\n onTouchMove: handleTouchMove,\n onTouchStart: handleTouchStart,\n ref: handleRef,\n tabIndex: disabled ? -1 : tabIndex\n }, buttonProps, other), children, enableTouchRipple ?\n /*#__PURE__*/\n\n /* TouchRipple is only needed client-side, x2 boost on the server. */\n React.createElement(TouchRipple, _extends({\n ref: rippleRef,\n center: centerRipple\n }, TouchRippleProps)) : null);\n});\nprocess.env.NODE_ENV !== \"production\" ? ButtonBase.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A ref for imperative actions.\n * It currently only supports `focusVisible()` action.\n */\n action: refType,\n\n /**\n * @ignore\n *\n * Use that prop to pass a ref to the native button component.\n * @deprecated Use `ref` instead.\n */\n buttonRef: refType,\n\n /**\n * If `true`, the ripples will be centered.\n * They won't start at the cursor interaction position.\n */\n centerRipple: PropTypes.bool,\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: elementTypeAcceptingRef,\n\n /**\n * If `true`, the base button will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the ripple effect will be disabled.\n *\n * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure\n * to highlight the element by applying separate styles with the `focusVisibleClassName`.\n */\n disableRipple: PropTypes.bool,\n\n /**\n * If `true`, the touch ripple effect will be disabled.\n */\n disableTouchRipple: PropTypes.bool,\n\n /**\n * If `true`, the base button will have a keyboard focus ripple.\n */\n focusRipple: PropTypes.bool,\n\n /**\n * This prop can help a person know which element has the keyboard focus.\n * The class name will be applied when the element gain the focus through a keyboard interaction.\n * It's a polyfill for the [CSS :focus-visible selector](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo).\n * The rationale for using this feature [is explained here](https://github.com/WICG/focus-visible/blob/master/explainer.md).\n * A [polyfill can be used](https://github.com/WICG/focus-visible) to apply a `focus-visible` class to other components\n * if needed.\n */\n focusVisibleClassName: PropTypes.string,\n\n /**\n * @ignore\n */\n href: PropTypes.string,\n\n /**\n * @ignore\n */\n onBlur: PropTypes.func,\n\n /**\n * @ignore\n */\n onClick: PropTypes.func,\n\n /**\n * @ignore\n */\n onDragLeave: PropTypes.func,\n\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n\n /**\n * Callback fired when the component is focused with a keyboard.\n * We trigger a `onFocus` callback too.\n */\n onFocusVisible: PropTypes.func,\n\n /**\n * @ignore\n */\n onKeyDown: PropTypes.func,\n\n /**\n * @ignore\n */\n onKeyUp: PropTypes.func,\n\n /**\n * @ignore\n */\n onMouseDown: PropTypes.func,\n\n /**\n * @ignore\n */\n onMouseLeave: PropTypes.func,\n\n /**\n * @ignore\n */\n onMouseUp: PropTypes.func,\n\n /**\n * @ignore\n */\n onTouchEnd: PropTypes.func,\n\n /**\n * @ignore\n */\n onTouchMove: PropTypes.func,\n\n /**\n * @ignore\n */\n onTouchStart: PropTypes.func,\n\n /**\n * @ignore\n */\n tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Props applied to the `TouchRipple` element.\n */\n TouchRippleProps: PropTypes.object,\n\n /**\n * @ignore\n */\n type: PropTypes.oneOfType([PropTypes.oneOf(['button', 'reset', 'submit']), PropTypes.string])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiButtonBase'\n})(ButtonBase);","/** @license React v17.0.2\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=require(\"object-assign\"),n=60103,p=60106;exports.Fragment=60107;exports.StrictMode=60108;exports.Profiler=60114;var q=60109,r=60110,t=60112;exports.Suspense=60113;var u=60115,v=60116;\nif(\"function\"===typeof Symbol&&Symbol.for){var w=Symbol.for;n=w(\"react.element\");p=w(\"react.portal\");exports.Fragment=w(\"react.fragment\");exports.StrictMode=w(\"react.strict_mode\");exports.Profiler=w(\"react.profiler\");q=w(\"react.provider\");r=w(\"react.context\");t=w(\"react.forward_ref\");exports.Suspense=w(\"react.suspense\");u=w(\"react.memo\");v=w(\"react.lazy\")}var x=\"function\"===typeof Symbol&&Symbol.iterator;\nfunction y(a){if(null===a||\"object\"!==typeof a)return null;a=x&&a[x]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}function z(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;c<arguments.length;c++)b+=\"&args[]=\"+encodeURIComponent(arguments[c]);return\"Minified React error #\"+a+\"; visit \"+b+\" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"}\nvar A={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B={};function C(a,b,c){this.props=a;this.context=b;this.refs=B;this.updater=c||A}C.prototype.isReactComponent={};C.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(z(85));this.updater.enqueueSetState(this,a,b,\"setState\")};C.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};\nfunction D(){}D.prototype=C.prototype;function E(a,b,c){this.props=a;this.context=b;this.refs=B;this.updater=c||A}var F=E.prototype=new D;F.constructor=E;l(F,C.prototype);F.isPureReactComponent=!0;var G={current:null},H=Object.prototype.hasOwnProperty,I={key:!0,ref:!0,__self:!0,__source:!0};\nfunction J(a,b,c){var e,d={},k=null,h=null;if(null!=b)for(e in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)H.call(b,e)&&!I.hasOwnProperty(e)&&(d[e]=b[e]);var g=arguments.length-2;if(1===g)d.children=c;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];d.children=f}if(a&&a.defaultProps)for(e in g=a.defaultProps,g)void 0===d[e]&&(d[e]=g[e]);return{$$typeof:n,type:a,key:k,ref:h,props:d,_owner:G.current}}\nfunction K(a,b){return{$$typeof:n,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function L(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===n}function escape(a){var b={\"=\":\"=0\",\":\":\"=2\"};return\"$\"+a.replace(/[=:]/g,function(a){return b[a]})}var M=/\\/+/g;function N(a,b){return\"object\"===typeof a&&null!==a&&null!=a.key?escape(\"\"+a.key):b.toString(36)}\nfunction O(a,b,c,e,d){var k=typeof a;if(\"undefined\"===k||\"boolean\"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case \"string\":case \"number\":h=!0;break;case \"object\":switch(a.$$typeof){case n:case p:h=!0}}if(h)return h=a,d=d(h),a=\"\"===e?\".\"+N(h,0):e,Array.isArray(d)?(c=\"\",null!=a&&(c=a.replace(M,\"$&/\")+\"/\"),O(d,b,c,\"\",function(a){return a})):null!=d&&(L(d)&&(d=K(d,c+(!d.key||h&&h.key===d.key?\"\":(\"\"+d.key).replace(M,\"$&/\")+\"/\")+a)),b.push(d)),1;h=0;e=\"\"===e?\".\":e+\":\";if(Array.isArray(a))for(var g=\n0;g<a.length;g++){k=a[g];var f=e+N(k,g);h+=O(k,b,c,f,d)}else if(f=y(a),\"function\"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=e+N(k,g++),h+=O(k,b,c,f,d);else if(\"object\"===k)throw b=\"\"+a,Error(z(31,\"[object Object]\"===b?\"object with keys {\"+Object.keys(a).join(\", \")+\"}\":b));return h}function P(a,b,c){if(null==a)return a;var e=[],d=0;O(a,e,\"\",\"\",function(a){return b.call(c,a,d++)});return e}\nfunction Q(a){if(-1===a._status){var b=a._result;b=b();a._status=0;a._result=b;b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)})}if(1===a._status)return a._result;throw a._result;}var R={current:null};function S(){var a=R.current;if(null===a)throw Error(z(321));return a}var T={ReactCurrentDispatcher:R,ReactCurrentBatchConfig:{transition:0},ReactCurrentOwner:G,IsSomeRendererActing:{current:!1},assign:l};\nexports.Children={map:P,forEach:function(a,b,c){P(a,function(){b.apply(this,arguments)},c)},count:function(a){var b=0;P(a,function(){b++});return b},toArray:function(a){return P(a,function(a){return a})||[]},only:function(a){if(!L(a))throw Error(z(143));return a}};exports.Component=C;exports.PureComponent=E;exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=T;\nexports.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error(z(267,a));var e=l({},a.props),d=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=G.current);void 0!==b.key&&(d=\"\"+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)H.call(b,f)&&!I.hasOwnProperty(f)&&(e[f]=void 0===b[f]&&void 0!==g?g[f]:b[f])}var f=arguments.length-2;if(1===f)e.children=c;else if(1<f){g=Array(f);for(var m=0;m<f;m++)g[m]=arguments[m+2];e.children=g}return{$$typeof:n,type:a.type,\nkey:d,ref:k,props:e,_owner:h}};exports.createContext=function(a,b){void 0===b&&(b=null);a={$$typeof:r,_calculateChangedBits:b,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null};a.Provider={$$typeof:q,_context:a};return a.Consumer=a};exports.createElement=J;exports.createFactory=function(a){var b=J.bind(null,a);b.type=a;return b};exports.createRef=function(){return{current:null}};exports.forwardRef=function(a){return{$$typeof:t,render:a}};exports.isValidElement=L;\nexports.lazy=function(a){return{$$typeof:v,_payload:{_status:-1,_result:a},_init:Q}};exports.memo=function(a,b){return{$$typeof:u,type:a,compare:void 0===b?null:b}};exports.useCallback=function(a,b){return S().useCallback(a,b)};exports.useContext=function(a,b){return S().useContext(a,b)};exports.useDebugValue=function(){};exports.useEffect=function(a,b){return S().useEffect(a,b)};exports.useImperativeHandle=function(a,b,c){return S().useImperativeHandle(a,b,c)};\nexports.useLayoutEffect=function(a,b){return S().useLayoutEffect(a,b)};exports.useMemo=function(a,b){return S().useMemo(a,b)};exports.useReducer=function(a,b,c){return S().useReducer(a,b,c)};exports.useRef=function(a){return S().useRef(a)};exports.useState=function(a){return S().useState(a)};exports.version=\"17.0.2\";\n","/** @license React v17.0.2\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),m=require(\"object-assign\"),r=require(\"scheduler\");function y(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;c<arguments.length;c++)b+=\"&args[]=\"+encodeURIComponent(arguments[c]);return\"Minified React error #\"+a+\"; visit \"+b+\" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"}if(!aa)throw Error(y(227));var ba=new Set,ca={};function da(a,b){ea(a,b);ea(a+\"Capture\",b)}\nfunction ea(a,b){ca[a]=b;for(a=0;a<b.length;a++)ba.add(b[a])}\nvar fa=!(\"undefined\"===typeof window||\"undefined\"===typeof window.document||\"undefined\"===typeof window.document.createElement),ha=/^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$/,ia=Object.prototype.hasOwnProperty,\nja={},ka={};function la(a){if(ia.call(ka,a))return!0;if(ia.call(ja,a))return!1;if(ha.test(a))return ka[a]=!0;ja[a]=!0;return!1}function ma(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case \"function\":case \"symbol\":return!0;case \"boolean\":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return\"data-\"!==a&&\"aria-\"!==a;default:return!1}}\nfunction na(a,b,c,d){if(null===b||\"undefined\"===typeof b||ma(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function B(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var D={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){D[a]=new B(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];D[b]=new B(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){D[a]=new B(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){D[a]=new B(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){D[a]=new B(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){D[a]=new B(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){D[a]=new B(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){D[a]=new B(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){D[a]=new B(a,5,!1,a.toLowerCase(),null,!1,!1)});var oa=/[\\-:]([a-z])/g;function pa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(oa,\npa);D[b]=new B(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(oa,pa);D[b]=new B(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(oa,pa);D[b]=new B(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!1,!1)});\nD.xlinkHref=new B(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction qa(a,b,c,d){var e=D.hasOwnProperty(b)?D[b]:null;var f=null!==e?0===e.type:d?!1:!(2<b.length)||\"o\"!==b[0]&&\"O\"!==b[0]||\"n\"!==b[1]&&\"N\"!==b[1]?!1:!0;f||(na(b,c,e,d)&&(c=null),d||null===e?la(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,\"\"+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:\"\":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?\"\":\"\"+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c))))}\nvar ra=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,sa=60103,ta=60106,ua=60107,wa=60108,xa=60114,ya=60109,za=60110,Aa=60112,Ba=60113,Ca=60120,Da=60115,Ea=60116,Fa=60121,Ga=60128,Ha=60129,Ia=60130,Ja=60131;\nif(\"function\"===typeof Symbol&&Symbol.for){var E=Symbol.for;sa=E(\"react.element\");ta=E(\"react.portal\");ua=E(\"react.fragment\");wa=E(\"react.strict_mode\");xa=E(\"react.profiler\");ya=E(\"react.provider\");za=E(\"react.context\");Aa=E(\"react.forward_ref\");Ba=E(\"react.suspense\");Ca=E(\"react.suspense_list\");Da=E(\"react.memo\");Ea=E(\"react.lazy\");Fa=E(\"react.block\");E(\"react.scope\");Ga=E(\"react.opaque.id\");Ha=E(\"react.debug_trace_mode\");Ia=E(\"react.offscreen\");Ja=E(\"react.legacy_hidden\")}\nvar Ka=\"function\"===typeof Symbol&&Symbol.iterator;function La(a){if(null===a||\"object\"!==typeof a)return null;a=Ka&&a[Ka]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}var Ma;function Na(a){if(void 0===Ma)try{throw Error();}catch(c){var b=c.stack.trim().match(/\\n( *(at )?)/);Ma=b&&b[1]||\"\"}return\"\\n\"+Ma+a}var Oa=!1;\nfunction Pa(a,b){if(!a||Oa)return\"\";Oa=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(b)if(b=function(){throw Error();},Object.defineProperty(b.prototype,\"props\",{set:function(){throw Error();}}),\"object\"===typeof Reflect&&Reflect.construct){try{Reflect.construct(b,[])}catch(k){var d=k}Reflect.construct(a,[],b)}else{try{b.call()}catch(k){d=k}a.call(b.prototype)}else{try{throw Error();}catch(k){d=k}a()}}catch(k){if(k&&d&&\"string\"===typeof k.stack){for(var e=k.stack.split(\"\\n\"),\nf=d.stack.split(\"\\n\"),g=e.length-1,h=f.length-1;1<=g&&0<=h&&e[g]!==f[h];)h--;for(;1<=g&&0<=h;g--,h--)if(e[g]!==f[h]){if(1!==g||1!==h){do if(g--,h--,0>h||e[g]!==f[h])return\"\\n\"+e[g].replace(\" at new \",\" at \");while(1<=g&&0<=h)}break}}}finally{Oa=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Na(a):\"\"}\nfunction Qa(a){switch(a.tag){case 5:return Na(a.type);case 16:return Na(\"Lazy\");case 13:return Na(\"Suspense\");case 19:return Na(\"SuspenseList\");case 0:case 2:case 15:return a=Pa(a.type,!1),a;case 11:return a=Pa(a.type.render,!1),a;case 22:return a=Pa(a.type._render,!1),a;case 1:return a=Pa(a.type,!0),a;default:return\"\"}}\nfunction Ra(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ua:return\"Fragment\";case ta:return\"Portal\";case xa:return\"Profiler\";case wa:return\"StrictMode\";case Ba:return\"Suspense\";case Ca:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case za:return(a.displayName||\"Context\")+\".Consumer\";case ya:return(a._context.displayName||\"Context\")+\".Provider\";case Aa:var b=a.render;b=b.displayName||b.name||\"\";\nreturn a.displayName||(\"\"!==b?\"ForwardRef(\"+b+\")\":\"ForwardRef\");case Da:return Ra(a.type);case Fa:return Ra(a._render);case Ea:b=a._payload;a=a._init;try{return Ra(a(b))}catch(c){}}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"object\":case \"string\":case \"undefined\":return a;default:return\"\"}}function Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return m({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function $a(a,b){b=b.checked;null!=b&&qa(a,\"checked\",b,!1)}\nfunction ab(a,b){$a(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?bb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&bb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction cb(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction bb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}function db(a){var b=\"\";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}function eb(a,b){a=m({children:void 0},b);if(b=db(b.children))a.children=b;return a}\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b[\"$\"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty(\"$\"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=\"\"+Sa(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}\nfunction gb(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(y(91));return m({},b,{value:void 0,defaultValue:void 0,children:\"\"+a._wrapperState.initialValue})}function hb(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(y(92));if(Array.isArray(c)){if(!(1>=c.length))throw Error(y(93));c=c[0]}b=c}null==b&&(b=\"\");c=b}a._wrapperState={initialValue:Sa(c)}}\nfunction ib(a,b){var c=Sa(b.value),d=Sa(b.defaultValue);null!=c&&(c=\"\"+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=\"\"+d)}function jb(a){var b=a.textContent;b===a._wrapperState.initialValue&&\"\"!==b&&null!==b&&(a.value=b)}var kb={html:\"http://www.w3.org/1999/xhtml\",mathml:\"http://www.w3.org/1998/Math/MathML\",svg:\"http://www.w3.org/2000/svg\"};\nfunction lb(a){switch(a){case \"svg\":return\"http://www.w3.org/2000/svg\";case \"math\":return\"http://www.w3.org/1998/Math/MathML\";default:return\"http://www.w3.org/1999/xhtml\"}}function mb(a,b){return null==a||\"http://www.w3.org/1999/xhtml\"===a?lb(b):\"http://www.w3.org/2000/svg\"===a&&\"foreignObject\"===b?\"http://www.w3.org/1999/xhtml\":a}\nvar nb,ob=function(a){return\"undefined\"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(a.namespaceURI!==kb.svg||\"innerHTML\"in a)a.innerHTML=b;else{nb=nb||document.createElement(\"div\");nb.innerHTML=\"<svg>\"+b.valueOf().toString()+\"</svg>\";for(b=nb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction pb(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar qb={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,\nfloodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},rb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(qb).forEach(function(a){rb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);qb[b]=qb[a]})});function sb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||qb.hasOwnProperty(a)&&qb[a]?(\"\"+b).trim():b+\"px\"}\nfunction tb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=sb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var ub=m({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction vb(a,b){if(b){if(ub[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(y(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(y(60));if(!(\"object\"===typeof b.dangerouslySetInnerHTML&&\"__html\"in b.dangerouslySetInnerHTML))throw Error(y(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(y(62));}}\nfunction wb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(y(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a<b.length;a++)Bb(b[a])}}function Gb(a,b){return a(b)}function Hb(a,b,c,d,e){return a(b,c,d,e)}function Ib(){}var Jb=Gb,Kb=!1,Lb=!1;function Mb(){if(null!==zb||null!==Ab)Ib(),Fb()}\nfunction Nb(a,b,c){if(Lb)return a(b,c);Lb=!0;try{return Jb(a,b,c)}finally{Lb=!1,Mb()}}\nfunction Ob(a,b){var c=a.stateNode;if(null===c)return null;var d=Db(c);if(null===d)return null;c=d[b];a:switch(b){case \"onClick\":case \"onClickCapture\":case \"onDoubleClick\":case \"onDoubleClickCapture\":case \"onMouseDown\":case \"onMouseDownCapture\":case \"onMouseMove\":case \"onMouseMoveCapture\":case \"onMouseUp\":case \"onMouseUpCapture\":case \"onMouseEnter\":(d=!d.disabled)||(a=a.type,d=!(\"button\"===a||\"input\"===a||\"select\"===a||\"textarea\"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&\"function\"!==\ntypeof c)throw Error(y(231,b,typeof c));return c}var Pb=!1;if(fa)try{var Qb={};Object.defineProperty(Qb,\"passive\",{get:function(){Pb=!0}});window.addEventListener(\"test\",Qb,Qb);window.removeEventListener(\"test\",Qb,Qb)}catch(a){Pb=!1}function Rb(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(n){this.onError(n)}}var Sb=!1,Tb=null,Ub=!1,Vb=null,Wb={onError:function(a){Sb=!0;Tb=a}};function Xb(a,b,c,d,e,f,g,h,k){Sb=!1;Tb=null;Rb.apply(Wb,arguments)}\nfunction Yb(a,b,c,d,e,f,g,h,k){Xb.apply(this,arguments);if(Sb){if(Sb){var l=Tb;Sb=!1;Tb=null}else throw Error(y(198));Ub||(Ub=!0,Vb=l)}}function Zb(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.flags&1026)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function $b(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function ac(a){if(Zb(a)!==a)throw Error(y(188));}\nfunction bc(a){var b=a.alternate;if(!b){b=Zb(a);if(null===b)throw Error(y(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return ac(e),a;if(f===d)return ac(e),b;f=f.sibling}throw Error(y(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===\nc){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(y(189));}}if(c.alternate!==d)throw Error(y(190));}if(3!==c.tag)throw Error(y(188));return c.stateNode.current===c?a:b}function cc(a){a=bc(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}}return null}\nfunction dc(a,b){for(var c=a.alternate;null!==b;){if(b===a||b===c)return!0;b=b.return}return!1}var ec,fc,gc,hc,ic=!1,jc=[],kc=null,lc=null,mc=null,nc=new Map,oc=new Map,pc=[],qc=\"mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit\".split(\" \");\nfunction rc(a,b,c,d,e){return{blockedOn:a,domEventName:b,eventSystemFlags:c|16,nativeEvent:e,targetContainers:[d]}}function sc(a,b){switch(a){case \"focusin\":case \"focusout\":kc=null;break;case \"dragenter\":case \"dragleave\":lc=null;break;case \"mouseover\":case \"mouseout\":mc=null;break;case \"pointerover\":case \"pointerout\":nc.delete(b.pointerId);break;case \"gotpointercapture\":case \"lostpointercapture\":oc.delete(b.pointerId)}}\nfunction tc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a=rc(b,c,d,e,f),null!==b&&(b=Cb(b),null!==b&&fc(b)),a;a.eventSystemFlags|=d;b=a.targetContainers;null!==e&&-1===b.indexOf(e)&&b.push(e);return a}\nfunction uc(a,b,c,d,e){switch(b){case \"focusin\":return kc=tc(kc,a,b,c,d,e),!0;case \"dragenter\":return lc=tc(lc,a,b,c,d,e),!0;case \"mouseover\":return mc=tc(mc,a,b,c,d,e),!0;case \"pointerover\":var f=e.pointerId;nc.set(f,tc(nc.get(f)||null,a,b,c,d,e));return!0;case \"gotpointercapture\":return f=e.pointerId,oc.set(f,tc(oc.get(f)||null,a,b,c,d,e)),!0}return!1}\nfunction vc(a){var b=wc(a.target);if(null!==b){var c=Zb(b);if(null!==c)if(b=c.tag,13===b){if(b=$b(c),null!==b){a.blockedOn=b;hc(a.lanePriority,function(){r.unstable_runWithPriority(a.priority,function(){gc(c)})});return}}else if(3===b&&c.stateNode.hydrate){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}\nfunction xc(a){if(null!==a.blockedOn)return!1;for(var b=a.targetContainers;0<b.length;){var c=yc(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null!==c)return b=Cb(c),null!==b&&fc(b),a.blockedOn=c,!1;b.shift()}return!0}function zc(a,b,c){xc(a)&&c.delete(b)}\nfunction Ac(){for(ic=!1;0<jc.length;){var a=jc[0];if(null!==a.blockedOn){a=Cb(a.blockedOn);null!==a&&ec(a);break}for(var b=a.targetContainers;0<b.length;){var c=yc(a.domEventName,a.eventSystemFlags,b[0],a.nativeEvent);if(null!==c){a.blockedOn=c;break}b.shift()}null===a.blockedOn&&jc.shift()}null!==kc&&xc(kc)&&(kc=null);null!==lc&&xc(lc)&&(lc=null);null!==mc&&xc(mc)&&(mc=null);nc.forEach(zc);oc.forEach(zc)}\nfunction Bc(a,b){a.blockedOn===b&&(a.blockedOn=null,ic||(ic=!0,r.unstable_scheduleCallback(r.unstable_NormalPriority,Ac)))}\nfunction Cc(a){function b(b){return Bc(b,a)}if(0<jc.length){Bc(jc[0],a);for(var c=1;c<jc.length;c++){var d=jc[c];d.blockedOn===a&&(d.blockedOn=null)}}null!==kc&&Bc(kc,a);null!==lc&&Bc(lc,a);null!==mc&&Bc(mc,a);nc.forEach(b);oc.forEach(b);for(c=0;c<pc.length;c++)d=pc[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<pc.length&&(c=pc[0],null===c.blockedOn);)vc(c),null===c.blockedOn&&pc.shift()}\nfunction Dc(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c[\"Webkit\"+a]=\"webkit\"+b;c[\"Moz\"+a]=\"moz\"+b;return c}var Ec={animationend:Dc(\"Animation\",\"AnimationEnd\"),animationiteration:Dc(\"Animation\",\"AnimationIteration\"),animationstart:Dc(\"Animation\",\"AnimationStart\"),transitionend:Dc(\"Transition\",\"TransitionEnd\")},Fc={},Gc={};\nfa&&(Gc=document.createElement(\"div\").style,\"AnimationEvent\"in window||(delete Ec.animationend.animation,delete Ec.animationiteration.animation,delete Ec.animationstart.animation),\"TransitionEvent\"in window||delete Ec.transitionend.transition);function Hc(a){if(Fc[a])return Fc[a];if(!Ec[a])return a;var b=Ec[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Gc)return Fc[a]=b[c];return a}\nvar Ic=Hc(\"animationend\"),Jc=Hc(\"animationiteration\"),Kc=Hc(\"animationstart\"),Lc=Hc(\"transitionend\"),Mc=new Map,Nc=new Map,Oc=[\"abort\",\"abort\",Ic,\"animationEnd\",Jc,\"animationIteration\",Kc,\"animationStart\",\"canplay\",\"canPlay\",\"canplaythrough\",\"canPlayThrough\",\"durationchange\",\"durationChange\",\"emptied\",\"emptied\",\"encrypted\",\"encrypted\",\"ended\",\"ended\",\"error\",\"error\",\"gotpointercapture\",\"gotPointerCapture\",\"load\",\"load\",\"loadeddata\",\"loadedData\",\"loadedmetadata\",\"loadedMetadata\",\"loadstart\",\"loadStart\",\n\"lostpointercapture\",\"lostPointerCapture\",\"playing\",\"playing\",\"progress\",\"progress\",\"seeking\",\"seeking\",\"stalled\",\"stalled\",\"suspend\",\"suspend\",\"timeupdate\",\"timeUpdate\",Lc,\"transitionEnd\",\"waiting\",\"waiting\"];function Pc(a,b){for(var c=0;c<a.length;c+=2){var d=a[c],e=a[c+1];e=\"on\"+(e[0].toUpperCase()+e.slice(1));Nc.set(d,b);Mc.set(d,e);da(e,[d])}}var Qc=r.unstable_now;Qc();var F=8;\nfunction Rc(a){if(0!==(1&a))return F=15,1;if(0!==(2&a))return F=14,2;if(0!==(4&a))return F=13,4;var b=24&a;if(0!==b)return F=12,b;if(0!==(a&32))return F=11,32;b=192&a;if(0!==b)return F=10,b;if(0!==(a&256))return F=9,256;b=3584&a;if(0!==b)return F=8,b;if(0!==(a&4096))return F=7,4096;b=4186112&a;if(0!==b)return F=6,b;b=62914560&a;if(0!==b)return F=5,b;if(a&67108864)return F=4,67108864;if(0!==(a&134217728))return F=3,134217728;b=805306368&a;if(0!==b)return F=2,b;if(0!==(1073741824&a))return F=1,1073741824;\nF=8;return a}function Sc(a){switch(a){case 99:return 15;case 98:return 10;case 97:case 96:return 8;case 95:return 2;default:return 0}}function Tc(a){switch(a){case 15:case 14:return 99;case 13:case 12:case 11:case 10:return 98;case 9:case 8:case 7:case 6:case 4:case 5:return 97;case 3:case 2:case 1:return 95;case 0:return 90;default:throw Error(y(358,a));}}\nfunction Uc(a,b){var c=a.pendingLanes;if(0===c)return F=0;var d=0,e=0,f=a.expiredLanes,g=a.suspendedLanes,h=a.pingedLanes;if(0!==f)d=f,e=F=15;else if(f=c&134217727,0!==f){var k=f&~g;0!==k?(d=Rc(k),e=F):(h&=f,0!==h&&(d=Rc(h),e=F))}else f=c&~g,0!==f?(d=Rc(f),e=F):0!==h&&(d=Rc(h),e=F);if(0===d)return 0;d=31-Vc(d);d=c&((0>d?0:1<<d)<<1)-1;if(0!==b&&b!==d&&0===(b&g)){Rc(b);if(e<=F)return b;F=e}b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0<b;)c=31-Vc(b),e=1<<c,d|=a[c],b&=~e;return d}\nfunction Wc(a){a=a.pendingLanes&-1073741825;return 0!==a?a:a&1073741824?1073741824:0}function Xc(a,b){switch(a){case 15:return 1;case 14:return 2;case 12:return a=Yc(24&~b),0===a?Xc(10,b):a;case 10:return a=Yc(192&~b),0===a?Xc(8,b):a;case 8:return a=Yc(3584&~b),0===a&&(a=Yc(4186112&~b),0===a&&(a=512)),a;case 2:return b=Yc(805306368&~b),0===b&&(b=268435456),b}throw Error(y(358,a));}function Yc(a){return a&-a}function Zc(a){for(var b=[],c=0;31>c;c++)b.push(a);return b}\nfunction $c(a,b,c){a.pendingLanes|=b;var d=b-1;a.suspendedLanes&=d;a.pingedLanes&=d;a=a.eventTimes;b=31-Vc(b);a[b]=c}var Vc=Math.clz32?Math.clz32:ad,bd=Math.log,cd=Math.LN2;function ad(a){return 0===a?32:31-(bd(a)/cd|0)|0}var dd=r.unstable_UserBlockingPriority,ed=r.unstable_runWithPriority,fd=!0;function gd(a,b,c,d){Kb||Ib();var e=hd,f=Kb;Kb=!0;try{Hb(e,a,b,c,d)}finally{(Kb=f)||Mb()}}function id(a,b,c,d){ed(dd,hd.bind(null,a,b,c,d))}\nfunction hd(a,b,c,d){if(fd){var e;if((e=0===(b&4))&&0<jc.length&&-1<qc.indexOf(a))a=rc(null,a,b,c,d),jc.push(a);else{var f=yc(a,b,c,d);if(null===f)e&&sc(a,d);else{if(e){if(-1<qc.indexOf(a)){a=rc(f,a,b,c,d);jc.push(a);return}if(uc(f,a,b,c,d))return;sc(a,d)}jd(a,b,d,null,c)}}}}\nfunction yc(a,b,c,d){var e=xb(d);e=wc(e);if(null!==e){var f=Zb(e);if(null===f)e=null;else{var g=f.tag;if(13===g){e=$b(f);if(null!==e)return e;e=null}else if(3===g){if(f.stateNode.hydrate)return 3===f.tag?f.stateNode.containerInfo:null;e=null}else f!==e&&(e=null)}}jd(a,b,d,e,c);return null}var kd=null,ld=null,md=null;\nfunction nd(){if(md)return md;var a,b=ld,c=b.length,d,e=\"value\"in kd?kd.value:kd.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return md=e.slice(a,1<d?1-d:void 0)}function od(a){var b=a.keyCode;\"charCode\"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function pd(){return!0}function qd(){return!1}\nfunction rd(a){function b(b,d,e,f,g){this._reactName=b;this._targetInst=e;this.type=d;this.nativeEvent=f;this.target=g;this.currentTarget=null;for(var c in a)a.hasOwnProperty(c)&&(b=a[c],this[c]=b?b(f):f[c]);this.isDefaultPrevented=(null!=f.defaultPrevented?f.defaultPrevented:!1===f.returnValue)?pd:qd;this.isPropagationStopped=qd;return this}m(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():\"unknown\"!==typeof a.returnValue&&\n(a.returnValue=!1),this.isDefaultPrevented=pd)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():\"unknown\"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=pd)},persist:function(){},isPersistent:pd});return b}\nvar sd={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},td=rd(sd),ud=m({},sd,{view:0,detail:0}),vd=rd(ud),wd,xd,yd,Ad=m({},ud,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){if(\"movementX\"in\na)return a.movementX;a!==yd&&(yd&&\"mousemove\"===a.type?(wd=a.screenX-yd.screenX,xd=a.screenY-yd.screenY):xd=wd=0,yd=a);return wd},movementY:function(a){return\"movementY\"in a?a.movementY:xd}}),Bd=rd(Ad),Cd=m({},Ad,{dataTransfer:0}),Dd=rd(Cd),Ed=m({},ud,{relatedTarget:0}),Fd=rd(Ed),Gd=m({},sd,{animationName:0,elapsedTime:0,pseudoElement:0}),Hd=rd(Gd),Id=m({},sd,{clipboardData:function(a){return\"clipboardData\"in a?a.clipboardData:window.clipboardData}}),Jd=rd(Id),Kd=m({},sd,{data:0}),Ld=rd(Kd),Md={Esc:\"Escape\",\nSpacebar:\" \",Left:\"ArrowLeft\",Up:\"ArrowUp\",Right:\"ArrowRight\",Down:\"ArrowDown\",Del:\"Delete\",Win:\"OS\",Menu:\"ContextMenu\",Apps:\"ContextMenu\",Scroll:\"ScrollLock\",MozPrintableKey:\"Unidentified\"},Nd={8:\"Backspace\",9:\"Tab\",12:\"Clear\",13:\"Enter\",16:\"Shift\",17:\"Control\",18:\"Alt\",19:\"Pause\",20:\"CapsLock\",27:\"Escape\",32:\" \",33:\"PageUp\",34:\"PageDown\",35:\"End\",36:\"Home\",37:\"ArrowLeft\",38:\"ArrowUp\",39:\"ArrowRight\",40:\"ArrowDown\",45:\"Insert\",46:\"Delete\",112:\"F1\",113:\"F2\",114:\"F3\",115:\"F4\",116:\"F5\",117:\"F6\",118:\"F7\",\n119:\"F8\",120:\"F9\",121:\"F10\",122:\"F11\",123:\"F12\",144:\"NumLock\",145:\"ScrollLock\",224:\"Meta\"},Od={Alt:\"altKey\",Control:\"ctrlKey\",Meta:\"metaKey\",Shift:\"shiftKey\"};function Pd(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Od[a])?!!b[a]:!1}function zd(){return Pd}\nvar Qd=m({},ud,{key:function(a){if(a.key){var b=Md[a.key]||a.key;if(\"Unidentified\"!==b)return b}return\"keypress\"===a.type?(a=od(a),13===a?\"Enter\":String.fromCharCode(a)):\"keydown\"===a.type||\"keyup\"===a.type?Nd[a.keyCode]||\"Unidentified\":\"\"},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(a){return\"keypress\"===a.type?od(a):0},keyCode:function(a){return\"keydown\"===a.type||\"keyup\"===a.type?a.keyCode:0},which:function(a){return\"keypress\"===\na.type?od(a):\"keydown\"===a.type||\"keyup\"===a.type?a.keyCode:0}}),Rd=rd(Qd),Sd=m({},Ad,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Td=rd(Sd),Ud=m({},ud,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd}),Vd=rd(Ud),Wd=m({},sd,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xd=rd(Wd),Yd=m({},Ad,{deltaX:function(a){return\"deltaX\"in a?a.deltaX:\"wheelDeltaX\"in a?-a.wheelDeltaX:0},\ndeltaY:function(a){return\"deltaY\"in a?a.deltaY:\"wheelDeltaY\"in a?-a.wheelDeltaY:\"wheelDelta\"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0}),Zd=rd(Yd),$d=[9,13,27,32],ae=fa&&\"CompositionEvent\"in window,be=null;fa&&\"documentMode\"in document&&(be=document.documentMode);var ce=fa&&\"TextEvent\"in window&&!be,de=fa&&(!ae||be&&8<be&&11>=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case \"compositionend\":return de&&\"ko\"!==b.locale?null:b.data;default:return null}}\nvar le={color:!0,date:!0,datetime:!0,\"datetime-local\":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function me(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return\"input\"===b?!!le[a.type]:\"textarea\"===b?!0:!1}function ne(a,b,c,d){Eb(d);b=oe(b,\"onChange\");0<b.length&&(c=new td(\"onChange\",\"change\",null,c,d),a.push({event:c,listeners:b}))}var pe=null,qe=null;function re(a){se(a,0)}function te(a){var b=ue(a);if(Wa(b))return a}\nfunction ve(a,b){if(\"change\"===a)return b}var we=!1;if(fa){var xe;if(fa){var ye=\"oninput\"in document;if(!ye){var ze=document.createElement(\"div\");ze.setAttribute(\"oninput\",\"return;\");ye=\"function\"===typeof ze.oninput}xe=ye}else xe=!1;we=xe&&(!document.documentMode||9<document.documentMode)}function Ae(){pe&&(pe.detachEvent(\"onpropertychange\",Be),qe=pe=null)}function Be(a){if(\"value\"===a.propertyName&&te(qe)){var b=[];ne(b,qe,a,xb(a));a=re;if(Kb)a(b);else{Kb=!0;try{Gb(a,b)}finally{Kb=!1,Mb()}}}}\nfunction Ce(a,b,c){\"focusin\"===a?(Ae(),pe=b,qe=c,pe.attachEvent(\"onpropertychange\",Be)):\"focusout\"===a&&Ae()}function De(a){if(\"selectionchange\"===a||\"keyup\"===a||\"keydown\"===a)return te(qe)}function Ee(a,b){if(\"click\"===a)return te(b)}function Fe(a,b){if(\"input\"===a||\"change\"===a)return te(b)}function Ge(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var He=\"function\"===typeof Object.is?Object.is:Ge,Ie=Object.prototype.hasOwnProperty;\nfunction Je(a,b){if(He(a,b))return!0;if(\"object\"!==typeof a||null===a||\"object\"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++)if(!Ie.call(b,c[d])||!He(a[c[d]],b[c[d]]))return!1;return!0}function Ke(a){for(;a&&a.firstChild;)a=a.firstChild;return a}\nfunction Le(a,b){var c=Ke(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Ke(c)}}function Me(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Me(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Ne(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Oe(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nvar Pe=fa&&\"documentMode\"in document&&11>=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Oe(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Je(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0<d.length&&(b=new td(\"onSelect\",\"select\",null,b,c),a.push({event:b,listeners:d}),b.target=Qe)))}\nPc(\"cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focusin focus focusout blur input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange\".split(\" \"),\n0);Pc(\"drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel\".split(\" \"),1);Pc(Oc,2);for(var Ve=\"change selectionchange textInput compositionstart compositionend compositionupdate\".split(\" \"),We=0;We<Ve.length;We++)Nc.set(Ve[We],0);ea(\"onMouseEnter\",[\"mouseout\",\"mouseover\"]);\nea(\"onMouseLeave\",[\"mouseout\",\"mouseover\"]);ea(\"onPointerEnter\",[\"pointerout\",\"pointerover\"]);ea(\"onPointerLeave\",[\"pointerout\",\"pointerover\"]);da(\"onChange\",\"change click focusin focusout input keydown keyup selectionchange\".split(\" \"));da(\"onSelect\",\"focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange\".split(\" \"));da(\"onBeforeInput\",[\"compositionend\",\"keypress\",\"textInput\",\"paste\"]);da(\"onCompositionEnd\",\"compositionend focusout keydown keypress keyup mousedown\".split(\" \"));\nda(\"onCompositionStart\",\"compositionstart focusout keydown keypress keyup mousedown\".split(\" \"));da(\"onCompositionUpdate\",\"compositionupdate focusout keydown keypress keyup mousedown\".split(\" \"));var Xe=\"abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting\".split(\" \"),Ye=new Set(\"cancel close invalid load scroll toggle\".split(\" \").concat(Xe));\nfunction Ze(a,b,c){var d=a.type||\"unknown-event\";a.currentTarget=c;Yb(d,b,void 0,a);a.currentTarget=null}\nfunction se(a,b){b=0!==(b&4);for(var c=0;c<a.length;c++){var d=a[c],e=d.event;d=d.listeners;a:{var f=void 0;if(b)for(var g=d.length-1;0<=g;g--){var h=d[g],k=h.instance,l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;Ze(e,h,l);f=k}else for(g=0;g<d.length;g++){h=d[g];k=h.instance;l=h.currentTarget;h=h.listener;if(k!==f&&e.isPropagationStopped())break a;Ze(e,h,l);f=k}}}if(Ub)throw a=Vb,Ub=!1,Vb=null,a;}\nfunction G(a,b){var c=$e(b),d=a+\"__bubble\";c.has(d)||(af(b,a,2,!1),c.add(d))}var bf=\"_reactListening\"+Math.random().toString(36).slice(2);function cf(a){a[bf]||(a[bf]=!0,ba.forEach(function(b){Ye.has(b)||df(b,!1,a,null);df(b,!0,a,null)}))}\nfunction df(a,b,c,d){var e=4<arguments.length&&void 0!==arguments[4]?arguments[4]:0,f=c;\"selectionchange\"===a&&9!==c.nodeType&&(f=c.ownerDocument);if(null!==d&&!b&&Ye.has(a)){if(\"scroll\"!==a)return;e|=2;f=d}var g=$e(f),h=a+\"__\"+(b?\"capture\":\"bubble\");g.has(h)||(b&&(e|=4),af(f,a,e,b),g.add(h))}\nfunction af(a,b,c,d){var e=Nc.get(b);switch(void 0===e?2:e){case 0:e=gd;break;case 1:e=id;break;default:e=hd}c=e.bind(null,b,c,a);e=void 0;!Pb||\"touchstart\"!==b&&\"touchmove\"!==b&&\"wheel\"!==b||(e=!0);d?void 0!==e?a.addEventListener(b,c,{capture:!0,passive:e}):a.addEventListener(b,c,!0):void 0!==e?a.addEventListener(b,c,{passive:e}):a.addEventListener(b,c,!1)}\nfunction jd(a,b,c,d,e){var f=d;if(0===(b&1)&&0===(b&2)&&null!==d)a:for(;;){if(null===d)return;var g=d.tag;if(3===g||4===g){var h=d.stateNode.containerInfo;if(h===e||8===h.nodeType&&h.parentNode===e)break;if(4===g)for(g=d.return;null!==g;){var k=g.tag;if(3===k||4===k)if(k=g.stateNode.containerInfo,k===e||8===k.nodeType&&k.parentNode===e)return;g=g.return}for(;null!==h;){g=wc(h);if(null===g)return;k=g.tag;if(5===k||6===k){d=f=g;continue a}h=h.parentNode}}d=d.return}Nb(function(){var d=f,e=xb(c),g=[];\na:{var h=Mc.get(a);if(void 0!==h){var k=td,x=a;switch(a){case \"keypress\":if(0===od(c))break a;case \"keydown\":case \"keyup\":k=Rd;break;case \"focusin\":x=\"focus\";k=Fd;break;case \"focusout\":x=\"blur\";k=Fd;break;case \"beforeblur\":case \"afterblur\":k=Fd;break;case \"click\":if(2===c.button)break a;case \"auxclick\":case \"dblclick\":case \"mousedown\":case \"mousemove\":case \"mouseup\":case \"mouseout\":case \"mouseover\":case \"contextmenu\":k=Bd;break;case \"drag\":case \"dragend\":case \"dragenter\":case \"dragexit\":case \"dragleave\":case \"dragover\":case \"dragstart\":case \"drop\":k=\nDd;break;case \"touchcancel\":case \"touchend\":case \"touchmove\":case \"touchstart\":k=Vd;break;case Ic:case Jc:case Kc:k=Hd;break;case Lc:k=Xd;break;case \"scroll\":k=vd;break;case \"wheel\":k=Zd;break;case \"copy\":case \"cut\":case \"paste\":k=Jd;break;case \"gotpointercapture\":case \"lostpointercapture\":case \"pointercancel\":case \"pointerdown\":case \"pointermove\":case \"pointerout\":case \"pointerover\":case \"pointerup\":k=Td}var w=0!==(b&4),z=!w&&\"scroll\"===a,u=w?null!==h?h+\"Capture\":null:h;w=[];for(var t=d,q;null!==\nt;){q=t;var v=q.stateNode;5===q.tag&&null!==v&&(q=v,null!==u&&(v=Ob(t,u),null!=v&&w.push(ef(t,v,q))));if(z)break;t=t.return}0<w.length&&(h=new k(h,x,null,c,e),g.push({event:h,listeners:w}))}}if(0===(b&7)){a:{h=\"mouseover\"===a||\"pointerover\"===a;k=\"mouseout\"===a||\"pointerout\"===a;if(h&&0===(b&16)&&(x=c.relatedTarget||c.fromElement)&&(wc(x)||x[ff]))break a;if(k||h){h=e.window===e?e:(h=e.ownerDocument)?h.defaultView||h.parentWindow:window;if(k){if(x=c.relatedTarget||c.toElement,k=d,x=x?wc(x):null,null!==\nx&&(z=Zb(x),x!==z||5!==x.tag&&6!==x.tag))x=null}else k=null,x=d;if(k!==x){w=Bd;v=\"onMouseLeave\";u=\"onMouseEnter\";t=\"mouse\";if(\"pointerout\"===a||\"pointerover\"===a)w=Td,v=\"onPointerLeave\",u=\"onPointerEnter\",t=\"pointer\";z=null==k?h:ue(k);q=null==x?h:ue(x);h=new w(v,t+\"leave\",k,c,e);h.target=z;h.relatedTarget=q;v=null;wc(e)===d&&(w=new w(u,t+\"enter\",x,c,e),w.target=q,w.relatedTarget=z,v=w);z=v;if(k&&x)b:{w=k;u=x;t=0;for(q=w;q;q=gf(q))t++;q=0;for(v=u;v;v=gf(v))q++;for(;0<t-q;)w=gf(w),t--;for(;0<q-t;)u=\ngf(u),q--;for(;t--;){if(w===u||null!==u&&w===u.alternate)break b;w=gf(w);u=gf(u)}w=null}else w=null;null!==k&&hf(g,h,k,w,!1);null!==x&&null!==z&&hf(g,z,x,w,!0)}}}a:{h=d?ue(d):window;k=h.nodeName&&h.nodeName.toLowerCase();if(\"select\"===k||\"input\"===k&&\"file\"===h.type)var J=ve;else if(me(h))if(we)J=Fe;else{J=De;var K=Ce}else(k=h.nodeName)&&\"input\"===k.toLowerCase()&&(\"checkbox\"===h.type||\"radio\"===h.type)&&(J=Ee);if(J&&(J=J(a,d))){ne(g,J,c,e);break a}K&&K(a,h,d);\"focusout\"===a&&(K=h._wrapperState)&&\nK.controlled&&\"number\"===h.type&&bb(h,\"number\",h.value)}K=d?ue(d):window;switch(a){case \"focusin\":if(me(K)||\"true\"===K.contentEditable)Qe=K,Re=d,Se=null;break;case \"focusout\":Se=Re=Qe=null;break;case \"mousedown\":Te=!0;break;case \"contextmenu\":case \"mouseup\":case \"dragend\":Te=!1;Ue(g,c,e);break;case \"selectionchange\":if(Pe)break;case \"keydown\":case \"keyup\":Ue(g,c,e)}var Q;if(ae)b:{switch(a){case \"compositionstart\":var L=\"onCompositionStart\";break b;case \"compositionend\":L=\"onCompositionEnd\";break b;\ncase \"compositionupdate\":L=\"onCompositionUpdate\";break b}L=void 0}else ie?ge(a,c)&&(L=\"onCompositionEnd\"):\"keydown\"===a&&229===c.keyCode&&(L=\"onCompositionStart\");L&&(de&&\"ko\"!==c.locale&&(ie||\"onCompositionStart\"!==L?\"onCompositionEnd\"===L&&ie&&(Q=nd()):(kd=e,ld=\"value\"in kd?kd.value:kd.textContent,ie=!0)),K=oe(d,L),0<K.length&&(L=new Ld(L,a,null,c,e),g.push({event:L,listeners:K}),Q?L.data=Q:(Q=he(c),null!==Q&&(L.data=Q))));if(Q=ce?je(a,c):ke(a,c))d=oe(d,\"onBeforeInput\"),0<d.length&&(e=new Ld(\"onBeforeInput\",\n\"beforeinput\",null,c,e),g.push({event:e,listeners:d}),e.data=Q)}se(g,b)})}function ef(a,b,c){return{instance:a,listener:b,currentTarget:c}}function oe(a,b){for(var c=b+\"Capture\",d=[];null!==a;){var e=a,f=e.stateNode;5===e.tag&&null!==f&&(e=f,f=Ob(a,c),null!=f&&d.unshift(ef(a,f,e)),f=Ob(a,b),null!=f&&d.push(ef(a,f,e)));a=a.return}return d}function gf(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a?a:null}\nfunction hf(a,b,c,d,e){for(var f=b._reactName,g=[];null!==c&&c!==d;){var h=c,k=h.alternate,l=h.stateNode;if(null!==k&&k===d)break;5===h.tag&&null!==l&&(h=l,e?(k=Ob(c,f),null!=k&&g.unshift(ef(c,k,h))):e||(k=Ob(c,f),null!=k&&g.push(ef(c,k,h))));c=c.return}0!==g.length&&a.push({event:b,listeners:g})}function jf(){}var kf=null,lf=null;function mf(a,b){switch(a){case \"button\":case \"input\":case \"select\":case \"textarea\":return!!b.autoFocus}return!1}\nfunction nf(a,b){return\"textarea\"===a||\"option\"===a||\"noscript\"===a||\"string\"===typeof b.children||\"number\"===typeof b.children||\"object\"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}var of=\"function\"===typeof setTimeout?setTimeout:void 0,pf=\"function\"===typeof clearTimeout?clearTimeout:void 0;function qf(a){1===a.nodeType?a.textContent=\"\":9===a.nodeType&&(a=a.body,null!=a&&(a.textContent=\"\"))}\nfunction rf(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a}function sf(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(\"$\"===c||\"$!\"===c||\"$?\"===c){if(0===b)return a;b--}else\"/$\"===c&&b++}a=a.previousSibling}return null}var tf=0;function uf(a){return{$$typeof:Ga,toString:a,valueOf:a}}var vf=Math.random().toString(36).slice(2),wf=\"__reactFiber$\"+vf,xf=\"__reactProps$\"+vf,ff=\"__reactContainer$\"+vf,yf=\"__reactEvents$\"+vf;\nfunction wc(a){var b=a[wf];if(b)return b;for(var c=a.parentNode;c;){if(b=c[ff]||c[wf]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=sf(a);null!==a;){if(c=a[wf])return c;a=sf(a)}return b}a=c;c=a.parentNode}return null}function Cb(a){a=a[wf]||a[ff];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function ue(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(y(33));}function Db(a){return a[xf]||null}\nfunction $e(a){var b=a[yf];void 0===b&&(b=a[yf]=new Set);return b}var zf=[],Af=-1;function Bf(a){return{current:a}}function H(a){0>Af||(a.current=zf[Af],zf[Af]=null,Af--)}function I(a,b){Af++;zf[Af]=a.current;a.current=b}var Cf={},M=Bf(Cf),N=Bf(!1),Df=Cf;\nfunction Ef(a,b){var c=a.type.contextTypes;if(!c)return Cf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function Ff(a){a=a.childContextTypes;return null!==a&&void 0!==a}function Gf(){H(N);H(M)}function Hf(a,b,c){if(M.current!==Cf)throw Error(y(168));I(M,b);I(N,c)}\nfunction If(a,b,c){var d=a.stateNode;a=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(y(108,Ra(b)||\"Unknown\",e));return m({},c,d)}function Jf(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Cf;Df=M.current;I(M,a);I(N,N.current);return!0}function Kf(a,b,c){var d=a.stateNode;if(!d)throw Error(y(169));c?(a=If(a,b,Df),d.__reactInternalMemoizedMergedChildContext=a,H(N),H(M),I(M,a)):H(N);I(N,c)}\nvar Lf=null,Mf=null,Nf=r.unstable_runWithPriority,Of=r.unstable_scheduleCallback,Pf=r.unstable_cancelCallback,Qf=r.unstable_shouldYield,Rf=r.unstable_requestPaint,Sf=r.unstable_now,Tf=r.unstable_getCurrentPriorityLevel,Uf=r.unstable_ImmediatePriority,Vf=r.unstable_UserBlockingPriority,Wf=r.unstable_NormalPriority,Xf=r.unstable_LowPriority,Yf=r.unstable_IdlePriority,Zf={},$f=void 0!==Rf?Rf:function(){},ag=null,bg=null,cg=!1,dg=Sf(),O=1E4>dg?Sf:function(){return Sf()-dg};\nfunction eg(){switch(Tf()){case Uf:return 99;case Vf:return 98;case Wf:return 97;case Xf:return 96;case Yf:return 95;default:throw Error(y(332));}}function fg(a){switch(a){case 99:return Uf;case 98:return Vf;case 97:return Wf;case 96:return Xf;case 95:return Yf;default:throw Error(y(332));}}function gg(a,b){a=fg(a);return Nf(a,b)}function hg(a,b,c){a=fg(a);return Of(a,b,c)}function ig(){if(null!==bg){var a=bg;bg=null;Pf(a)}jg()}\nfunction jg(){if(!cg&&null!==ag){cg=!0;var a=0;try{var b=ag;gg(99,function(){for(;a<b.length;a++){var c=b[a];do c=c(!0);while(null!==c)}});ag=null}catch(c){throw null!==ag&&(ag=ag.slice(a+1)),Of(Uf,ig),c;}finally{cg=!1}}}var kg=ra.ReactCurrentBatchConfig;function lg(a,b){if(a&&a.defaultProps){b=m({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b}var mg=Bf(null),ng=null,og=null,pg=null;function qg(){pg=og=ng=null}\nfunction rg(a){var b=mg.current;H(mg);a.type._context._currentValue=b}function sg(a,b){for(;null!==a;){var c=a.alternate;if((a.childLanes&b)===b)if(null===c||(c.childLanes&b)===b)break;else c.childLanes|=b;else a.childLanes|=b,null!==c&&(c.childLanes|=b);a=a.return}}function tg(a,b){ng=a;pg=og=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(ug=!0),a.firstContext=null)}\nfunction vg(a,b){if(pg!==a&&!1!==b&&0!==b){if(\"number\"!==typeof b||1073741823===b)pg=a,b=1073741823;b={context:a,observedBits:b,next:null};if(null===og){if(null===ng)throw Error(y(308));og=b;ng.dependencies={lanes:0,firstContext:b,responders:null}}else og=og.next=b}return a._currentValue}var wg=!1;function xg(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null},effects:null}}\nfunction yg(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function zg(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}function Ag(a,b){a=a.updateQueue;if(null!==a){a=a.shared;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}}\nfunction Bg(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction Cg(a,b,c,d){var e=a.updateQueue;wg=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var n=a.alternate;if(null!==n){n=n.updateQueue;var A=n.lastBaseUpdate;A!==g&&(null===A?n.firstBaseUpdate=l:A.next=l,n.lastBaseUpdate=k)}}if(null!==f){A=e.baseState;g=0;n=l=k=null;do{h=f.lane;var p=f.eventTime;if((d&h)===h){null!==n&&(n=n.next={eventTime:p,lane:0,tag:f.tag,payload:f.payload,callback:f.callback,\nnext:null});a:{var C=a,x=f;h=b;p=c;switch(x.tag){case 1:C=x.payload;if(\"function\"===typeof C){A=C.call(p,A,h);break a}A=C;break a;case 3:C.flags=C.flags&-4097|64;case 0:C=x.payload;h=\"function\"===typeof C?C.call(p,A,h):C;if(null===h||void 0===h)break a;A=m({},A,h);break a;case 2:wg=!0}}null!==f.callback&&(a.flags|=32,h=e.effects,null===h?e.effects=[f]:h.push(f))}else p={eventTime:p,lane:h,tag:f.tag,payload:f.payload,callback:f.callback,next:null},null===n?(l=n=p,k=A):n=n.next=p,g|=h;f=f.next;if(null===\nf)if(h=e.shared.pending,null===h)break;else f=h.next,h.next=null,e.lastBaseUpdate=h,e.shared.pending=null}while(1);null===n&&(k=A);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=n;Dg|=g;a.lanes=g;a.memoizedState=A}}function Eg(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=c;if(\"function\"!==typeof e)throw Error(y(191,e));e.call(d)}}}var Fg=(new aa.Component).refs;\nfunction Gg(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:m({},b,c);a.memoizedState=c;0===a.lanes&&(a.updateQueue.baseState=c)}\nvar Kg={isMounted:function(a){return(a=a._reactInternals)?Zb(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternals;var d=Hg(),e=Ig(a),f=zg(d,e);f.payload=b;void 0!==c&&null!==c&&(f.callback=c);Ag(a,f);Jg(a,e,d)},enqueueReplaceState:function(a,b,c){a=a._reactInternals;var d=Hg(),e=Ig(a),f=zg(d,e);f.tag=1;f.payload=b;void 0!==c&&null!==c&&(f.callback=c);Ag(a,f);Jg(a,e,d)},enqueueForceUpdate:function(a,b){a=a._reactInternals;var c=Hg(),d=Ig(a),e=zg(c,d);e.tag=2;void 0!==b&&null!==b&&(e.callback=\nb);Ag(a,e);Jg(a,d,c)}};function Lg(a,b,c,d,e,f,g){a=a.stateNode;return\"function\"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!Je(c,d)||!Je(e,f):!0}\nfunction Mg(a,b,c){var d=!1,e=Cf;var f=b.contextType;\"object\"===typeof f&&null!==f?f=vg(f):(e=Ff(b)?Df:M.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Ef(a,e):Cf);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=Kg;a.stateNode=b;b._reactInternals=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}\nfunction Ng(a,b,c,d){a=b.state;\"function\"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);\"function\"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&Kg.enqueueReplaceState(b,b.state,null)}\nfunction Og(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=Fg;xg(a);var f=b.contextType;\"object\"===typeof f&&null!==f?e.context=vg(f):(f=Ff(b)?Df:M.current,e.context=Ef(a,f));Cg(a,c,e,d);e.state=a.memoizedState;f=b.getDerivedStateFromProps;\"function\"===typeof f&&(Gg(a,b,f,c),e.state=a.memoizedState);\"function\"===typeof b.getDerivedStateFromProps||\"function\"===typeof e.getSnapshotBeforeUpdate||\"function\"!==typeof e.UNSAFE_componentWillMount&&\"function\"!==typeof e.componentWillMount||\n(b=e.state,\"function\"===typeof e.componentWillMount&&e.componentWillMount(),\"function\"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Kg.enqueueReplaceState(e,e.state,null),Cg(a,c,e,d),e.state=a.memoizedState);\"function\"===typeof e.componentDidMount&&(a.flags|=4)}var Pg=Array.isArray;\nfunction Qg(a,b,c){a=c.ref;if(null!==a&&\"function\"!==typeof a&&\"object\"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(y(309));var d=c.stateNode}if(!d)throw Error(y(147,a));var e=\"\"+a;if(null!==b&&null!==b.ref&&\"function\"===typeof b.ref&&b.ref._stringRef===e)return b.ref;b=function(a){var b=d.refs;b===Fg&&(b=d.refs={});null===a?delete b[e]:b[e]=a};b._stringRef=e;return b}if(\"string\"!==typeof a)throw Error(y(284));if(!c._owner)throw Error(y(290,a));}return a}\nfunction Rg(a,b){if(\"textarea\"!==a.type)throw Error(y(31,\"[object Object]\"===Object.prototype.toString.call(b)?\"object with keys {\"+Object.keys(b).join(\", \")+\"}\":b));}\nfunction Sg(a){function b(b,c){if(a){var d=b.lastEffect;null!==d?(d.nextEffect=c,b.lastEffect=c):b.firstEffect=b.lastEffect=c;c.nextEffect=null;c.flags=8}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=Tg(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.flags=2,\nc):d;b.flags=2;return c}function g(b){a&&null===b.alternate&&(b.flags=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=Ug(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){if(null!==b&&b.elementType===c.type)return d=e(b,c.props),d.ref=Qg(a,b,c),d.return=a,d;d=Vg(c.type,c.key,c.props,null,a.mode,d);d.ref=Qg(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=\nWg(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function n(a,b,c,d,f){if(null===b||7!==b.tag)return b=Xg(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function A(a,b,c){if(\"string\"===typeof b||\"number\"===typeof b)return b=Ug(\"\"+b,a.mode,c),b.return=a,b;if(\"object\"===typeof b&&null!==b){switch(b.$$typeof){case sa:return c=Vg(b.type,b.key,b.props,null,a.mode,c),c.ref=Qg(a,null,b),c.return=a,c;case ta:return b=Wg(b,a.mode,c),b.return=a,b}if(Pg(b)||La(b))return b=Xg(b,\na.mode,c,null),b.return=a,b;Rg(a,b)}return null}function p(a,b,c,d){var e=null!==b?b.key:null;if(\"string\"===typeof c||\"number\"===typeof c)return null!==e?null:h(a,b,\"\"+c,d);if(\"object\"===typeof c&&null!==c){switch(c.$$typeof){case sa:return c.key===e?c.type===ua?n(a,b,c.props.children,d,e):k(a,b,c,d):null;case ta:return c.key===e?l(a,b,c,d):null}if(Pg(c)||La(c))return null!==e?null:n(a,b,c,d,null);Rg(a,c)}return null}function C(a,b,c,d,e){if(\"string\"===typeof d||\"number\"===typeof d)return a=a.get(c)||\nnull,h(b,a,\"\"+d,e);if(\"object\"===typeof d&&null!==d){switch(d.$$typeof){case sa:return a=a.get(null===d.key?c:d.key)||null,d.type===ua?n(b,a,d.props.children,e,d.key):k(b,a,d,e);case ta:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e)}if(Pg(d)||La(d))return a=a.get(c)||null,n(b,a,d,e,null);Rg(b,d)}return null}function x(e,g,h,k){for(var l=null,t=null,u=g,z=g=0,q=null;null!==u&&z<h.length;z++){u.index>z?(q=u,u=null):q=u.sibling;var n=p(e,u,h[z],k);if(null===n){null===u&&(u=q);break}a&&u&&null===\nn.alternate&&b(e,u);g=f(n,g,z);null===t?l=n:t.sibling=n;t=n;u=q}if(z===h.length)return c(e,u),l;if(null===u){for(;z<h.length;z++)u=A(e,h[z],k),null!==u&&(g=f(u,g,z),null===t?l=u:t.sibling=u,t=u);return l}for(u=d(e,u);z<h.length;z++)q=C(u,e,z,h[z],k),null!==q&&(a&&null!==q.alternate&&u.delete(null===q.key?z:q.key),g=f(q,g,z),null===t?l=q:t.sibling=q,t=q);a&&u.forEach(function(a){return b(e,a)});return l}function w(e,g,h,k){var l=La(h);if(\"function\"!==typeof l)throw Error(y(150));h=l.call(h);if(null==\nh)throw Error(y(151));for(var t=l=null,u=g,z=g=0,q=null,n=h.next();null!==u&&!n.done;z++,n=h.next()){u.index>z?(q=u,u=null):q=u.sibling;var w=p(e,u,n.value,k);if(null===w){null===u&&(u=q);break}a&&u&&null===w.alternate&&b(e,u);g=f(w,g,z);null===t?l=w:t.sibling=w;t=w;u=q}if(n.done)return c(e,u),l;if(null===u){for(;!n.done;z++,n=h.next())n=A(e,n.value,k),null!==n&&(g=f(n,g,z),null===t?l=n:t.sibling=n,t=n);return l}for(u=d(e,u);!n.done;z++,n=h.next())n=C(u,e,z,n.value,k),null!==n&&(a&&null!==n.alternate&&\nu.delete(null===n.key?z:n.key),g=f(n,g,z),null===t?l=n:t.sibling=n,t=n);a&&u.forEach(function(a){return b(e,a)});return l}return function(a,d,f,h){var k=\"object\"===typeof f&&null!==f&&f.type===ua&&null===f.key;k&&(f=f.props.children);var l=\"object\"===typeof f&&null!==f;if(l)switch(f.$$typeof){case sa:a:{l=f.key;for(k=d;null!==k;){if(k.key===l){switch(k.tag){case 7:if(f.type===ua){c(a,k.sibling);d=e(k,f.props.children);d.return=a;a=d;break a}break;default:if(k.elementType===f.type){c(a,k.sibling);\nd=e(k,f.props);d.ref=Qg(a,k,f);d.return=a;a=d;break a}}c(a,k);break}else b(a,k);k=k.sibling}f.type===ua?(d=Xg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Vg(f.type,f.key,f.props,null,a.mode,h),h.ref=Qg(a,d,f),h.return=a,a=h)}return g(a);case ta:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=\nWg(f,a.mode,h);d.return=a;a=d}return g(a)}if(\"string\"===typeof f||\"number\"===typeof f)return f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=Ug(f,a.mode,h),d.return=a,a=d),g(a);if(Pg(f))return x(a,d,f,h);if(La(f))return w(a,d,f,h);l&&Rg(a,f);if(\"undefined\"===typeof f&&!k)switch(a.tag){case 1:case 22:case 0:case 11:case 15:throw Error(y(152,Ra(a.type)||\"Component\"));}return c(a,d)}}var Yg=Sg(!0),Zg=Sg(!1),$g={},ah=Bf($g),bh=Bf($g),ch=Bf($g);\nfunction dh(a){if(a===$g)throw Error(y(174));return a}function eh(a,b){I(ch,b);I(bh,a);I(ah,$g);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:mb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=mb(b,a)}H(ah);I(ah,b)}function fh(){H(ah);H(bh);H(ch)}function gh(a){dh(ch.current);var b=dh(ah.current);var c=mb(b,a.type);b!==c&&(I(bh,a),I(ah,c))}function hh(a){bh.current===a&&(H(ah),H(bh))}var P=Bf(0);\nfunction ih(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var jh=null,kh=null,lh=!1;\nfunction mh(a,b){var c=nh(5,null,null,0);c.elementType=\"DELETED\";c.type=\"DELETED\";c.stateNode=b;c.return=a;c.flags=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c}function oh(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=\"\"===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}}\nfunction ph(a){if(lh){var b=kh;if(b){var c=b;if(!oh(a,b)){b=rf(c.nextSibling);if(!b||!oh(a,b)){a.flags=a.flags&-1025|2;lh=!1;jh=a;return}mh(jh,c)}jh=a;kh=rf(b.firstChild)}else a.flags=a.flags&-1025|2,lh=!1,jh=a}}function qh(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;jh=a}\nfunction rh(a){if(a!==jh)return!1;if(!lh)return qh(a),lh=!0,!1;var b=a.type;if(5!==a.tag||\"head\"!==b&&\"body\"!==b&&!nf(b,a.memoizedProps))for(b=kh;b;)mh(a,b),b=rf(b.nextSibling);qh(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(y(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if(\"/$\"===c){if(0===b){kh=rf(a.nextSibling);break a}b--}else\"$\"!==c&&\"$!\"!==c&&\"$?\"!==c||b++}a=a.nextSibling}kh=null}}else kh=jh?rf(a.stateNode.nextSibling):null;return!0}\nfunction sh(){kh=jh=null;lh=!1}var th=[];function uh(){for(var a=0;a<th.length;a++)th[a]._workInProgressVersionPrimary=null;th.length=0}var vh=ra.ReactCurrentDispatcher,wh=ra.ReactCurrentBatchConfig,xh=0,R=null,S=null,T=null,yh=!1,zh=!1;function Ah(){throw Error(y(321));}function Bh(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!He(a[c],b[c]))return!1;return!0}\nfunction Ch(a,b,c,d,e,f){xh=f;R=b;b.memoizedState=null;b.updateQueue=null;b.lanes=0;vh.current=null===a||null===a.memoizedState?Dh:Eh;a=c(d,e);if(zh){f=0;do{zh=!1;if(!(25>f))throw Error(y(301));f+=1;T=S=null;b.updateQueue=null;vh.current=Fh;a=c(d,e)}while(zh)}vh.current=Gh;b=null!==S&&null!==S.next;xh=0;T=S=R=null;yh=!1;if(b)throw Error(y(300));return a}function Hh(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===T?R.memoizedState=T=a:T=T.next=a;return T}\nfunction Ih(){if(null===S){var a=R.alternate;a=null!==a?a.memoizedState:null}else a=S.next;var b=null===T?R.memoizedState:T.next;if(null!==b)T=b,S=a;else{if(null===a)throw Error(y(310));S=a;a={memoizedState:S.memoizedState,baseState:S.baseState,baseQueue:S.baseQueue,queue:S.queue,next:null};null===T?R.memoizedState=T=a:T=T.next=a}return T}function Jh(a,b){return\"function\"===typeof b?b(a):b}\nfunction Kh(a){var b=Ih(),c=b.queue;if(null===c)throw Error(y(311));c.lastRenderedReducer=a;var d=S,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){e=e.next;d=d.baseState;var h=g=f=null,k=e;do{var l=k.lane;if((xh&l)===l)null!==h&&(h=h.next={lane:0,action:k.action,eagerReducer:k.eagerReducer,eagerState:k.eagerState,next:null}),d=k.eagerReducer===a?k.eagerState:a(d,k.action);else{var n={lane:l,action:k.action,eagerReducer:k.eagerReducer,\neagerState:k.eagerState,next:null};null===h?(g=h=n,f=d):h=h.next=n;R.lanes|=l;Dg|=l}k=k.next}while(null!==k&&k!==e);null===h?f=d:h.next=g;He(d,b.memoizedState)||(ug=!0);b.memoizedState=d;b.baseState=f;b.baseQueue=h;c.lastRenderedState=d}return[b.memoizedState,c.dispatch]}\nfunction Lh(a){var b=Ih(),c=b.queue;if(null===c)throw Error(y(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);He(f,b.memoizedState)||(ug=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}\nfunction Mh(a,b,c){var d=b._getVersion;d=d(b._source);var e=b._workInProgressVersionPrimary;if(null!==e)a=e===d;else if(a=a.mutableReadLanes,a=(xh&a)===a)b._workInProgressVersionPrimary=d,th.push(b);if(a)return c(b._source);th.push(b);throw Error(y(350));}\nfunction Nh(a,b,c,d){var e=U;if(null===e)throw Error(y(349));var f=b._getVersion,g=f(b._source),h=vh.current,k=h.useState(function(){return Mh(e,b,c)}),l=k[1],n=k[0];k=T;var A=a.memoizedState,p=A.refs,C=p.getSnapshot,x=A.source;A=A.subscribe;var w=R;a.memoizedState={refs:p,source:b,subscribe:d};h.useEffect(function(){p.getSnapshot=c;p.setSnapshot=l;var a=f(b._source);if(!He(g,a)){a=c(b._source);He(n,a)||(l(a),a=Ig(w),e.mutableReadLanes|=a&e.pendingLanes);a=e.mutableReadLanes;e.entangledLanes|=a;for(var d=\ne.entanglements,h=a;0<h;){var k=31-Vc(h),v=1<<k;d[k]|=a;h&=~v}}},[c,b,d]);h.useEffect(function(){return d(b._source,function(){var a=p.getSnapshot,c=p.setSnapshot;try{c(a(b._source));var d=Ig(w);e.mutableReadLanes|=d&e.pendingLanes}catch(q){c(function(){throw q;})}})},[b,d]);He(C,c)&&He(x,b)&&He(A,d)||(a={pending:null,dispatch:null,lastRenderedReducer:Jh,lastRenderedState:n},a.dispatch=l=Oh.bind(null,R,a),k.queue=a,k.baseQueue=null,n=Mh(e,b,c),k.memoizedState=k.baseState=n);return n}\nfunction Ph(a,b,c){var d=Ih();return Nh(d,a,b,c)}function Qh(a){var b=Hh();\"function\"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={pending:null,dispatch:null,lastRenderedReducer:Jh,lastRenderedState:a};a=a.dispatch=Oh.bind(null,R,a);return[b.memoizedState,a]}\nfunction Rh(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=R.updateQueue;null===b?(b={lastEffect:null},R.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function Sh(a){var b=Hh();a={current:a};return b.memoizedState=a}function Th(){return Ih().memoizedState}function Uh(a,b,c,d){var e=Hh();R.flags|=a;e.memoizedState=Rh(1|b,c,void 0,void 0===d?null:d)}\nfunction Vh(a,b,c,d){var e=Ih();d=void 0===d?null:d;var f=void 0;if(null!==S){var g=S.memoizedState;f=g.destroy;if(null!==d&&Bh(d,g.deps)){Rh(b,c,f,d);return}}R.flags|=a;e.memoizedState=Rh(1|b,c,f,d)}function Wh(a,b){return Uh(516,4,a,b)}function Xh(a,b){return Vh(516,4,a,b)}function Yh(a,b){return Vh(4,2,a,b)}function Zh(a,b){if(\"function\"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}\nfunction $h(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Vh(4,2,Zh.bind(null,b,a),c)}function ai(){}function bi(a,b){var c=Ih();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Bh(b,d[1]))return d[0];c.memoizedState=[a,b];return a}function ci(a,b){var c=Ih();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Bh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}\nfunction di(a,b){var c=eg();gg(98>c?98:c,function(){a(!0)});gg(97<c?97:c,function(){var c=wh.transition;wh.transition=1;try{a(!1),b()}finally{wh.transition=c}})}\nfunction Oh(a,b,c){var d=Hg(),e=Ig(a),f={lane:e,action:c,eagerReducer:null,eagerState:null,next:null},g=b.pending;null===g?f.next=f:(f.next=g.next,g.next=f);b.pending=f;g=a.alternate;if(a===R||null!==g&&g===R)zh=yh=!0;else{if(0===a.lanes&&(null===g||0===g.lanes)&&(g=b.lastRenderedReducer,null!==g))try{var h=b.lastRenderedState,k=g(h,c);f.eagerReducer=g;f.eagerState=k;if(He(k,h))return}catch(l){}finally{}Jg(a,e,d)}}\nvar Gh={readContext:vg,useCallback:Ah,useContext:Ah,useEffect:Ah,useImperativeHandle:Ah,useLayoutEffect:Ah,useMemo:Ah,useReducer:Ah,useRef:Ah,useState:Ah,useDebugValue:Ah,useDeferredValue:Ah,useTransition:Ah,useMutableSource:Ah,useOpaqueIdentifier:Ah,unstable_isNewReconciler:!1},Dh={readContext:vg,useCallback:function(a,b){Hh().memoizedState=[a,void 0===b?null:b];return a},useContext:vg,useEffect:Wh,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Uh(4,2,Zh.bind(null,\nb,a),c)},useLayoutEffect:function(a,b){return Uh(4,2,a,b)},useMemo:function(a,b){var c=Hh();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Hh();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a=d.queue={pending:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};a=a.dispatch=Oh.bind(null,R,a);return[d.memoizedState,a]},useRef:Sh,useState:Qh,useDebugValue:ai,useDeferredValue:function(a){var b=Qh(a),c=b[0],d=b[1];Wh(function(){var b=wh.transition;\nwh.transition=1;try{d(a)}finally{wh.transition=b}},[a]);return c},useTransition:function(){var a=Qh(!1),b=a[0];a=di.bind(null,a[1]);Sh(a);return[a,b]},useMutableSource:function(a,b,c){var d=Hh();d.memoizedState={refs:{getSnapshot:b,setSnapshot:null},source:a,subscribe:c};return Nh(d,a,b,c)},useOpaqueIdentifier:function(){if(lh){var a=!1,b=uf(function(){a||(a=!0,c(\"r:\"+(tf++).toString(36)));throw Error(y(355));}),c=Qh(b)[1];0===(R.mode&2)&&(R.flags|=516,Rh(5,function(){c(\"r:\"+(tf++).toString(36))},\nvoid 0,null));return b}b=\"r:\"+(tf++).toString(36);Qh(b);return b},unstable_isNewReconciler:!1},Eh={readContext:vg,useCallback:bi,useContext:vg,useEffect:Xh,useImperativeHandle:$h,useLayoutEffect:Yh,useMemo:ci,useReducer:Kh,useRef:Th,useState:function(){return Kh(Jh)},useDebugValue:ai,useDeferredValue:function(a){var b=Kh(Jh),c=b[0],d=b[1];Xh(function(){var b=wh.transition;wh.transition=1;try{d(a)}finally{wh.transition=b}},[a]);return c},useTransition:function(){var a=Kh(Jh)[0];return[Th().current,\na]},useMutableSource:Ph,useOpaqueIdentifier:function(){return Kh(Jh)[0]},unstable_isNewReconciler:!1},Fh={readContext:vg,useCallback:bi,useContext:vg,useEffect:Xh,useImperativeHandle:$h,useLayoutEffect:Yh,useMemo:ci,useReducer:Lh,useRef:Th,useState:function(){return Lh(Jh)},useDebugValue:ai,useDeferredValue:function(a){var b=Lh(Jh),c=b[0],d=b[1];Xh(function(){var b=wh.transition;wh.transition=1;try{d(a)}finally{wh.transition=b}},[a]);return c},useTransition:function(){var a=Lh(Jh)[0];return[Th().current,\na]},useMutableSource:Ph,useOpaqueIdentifier:function(){return Lh(Jh)[0]},unstable_isNewReconciler:!1},ei=ra.ReactCurrentOwner,ug=!1;function fi(a,b,c,d){b.child=null===a?Zg(b,null,c,d):Yg(b,a.child,c,d)}function gi(a,b,c,d,e){c=c.render;var f=b.ref;tg(b,e);d=Ch(a,b,c,d,f,e);if(null!==a&&!ug)return b.updateQueue=a.updateQueue,b.flags&=-517,a.lanes&=~e,hi(a,b,e);b.flags|=1;fi(a,b,d,e);return b.child}\nfunction ii(a,b,c,d,e,f){if(null===a){var g=c.type;if(\"function\"===typeof g&&!ji(g)&&void 0===g.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=g,ki(a,b,g,d,e,f);a=Vg(c.type,null,d,b,b.mode,f);a.ref=b.ref;a.return=b;return b.child=a}g=a.child;if(0===(e&f)&&(e=g.memoizedProps,c=c.compare,c=null!==c?c:Je,c(e,d)&&a.ref===b.ref))return hi(a,b,f);b.flags|=1;a=Tg(g,d);a.ref=b.ref;a.return=b;return b.child=a}\nfunction ki(a,b,c,d,e,f){if(null!==a&&Je(a.memoizedProps,d)&&a.ref===b.ref)if(ug=!1,0!==(f&e))0!==(a.flags&16384)&&(ug=!0);else return b.lanes=a.lanes,hi(a,b,f);return li(a,b,c,d,f)}\nfunction mi(a,b,c){var d=b.pendingProps,e=d.children,f=null!==a?a.memoizedState:null;if(\"hidden\"===d.mode||\"unstable-defer-without-hiding\"===d.mode)if(0===(b.mode&4))b.memoizedState={baseLanes:0},ni(b,c);else if(0!==(c&1073741824))b.memoizedState={baseLanes:0},ni(b,null!==f?f.baseLanes:c);else return a=null!==f?f.baseLanes|c:c,b.lanes=b.childLanes=1073741824,b.memoizedState={baseLanes:a},ni(b,a),null;else null!==f?(d=f.baseLanes|c,b.memoizedState=null):d=c,ni(b,d);fi(a,b,e,c);return b.child}\nfunction oi(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.flags|=128}function li(a,b,c,d,e){var f=Ff(c)?Df:M.current;f=Ef(b,f);tg(b,e);c=Ch(a,b,c,d,f,e);if(null!==a&&!ug)return b.updateQueue=a.updateQueue,b.flags&=-517,a.lanes&=~e,hi(a,b,e);b.flags|=1;fi(a,b,c,e);return b.child}\nfunction pi(a,b,c,d,e){if(Ff(c)){var f=!0;Jf(b)}else f=!1;tg(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),Mg(b,c,d),Og(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;\"object\"===typeof l&&null!==l?l=vg(l):(l=Ff(c)?Df:M.current,l=Ef(b,l));var n=c.getDerivedStateFromProps,A=\"function\"===typeof n||\"function\"===typeof g.getSnapshotBeforeUpdate;A||\"function\"!==typeof g.UNSAFE_componentWillReceiveProps&&\n\"function\"!==typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Ng(b,g,d,l);wg=!1;var p=b.memoizedState;g.state=p;Cg(b,d,g,e);k=b.memoizedState;h!==d||p!==k||N.current||wg?(\"function\"===typeof n&&(Gg(b,c,n,d),k=b.memoizedState),(h=wg||Lg(b,c,h,d,p,k,l))?(A||\"function\"!==typeof g.UNSAFE_componentWillMount&&\"function\"!==typeof g.componentWillMount||(\"function\"===typeof g.componentWillMount&&g.componentWillMount(),\"function\"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),\"function\"===\ntypeof g.componentDidMount&&(b.flags|=4)):(\"function\"===typeof g.componentDidMount&&(b.flags|=4),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):(\"function\"===typeof g.componentDidMount&&(b.flags|=4),d=!1)}else{g=b.stateNode;yg(a,b);h=b.memoizedProps;l=b.type===b.elementType?h:lg(b.type,h);g.props=l;A=b.pendingProps;p=g.context;k=c.contextType;\"object\"===typeof k&&null!==k?k=vg(k):(k=Ff(c)?Df:M.current,k=Ef(b,k));var C=c.getDerivedStateFromProps;(n=\"function\"===typeof C||\n\"function\"===typeof g.getSnapshotBeforeUpdate)||\"function\"!==typeof g.UNSAFE_componentWillReceiveProps&&\"function\"!==typeof g.componentWillReceiveProps||(h!==A||p!==k)&&Ng(b,g,d,k);wg=!1;p=b.memoizedState;g.state=p;Cg(b,d,g,e);var x=b.memoizedState;h!==A||p!==x||N.current||wg?(\"function\"===typeof C&&(Gg(b,c,C,d),x=b.memoizedState),(l=wg||Lg(b,c,l,d,p,x,k))?(n||\"function\"!==typeof g.UNSAFE_componentWillUpdate&&\"function\"!==typeof g.componentWillUpdate||(\"function\"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,\nx,k),\"function\"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,x,k)),\"function\"===typeof g.componentDidUpdate&&(b.flags|=4),\"function\"===typeof g.getSnapshotBeforeUpdate&&(b.flags|=256)):(\"function\"!==typeof g.componentDidUpdate||h===a.memoizedProps&&p===a.memoizedState||(b.flags|=4),\"function\"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&p===a.memoizedState||(b.flags|=256),b.memoizedProps=d,b.memoizedState=x),g.props=d,g.state=x,g.context=k,d=l):(\"function\"!==typeof g.componentDidUpdate||\nh===a.memoizedProps&&p===a.memoizedState||(b.flags|=4),\"function\"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&p===a.memoizedState||(b.flags|=256),d=!1)}return qi(a,b,c,d,f,e)}\nfunction qi(a,b,c,d,e,f){oi(a,b);var g=0!==(b.flags&64);if(!d&&!g)return e&&Kf(b,c,!1),hi(a,b,f);d=b.stateNode;ei.current=b;var h=g&&\"function\"!==typeof c.getDerivedStateFromError?null:d.render();b.flags|=1;null!==a&&g?(b.child=Yg(b,a.child,null,f),b.child=Yg(b,null,h,f)):fi(a,b,h,f);b.memoizedState=d.state;e&&Kf(b,c,!0);return b.child}function ri(a){var b=a.stateNode;b.pendingContext?Hf(a,b.pendingContext,b.pendingContext!==b.context):b.context&&Hf(a,b.context,!1);eh(a,b.containerInfo)}\nvar si={dehydrated:null,retryLane:0};\nfunction ti(a,b,c){var d=b.pendingProps,e=P.current,f=!1,g;(g=0!==(b.flags&64))||(g=null!==a&&null===a.memoizedState?!1:0!==(e&2));g?(f=!0,b.flags&=-65):null!==a&&null===a.memoizedState||void 0===d.fallback||!0===d.unstable_avoidThisFallback||(e|=1);I(P,e&1);if(null===a){void 0!==d.fallback&&ph(b);a=d.children;e=d.fallback;if(f)return a=ui(b,a,e,c),b.child.memoizedState={baseLanes:c},b.memoizedState=si,a;if(\"number\"===typeof d.unstable_expectedLoadTime)return a=ui(b,a,e,c),b.child.memoizedState={baseLanes:c},\nb.memoizedState=si,b.lanes=33554432,a;c=vi({mode:\"visible\",children:a},b.mode,c,null);c.return=b;return b.child=c}if(null!==a.memoizedState){if(f)return d=wi(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState=null===e?{baseLanes:c}:{baseLanes:e.baseLanes|c},f.childLanes=a.childLanes&~c,b.memoizedState=si,d;c=xi(a,b,d.children,c);b.memoizedState=null;return c}if(f)return d=wi(a,b,d.children,d.fallback,c),f=b.child,e=a.child.memoizedState,f.memoizedState=null===e?{baseLanes:c}:\n{baseLanes:e.baseLanes|c},f.childLanes=a.childLanes&~c,b.memoizedState=si,d;c=xi(a,b,d.children,c);b.memoizedState=null;return c}function ui(a,b,c,d){var e=a.mode,f=a.child;b={mode:\"hidden\",children:b};0===(e&2)&&null!==f?(f.childLanes=0,f.pendingProps=b):f=vi(b,e,0,null);c=Xg(c,e,d,null);f.return=a;c.return=a;f.sibling=c;a.child=f;return c}\nfunction xi(a,b,c,d){var e=a.child;a=e.sibling;c=Tg(e,{mode:\"visible\",children:c});0===(b.mode&2)&&(c.lanes=d);c.return=b;c.sibling=null;null!==a&&(a.nextEffect=null,a.flags=8,b.firstEffect=b.lastEffect=a);return b.child=c}\nfunction wi(a,b,c,d,e){var f=b.mode,g=a.child;a=g.sibling;var h={mode:\"hidden\",children:c};0===(f&2)&&b.child!==g?(c=b.child,c.childLanes=0,c.pendingProps=h,g=c.lastEffect,null!==g?(b.firstEffect=c.firstEffect,b.lastEffect=g,g.nextEffect=null):b.firstEffect=b.lastEffect=null):c=Tg(g,h);null!==a?d=Tg(a,d):(d=Xg(d,f,e,null),d.flags|=2);d.return=b;c.return=b;c.sibling=d;b.child=c;return d}function yi(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);sg(a.return,b)}\nfunction zi(a,b,c,d,e,f){var g=a.memoizedState;null===g?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailMode:e,lastEffect:f}:(g.isBackwards=b,g.rendering=null,g.renderingStartTime=0,g.last=d,g.tail=c,g.tailMode=e,g.lastEffect=f)}\nfunction Ai(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;fi(a,b,d.children,c);d=P.current;if(0!==(d&2))d=d&1|2,b.flags|=64;else{if(null!==a&&0!==(a.flags&64))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&yi(a,c);else if(19===a.tag)yi(a,c);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}I(P,d);if(0===(b.mode&2))b.memoizedState=\nnull;else switch(e){case \"forwards\":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===ih(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);zi(b,!1,e,c,f,b.lastEffect);break;case \"backwards\":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===ih(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}zi(b,!0,c,null,f,b.lastEffect);break;case \"together\":zi(b,!1,null,null,void 0,b.lastEffect);break;default:b.memoizedState=null}return b.child}\nfunction hi(a,b,c){null!==a&&(b.dependencies=a.dependencies);Dg|=b.lanes;if(0!==(c&b.childLanes)){if(null!==a&&b.child!==a.child)throw Error(y(153));if(null!==b.child){a=b.child;c=Tg(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=Tg(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}return null}var Bi,Ci,Di,Ei;\nBi=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};Ci=function(){};\nDi=function(a,b,c,d){var e=a.memoizedProps;if(e!==d){a=b.stateNode;dh(ah.current);var f=null;switch(c){case \"input\":e=Ya(a,e);d=Ya(a,d);f=[];break;case \"option\":e=eb(a,e);d=eb(a,d);f=[];break;case \"select\":e=m({},e,{value:void 0});d=m({},d,{value:void 0});f=[];break;case \"textarea\":e=gb(a,e);d=gb(a,d);f=[];break;default:\"function\"!==typeof e.onClick&&\"function\"===typeof d.onClick&&(a.onclick=jf)}vb(c,d);var g;c=null;for(l in e)if(!d.hasOwnProperty(l)&&e.hasOwnProperty(l)&&null!=e[l])if(\"style\"===\nl){var h=e[l];for(g in h)h.hasOwnProperty(g)&&(c||(c={}),c[g]=\"\")}else\"dangerouslySetInnerHTML\"!==l&&\"children\"!==l&&\"suppressContentEditableWarning\"!==l&&\"suppressHydrationWarning\"!==l&&\"autoFocus\"!==l&&(ca.hasOwnProperty(l)?f||(f=[]):(f=f||[]).push(l,null));for(l in d){var k=d[l];h=null!=e?e[l]:void 0;if(d.hasOwnProperty(l)&&k!==h&&(null!=k||null!=h))if(\"style\"===l)if(h){for(g in h)!h.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(c||(c={}),c[g]=\"\");for(g in k)k.hasOwnProperty(g)&&h[g]!==k[g]&&(c||\n(c={}),c[g]=k[g])}else c||(f||(f=[]),f.push(l,c)),c=k;else\"dangerouslySetInnerHTML\"===l?(k=k?k.__html:void 0,h=h?h.__html:void 0,null!=k&&h!==k&&(f=f||[]).push(l,k)):\"children\"===l?\"string\"!==typeof k&&\"number\"!==typeof k||(f=f||[]).push(l,\"\"+k):\"suppressContentEditableWarning\"!==l&&\"suppressHydrationWarning\"!==l&&(ca.hasOwnProperty(l)?(null!=k&&\"onScroll\"===l&&G(\"scroll\",a),f||h===k||(f=[])):\"object\"===typeof k&&null!==k&&k.$$typeof===Ga?k.toString():(f=f||[]).push(l,k))}c&&(f=f||[]).push(\"style\",\nc);var l=f;if(b.updateQueue=l)b.flags|=4}};Ei=function(a,b,c,d){c!==d&&(b.flags|=4)};function Fi(a,b){if(!lh)switch(a.tailMode){case \"hidden\":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case \"collapsed\":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}\nfunction Gi(a,b,c){var d=b.pendingProps;switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return null;case 1:return Ff(b.type)&&Gf(),null;case 3:fh();H(N);H(M);uh();d=b.stateNode;d.pendingContext&&(d.context=d.pendingContext,d.pendingContext=null);if(null===a||null===a.child)rh(b)?b.flags|=4:d.hydrate||(b.flags|=256);Ci(b);return null;case 5:hh(b);var e=dh(ch.current);c=b.type;if(null!==a&&null!=b.stateNode)Di(a,b,c,d,e),a.ref!==b.ref&&(b.flags|=128);else{if(!d){if(null===\nb.stateNode)throw Error(y(166));return null}a=dh(ah.current);if(rh(b)){d=b.stateNode;c=b.type;var f=b.memoizedProps;d[wf]=b;d[xf]=f;switch(c){case \"dialog\":G(\"cancel\",d);G(\"close\",d);break;case \"iframe\":case \"object\":case \"embed\":G(\"load\",d);break;case \"video\":case \"audio\":for(a=0;a<Xe.length;a++)G(Xe[a],d);break;case \"source\":G(\"error\",d);break;case \"img\":case \"image\":case \"link\":G(\"error\",d);G(\"load\",d);break;case \"details\":G(\"toggle\",d);break;case \"input\":Za(d,f);G(\"invalid\",d);break;case \"select\":d._wrapperState=\n{wasMultiple:!!f.multiple};G(\"invalid\",d);break;case \"textarea\":hb(d,f),G(\"invalid\",d)}vb(c,f);a=null;for(var g in f)f.hasOwnProperty(g)&&(e=f[g],\"children\"===g?\"string\"===typeof e?d.textContent!==e&&(a=[\"children\",e]):\"number\"===typeof e&&d.textContent!==\"\"+e&&(a=[\"children\",\"\"+e]):ca.hasOwnProperty(g)&&null!=e&&\"onScroll\"===g&&G(\"scroll\",d));switch(c){case \"input\":Va(d);cb(d,f,!0);break;case \"textarea\":Va(d);jb(d);break;case \"select\":case \"option\":break;default:\"function\"===typeof f.onClick&&(d.onclick=\njf)}d=a;b.updateQueue=d;null!==d&&(b.flags|=4)}else{g=9===e.nodeType?e:e.ownerDocument;a===kb.html&&(a=lb(c));a===kb.html?\"script\"===c?(a=g.createElement(\"div\"),a.innerHTML=\"<script>\\x3c/script>\",a=a.removeChild(a.firstChild)):\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[wf]=b;a[xf]=d;Bi(a,b,!1,!1);b.stateNode=a;g=wb(c,d);switch(c){case \"dialog\":G(\"cancel\",a);G(\"close\",a);\ne=d;break;case \"iframe\":case \"object\":case \"embed\":G(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;e<Xe.length;e++)G(Xe[e],a);e=d;break;case \"source\":G(\"error\",a);e=d;break;case \"img\":case \"image\":case \"link\":G(\"error\",a);G(\"load\",a);e=d;break;case \"details\":G(\"toggle\",a);e=d;break;case \"input\":Za(a,d);e=Ya(a,d);G(\"invalid\",a);break;case \"option\":e=eb(a,d);break;case \"select\":a._wrapperState={wasMultiple:!!d.multiple};e=m({},d,{value:void 0});G(\"invalid\",a);break;case \"textarea\":hb(a,d);e=\ngb(a,d);G(\"invalid\",a);break;default:e=d}vb(c,e);var h=e;for(f in h)if(h.hasOwnProperty(f)){var k=h[f];\"style\"===f?tb(a,k):\"dangerouslySetInnerHTML\"===f?(k=k?k.__html:void 0,null!=k&&ob(a,k)):\"children\"===f?\"string\"===typeof k?(\"textarea\"!==c||\"\"!==k)&&pb(a,k):\"number\"===typeof k&&pb(a,\"\"+k):\"suppressContentEditableWarning\"!==f&&\"suppressHydrationWarning\"!==f&&\"autoFocus\"!==f&&(ca.hasOwnProperty(f)?null!=k&&\"onScroll\"===f&&G(\"scroll\",a):null!=k&&qa(a,f,k,g))}switch(c){case \"input\":Va(a);cb(a,d,!1);\nbreak;case \"textarea\":Va(a);jb(a);break;case \"option\":null!=d.value&&a.setAttribute(\"value\",\"\"+Sa(d.value));break;case \"select\":a.multiple=!!d.multiple;f=d.value;null!=f?fb(a,!!d.multiple,f,!1):null!=d.defaultValue&&fb(a,!!d.multiple,d.defaultValue,!0);break;default:\"function\"===typeof e.onClick&&(a.onclick=jf)}mf(c,d)&&(b.flags|=4)}null!==b.ref&&(b.flags|=128)}return null;case 6:if(a&&null!=b.stateNode)Ei(a,b,a.memoizedProps,d);else{if(\"string\"!==typeof d&&null===b.stateNode)throw Error(y(166));\nc=dh(ch.current);dh(ah.current);rh(b)?(d=b.stateNode,c=b.memoizedProps,d[wf]=b,d.nodeValue!==c&&(b.flags|=4)):(d=(9===c.nodeType?c:c.ownerDocument).createTextNode(d),d[wf]=b,b.stateNode=d)}return null;case 13:H(P);d=b.memoizedState;if(0!==(b.flags&64))return b.lanes=c,b;d=null!==d;c=!1;null===a?void 0!==b.memoizedProps.fallback&&rh(b):c=null!==a.memoizedState;if(d&&!c&&0!==(b.mode&2))if(null===a&&!0!==b.memoizedProps.unstable_avoidThisFallback||0!==(P.current&1))0===V&&(V=3);else{if(0===V||3===V)V=\n4;null===U||0===(Dg&134217727)&&0===(Hi&134217727)||Ii(U,W)}if(d||c)b.flags|=4;return null;case 4:return fh(),Ci(b),null===a&&cf(b.stateNode.containerInfo),null;case 10:return rg(b),null;case 17:return Ff(b.type)&&Gf(),null;case 19:H(P);d=b.memoizedState;if(null===d)return null;f=0!==(b.flags&64);g=d.rendering;if(null===g)if(f)Fi(d,!1);else{if(0!==V||null!==a&&0!==(a.flags&64))for(a=b.child;null!==a;){g=ih(a);if(null!==g){b.flags|=64;Fi(d,!1);f=g.updateQueue;null!==f&&(b.updateQueue=f,b.flags|=4);\nnull===d.lastEffect&&(b.firstEffect=null);b.lastEffect=d.lastEffect;d=c;for(c=b.child;null!==c;)f=c,a=d,f.flags&=2,f.nextEffect=null,f.firstEffect=null,f.lastEffect=null,g=f.alternate,null===g?(f.childLanes=0,f.lanes=a,f.child=null,f.memoizedProps=null,f.memoizedState=null,f.updateQueue=null,f.dependencies=null,f.stateNode=null):(f.childLanes=g.childLanes,f.lanes=g.lanes,f.child=g.child,f.memoizedProps=g.memoizedProps,f.memoizedState=g.memoizedState,f.updateQueue=g.updateQueue,f.type=g.type,a=g.dependencies,\nf.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),c=c.sibling;I(P,P.current&1|2);return b.child}a=a.sibling}null!==d.tail&&O()>Ji&&(b.flags|=64,f=!0,Fi(d,!1),b.lanes=33554432)}else{if(!f)if(a=ih(g),null!==a){if(b.flags|=64,f=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Fi(d,!0),null===d.tail&&\"hidden\"===d.tailMode&&!g.alternate&&!lh)return b=b.lastEffect=d.lastEffect,null!==b&&(b.nextEffect=null),null}else 2*O()-d.renderingStartTime>Ji&&1073741824!==c&&(b.flags|=\n64,f=!0,Fi(d,!1),b.lanes=33554432);d.isBackwards?(g.sibling=b.child,b.child=g):(c=d.last,null!==c?c.sibling=g:b.child=g,d.last=g)}return null!==d.tail?(c=d.tail,d.rendering=c,d.tail=c.sibling,d.lastEffect=b.lastEffect,d.renderingStartTime=O(),c.sibling=null,b=P.current,I(P,f?b&1|2:b&1),c):null;case 23:case 24:return Ki(),null!==a&&null!==a.memoizedState!==(null!==b.memoizedState)&&\"unstable-defer-without-hiding\"!==d.mode&&(b.flags|=4),null}throw Error(y(156,b.tag));}\nfunction Li(a){switch(a.tag){case 1:Ff(a.type)&&Gf();var b=a.flags;return b&4096?(a.flags=b&-4097|64,a):null;case 3:fh();H(N);H(M);uh();b=a.flags;if(0!==(b&64))throw Error(y(285));a.flags=b&-4097|64;return a;case 5:return hh(a),null;case 13:return H(P),b=a.flags,b&4096?(a.flags=b&-4097|64,a):null;case 19:return H(P),null;case 4:return fh(),null;case 10:return rg(a),null;case 23:case 24:return Ki(),null;default:return null}}\nfunction Mi(a,b){try{var c=\"\",d=b;do c+=Qa(d),d=d.return;while(d);var e=c}catch(f){e=\"\\nError generating stack: \"+f.message+\"\\n\"+f.stack}return{value:a,source:b,stack:e}}function Ni(a,b){try{console.error(b.value)}catch(c){setTimeout(function(){throw c;})}}var Oi=\"function\"===typeof WeakMap?WeakMap:Map;function Pi(a,b,c){c=zg(-1,c);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Qi||(Qi=!0,Ri=d);Ni(a,b)};return c}\nfunction Si(a,b,c){c=zg(-1,c);c.tag=3;var d=a.type.getDerivedStateFromError;if(\"function\"===typeof d){var e=b.value;c.payload=function(){Ni(a,b);return d(e)}}var f=a.stateNode;null!==f&&\"function\"===typeof f.componentDidCatch&&(c.callback=function(){\"function\"!==typeof d&&(null===Ti?Ti=new Set([this]):Ti.add(this),Ni(a,b));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:\"\"})});return c}var Ui=\"function\"===typeof WeakSet?WeakSet:Set;\nfunction Vi(a){var b=a.ref;if(null!==b)if(\"function\"===typeof b)try{b(null)}catch(c){Wi(a,c)}else b.current=null}function Xi(a,b){switch(b.tag){case 0:case 11:case 15:case 22:return;case 1:if(b.flags&256&&null!==a){var c=a.memoizedProps,d=a.memoizedState;a=b.stateNode;b=a.getSnapshotBeforeUpdate(b.elementType===b.type?c:lg(b.type,c),d);a.__reactInternalSnapshotBeforeUpdate=b}return;case 3:b.flags&256&&qf(b.stateNode.containerInfo);return;case 5:case 6:case 4:case 17:return}throw Error(y(163));}\nfunction Yi(a,b,c){switch(c.tag){case 0:case 11:case 15:case 22:b=c.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){a=b=b.next;do{if(3===(a.tag&3)){var d=a.create;a.destroy=d()}a=a.next}while(a!==b)}b=c.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){a=b=b.next;do{var e=a;d=e.next;e=e.tag;0!==(e&4)&&0!==(e&1)&&(Zi(c,a),$i(c,a));a=d}while(a!==b)}return;case 1:a=c.stateNode;c.flags&4&&(null===b?a.componentDidMount():(d=c.elementType===c.type?b.memoizedProps:lg(c.type,b.memoizedProps),a.componentDidUpdate(d,\nb.memoizedState,a.__reactInternalSnapshotBeforeUpdate)));b=c.updateQueue;null!==b&&Eg(c,b,a);return;case 3:b=c.updateQueue;if(null!==b){a=null;if(null!==c.child)switch(c.child.tag){case 5:a=c.child.stateNode;break;case 1:a=c.child.stateNode}Eg(c,b,a)}return;case 5:a=c.stateNode;null===b&&c.flags&4&&mf(c.type,c.memoizedProps)&&a.focus();return;case 6:return;case 4:return;case 12:return;case 13:null===c.memoizedState&&(c=c.alternate,null!==c&&(c=c.memoizedState,null!==c&&(c=c.dehydrated,null!==c&&Cc(c))));\nreturn;case 19:case 17:case 20:case 21:case 23:case 24:return}throw Error(y(163));}\nfunction aj(a,b){for(var c=a;;){if(5===c.tag){var d=c.stateNode;if(b)d=d.style,\"function\"===typeof d.setProperty?d.setProperty(\"display\",\"none\",\"important\"):d.display=\"none\";else{d=c.stateNode;var e=c.memoizedProps.style;e=void 0!==e&&null!==e&&e.hasOwnProperty(\"display\")?e.display:null;d.style.display=sb(\"display\",e)}}else if(6===c.tag)c.stateNode.nodeValue=b?\"\":c.memoizedProps;else if((23!==c.tag&&24!==c.tag||null===c.memoizedState||c===a)&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===\na)break;for(;null===c.sibling;){if(null===c.return||c.return===a)return;c=c.return}c.sibling.return=c.return;c=c.sibling}}\nfunction bj(a,b){if(Mf&&\"function\"===typeof Mf.onCommitFiberUnmount)try{Mf.onCommitFiberUnmount(Lf,b)}catch(f){}switch(b.tag){case 0:case 11:case 14:case 15:case 22:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var c=a=a.next;do{var d=c,e=d.destroy;d=d.tag;if(void 0!==e)if(0!==(d&4))Zi(b,c);else{d=b;try{e()}catch(f){Wi(d,f)}}c=c.next}while(c!==a)}break;case 1:Vi(b);a=b.stateNode;if(\"function\"===typeof a.componentWillUnmount)try{a.props=b.memoizedProps,a.state=b.memoizedState,a.componentWillUnmount()}catch(f){Wi(b,\nf)}break;case 5:Vi(b);break;case 4:cj(a,b)}}function dj(a){a.alternate=null;a.child=null;a.dependencies=null;a.firstEffect=null;a.lastEffect=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.return=null;a.updateQueue=null}function ej(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction fj(a){a:{for(var b=a.return;null!==b;){if(ej(b))break a;b=b.return}throw Error(y(160));}var c=b;b=c.stateNode;switch(c.tag){case 5:var d=!1;break;case 3:b=b.containerInfo;d=!0;break;case 4:b=b.containerInfo;d=!0;break;default:throw Error(y(161));}c.flags&16&&(pb(b,\"\"),c.flags&=-17);a:b:for(c=a;;){for(;null===c.sibling;){if(null===c.return||ej(c.return)){c=null;break a}c=c.return}c.sibling.return=c.return;for(c=c.sibling;5!==c.tag&&6!==c.tag&&18!==c.tag;){if(c.flags&2)continue b;if(null===\nc.child||4===c.tag)continue b;else c.child.return=c,c=c.child}if(!(c.flags&2)){c=c.stateNode;break a}}d?gj(a,c,b):hj(a,c,b)}\nfunction gj(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=jf));else if(4!==d&&(a=a.child,null!==a))for(gj(a,b,c),a=a.sibling;null!==a;)gj(a,b,c),a=a.sibling}\nfunction hj(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(hj(a,b,c),a=a.sibling;null!==a;)hj(a,b,c),a=a.sibling}\nfunction cj(a,b){for(var c=b,d=!1,e,f;;){if(!d){d=c.return;a:for(;;){if(null===d)throw Error(y(160));e=d.stateNode;switch(d.tag){case 5:f=!1;break a;case 3:e=e.containerInfo;f=!0;break a;case 4:e=e.containerInfo;f=!0;break a}d=d.return}d=!0}if(5===c.tag||6===c.tag){a:for(var g=a,h=c,k=h;;)if(bj(g,k),null!==k.child&&4!==k.tag)k.child.return=k,k=k.child;else{if(k===h)break a;for(;null===k.sibling;){if(null===k.return||k.return===h)break a;k=k.return}k.sibling.return=k.return;k=k.sibling}f?(g=e,h=c.stateNode,\n8===g.nodeType?g.parentNode.removeChild(h):g.removeChild(h)):e.removeChild(c.stateNode)}else if(4===c.tag){if(null!==c.child){e=c.stateNode.containerInfo;f=!0;c.child.return=c;c=c.child;continue}}else if(bj(a,c),null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return;4===c.tag&&(d=!1)}c.sibling.return=c.return;c=c.sibling}}\nfunction ij(a,b){switch(b.tag){case 0:case 11:case 14:case 15:case 22:var c=b.updateQueue;c=null!==c?c.lastEffect:null;if(null!==c){var d=c=c.next;do 3===(d.tag&3)&&(a=d.destroy,d.destroy=void 0,void 0!==a&&a()),d=d.next;while(d!==c)}return;case 1:return;case 5:c=b.stateNode;if(null!=c){d=b.memoizedProps;var e=null!==a?a.memoizedProps:d;a=b.type;var f=b.updateQueue;b.updateQueue=null;if(null!==f){c[xf]=d;\"input\"===a&&\"radio\"===d.type&&null!=d.name&&$a(c,d);wb(a,e);b=wb(a,d);for(e=0;e<f.length;e+=\n2){var g=f[e],h=f[e+1];\"style\"===g?tb(c,h):\"dangerouslySetInnerHTML\"===g?ob(c,h):\"children\"===g?pb(c,h):qa(c,g,h,b)}switch(a){case \"input\":ab(c,d);break;case \"textarea\":ib(c,d);break;case \"select\":a=c._wrapperState.wasMultiple,c._wrapperState.wasMultiple=!!d.multiple,f=d.value,null!=f?fb(c,!!d.multiple,f,!1):a!==!!d.multiple&&(null!=d.defaultValue?fb(c,!!d.multiple,d.defaultValue,!0):fb(c,!!d.multiple,d.multiple?[]:\"\",!1))}}}return;case 6:if(null===b.stateNode)throw Error(y(162));b.stateNode.nodeValue=\nb.memoizedProps;return;case 3:c=b.stateNode;c.hydrate&&(c.hydrate=!1,Cc(c.containerInfo));return;case 12:return;case 13:null!==b.memoizedState&&(jj=O(),aj(b.child,!0));kj(b);return;case 19:kj(b);return;case 17:return;case 23:case 24:aj(b,null!==b.memoizedState);return}throw Error(y(163));}function kj(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Ui);b.forEach(function(b){var d=lj.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction mj(a,b){return null!==a&&(a=a.memoizedState,null===a||null!==a.dehydrated)?(b=b.memoizedState,null!==b&&null===b.dehydrated):!1}var nj=Math.ceil,oj=ra.ReactCurrentDispatcher,pj=ra.ReactCurrentOwner,X=0,U=null,Y=null,W=0,qj=0,rj=Bf(0),V=0,sj=null,tj=0,Dg=0,Hi=0,uj=0,vj=null,jj=0,Ji=Infinity;function wj(){Ji=O()+500}var Z=null,Qi=!1,Ri=null,Ti=null,xj=!1,yj=null,zj=90,Aj=[],Bj=[],Cj=null,Dj=0,Ej=null,Fj=-1,Gj=0,Hj=0,Ij=null,Jj=!1;function Hg(){return 0!==(X&48)?O():-1!==Fj?Fj:Fj=O()}\nfunction Ig(a){a=a.mode;if(0===(a&2))return 1;if(0===(a&4))return 99===eg()?1:2;0===Gj&&(Gj=tj);if(0!==kg.transition){0!==Hj&&(Hj=null!==vj?vj.pendingLanes:0);a=Gj;var b=4186112&~Hj;b&=-b;0===b&&(a=4186112&~a,b=a&-a,0===b&&(b=8192));return b}a=eg();0!==(X&4)&&98===a?a=Xc(12,Gj):(a=Sc(a),a=Xc(a,Gj));return a}\nfunction Jg(a,b,c){if(50<Dj)throw Dj=0,Ej=null,Error(y(185));a=Kj(a,b);if(null===a)return null;$c(a,b,c);a===U&&(Hi|=b,4===V&&Ii(a,W));var d=eg();1===b?0!==(X&8)&&0===(X&48)?Lj(a):(Mj(a,c),0===X&&(wj(),ig())):(0===(X&4)||98!==d&&99!==d||(null===Cj?Cj=new Set([a]):Cj.add(a)),Mj(a,c));vj=a}function Kj(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}\nfunction Mj(a,b){for(var c=a.callbackNode,d=a.suspendedLanes,e=a.pingedLanes,f=a.expirationTimes,g=a.pendingLanes;0<g;){var h=31-Vc(g),k=1<<h,l=f[h];if(-1===l){if(0===(k&d)||0!==(k&e)){l=b;Rc(k);var n=F;f[h]=10<=n?l+250:6<=n?l+5E3:-1}}else l<=b&&(a.expiredLanes|=k);g&=~k}d=Uc(a,a===U?W:0);b=F;if(0===d)null!==c&&(c!==Zf&&Pf(c),a.callbackNode=null,a.callbackPriority=0);else{if(null!==c){if(a.callbackPriority===b)return;c!==Zf&&Pf(c)}15===b?(c=Lj.bind(null,a),null===ag?(ag=[c],bg=Of(Uf,jg)):ag.push(c),\nc=Zf):14===b?c=hg(99,Lj.bind(null,a)):(c=Tc(b),c=hg(c,Nj.bind(null,a)));a.callbackPriority=b;a.callbackNode=c}}\nfunction Nj(a){Fj=-1;Hj=Gj=0;if(0!==(X&48))throw Error(y(327));var b=a.callbackNode;if(Oj()&&a.callbackNode!==b)return null;var c=Uc(a,a===U?W:0);if(0===c)return null;var d=c;var e=X;X|=16;var f=Pj();if(U!==a||W!==d)wj(),Qj(a,d);do try{Rj();break}catch(h){Sj(a,h)}while(1);qg();oj.current=f;X=e;null!==Y?d=0:(U=null,W=0,d=V);if(0!==(tj&Hi))Qj(a,0);else if(0!==d){2===d&&(X|=64,a.hydrate&&(a.hydrate=!1,qf(a.containerInfo)),c=Wc(a),0!==c&&(d=Tj(a,c)));if(1===d)throw b=sj,Qj(a,0),Ii(a,c),Mj(a,O()),b;a.finishedWork=\na.current.alternate;a.finishedLanes=c;switch(d){case 0:case 1:throw Error(y(345));case 2:Uj(a);break;case 3:Ii(a,c);if((c&62914560)===c&&(d=jj+500-O(),10<d)){if(0!==Uc(a,0))break;e=a.suspendedLanes;if((e&c)!==c){Hg();a.pingedLanes|=a.suspendedLanes&e;break}a.timeoutHandle=of(Uj.bind(null,a),d);break}Uj(a);break;case 4:Ii(a,c);if((c&4186112)===c)break;d=a.eventTimes;for(e=-1;0<c;){var g=31-Vc(c);f=1<<g;g=d[g];g>e&&(e=g);c&=~f}c=e;c=O()-c;c=(120>c?120:480>c?480:1080>c?1080:1920>c?1920:3E3>c?3E3:4320>\nc?4320:1960*nj(c/1960))-c;if(10<c){a.timeoutHandle=of(Uj.bind(null,a),c);break}Uj(a);break;case 5:Uj(a);break;default:throw Error(y(329));}}Mj(a,O());return a.callbackNode===b?Nj.bind(null,a):null}function Ii(a,b){b&=~uj;b&=~Hi;a.suspendedLanes|=b;a.pingedLanes&=~b;for(a=a.expirationTimes;0<b;){var c=31-Vc(b),d=1<<c;a[c]=-1;b&=~d}}\nfunction Lj(a){if(0!==(X&48))throw Error(y(327));Oj();if(a===U&&0!==(a.expiredLanes&W)){var b=W;var c=Tj(a,b);0!==(tj&Hi)&&(b=Uc(a,b),c=Tj(a,b))}else b=Uc(a,0),c=Tj(a,b);0!==a.tag&&2===c&&(X|=64,a.hydrate&&(a.hydrate=!1,qf(a.containerInfo)),b=Wc(a),0!==b&&(c=Tj(a,b)));if(1===c)throw c=sj,Qj(a,0),Ii(a,b),Mj(a,O()),c;a.finishedWork=a.current.alternate;a.finishedLanes=b;Uj(a);Mj(a,O());return null}\nfunction Vj(){if(null!==Cj){var a=Cj;Cj=null;a.forEach(function(a){a.expiredLanes|=24&a.pendingLanes;Mj(a,O())})}ig()}function Wj(a,b){var c=X;X|=1;try{return a(b)}finally{X=c,0===X&&(wj(),ig())}}function Xj(a,b){var c=X;X&=-2;X|=8;try{return a(b)}finally{X=c,0===X&&(wj(),ig())}}function ni(a,b){I(rj,qj);qj|=b;tj|=b}function Ki(){qj=rj.current;H(rj)}\nfunction Qj(a,b){a.finishedWork=null;a.finishedLanes=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,pf(c));if(null!==Y)for(c=Y.return;null!==c;){var d=c;switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&Gf();break;case 3:fh();H(N);H(M);uh();break;case 5:hh(d);break;case 4:fh();break;case 13:H(P);break;case 19:H(P);break;case 10:rg(d);break;case 23:case 24:Ki()}c=c.return}U=a;Y=Tg(a.current,null);W=qj=tj=b;V=0;sj=null;uj=Hi=Dg=0}\nfunction Sj(a,b){do{var c=Y;try{qg();vh.current=Gh;if(yh){for(var d=R.memoizedState;null!==d;){var e=d.queue;null!==e&&(e.pending=null);d=d.next}yh=!1}xh=0;T=S=R=null;zh=!1;pj.current=null;if(null===c||null===c.return){V=1;sj=b;Y=null;break}a:{var f=a,g=c.return,h=c,k=b;b=W;h.flags|=2048;h.firstEffect=h.lastEffect=null;if(null!==k&&\"object\"===typeof k&&\"function\"===typeof k.then){var l=k;if(0===(h.mode&2)){var n=h.alternate;n?(h.updateQueue=n.updateQueue,h.memoizedState=n.memoizedState,h.lanes=n.lanes):\n(h.updateQueue=null,h.memoizedState=null)}var A=0!==(P.current&1),p=g;do{var C;if(C=13===p.tag){var x=p.memoizedState;if(null!==x)C=null!==x.dehydrated?!0:!1;else{var w=p.memoizedProps;C=void 0===w.fallback?!1:!0!==w.unstable_avoidThisFallback?!0:A?!1:!0}}if(C){var z=p.updateQueue;if(null===z){var u=new Set;u.add(l);p.updateQueue=u}else z.add(l);if(0===(p.mode&2)){p.flags|=64;h.flags|=16384;h.flags&=-2981;if(1===h.tag)if(null===h.alternate)h.tag=17;else{var t=zg(-1,1);t.tag=2;Ag(h,t)}h.lanes|=1;break a}k=\nvoid 0;h=b;var q=f.pingCache;null===q?(q=f.pingCache=new Oi,k=new Set,q.set(l,k)):(k=q.get(l),void 0===k&&(k=new Set,q.set(l,k)));if(!k.has(h)){k.add(h);var v=Yj.bind(null,f,l,h);l.then(v,v)}p.flags|=4096;p.lanes=b;break a}p=p.return}while(null!==p);k=Error((Ra(h.type)||\"A React component\")+\" suspended while rendering, but no fallback UI was specified.\\n\\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.\")}5!==V&&(V=2);k=Mi(k,h);p=\ng;do{switch(p.tag){case 3:f=k;p.flags|=4096;b&=-b;p.lanes|=b;var J=Pi(p,f,b);Bg(p,J);break a;case 1:f=k;var K=p.type,Q=p.stateNode;if(0===(p.flags&64)&&(\"function\"===typeof K.getDerivedStateFromError||null!==Q&&\"function\"===typeof Q.componentDidCatch&&(null===Ti||!Ti.has(Q)))){p.flags|=4096;b&=-b;p.lanes|=b;var L=Si(p,f,b);Bg(p,L);break a}}p=p.return}while(null!==p)}Zj(c)}catch(va){b=va;Y===c&&null!==c&&(Y=c=c.return);continue}break}while(1)}\nfunction Pj(){var a=oj.current;oj.current=Gh;return null===a?Gh:a}function Tj(a,b){var c=X;X|=16;var d=Pj();U===a&&W===b||Qj(a,b);do try{ak();break}catch(e){Sj(a,e)}while(1);qg();X=c;oj.current=d;if(null!==Y)throw Error(y(261));U=null;W=0;return V}function ak(){for(;null!==Y;)bk(Y)}function Rj(){for(;null!==Y&&!Qf();)bk(Y)}function bk(a){var b=ck(a.alternate,a,qj);a.memoizedProps=a.pendingProps;null===b?Zj(a):Y=b;pj.current=null}\nfunction Zj(a){var b=a;do{var c=b.alternate;a=b.return;if(0===(b.flags&2048)){c=Gi(c,b,qj);if(null!==c){Y=c;return}c=b;if(24!==c.tag&&23!==c.tag||null===c.memoizedState||0!==(qj&1073741824)||0===(c.mode&4)){for(var d=0,e=c.child;null!==e;)d|=e.lanes|e.childLanes,e=e.sibling;c.childLanes=d}null!==a&&0===(a.flags&2048)&&(null===a.firstEffect&&(a.firstEffect=b.firstEffect),null!==b.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=b.firstEffect),a.lastEffect=b.lastEffect),1<b.flags&&(null!==\na.lastEffect?a.lastEffect.nextEffect=b:a.firstEffect=b,a.lastEffect=b))}else{c=Li(b);if(null!==c){c.flags&=2047;Y=c;return}null!==a&&(a.firstEffect=a.lastEffect=null,a.flags|=2048)}b=b.sibling;if(null!==b){Y=b;return}Y=b=a}while(null!==b);0===V&&(V=5)}function Uj(a){var b=eg();gg(99,dk.bind(null,a,b));return null}\nfunction dk(a,b){do Oj();while(null!==yj);if(0!==(X&48))throw Error(y(327));var c=a.finishedWork;if(null===c)return null;a.finishedWork=null;a.finishedLanes=0;if(c===a.current)throw Error(y(177));a.callbackNode=null;var d=c.lanes|c.childLanes,e=d,f=a.pendingLanes&~e;a.pendingLanes=e;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=e;a.mutableReadLanes&=e;a.entangledLanes&=e;e=a.entanglements;for(var g=a.eventTimes,h=a.expirationTimes;0<f;){var k=31-Vc(f),l=1<<k;e[k]=0;g[k]=-1;h[k]=-1;f&=~l}null!==\nCj&&0===(d&24)&&Cj.has(a)&&Cj.delete(a);a===U&&(Y=U=null,W=0);1<c.flags?null!==c.lastEffect?(c.lastEffect.nextEffect=c,d=c.firstEffect):d=c:d=c.firstEffect;if(null!==d){e=X;X|=32;pj.current=null;kf=fd;g=Ne();if(Oe(g)){if(\"selectionStart\"in g)h={start:g.selectionStart,end:g.selectionEnd};else a:if(h=(h=g.ownerDocument)&&h.defaultView||window,(l=h.getSelection&&h.getSelection())&&0!==l.rangeCount){h=l.anchorNode;f=l.anchorOffset;k=l.focusNode;l=l.focusOffset;try{h.nodeType,k.nodeType}catch(va){h=null;\nbreak a}var n=0,A=-1,p=-1,C=0,x=0,w=g,z=null;b:for(;;){for(var u;;){w!==h||0!==f&&3!==w.nodeType||(A=n+f);w!==k||0!==l&&3!==w.nodeType||(p=n+l);3===w.nodeType&&(n+=w.nodeValue.length);if(null===(u=w.firstChild))break;z=w;w=u}for(;;){if(w===g)break b;z===h&&++C===f&&(A=n);z===k&&++x===l&&(p=n);if(null!==(u=w.nextSibling))break;w=z;z=w.parentNode}w=u}h=-1===A||-1===p?null:{start:A,end:p}}else h=null;h=h||{start:0,end:0}}else h=null;lf={focusedElem:g,selectionRange:h};fd=!1;Ij=null;Jj=!1;Z=d;do try{ek()}catch(va){if(null===\nZ)throw Error(y(330));Wi(Z,va);Z=Z.nextEffect}while(null!==Z);Ij=null;Z=d;do try{for(g=a;null!==Z;){var t=Z.flags;t&16&&pb(Z.stateNode,\"\");if(t&128){var q=Z.alternate;if(null!==q){var v=q.ref;null!==v&&(\"function\"===typeof v?v(null):v.current=null)}}switch(t&1038){case 2:fj(Z);Z.flags&=-3;break;case 6:fj(Z);Z.flags&=-3;ij(Z.alternate,Z);break;case 1024:Z.flags&=-1025;break;case 1028:Z.flags&=-1025;ij(Z.alternate,Z);break;case 4:ij(Z.alternate,Z);break;case 8:h=Z;cj(g,h);var J=h.alternate;dj(h);null!==\nJ&&dj(J)}Z=Z.nextEffect}}catch(va){if(null===Z)throw Error(y(330));Wi(Z,va);Z=Z.nextEffect}while(null!==Z);v=lf;q=Ne();t=v.focusedElem;g=v.selectionRange;if(q!==t&&t&&t.ownerDocument&&Me(t.ownerDocument.documentElement,t)){null!==g&&Oe(t)&&(q=g.start,v=g.end,void 0===v&&(v=q),\"selectionStart\"in t?(t.selectionStart=q,t.selectionEnd=Math.min(v,t.value.length)):(v=(q=t.ownerDocument||document)&&q.defaultView||window,v.getSelection&&(v=v.getSelection(),h=t.textContent.length,J=Math.min(g.start,h),g=void 0===\ng.end?J:Math.min(g.end,h),!v.extend&&J>g&&(h=g,g=J,J=h),h=Le(t,J),f=Le(t,g),h&&f&&(1!==v.rangeCount||v.anchorNode!==h.node||v.anchorOffset!==h.offset||v.focusNode!==f.node||v.focusOffset!==f.offset)&&(q=q.createRange(),q.setStart(h.node,h.offset),v.removeAllRanges(),J>g?(v.addRange(q),v.extend(f.node,f.offset)):(q.setEnd(f.node,f.offset),v.addRange(q))))));q=[];for(v=t;v=v.parentNode;)1===v.nodeType&&q.push({element:v,left:v.scrollLeft,top:v.scrollTop});\"function\"===typeof t.focus&&t.focus();for(t=\n0;t<q.length;t++)v=q[t],v.element.scrollLeft=v.left,v.element.scrollTop=v.top}fd=!!kf;lf=kf=null;a.current=c;Z=d;do try{for(t=a;null!==Z;){var K=Z.flags;K&36&&Yi(t,Z.alternate,Z);if(K&128){q=void 0;var Q=Z.ref;if(null!==Q){var L=Z.stateNode;switch(Z.tag){case 5:q=L;break;default:q=L}\"function\"===typeof Q?Q(q):Q.current=q}}Z=Z.nextEffect}}catch(va){if(null===Z)throw Error(y(330));Wi(Z,va);Z=Z.nextEffect}while(null!==Z);Z=null;$f();X=e}else a.current=c;if(xj)xj=!1,yj=a,zj=b;else for(Z=d;null!==Z;)b=\nZ.nextEffect,Z.nextEffect=null,Z.flags&8&&(K=Z,K.sibling=null,K.stateNode=null),Z=b;d=a.pendingLanes;0===d&&(Ti=null);1===d?a===Ej?Dj++:(Dj=0,Ej=a):Dj=0;c=c.stateNode;if(Mf&&\"function\"===typeof Mf.onCommitFiberRoot)try{Mf.onCommitFiberRoot(Lf,c,void 0,64===(c.current.flags&64))}catch(va){}Mj(a,O());if(Qi)throw Qi=!1,a=Ri,Ri=null,a;if(0!==(X&8))return null;ig();return null}\nfunction ek(){for(;null!==Z;){var a=Z.alternate;Jj||null===Ij||(0!==(Z.flags&8)?dc(Z,Ij)&&(Jj=!0):13===Z.tag&&mj(a,Z)&&dc(Z,Ij)&&(Jj=!0));var b=Z.flags;0!==(b&256)&&Xi(a,Z);0===(b&512)||xj||(xj=!0,hg(97,function(){Oj();return null}));Z=Z.nextEffect}}function Oj(){if(90!==zj){var a=97<zj?97:zj;zj=90;return gg(a,fk)}return!1}function $i(a,b){Aj.push(b,a);xj||(xj=!0,hg(97,function(){Oj();return null}))}function Zi(a,b){Bj.push(b,a);xj||(xj=!0,hg(97,function(){Oj();return null}))}\nfunction fk(){if(null===yj)return!1;var a=yj;yj=null;if(0!==(X&48))throw Error(y(331));var b=X;X|=32;var c=Bj;Bj=[];for(var d=0;d<c.length;d+=2){var e=c[d],f=c[d+1],g=e.destroy;e.destroy=void 0;if(\"function\"===typeof g)try{g()}catch(k){if(null===f)throw Error(y(330));Wi(f,k)}}c=Aj;Aj=[];for(d=0;d<c.length;d+=2){e=c[d];f=c[d+1];try{var h=e.create;e.destroy=h()}catch(k){if(null===f)throw Error(y(330));Wi(f,k)}}for(h=a.current.firstEffect;null!==h;)a=h.nextEffect,h.nextEffect=null,h.flags&8&&(h.sibling=\nnull,h.stateNode=null),h=a;X=b;ig();return!0}function gk(a,b,c){b=Mi(c,b);b=Pi(a,b,1);Ag(a,b);b=Hg();a=Kj(a,1);null!==a&&($c(a,1,b),Mj(a,b))}\nfunction Wi(a,b){if(3===a.tag)gk(a,a,b);else for(var c=a.return;null!==c;){if(3===c.tag){gk(c,a,b);break}else if(1===c.tag){var d=c.stateNode;if(\"function\"===typeof c.type.getDerivedStateFromError||\"function\"===typeof d.componentDidCatch&&(null===Ti||!Ti.has(d))){a=Mi(b,a);var e=Si(c,a,1);Ag(c,e);e=Hg();c=Kj(c,1);if(null!==c)$c(c,1,e),Mj(c,e);else if(\"function\"===typeof d.componentDidCatch&&(null===Ti||!Ti.has(d)))try{d.componentDidCatch(b,a)}catch(f){}break}}c=c.return}}\nfunction Yj(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);b=Hg();a.pingedLanes|=a.suspendedLanes&c;U===a&&(W&c)===c&&(4===V||3===V&&(W&62914560)===W&&500>O()-jj?Qj(a,0):uj|=c);Mj(a,b)}function lj(a,b){var c=a.stateNode;null!==c&&c.delete(b);b=0;0===b&&(b=a.mode,0===(b&2)?b=1:0===(b&4)?b=99===eg()?1:2:(0===Gj&&(Gj=tj),b=Yc(62914560&~Gj),0===b&&(b=4194304)));c=Hg();a=Kj(a,b);null!==a&&($c(a,b,c),Mj(a,c))}var ck;\nck=function(a,b,c){var d=b.lanes;if(null!==a)if(a.memoizedProps!==b.pendingProps||N.current)ug=!0;else if(0!==(c&d))ug=0!==(a.flags&16384)?!0:!1;else{ug=!1;switch(b.tag){case 3:ri(b);sh();break;case 5:gh(b);break;case 1:Ff(b.type)&&Jf(b);break;case 4:eh(b,b.stateNode.containerInfo);break;case 10:d=b.memoizedProps.value;var e=b.type._context;I(mg,e._currentValue);e._currentValue=d;break;case 13:if(null!==b.memoizedState){if(0!==(c&b.child.childLanes))return ti(a,b,c);I(P,P.current&1);b=hi(a,b,c);return null!==\nb?b.sibling:null}I(P,P.current&1);break;case 19:d=0!==(c&b.childLanes);if(0!==(a.flags&64)){if(d)return Ai(a,b,c);b.flags|=64}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null,e.lastEffect=null);I(P,P.current);if(d)break;else return null;case 23:case 24:return b.lanes=0,mi(a,b,c)}return hi(a,b,c)}else ug=!1;b.lanes=0;switch(b.tag){case 2:d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);a=b.pendingProps;e=Ef(b,M.current);tg(b,c);e=Ch(null,b,d,a,e,c);b.flags|=1;if(\"object\"===\ntypeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof){b.tag=1;b.memoizedState=null;b.updateQueue=null;if(Ff(d)){var f=!0;Jf(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;xg(b);var g=d.getDerivedStateFromProps;\"function\"===typeof g&&Gg(b,d,g,a);e.updater=Kg;b.stateNode=e;e._reactInternals=b;Og(b,d,a,c);b=qi(null,b,d,!0,f,c)}else b.tag=0,fi(null,b,e,c),b=b.child;return b;case 16:e=b.elementType;a:{null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2);\na=b.pendingProps;f=e._init;e=f(e._payload);b.type=e;f=b.tag=hk(e);a=lg(e,a);switch(f){case 0:b=li(null,b,e,a,c);break a;case 1:b=pi(null,b,e,a,c);break a;case 11:b=gi(null,b,e,a,c);break a;case 14:b=ii(null,b,e,lg(e.type,a),d,c);break a}throw Error(y(306,e,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:lg(d,e),li(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:lg(d,e),pi(a,b,d,e,c);case 3:ri(b);d=b.updateQueue;if(null===a||null===d)throw Error(y(282));\nd=b.pendingProps;e=b.memoizedState;e=null!==e?e.element:null;yg(a,b);Cg(b,d,null,c);d=b.memoizedState.element;if(d===e)sh(),b=hi(a,b,c);else{e=b.stateNode;if(f=e.hydrate)kh=rf(b.stateNode.containerInfo.firstChild),jh=b,f=lh=!0;if(f){a=e.mutableSourceEagerHydrationData;if(null!=a)for(e=0;e<a.length;e+=2)f=a[e],f._workInProgressVersionPrimary=a[e+1],th.push(f);c=Zg(b,null,d,c);for(b.child=c;c;)c.flags=c.flags&-3|1024,c=c.sibling}else fi(a,b,d,c),sh();b=b.child}return b;case 5:return gh(b),null===a&&\nph(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,nf(d,e)?g=null:null!==f&&nf(d,f)&&(b.flags|=16),oi(a,b),fi(a,b,g,c),b.child;case 6:return null===a&&ph(b),null;case 13:return ti(a,b,c);case 4:return eh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Yg(b,null,d,c):fi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:lg(d,e),gi(a,b,d,e,c);case 7:return fi(a,b,b.pendingProps,c),b.child;case 8:return fi(a,b,b.pendingProps.children,\nc),b.child;case 12:return fi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;g=b.memoizedProps;f=e.value;var h=b.type._context;I(mg,h._currentValue);h._currentValue=f;if(null!==g)if(h=g.value,f=He(h,f)?0:(\"function\"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0,0===f){if(g.children===e.children&&!N.current){b=hi(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var k=h.dependencies;if(null!==k){g=h.child;for(var l=\nk.firstContext;null!==l;){if(l.context===d&&0!==(l.observedBits&f)){1===h.tag&&(l=zg(-1,c&-c),l.tag=2,Ag(h,l));h.lanes|=c;l=h.alternate;null!==l&&(l.lanes|=c);sg(h.return,c);k.lanes|=c;break}l=l.next}}else g=10===h.tag?h.type===b.type?null:h.child:h.child;if(null!==g)g.return=h;else for(g=h;null!==g;){if(g===b){g=null;break}h=g.sibling;if(null!==h){h.return=g.return;g=h;break}g=g.return}h=g}fi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,f=b.pendingProps,d=f.children,tg(b,c),e=vg(e,\nf.unstable_observedBits),d=d(e),b.flags|=1,fi(a,b,d,c),b.child;case 14:return e=b.type,f=lg(e,b.pendingProps),f=lg(e.type,f),ii(a,b,e,f,d,c);case 15:return ki(a,b,b.type,b.pendingProps,d,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:lg(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.flags|=2),b.tag=1,Ff(d)?(a=!0,Jf(b)):a=!1,tg(b,c),Mg(b,d,e),Og(b,d,e,c),qi(null,b,d,!0,a,c);case 19:return Ai(a,b,c);case 23:return mi(a,b,c);case 24:return mi(a,b,c)}throw Error(y(156,b.tag));\n};function ik(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.flags=0;this.lastEffect=this.firstEffect=this.nextEffect=null;this.childLanes=this.lanes=0;this.alternate=null}function nh(a,b,c,d){return new ik(a,b,c,d)}function ji(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction hk(a){if(\"function\"===typeof a)return ji(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Aa)return 11;if(a===Da)return 14}return 2}\nfunction Tg(a,b){var c=a.alternate;null===c?(c=nh(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.nextEffect=null,c.firstEffect=null,c.lastEffect=null);c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction Vg(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)ji(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ua:return Xg(c.children,e,f,b);case Ha:g=8;e|=16;break;case wa:g=8;e|=1;break;case xa:return a=nh(12,c,b,e|8),a.elementType=xa,a.type=xa,a.lanes=f,a;case Ba:return a=nh(13,c,b,e),a.type=Ba,a.elementType=Ba,a.lanes=f,a;case Ca:return a=nh(19,c,b,e),a.elementType=Ca,a.lanes=f,a;case Ia:return vi(c,e,f,b);case Ja:return a=nh(24,c,b,e),a.elementType=Ja,a.lanes=f,a;default:if(\"object\"===\ntypeof a&&null!==a)switch(a.$$typeof){case ya:g=10;break a;case za:g=9;break a;case Aa:g=11;break a;case Da:g=14;break a;case Ea:g=16;d=null;break a;case Fa:g=22;break a}throw Error(y(130,null==a?a:typeof a,\"\"));}b=nh(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Xg(a,b,c,d){a=nh(7,a,d,b);a.lanes=c;return a}function vi(a,b,c,d){a=nh(23,a,d,b);a.elementType=Ia;a.lanes=c;return a}function Ug(a,b,c){a=nh(6,a,null,b);a.lanes=c;return a}\nfunction Wg(a,b,c){b=nh(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction jk(a,b,c){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.pendingContext=this.context=null;this.hydrate=c;this.callbackNode=null;this.callbackPriority=0;this.eventTimes=Zc(0);this.expirationTimes=Zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=Zc(0);this.mutableSourceEagerHydrationData=null}\nfunction kk(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:ta,key:null==d?null:\"\"+d,children:a,containerInfo:b,implementation:c}}\nfunction lk(a,b,c,d){var e=b.current,f=Hg(),g=Ig(e);a:if(c){c=c._reactInternals;b:{if(Zb(c)!==c||1!==c.tag)throw Error(y(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(Ff(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}h=h.return}while(null!==h);throw Error(y(171));}if(1===c.tag){var k=c.type;if(Ff(k)){c=If(c,k,h);break a}}c=h}else c=Cf;null===b.context?b.context=c:b.pendingContext=c;b=zg(f,g);b.payload={element:a};d=void 0===d?null:d;null!==\nd&&(b.callback=d);Ag(e,b);Jg(e,g,f);return g}function mk(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function nk(a,b){a=a.memoizedState;if(null!==a&&null!==a.dehydrated){var c=a.retryLane;a.retryLane=0!==c&&c<b?c:b}}function ok(a,b){nk(a,b);(a=a.alternate)&&nk(a,b)}function pk(){return null}\nfunction qk(a,b,c){var d=null!=c&&null!=c.hydrationOptions&&c.hydrationOptions.mutableSources||null;c=new jk(a,b,null!=c&&!0===c.hydrate);b=nh(3,null,null,2===b?7:1===b?3:0);c.current=b;b.stateNode=c;xg(b);a[ff]=c.current;cf(8===a.nodeType?a.parentNode:a);if(d)for(a=0;a<d.length;a++){b=d[a];var e=b._getVersion;e=e(b._source);null==c.mutableSourceEagerHydrationData?c.mutableSourceEagerHydrationData=[b,e]:c.mutableSourceEagerHydrationData.push(b,e)}this._internalRoot=c}\nqk.prototype.render=function(a){lk(a,this._internalRoot,null,null)};qk.prototype.unmount=function(){var a=this._internalRoot,b=a.containerInfo;lk(null,a,null,function(){b[ff]=null})};function rk(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||\" react-mount-point-unstable \"!==a.nodeValue))}\nfunction sk(a,b){b||(b=a?9===a.nodeType?a.documentElement:a.firstChild:null,b=!(!b||1!==b.nodeType||!b.hasAttribute(\"data-reactroot\")));if(!b)for(var c;c=a.lastChild;)a.removeChild(c);return new qk(a,0,b?{hydrate:!0}:void 0)}\nfunction tk(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f._internalRoot;if(\"function\"===typeof e){var h=e;e=function(){var a=mk(g);h.call(a)}}lk(b,g,a,e)}else{f=c._reactRootContainer=sk(c,d);g=f._internalRoot;if(\"function\"===typeof e){var k=e;e=function(){var a=mk(g);k.call(a)}}Xj(function(){lk(b,g,a,e)})}return mk(g)}ec=function(a){if(13===a.tag){var b=Hg();Jg(a,4,b);ok(a,4)}};fc=function(a){if(13===a.tag){var b=Hg();Jg(a,67108864,b);ok(a,67108864)}};\ngc=function(a){if(13===a.tag){var b=Hg(),c=Ig(a);Jg(a,c,b);ok(a,c)}};hc=function(a,b){return b()};\nyb=function(a,b,c){switch(b){case \"input\":ab(a,c);b=c.name;if(\"radio\"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll(\"input[name=\"+JSON.stringify(\"\"+b)+'][type=\"radio\"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Db(d);if(!e)throw Error(y(90));Wa(d);ab(d,e)}}}break;case \"textarea\":ib(a,c);break;case \"select\":b=c.value,null!=b&&fb(a,!!c.multiple,b,!1)}};Gb=Wj;\nHb=function(a,b,c,d,e){var f=X;X|=4;try{return gg(98,a.bind(null,b,c,d,e))}finally{X=f,0===X&&(wj(),ig())}};Ib=function(){0===(X&49)&&(Vj(),Oj())};Jb=function(a,b){var c=X;X|=2;try{return a(b)}finally{X=c,0===X&&(wj(),ig())}};function uk(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!rk(b))throw Error(y(200));return kk(a,b,null,c)}var vk={Events:[Cb,ue,Db,Eb,Fb,Oj,{current:!1}]},wk={findFiberByHostInstance:wc,bundleType:0,version:\"17.0.2\",rendererPackageName:\"react-dom\"};\nvar xk={bundleType:wk.bundleType,version:wk.version,rendererPackageName:wk.rendererPackageName,rendererConfig:wk.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:ra.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=cc(a);return null===a?null:a.stateNode},findFiberByHostInstance:wk.findFiberByHostInstance||\npk,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null};if(\"undefined\"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var yk=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!yk.isDisabled&&yk.supportsFiber)try{Lf=yk.inject(xk),Mf=yk}catch(a){}}exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=vk;exports.createPortal=uk;\nexports.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternals;if(void 0===b){if(\"function\"===typeof a.render)throw Error(y(188));throw Error(y(268,Object.keys(a)));}a=cc(b);a=null===a?null:a.stateNode;return a};exports.flushSync=function(a,b){var c=X;if(0!==(c&48))return a(b);X|=1;try{if(a)return gg(99,a.bind(null,b))}finally{X=c,ig()}};exports.hydrate=function(a,b,c){if(!rk(b))throw Error(y(200));return tk(null,a,b,!0,c)};\nexports.render=function(a,b,c){if(!rk(b))throw Error(y(200));return tk(null,a,b,!1,c)};exports.unmountComponentAtNode=function(a){if(!rk(a))throw Error(y(40));return a._reactRootContainer?(Xj(function(){tk(null,null,a,!1,function(){a._reactRootContainer=null;a[ff]=null})}),!0):!1};exports.unstable_batchedUpdates=Wj;exports.unstable_createPortal=function(a,b){return uk(a,b,2<arguments.length&&void 0!==arguments[2]?arguments[2]:null)};\nexports.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!rk(c))throw Error(y(200));if(null==a||void 0===a._reactInternals)throw Error(y(38));return tk(a,b,c,!1,d)};exports.version=\"17.0.2\";\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/** @license React v0.20.2\n * scheduler.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var f,g,h,k;if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}\nif(\"undefined\"===typeof window||\"function\"!==typeof MessageChannel){var t=null,u=null,w=function(){if(null!==t)try{var a=exports.unstable_now();t(!0,a);t=null}catch(b){throw setTimeout(w,0),b;}};f=function(a){null!==t?setTimeout(f,0,a):(t=a,setTimeout(w,0))};g=function(a,b){u=setTimeout(a,b)};h=function(){clearTimeout(u)};exports.unstable_shouldYield=function(){return!1};k=exports.unstable_forceFrameRate=function(){}}else{var x=window.setTimeout,y=window.clearTimeout;if(\"undefined\"!==typeof console){var z=\nwindow.cancelAnimationFrame;\"function\"!==typeof window.requestAnimationFrame&&console.error(\"This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills\");\"function\"!==typeof z&&console.error(\"This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills\")}var A=!1,B=null,C=-1,D=5,E=0;exports.unstable_shouldYield=function(){return exports.unstable_now()>=\nE};k=function(){};exports.unstable_forceFrameRate=function(a){0>a||125<a?console.error(\"forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported\"):D=0<a?Math.floor(1E3/a):5};var F=new MessageChannel,G=F.port2;F.port1.onmessage=function(){if(null!==B){var a=exports.unstable_now();E=a+D;try{B(!0,a)?G.postMessage(null):(A=!1,B=null)}catch(b){throw G.postMessage(null),b;}}else A=!1};f=function(a){B=a;A||(A=!0,G.postMessage(null))};g=function(a,b){C=\nx(function(){a(exports.unstable_now())},b)};h=function(){y(C);C=-1}}function H(a,b){var c=a.length;a.push(b);a:for(;;){var d=c-1>>>1,e=a[d];if(void 0!==e&&0<I(e,b))a[d]=b,a[c]=e,c=d;else break a}}function J(a){a=a[0];return void 0===a?null:a}\nfunction K(a){var b=a[0];if(void 0!==b){var c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length;d<e;){var m=2*(d+1)-1,n=a[m],v=m+1,r=a[v];if(void 0!==n&&0>I(n,c))void 0!==r&&0>I(r,n)?(a[d]=r,a[v]=c,d=v):(a[d]=n,a[m]=c,d=m);else if(void 0!==r&&0>I(r,c))a[d]=r,a[v]=c,d=v;else break a}}return b}return null}function I(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}var L=[],M=[],N=1,O=null,P=3,Q=!1,R=!1,S=!1;\nfunction T(a){for(var b=J(M);null!==b;){if(null===b.callback)K(M);else if(b.startTime<=a)K(M),b.sortIndex=b.expirationTime,H(L,b);else break;b=J(M)}}function U(a){S=!1;T(a);if(!R)if(null!==J(L))R=!0,f(V);else{var b=J(M);null!==b&&g(U,b.startTime-a)}}\nfunction V(a,b){R=!1;S&&(S=!1,h());Q=!0;var c=P;try{T(b);for(O=J(L);null!==O&&(!(O.expirationTime>b)||a&&!exports.unstable_shouldYield());){var d=O.callback;if(\"function\"===typeof d){O.callback=null;P=O.priorityLevel;var e=d(O.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?O.callback=e:O===J(L)&&K(L);T(b)}else K(L);O=J(L)}if(null!==O)var m=!0;else{var n=J(M);null!==n&&g(U,n.startTime-b);m=!1}return m}finally{O=null,P=c,Q=!1}}var W=k;exports.unstable_IdlePriority=5;\nexports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_continueExecution=function(){R||Q||(R=!0,f(V))};exports.unstable_getCurrentPriorityLevel=function(){return P};exports.unstable_getFirstCallbackNode=function(){return J(L)};\nexports.unstable_next=function(a){switch(P){case 1:case 2:case 3:var b=3;break;default:b=P}var c=P;P=b;try{return a()}finally{P=c}};exports.unstable_pauseExecution=function(){};exports.unstable_requestPaint=W;exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=P;P=a;try{return b()}finally{P=c}};\nexports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();\"object\"===typeof c&&null!==c?(c=c.delay,c=\"number\"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3}e=c+e;a={id:N++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,H(M,a),null===J(L)&&a===J(M)&&(S?h():S=!0,g(U,c-d))):(a.sortIndex=e,H(L,a),R||Q||(R=!0,f(V)));return a};\nexports.unstable_wrapCallback=function(a){var b=P;return function(){var c=P;P=b;try{return a.apply(this,arguments)}finally{P=c}}};\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\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","// A port of an algorithm by Johannes Baagøe <baagoe@baagoe.com>, 2010\n// http://baagoe.com/en/RandomMusings/javascript/\n// https://github.com/nquinlan/better-random-numbers-for-javascript-mirror\n// Original work is under MIT license -\n\n// Copyright (C) 2010 by Johannes Baagøe <baagoe@baagoe.org>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n\n\n(function(global, module, define) {\n\nfunction Alea(seed) {\n var me = this, mash = Mash();\n\n me.next = function() {\n var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32\n me.s0 = me.s1;\n me.s1 = me.s2;\n return me.s2 = t - (me.c = t | 0);\n };\n\n // Apply the seeding algorithm from Baagoe.\n me.c = 1;\n me.s0 = mash(' ');\n me.s1 = mash(' ');\n me.s2 = mash(' ');\n me.s0 -= mash(seed);\n if (me.s0 < 0) { me.s0 += 1; }\n me.s1 -= mash(seed);\n if (me.s1 < 0) { me.s1 += 1; }\n me.s2 -= mash(seed);\n if (me.s2 < 0) { me.s2 += 1; }\n mash = null;\n}\n\nfunction copy(f, t) {\n t.c = f.c;\n t.s0 = f.s0;\n t.s1 = f.s1;\n t.s2 = f.s2;\n return t;\n}\n\nfunction impl(seed, opts) {\n var xg = new Alea(seed),\n state = opts && opts.state,\n prng = xg.next;\n prng.int32 = function() { return (xg.next() * 0x100000000) | 0; }\n prng.double = function() {\n return prng() + (prng() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53\n };\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nfunction Mash() {\n var n = 0xefc8249d;\n\n var mash = function(data) {\n data = 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çois Panneton and Pierre L'ecuyer:\n// \"On the Xorgshift Random Number Generators\"\n// http://saluc.engr.uconn.edu/refs/crypto/rng/panneton05onthexorshift.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this;\n\n // Set up generator function.\n me.next = function() {\n // Update xor generator.\n var X = me.x, i = me.i, t, v, w;\n t = X[i]; t ^= (t >>> 7); v = t ^ (t << 24);\n t = X[(i + 1) & 7]; v ^= t ^ (t >>> 10);\n t = X[(i + 3) & 7]; v ^= t ^ (t >>> 3);\n t = X[(i + 4) & 7]; v ^= t ^ (t << 7);\n t = X[(i + 7) & 7]; t = t ^ (t << 13); v ^= t ^ (t << 9);\n X[i] = v;\n me.i = (i + 1) & 7;\n return v;\n };\n\n function init(me, seed) {\n var j, w, X = [];\n\n if (seed === (seed | 0)) {\n // Seed state array using a 32-bit integer.\n w = X[0] = seed;\n } else {\n // Seed state using a string.\n seed = '' + seed;\n for (j = 0; j < seed.length; ++j) {\n X[j & 7] = (X[j & 7] << 15) ^\n (seed.charCodeAt(j) + X[(j + 1) & 7] << 13);\n }\n }\n // Enforce an array length of 8, not all zeroes.\n while (X.length < 8) X.push(0);\n for (j = 0; j < 8 && X[j] === 0; ++j);\n if (j == 8) w = X[7] = -1; else w = X[j];\n\n me.x = X;\n me.i = 0;\n\n // Discard an initial 256 values.\n for (j = 256; j > 0; --j) {\n me.next();\n }\n }\n\n init(me, seed);\n}\n\nfunction copy(f, t) {\n t.x = f.x.slice();\n t.i = f.i;\n return t;\n}\n\nfunction impl(seed, opts) {\n if (seed == null) seed = +(new Date);\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (state.x) copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xorshift7 = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n","// A Javascript implementaion of Richard Brent's Xorgens xor4096 algorithm.\n//\n// This fast non-cryptographic random number generator is designed for\n// use in Monte-Carlo algorithms. It combines a long-period xorshift\n// generator with a Weyl generator, and it passes all common batteries\n// of stasticial tests for randomness while consuming only a few nanoseconds\n// for each prng generated. For background on the generator, see Brent's\n// paper: \"Some long-period random number generators using shifts and xors.\"\n// http://arxiv.org/pdf/1004.3115v1.pdf\n//\n// Usage:\n//\n// var xor4096 = require('xor4096');\n// random = xor4096(1); // Seed with int32 or string.\n// assert.equal(random(), 0.1520436450538547); // (0, 1) range, 53 bits.\n// assert.equal(random.int32(), 1806534897); // signed int32, 32 bits.\n//\n// For nonzero numeric keys, this impelementation provides a sequence\n// identical to that by Brent's xorgens 3 implementaion in C. This\n// implementation also provides for initalizing the generator with\n// string seeds, or for saving and restoring the state of the generator.\n//\n// On Chrome, this prng benchmarks about 2.1 times slower than\n// Javascript's built-in Math.random().\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this;\n\n // Set up generator function.\n me.next = function() {\n var w = me.w,\n X = me.X, i = me.i, t, v;\n // Update Weyl generator.\n me.w = w = (w + 0x61c88647) | 0;\n // Update xor generator.\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n // Update Xor generator array state.\n v = X[i] = v ^ t;\n me.i = i;\n // Result is the combination.\n return (v + (w ^ (w >>> 16))) | 0;\n };\n\n function init(me, seed) {\n var t, v, i, j, w, X = [], limit = 128;\n if (seed === (seed | 0)) {\n // Numeric seeds initialize v, which is used to generates X.\n v = seed;\n seed = null;\n } else {\n // String seeds are mixed into v and X one character at a time.\n seed = seed + '\\0';\n v = 0;\n limit = Math.max(limit, seed.length);\n }\n // Initialize circular array and weyl value.\n for (i = 0, j = -32; j < limit; ++j) {\n // Put the unicode characters into the array, and shuffle them.\n if (seed) v ^= seed.charCodeAt((j + 32) % seed.length);\n // After 32 shuffles, take v as the starting w value.\n if (j === 0) w = v;\n v ^= v << 10;\n v ^= v >>> 15;\n v ^= v << 4;\n v ^= v >>> 13;\n if (j >= 0) {\n w = (w + 0x61c88647) | 0; // Weyl.\n t = (X[j & 127] ^= (v + w)); // Combine xor and weyl to init array.\n i = (0 == t) ? i + 1 : 0; // Count zeroes.\n }\n }\n // We have detected all zeroes; make the key nonzero.\n if (i >= 128) {\n X[(seed && seed.length || 0) & 127] = -1;\n }\n // Run the generator 512 times to further mix the state before using it.\n // Factoring this as a function slows the main generator, so it is just\n // unrolled here. The weyl generator is not advanced while warming up.\n i = 127;\n for (j = 4 * 128; j > 0; --j) {\n v = X[(i + 34) & 127];\n t = X[i = ((i + 1) & 127)];\n v ^= v << 13;\n t ^= t << 17;\n v ^= v >>> 15;\n t ^= t >>> 12;\n X[i] = v ^ t;\n }\n // Storing state as object members is faster than using closure variables.\n me.w = w;\n me.X = X;\n me.i = i;\n }\n\n init(me, seed);\n}\n\nfunction copy(f, t) {\n t.i = f.i;\n t.w = f.w;\n t.X = f.X.slice();\n return t;\n};\n\nfunction impl(seed, opts) {\n if (seed == null) seed = +(new Date);\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (state.X) copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.xor4096 = impl;\n}\n\n})(\n this, // window object or global\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n","// A Javascript implementaion of the \"Tyche-i\" prng algorithm by\n// Samuel Neves and Filipe Araujo.\n// See https://eden.dei.uc.pt/~sneves/pubs/2011-snfa2.pdf\n\n(function(global, module, define) {\n\nfunction XorGen(seed) {\n var me = this, strseed = '';\n\n // Set up generator function.\n me.next = function() {\n var b = me.b, c = me.c, d = me.d, a = me.a;\n b = (b << 25) ^ (b >>> 7) ^ c;\n c = (c - d) | 0;\n d = (d << 24) ^ (d >>> 8) ^ a;\n a = (a - b) | 0;\n me.b = b = (b << 20) ^ (b >>> 12) ^ c;\n me.c = c = (c - d) | 0;\n me.d = (d << 16) ^ (c >>> 16) ^ a;\n return me.a = (a - b) | 0;\n };\n\n /* The following is non-inverted tyche, which has better internal\n * bit diffusion, but which is about 25% slower than tyche-i in JS.\n me.next = function() {\n var a = me.a, b = me.b, c = me.c, d = me.d;\n a = (me.a + me.b | 0) >>> 0;\n d = me.d ^ a; d = d << 16 ^ d >>> 16;\n c = me.c + d | 0;\n b = me.b ^ c; b = b << 12 ^ d >>> 20;\n me.a = a = a + b | 0;\n d = d ^ a; me.d = d = d << 8 ^ d >>> 24;\n me.c = c = c + d | 0;\n b = b ^ c;\n return me.b = (b << 7 ^ b >>> 25);\n }\n */\n\n me.a = 0;\n me.b = 0;\n me.c = 2654435769 | 0;\n me.d = 1367130551;\n\n if (seed === Math.floor(seed)) {\n // Integer seed.\n me.a = (seed / 0x100000000) | 0;\n me.b = seed | 0;\n } else {\n // String seed.\n strseed += seed;\n }\n\n // Mix in string seed, then discard an initial batch of 64 values.\n for (var k = 0; k < strseed.length + 20; k++) {\n me.b ^= strseed.charCodeAt(k) | 0;\n me.next();\n }\n}\n\nfunction copy(f, t) {\n t.a = f.a;\n t.b = f.b;\n t.c = f.c;\n t.d = f.d;\n return t;\n};\n\nfunction impl(seed, opts) {\n var xg = new XorGen(seed),\n state = opts && opts.state,\n prng = function() { return (xg.next() >>> 0) / 0x100000000; };\n prng.double = function() {\n do {\n var top = xg.next() >>> 11,\n bot = (xg.next() >>> 0) / 0x100000000,\n result = (top + bot) / (1 << 21);\n } while (result === 0);\n return result;\n };\n prng.int32 = xg.next;\n prng.quick = prng;\n if (state) {\n if (typeof(state) == 'object') copy(state, xg);\n prng.state = function() { return copy(xg, {}); }\n }\n return prng;\n}\n\nif (module && module.exports) {\n module.exports = impl;\n} else if (define && define.amd) {\n define(function() { return impl; });\n} else {\n this.tychei = impl;\n}\n\n})(\n this,\n (typeof module) == 'object' && module, // present in node.js\n (typeof define) == 'function' && define // present with an AMD loader\n);\n\n\n","/*\nCopyright 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","var scope = (typeof global !== \"undefined\" && global) ||\n (typeof self !== \"undefined\" && self) ||\n window;\nvar apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(scope, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\nrequire(\"setimmediate\");\n// On some exotic environments, it's not clear which object `setimmediate` was\n// able to install onto. Search each possibility in the same order as the\n// `setimmediate` library.\nexports.setImmediate = (typeof self !== \"undefined\" && self.setImmediate) ||\n (typeof global !== \"undefined\" && global.setImmediate) ||\n (this && this.setImmediate);\nexports.clearImmediate = (typeof self !== \"undefined\" && self.clearImmediate) ||\n (typeof global !== \"undefined\" && global.clearImmediate) ||\n (this && this.clearImmediate);\n","(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var script = doc.createElement(\"script\");\n script.onreadystatechange = function () {\n runIfPresent(handle);\n script.onreadystatechange = null;\n html.removeChild(script);\n script = null;\n };\n html.appendChild(script);\n };\n }\n\n function installSetTimeoutImplementation() {\n registerImmediate = function(handle) {\n setTimeout(runIfPresent, 0, handle);\n };\n }\n\n // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.\n var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);\n attachTo = attachTo && attachTo.setTimeout ? attachTo : global;\n\n // Don't get fooled by e.g. browserify environments.\n if ({}.toString.call(global.process) === \"[object process]\") {\n // For Node.js before 0.9\n installNextTickImplementation();\n\n } else if (canUsePostMessage()) {\n // For non-IE10 modern browsers\n installPostMessageImplementation();\n\n } else if (global.MessageChannel) {\n // For web workers, where supported\n installMessageChannelImplementation();\n\n } else if (doc && \"onreadystatechange\" in doc.createElement(\"script\")) {\n // For IE 6–8\n installReadyStateChangeImplementation();\n\n } else {\n // For older browsers\n installSetTimeoutImplementation();\n }\n\n attachTo.setImmediate = setImmediate;\n attachTo.clearImmediate = clearImmediate;\n}(typeof self === \"undefined\" ? typeof global === \"undefined\" ? this : global : self));\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","/** @license React v17.0.2\n * react-jsx-runtime.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';require(\"object-assign\");var f=require(\"react\"),g=60103;exports.Fragment=60107;if(\"function\"===typeof Symbol&&Symbol.for){var h=Symbol.for;g=h(\"react.element\");exports.Fragment=h(\"react.fragment\")}var m=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n=Object.prototype.hasOwnProperty,p={key:!0,ref:!0,__self:!0,__source:!0};\nfunction q(c,a,k){var b,d={},e=null,l=null;void 0!==k&&(e=\"\"+k);void 0!==a.key&&(e=\"\"+a.key);void 0!==a.ref&&(l=a.ref);for(b in a)n.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:g,type:c,key:e,ref:l,props:d,_owner:m.current}}exports.jsx=q;exports.jsxs=q;\n","/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};\n","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nexport function isPlainObject(item) {\n return item && _typeof(item) === 'object' && item.constructor === Object;\n}\nexport default function deepmerge(target, source) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {\n clone: true\n };\n var output = options.clone ? _extends({}, target) : target;\n\n if (isPlainObject(target) && isPlainObject(source)) {\n Object.keys(source).forEach(function (key) {\n // Avoid prototype pollution\n if (key === '__proto__') {\n return;\n }\n\n if (isPlainObject(source[key]) && key in target) {\n output[key] = deepmerge(target[key], source[key], options);\n } else {\n output[key] = source[key];\n }\n });\n }\n\n return output;\n}","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n var elevations = {};\n theme.shadows.forEach(function (shadow, index) {\n elevations[\"elevation\".concat(index)] = {\n boxShadow: shadow\n };\n });\n return _extends({\n /* Styles applied to the root element. */\n root: {\n backgroundColor: theme.palette.background.paper,\n color: theme.palette.text.primary,\n transition: theme.transitions.create('box-shadow')\n },\n\n /* Styles applied to the root element if `square={false}`. */\n rounded: {\n borderRadius: theme.shape.borderRadius\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"`. */\n outlined: {\n border: \"1px solid \".concat(theme.palette.divider)\n }\n }, elevations);\n};\nvar Paper = /*#__PURE__*/React.forwardRef(function Paper(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n _props$square = props.square,\n square = _props$square === void 0 ? false : _props$square,\n _props$elevation = props.elevation,\n elevation = _props$elevation === void 0 ? 1 : _props$elevation,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'elevation' : _props$variant,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"component\", \"square\", \"elevation\", \"variant\"]);\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, variant === 'outlined' ? classes.outlined : classes[\"elevation\".concat(elevation)], !square && classes.rounded),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? Paper.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * Shadow depth, corresponds to `dp` in the spec.\n * It accepts values between 0 and 24 inclusive.\n */\n elevation: chainPropTypes(PropTypes.number, function (props) {\n var classes = props.classes,\n elevation = props.elevation; // in case `withStyles` fails to inject we don't need this warning\n\n if (classes === undefined) {\n return null;\n }\n\n if (elevation != null && classes[\"elevation\".concat(elevation)] === undefined) {\n return new Error(\"Material-UI: This elevation `\".concat(elevation, \"` is not implemented.\"));\n }\n\n return null;\n }),\n\n /**\n * If `true`, rounded corners are disabled.\n */\n square: PropTypes.bool,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['elevation', 'outlined'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiPaper'\n})(Paper);","var _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nexport var isBrowser = (typeof window === \"undefined\" ? \"undefined\" : _typeof(window)) === \"object\" && (typeof document === \"undefined\" ? \"undefined\" : _typeof(document)) === 'object' && document.nodeType === 9;\n\nexport default isBrowser;\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport isInBrowser from 'is-in-browser';\nimport warning from 'tiny-warning';\nimport _createClass from '@babel/runtime/helpers/esm/createClass';\nimport _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose';\nimport _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized';\nimport _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose';\n\nvar plainObjectConstrurctor = {}.constructor;\nfunction cloneStyle(style) {\n if (style == null || typeof style !== 'object') return style;\n if (Array.isArray(style)) return style.map(cloneStyle);\n if (style.constructor !== plainObjectConstrurctor) return style;\n var newStyle = {};\n\n for (var name in style) {\n newStyle[name] = cloneStyle(style[name]);\n }\n\n return newStyle;\n}\n\n/**\n * Create a rule instance.\n */\n\nfunction createRule(name, decl, options) {\n if (name === void 0) {\n name = 'unnamed';\n }\n\n var jss = options.jss;\n var declCopy = cloneStyle(decl);\n var rule = jss.plugins.onCreateRule(name, declCopy, options);\n if (rule) return rule; // It is an at-rule and it has no instance.\n\n if (name[0] === '@') {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Unknown rule \" + name) : void 0;\n }\n\n return null;\n}\n\nvar join = function join(value, by) {\n var result = '';\n\n for (var i = 0; i < value.length; i++) {\n // Remove !important from the value, it will be readded later.\n if (value[i] === '!important') break;\n if (result) result += by;\n result += value[i];\n }\n\n return result;\n};\n\n/**\n * Converts array values to string.\n *\n * `margin: [['5px', '10px']]` > `margin: 5px 10px;`\n * `border: ['1px', '2px']` > `border: 1px, 2px;`\n * `margin: [['5px', '10px'], '!important']` > `margin: 5px 10px !important;`\n * `color: ['red', !important]` > `color: red !important;`\n */\nvar toCssValue = function toCssValue(value, ignoreImportant) {\n if (ignoreImportant === void 0) {\n ignoreImportant = false;\n }\n\n if (!Array.isArray(value)) return value;\n var cssValue = ''; // Support space separated values via `[['5px', '10px']]`.\n\n if (Array.isArray(value[0])) {\n for (var i = 0; i < value.length; i++) {\n if (value[i] === '!important') break;\n if (cssValue) cssValue += ', ';\n cssValue += join(value[i], ' ');\n }\n } else cssValue = join(value, ', '); // Add !important, because it was ignored.\n\n\n if (!ignoreImportant && value[value.length - 1] === '!important') {\n cssValue += ' !important';\n }\n\n return cssValue;\n};\n\n/**\n * Indent a string.\n * http://jsperf.com/array-join-vs-for\n */\nfunction indentStr(str, indent) {\n var result = '';\n\n for (var index = 0; index < indent; index++) {\n result += ' ';\n }\n\n return result + str;\n}\n/**\n * Converts a Rule to CSS string.\n */\n\n\nfunction toCss(selector, style, options) {\n if (options === void 0) {\n options = {};\n }\n\n var result = '';\n if (!style) return result;\n var _options = options,\n _options$indent = _options.indent,\n indent = _options$indent === void 0 ? 0 : _options$indent;\n var fallbacks = style.fallbacks;\n if (selector) indent++; // Apply fallbacks first.\n\n if (fallbacks) {\n // Array syntax {fallbacks: [{prop: value}]}\n if (Array.isArray(fallbacks)) {\n for (var index = 0; index < fallbacks.length; index++) {\n var fallback = fallbacks[index];\n\n for (var prop in fallback) {\n var value = fallback[prop];\n\n if (value != null) {\n if (result) result += '\\n';\n result += \"\" + indentStr(prop + \": \" + toCssValue(value) + \";\", indent);\n }\n }\n }\n } else {\n // Object syntax {fallbacks: {prop: value}}\n for (var _prop in fallbacks) {\n var _value = fallbacks[_prop];\n\n if (_value != null) {\n if (result) result += '\\n';\n result += \"\" + indentStr(_prop + \": \" + toCssValue(_value) + \";\", indent);\n }\n }\n }\n }\n\n for (var _prop2 in style) {\n var _value2 = style[_prop2];\n\n if (_value2 != null && _prop2 !== 'fallbacks') {\n if (result) result += '\\n';\n result += \"\" + indentStr(_prop2 + \": \" + toCssValue(_value2) + \";\", indent);\n }\n } // Allow empty style in this case, because properties will be added dynamically.\n\n\n if (!result && !options.allowEmpty) return result; // When rule is being stringified before selector was defined.\n\n if (!selector) return result;\n indent--;\n if (result) result = \"\\n\" + result + \"\\n\";\n return indentStr(selector + \" {\" + result, indent) + indentStr('}', indent);\n}\n\nvar escapeRegex = /([[\\].#*$><+~=|^:(),\"'`\\s])/g;\nvar nativeEscape = typeof CSS !== 'undefined' && CSS.escape;\nvar escape = (function (str) {\n return nativeEscape ? nativeEscape(str) : str.replace(escapeRegex, '\\\\$1');\n});\n\nvar BaseStyleRule =\n/*#__PURE__*/\nfunction () {\n function BaseStyleRule(key, style, options) {\n this.type = 'style';\n this.key = void 0;\n this.isProcessed = false;\n this.style = void 0;\n this.renderer = void 0;\n this.renderable = void 0;\n this.options = void 0;\n var sheet = options.sheet,\n Renderer = options.Renderer;\n this.key = key;\n this.options = options;\n this.style = style;\n if (sheet) this.renderer = sheet.renderer;else if (Renderer) this.renderer = new Renderer();\n }\n /**\n * Get or set a style property.\n */\n\n\n var _proto = BaseStyleRule.prototype;\n\n _proto.prop = function prop(name, value, options) {\n // It's a getter.\n if (value === undefined) return this.style[name]; // Don't do anything if the value has not changed.\n\n var force = options ? options.force : false;\n if (!force && this.style[name] === value) return this;\n var newValue = value;\n\n if (!options || options.process !== false) {\n newValue = this.options.jss.plugins.onChangeValue(value, name, this);\n }\n\n var isEmpty = newValue == null || newValue === false;\n var isDefined = name in this.style; // Value is empty and wasn't defined before.\n\n if (isEmpty && !isDefined && !force) return this; // We are going to remove this value.\n\n var remove = isEmpty && isDefined;\n if (remove) delete this.style[name];else this.style[name] = newValue; // Renderable is defined if StyleSheet option `link` is true.\n\n if (this.renderable && this.renderer) {\n if (remove) this.renderer.removeProperty(this.renderable, name);else this.renderer.setProperty(this.renderable, name, newValue);\n return this;\n }\n\n var sheet = this.options.sheet;\n\n if (sheet && sheet.attached) {\n process.env.NODE_ENV !== \"production\" ? warning(false, '[JSS] Rule is not linked. Missing sheet option \"link: true\".') : void 0;\n }\n\n return this;\n };\n\n return BaseStyleRule;\n}();\nvar StyleRule =\n/*#__PURE__*/\nfunction (_BaseStyleRule) {\n _inheritsLoose(StyleRule, _BaseStyleRule);\n\n function StyleRule(key, style, options) {\n var _this;\n\n _this = _BaseStyleRule.call(this, key, style, options) || this;\n _this.selectorText = void 0;\n _this.id = void 0;\n _this.renderable = void 0;\n var selector = options.selector,\n scoped = options.scoped,\n sheet = options.sheet,\n generateId = options.generateId;\n\n if (selector) {\n _this.selectorText = selector;\n } else if (scoped !== false) {\n _this.id = generateId(_assertThisInitialized(_assertThisInitialized(_this)), sheet);\n _this.selectorText = \".\" + escape(_this.id);\n }\n\n return _this;\n }\n /**\n * Set selector string.\n * Attention: use this with caution. Most browsers didn't implement\n * selectorText setter, so this may result in rerendering of entire Style Sheet.\n */\n\n\n var _proto2 = StyleRule.prototype;\n\n /**\n * Apply rule to an element inline.\n */\n _proto2.applyTo = function applyTo(renderable) {\n var renderer = this.renderer;\n\n if (renderer) {\n var json = this.toJSON();\n\n for (var prop in json) {\n renderer.setProperty(renderable, prop, json[prop]);\n }\n }\n\n return this;\n }\n /**\n * Returns JSON representation of the rule.\n * Fallbacks are not supported.\n * Useful for inline styles.\n */\n ;\n\n _proto2.toJSON = function toJSON() {\n var json = {};\n\n for (var prop in this.style) {\n var value = this.style[prop];\n if (typeof value !== 'object') json[prop] = value;else if (Array.isArray(value)) json[prop] = toCssValue(value);\n }\n\n return json;\n }\n /**\n * Generates a CSS string.\n */\n ;\n\n _proto2.toString = function toString(options) {\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n var opts = link ? _extends({}, options, {\n allowEmpty: true\n }) : options;\n return toCss(this.selectorText, this.style, opts);\n };\n\n _createClass(StyleRule, [{\n key: \"selector\",\n set: function set(selector) {\n if (selector === this.selectorText) return;\n this.selectorText = selector;\n var renderer = this.renderer,\n renderable = this.renderable;\n if (!renderable || !renderer) return;\n var hasChanged = renderer.setSelector(renderable, selector); // If selector setter is not implemented, rerender the rule.\n\n if (!hasChanged) {\n renderer.replaceRule(renderable, this);\n }\n }\n /**\n * Get selector string.\n */\n ,\n get: function get() {\n return this.selectorText;\n }\n }]);\n\n return StyleRule;\n}(BaseStyleRule);\nvar pluginStyleRule = {\n onCreateRule: function onCreateRule(name, style, options) {\n if (name[0] === '@' || options.parent && options.parent.type === 'keyframes') {\n return null;\n }\n\n return new StyleRule(name, style, options);\n }\n};\n\nvar defaultToStringOptions = {\n indent: 1,\n children: true\n};\nvar atRegExp = /@([\\w-]+)/;\n/**\n * Conditional rule for @media, @supports\n */\n\nvar ConditionalRule =\n/*#__PURE__*/\nfunction () {\n function ConditionalRule(key, styles, options) {\n this.type = 'conditional';\n this.at = void 0;\n this.key = void 0;\n this.query = void 0;\n this.rules = void 0;\n this.options = void 0;\n this.isProcessed = false;\n this.renderable = void 0;\n this.key = key;\n var atMatch = key.match(atRegExp);\n this.at = atMatch ? atMatch[1] : 'unknown'; // Key might contain a unique suffix in case the `name` passed by user was duplicate.\n\n this.query = options.name || \"@\" + this.at;\n this.options = options;\n this.rules = new RuleList(_extends({}, options, {\n parent: this\n }));\n\n for (var name in styles) {\n this.rules.add(name, styles[name]);\n }\n\n this.rules.process();\n }\n /**\n * Get a rule.\n */\n\n\n var _proto = ConditionalRule.prototype;\n\n _proto.getRule = function getRule(name) {\n return this.rules.get(name);\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.rules.indexOf(rule);\n }\n /**\n * Create and register rule, run plugins.\n */\n ;\n\n _proto.addRule = function addRule(name, style, options) {\n var rule = this.rules.add(name, style, options);\n if (!rule) return null;\n this.options.jss.plugins.onProcessRule(rule);\n return rule;\n }\n /**\n * Generates a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n if (options === void 0) {\n options = defaultToStringOptions;\n }\n\n if (options.indent == null) options.indent = defaultToStringOptions.indent;\n if (options.children == null) options.children = defaultToStringOptions.children;\n\n if (options.children === false) {\n return this.query + \" {}\";\n }\n\n var children = this.rules.toString(options);\n return children ? this.query + \" {\\n\" + children + \"\\n}\" : '';\n };\n\n return ConditionalRule;\n}();\nvar keyRegExp = /@media|@supports\\s+/;\nvar pluginConditionalRule = {\n onCreateRule: function onCreateRule(key, styles, options) {\n return keyRegExp.test(key) ? new ConditionalRule(key, styles, options) : null;\n }\n};\n\nvar defaultToStringOptions$1 = {\n indent: 1,\n children: true\n};\nvar nameRegExp = /@keyframes\\s+([\\w-]+)/;\n/**\n * Rule for @keyframes\n */\n\nvar KeyframesRule =\n/*#__PURE__*/\nfunction () {\n function KeyframesRule(key, frames, options) {\n this.type = 'keyframes';\n this.at = '@keyframes';\n this.key = void 0;\n this.name = void 0;\n this.id = void 0;\n this.rules = void 0;\n this.options = void 0;\n this.isProcessed = false;\n this.renderable = void 0;\n var nameMatch = key.match(nameRegExp);\n\n if (nameMatch && nameMatch[1]) {\n this.name = nameMatch[1];\n } else {\n this.name = 'noname';\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Bad keyframes name \" + key) : void 0;\n }\n\n this.key = this.type + \"-\" + this.name;\n this.options = options;\n var scoped = options.scoped,\n sheet = options.sheet,\n generateId = options.generateId;\n this.id = scoped === false ? this.name : escape(generateId(this, sheet));\n this.rules = new RuleList(_extends({}, options, {\n parent: this\n }));\n\n for (var name in frames) {\n this.rules.add(name, frames[name], _extends({}, options, {\n parent: this\n }));\n }\n\n this.rules.process();\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = KeyframesRule.prototype;\n\n _proto.toString = function toString(options) {\n if (options === void 0) {\n options = defaultToStringOptions$1;\n }\n\n if (options.indent == null) options.indent = defaultToStringOptions$1.indent;\n if (options.children == null) options.children = defaultToStringOptions$1.children;\n\n if (options.children === false) {\n return this.at + \" \" + this.id + \" {}\";\n }\n\n var children = this.rules.toString(options);\n if (children) children = \"\\n\" + children + \"\\n\";\n return this.at + \" \" + this.id + \" {\" + children + \"}\";\n };\n\n return KeyframesRule;\n}();\nvar keyRegExp$1 = /@keyframes\\s+/;\nvar refRegExp = /\\$([\\w-]+)/g;\n\nvar findReferencedKeyframe = function findReferencedKeyframe(val, keyframes) {\n if (typeof val === 'string') {\n return val.replace(refRegExp, function (match, name) {\n if (name in keyframes) {\n return keyframes[name];\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Referenced keyframes rule \\\"\" + name + \"\\\" is not defined.\") : void 0;\n return match;\n });\n }\n\n return val;\n};\n/**\n * Replace the reference for a animation name.\n */\n\n\nvar replaceRef = function replaceRef(style, prop, keyframes) {\n var value = style[prop];\n var refKeyframe = findReferencedKeyframe(value, keyframes);\n\n if (refKeyframe !== value) {\n style[prop] = refKeyframe;\n }\n};\n\nvar plugin = {\n onCreateRule: function onCreateRule(key, frames, options) {\n return typeof key === 'string' && keyRegExp$1.test(key) ? new KeyframesRule(key, frames, options) : null;\n },\n // Animation name ref replacer.\n onProcessStyle: function onProcessStyle(style, rule, sheet) {\n if (rule.type !== 'style' || !sheet) return style;\n if ('animation-name' in style) replaceRef(style, 'animation-name', sheet.keyframes);\n if ('animation' in style) replaceRef(style, 'animation', sheet.keyframes);\n return style;\n },\n onChangeValue: function onChangeValue(val, prop, rule) {\n var sheet = rule.options.sheet;\n\n if (!sheet) {\n return val;\n }\n\n switch (prop) {\n case 'animation':\n return findReferencedKeyframe(val, sheet.keyframes);\n\n case 'animation-name':\n return findReferencedKeyframe(val, sheet.keyframes);\n\n default:\n return val;\n }\n }\n};\n\nvar KeyframeRule =\n/*#__PURE__*/\nfunction (_BaseStyleRule) {\n _inheritsLoose(KeyframeRule, _BaseStyleRule);\n\n function KeyframeRule() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _BaseStyleRule.call.apply(_BaseStyleRule, [this].concat(args)) || this;\n _this.renderable = void 0;\n return _this;\n }\n\n var _proto = KeyframeRule.prototype;\n\n /**\n * Generates a CSS string.\n */\n _proto.toString = function toString(options) {\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n var opts = link ? _extends({}, options, {\n allowEmpty: true\n }) : options;\n return toCss(this.key, this.style, opts);\n };\n\n return KeyframeRule;\n}(BaseStyleRule);\nvar pluginKeyframeRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n if (options.parent && options.parent.type === 'keyframes') {\n return new KeyframeRule(key, style, options);\n }\n\n return null;\n }\n};\n\nvar FontFaceRule =\n/*#__PURE__*/\nfunction () {\n function FontFaceRule(key, style, options) {\n this.type = 'font-face';\n this.at = '@font-face';\n this.key = void 0;\n this.style = void 0;\n this.options = void 0;\n this.isProcessed = false;\n this.renderable = void 0;\n this.key = key;\n this.style = style;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = FontFaceRule.prototype;\n\n _proto.toString = function toString(options) {\n if (Array.isArray(this.style)) {\n var str = '';\n\n for (var index = 0; index < this.style.length; index++) {\n str += toCss(this.at, this.style[index]);\n if (this.style[index + 1]) str += '\\n';\n }\n\n return str;\n }\n\n return toCss(this.at, this.style, options);\n };\n\n return FontFaceRule;\n}();\nvar keyRegExp$2 = /@font-face/;\nvar pluginFontFaceRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n return keyRegExp$2.test(key) ? new FontFaceRule(key, style, options) : null;\n }\n};\n\nvar ViewportRule =\n/*#__PURE__*/\nfunction () {\n function ViewportRule(key, style, options) {\n this.type = 'viewport';\n this.at = '@viewport';\n this.key = void 0;\n this.style = void 0;\n this.options = void 0;\n this.isProcessed = false;\n this.renderable = void 0;\n this.key = key;\n this.style = style;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n\n\n var _proto = ViewportRule.prototype;\n\n _proto.toString = function toString(options) {\n return toCss(this.key, this.style, options);\n };\n\n return ViewportRule;\n}();\nvar pluginViewportRule = {\n onCreateRule: function onCreateRule(key, style, options) {\n return key === '@viewport' || key === '@-ms-viewport' ? new ViewportRule(key, style, options) : null;\n }\n};\n\nvar SimpleRule =\n/*#__PURE__*/\nfunction () {\n function SimpleRule(key, value, options) {\n this.type = 'simple';\n this.key = void 0;\n this.value = void 0;\n this.options = void 0;\n this.isProcessed = false;\n this.renderable = void 0;\n this.key = key;\n this.value = value;\n this.options = options;\n }\n /**\n * Generates a CSS string.\n */\n // eslint-disable-next-line no-unused-vars\n\n\n var _proto = SimpleRule.prototype;\n\n _proto.toString = function toString(options) {\n if (Array.isArray(this.value)) {\n var str = '';\n\n for (var index = 0; index < this.value.length; index++) {\n str += this.key + \" \" + this.value[index] + \";\";\n if (this.value[index + 1]) str += '\\n';\n }\n\n return str;\n }\n\n return this.key + \" \" + this.value + \";\";\n };\n\n return SimpleRule;\n}();\nvar keysMap = {\n '@charset': true,\n '@import': true,\n '@namespace': true\n};\nvar pluginSimpleRule = {\n onCreateRule: function onCreateRule(key, value, options) {\n return key in keysMap ? new SimpleRule(key, value, options) : null;\n }\n};\n\nvar plugins = [pluginStyleRule, pluginConditionalRule, plugin, pluginKeyframeRule, pluginFontFaceRule, pluginViewportRule, pluginSimpleRule];\n\nvar defaultUpdateOptions = {\n process: true\n};\nvar forceUpdateOptions = {\n force: true,\n process: true\n /**\n * Contains rules objects and allows adding/removing etc.\n * Is used for e.g. by `StyleSheet` or `ConditionalRule`.\n */\n\n};\n\nvar RuleList =\n/*#__PURE__*/\nfunction () {\n // Rules registry for access by .get() method.\n // It contains the same rule registered by name and by selector.\n // Original styles object.\n // Used to ensure correct rules order.\n function RuleList(options) {\n this.map = {};\n this.raw = {};\n this.index = [];\n this.counter = 0;\n this.options = void 0;\n this.classes = void 0;\n this.keyframes = void 0;\n this.options = options;\n this.classes = options.classes;\n this.keyframes = options.keyframes;\n }\n /**\n * Create and register rule.\n *\n * Will not render after Style Sheet was rendered the first time.\n */\n\n\n var _proto = RuleList.prototype;\n\n _proto.add = function add(name, decl, ruleOptions) {\n var _this$options = this.options,\n parent = _this$options.parent,\n sheet = _this$options.sheet,\n jss = _this$options.jss,\n Renderer = _this$options.Renderer,\n generateId = _this$options.generateId,\n scoped = _this$options.scoped;\n\n var options = _extends({\n classes: this.classes,\n parent: parent,\n sheet: sheet,\n jss: jss,\n Renderer: Renderer,\n generateId: generateId,\n scoped: scoped,\n name: name,\n keyframes: this.keyframes,\n selector: undefined\n }, ruleOptions); // When user uses .createStyleSheet(), duplicate names are not possible, but\n // `sheet.addRule()` opens the door for any duplicate rule name. When this happens\n // we need to make the key unique within this RuleList instance scope.\n\n\n var key = name;\n\n if (name in this.raw) {\n key = name + \"-d\" + this.counter++;\n } // We need to save the original decl before creating the rule\n // because cache plugin needs to use it as a key to return a cached rule.\n\n\n this.raw[key] = decl;\n\n if (key in this.classes) {\n // E.g. rules inside of @media container\n options.selector = \".\" + escape(this.classes[key]);\n }\n\n var rule = createRule(key, decl, options);\n if (!rule) return null;\n this.register(rule);\n var index = options.index === undefined ? this.index.length : options.index;\n this.index.splice(index, 0, rule);\n return rule;\n }\n /**\n * Get a rule.\n */\n ;\n\n _proto.get = function get(name) {\n return this.map[name];\n }\n /**\n * Delete a rule.\n */\n ;\n\n _proto.remove = function remove(rule) {\n this.unregister(rule);\n delete this.raw[rule.key];\n this.index.splice(this.index.indexOf(rule), 1);\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.index.indexOf(rule);\n }\n /**\n * Run `onProcessRule()` plugins on every rule.\n */\n ;\n\n _proto.process = function process() {\n var plugins = this.options.jss.plugins; // We need to clone array because if we modify the index somewhere else during a loop\n // we end up with very hard-to-track-down side effects.\n\n this.index.slice(0).forEach(plugins.onProcessRule, plugins);\n }\n /**\n * Register a rule in `.map`, `.classes` and `.keyframes` maps.\n */\n ;\n\n _proto.register = function register(rule) {\n this.map[rule.key] = rule;\n\n if (rule instanceof StyleRule) {\n this.map[rule.selector] = rule;\n if (rule.id) this.classes[rule.key] = rule.id;\n } else if (rule instanceof KeyframesRule && this.keyframes) {\n this.keyframes[rule.name] = rule.id;\n }\n }\n /**\n * Unregister a rule.\n */\n ;\n\n _proto.unregister = function unregister(rule) {\n delete this.map[rule.key];\n\n if (rule instanceof StyleRule) {\n delete this.map[rule.selector];\n delete this.classes[rule.key];\n } else if (rule instanceof KeyframesRule) {\n delete this.keyframes[rule.name];\n }\n }\n /**\n * Update the function values with a new data.\n */\n ;\n\n _proto.update = function update() {\n var name;\n var data;\n var options;\n\n if (typeof (arguments.length <= 0 ? undefined : arguments[0]) === 'string') {\n name = arguments.length <= 0 ? undefined : arguments[0]; // $FlowFixMe[invalid-tuple-index]\n\n data = arguments.length <= 1 ? undefined : arguments[1]; // $FlowFixMe[invalid-tuple-index]\n\n options = arguments.length <= 2 ? undefined : arguments[2];\n } else {\n data = arguments.length <= 0 ? undefined : arguments[0]; // $FlowFixMe[invalid-tuple-index]\n\n options = arguments.length <= 1 ? undefined : arguments[1];\n name = null;\n }\n\n if (name) {\n this.updateOne(this.map[name], data, options);\n } else {\n for (var index = 0; index < this.index.length; index++) {\n this.updateOne(this.index[index], data, options);\n }\n }\n }\n /**\n * Execute plugins, update rule props.\n */\n ;\n\n _proto.updateOne = function updateOne(rule, data, options) {\n if (options === void 0) {\n options = defaultUpdateOptions;\n }\n\n var _this$options2 = this.options,\n plugins = _this$options2.jss.plugins,\n sheet = _this$options2.sheet; // It is a rules container like for e.g. ConditionalRule.\n\n if (rule.rules instanceof RuleList) {\n rule.rules.update(data, options);\n return;\n }\n\n var styleRule = rule;\n var style = styleRule.style;\n plugins.onUpdate(data, rule, sheet, options); // We rely on a new `style` ref in case it was mutated during onUpdate hook.\n\n if (options.process && style && style !== styleRule.style) {\n // We need to run the plugins in case new `style` relies on syntax plugins.\n plugins.onProcessStyle(styleRule.style, styleRule, sheet); // Update and add props.\n\n for (var prop in styleRule.style) {\n var nextValue = styleRule.style[prop];\n var prevValue = style[prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule.\n // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here.\n\n if (nextValue !== prevValue) {\n styleRule.prop(prop, nextValue, forceUpdateOptions);\n }\n } // Remove props.\n\n\n for (var _prop in style) {\n var _nextValue = styleRule.style[_prop];\n var _prevValue = style[_prop]; // We need to use `force: true` because `rule.style` has been updated during onUpdate hook, so `rule.prop()` will not update the CSSOM rule.\n // We do this comparison to avoid unneeded `rule.prop()` calls, since we have the old `style` object here.\n\n if (_nextValue == null && _nextValue !== _prevValue) {\n styleRule.prop(_prop, null, forceUpdateOptions);\n }\n }\n }\n }\n /**\n * Convert rules to a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n var str = '';\n var sheet = this.options.sheet;\n var link = sheet ? sheet.options.link : false;\n\n for (var index = 0; index < this.index.length; index++) {\n var rule = this.index[index];\n var css = rule.toString(options); // No need to render an empty rule.\n\n if (!css && !link) continue;\n if (str) str += '\\n';\n str += css;\n }\n\n return str;\n };\n\n return RuleList;\n}();\n\nvar StyleSheet =\n/*#__PURE__*/\nfunction () {\n function StyleSheet(styles, options) {\n this.options = void 0;\n this.deployed = void 0;\n this.attached = void 0;\n this.rules = void 0;\n this.renderer = void 0;\n this.classes = void 0;\n this.keyframes = void 0;\n this.queue = void 0;\n this.attached = false;\n this.deployed = false;\n this.classes = {};\n this.keyframes = {};\n this.options = _extends({}, options, {\n sheet: this,\n parent: this,\n classes: this.classes,\n keyframes: this.keyframes\n });\n\n if (options.Renderer) {\n this.renderer = new options.Renderer(this);\n }\n\n this.rules = new RuleList(this.options);\n\n for (var name in styles) {\n this.rules.add(name, styles[name]);\n }\n\n this.rules.process();\n }\n /**\n * Attach renderable to the render tree.\n */\n\n\n var _proto = StyleSheet.prototype;\n\n _proto.attach = function attach() {\n if (this.attached) return this;\n if (this.renderer) this.renderer.attach();\n this.attached = true; // Order is important, because we can't use insertRule API if style element is not attached.\n\n if (!this.deployed) this.deploy();\n return this;\n }\n /**\n * Remove renderable from render tree.\n */\n ;\n\n _proto.detach = function detach() {\n if (!this.attached) return this;\n if (this.renderer) this.renderer.detach();\n this.attached = false;\n return this;\n }\n /**\n * Add a rule to the current stylesheet.\n * Will insert a rule also after the stylesheet has been rendered first time.\n */\n ;\n\n _proto.addRule = function addRule(name, decl, options) {\n var queue = this.queue; // Plugins can create rules.\n // In order to preserve the right order, we need to queue all `.addRule` calls,\n // which happen after the first `rules.add()` call.\n\n if (this.attached && !queue) this.queue = [];\n var rule = this.rules.add(name, decl, options);\n if (!rule) return null;\n this.options.jss.plugins.onProcessRule(rule);\n\n if (this.attached) {\n if (!this.deployed) return rule; // Don't insert rule directly if there is no stringified version yet.\n // It will be inserted all together when .attach is called.\n\n if (queue) queue.push(rule);else {\n this.insertRule(rule);\n\n if (this.queue) {\n this.queue.forEach(this.insertRule, this);\n this.queue = undefined;\n }\n }\n return rule;\n } // We can't add rules to a detached style node.\n // We will redeploy the sheet once user will attach it.\n\n\n this.deployed = false;\n return rule;\n }\n /**\n * Insert rule into the StyleSheet\n */\n ;\n\n _proto.insertRule = function insertRule(rule) {\n if (this.renderer) {\n this.renderer.insertRule(rule);\n }\n }\n /**\n * Create and add rules.\n * Will render also after Style Sheet was rendered the first time.\n */\n ;\n\n _proto.addRules = function addRules(styles, options) {\n var added = [];\n\n for (var name in styles) {\n var rule = this.addRule(name, styles[name], options);\n if (rule) added.push(rule);\n }\n\n return added;\n }\n /**\n * Get a rule by name.\n */\n ;\n\n _proto.getRule = function getRule(name) {\n return this.rules.get(name);\n }\n /**\n * Delete a rule by name.\n * Returns `true`: if rule has been deleted from the DOM.\n */\n ;\n\n _proto.deleteRule = function deleteRule(name) {\n var rule = typeof name === 'object' ? name : this.rules.get(name);\n\n if (!rule || // Style sheet was created without link: true and attached, in this case we\n // won't be able to remove the CSS rule from the DOM.\n this.attached && !rule.renderable) {\n return false;\n }\n\n this.rules.remove(rule);\n\n if (this.attached && rule.renderable && this.renderer) {\n return this.renderer.deleteRule(rule.renderable);\n }\n\n return true;\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.rules.indexOf(rule);\n }\n /**\n * Deploy pure CSS string to a renderable.\n */\n ;\n\n _proto.deploy = function deploy() {\n if (this.renderer) this.renderer.deploy();\n this.deployed = true;\n return this;\n }\n /**\n * Update the function values with a new data.\n */\n ;\n\n _proto.update = function update() {\n var _this$rules;\n\n (_this$rules = this.rules).update.apply(_this$rules, arguments);\n\n return this;\n }\n /**\n * Updates a single rule.\n */\n ;\n\n _proto.updateOne = function updateOne(rule, data, options) {\n this.rules.updateOne(rule, data, options);\n return this;\n }\n /**\n * Convert rules to a CSS string.\n */\n ;\n\n _proto.toString = function toString(options) {\n return this.rules.toString(options);\n };\n\n return StyleSheet;\n}();\n\nvar PluginsRegistry =\n/*#__PURE__*/\nfunction () {\n function PluginsRegistry() {\n this.plugins = {\n internal: [],\n external: []\n };\n this.registry = void 0;\n }\n\n var _proto = PluginsRegistry.prototype;\n\n /**\n * Call `onCreateRule` hooks and return an object if returned by a hook.\n */\n _proto.onCreateRule = function onCreateRule(name, decl, options) {\n for (var i = 0; i < this.registry.onCreateRule.length; i++) {\n var rule = this.registry.onCreateRule[i](name, decl, options);\n if (rule) return rule;\n }\n\n return null;\n }\n /**\n * Call `onProcessRule` hooks.\n */\n ;\n\n _proto.onProcessRule = function onProcessRule(rule) {\n if (rule.isProcessed) return;\n var sheet = rule.options.sheet;\n\n for (var i = 0; i < this.registry.onProcessRule.length; i++) {\n this.registry.onProcessRule[i](rule, sheet);\n }\n\n if (rule.style) this.onProcessStyle(rule.style, rule, sheet);\n rule.isProcessed = true;\n }\n /**\n * Call `onProcessStyle` hooks.\n */\n ;\n\n _proto.onProcessStyle = function onProcessStyle(style, rule, sheet) {\n for (var i = 0; i < this.registry.onProcessStyle.length; i++) {\n // $FlowFixMe[prop-missing]\n rule.style = this.registry.onProcessStyle[i](rule.style, rule, sheet);\n }\n }\n /**\n * Call `onProcessSheet` hooks.\n */\n ;\n\n _proto.onProcessSheet = function onProcessSheet(sheet) {\n for (var i = 0; i < this.registry.onProcessSheet.length; i++) {\n this.registry.onProcessSheet[i](sheet);\n }\n }\n /**\n * Call `onUpdate` hooks.\n */\n ;\n\n _proto.onUpdate = function onUpdate(data, rule, sheet, options) {\n for (var i = 0; i < this.registry.onUpdate.length; i++) {\n this.registry.onUpdate[i](data, rule, sheet, options);\n }\n }\n /**\n * Call `onChangeValue` hooks.\n */\n ;\n\n _proto.onChangeValue = function onChangeValue(value, prop, rule) {\n var processedValue = value;\n\n for (var i = 0; i < this.registry.onChangeValue.length; i++) {\n processedValue = this.registry.onChangeValue[i](processedValue, prop, rule);\n }\n\n return processedValue;\n }\n /**\n * Register a plugin.\n */\n ;\n\n _proto.use = function use(newPlugin, options) {\n if (options === void 0) {\n options = {\n queue: 'external'\n };\n }\n\n var plugins = this.plugins[options.queue]; // Avoids applying same plugin twice, at least based on ref.\n\n if (plugins.indexOf(newPlugin) !== -1) {\n return;\n }\n\n plugins.push(newPlugin);\n this.registry = [].concat(this.plugins.external, this.plugins.internal).reduce(function (registry, plugin) {\n for (var name in plugin) {\n if (name in registry) {\n registry[name].push(plugin[name]);\n } else {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Unknown hook \\\"\" + name + \"\\\".\") : void 0;\n }\n }\n\n return registry;\n }, {\n onCreateRule: [],\n onProcessRule: [],\n onProcessStyle: [],\n onProcessSheet: [],\n onChangeValue: [],\n onUpdate: []\n });\n };\n\n return PluginsRegistry;\n}();\n\n/**\n * Sheets registry to access them all at one place.\n */\nvar SheetsRegistry =\n/*#__PURE__*/\nfunction () {\n function SheetsRegistry() {\n this.registry = [];\n }\n\n var _proto = SheetsRegistry.prototype;\n\n /**\n * Register a Style Sheet.\n */\n _proto.add = function add(sheet) {\n var registry = this.registry;\n var index = sheet.options.index;\n if (registry.indexOf(sheet) !== -1) return;\n\n if (registry.length === 0 || index >= this.index) {\n registry.push(sheet);\n return;\n } // Find a position.\n\n\n for (var i = 0; i < registry.length; i++) {\n if (registry[i].options.index > index) {\n registry.splice(i, 0, sheet);\n return;\n }\n }\n }\n /**\n * Reset the registry.\n */\n ;\n\n _proto.reset = function reset() {\n this.registry = [];\n }\n /**\n * Remove a Style Sheet.\n */\n ;\n\n _proto.remove = function remove(sheet) {\n var index = this.registry.indexOf(sheet);\n this.registry.splice(index, 1);\n }\n /**\n * Convert all attached sheets to a CSS string.\n */\n ;\n\n _proto.toString = function toString(_temp) {\n var _ref = _temp === void 0 ? {} : _temp,\n attached = _ref.attached,\n options = _objectWithoutPropertiesLoose(_ref, [\"attached\"]);\n\n var css = '';\n\n for (var i = 0; i < this.registry.length; i++) {\n var sheet = this.registry[i];\n\n if (attached != null && sheet.attached !== attached) {\n continue;\n }\n\n if (css) css += '\\n';\n css += sheet.toString(options);\n }\n\n return css;\n };\n\n _createClass(SheetsRegistry, [{\n key: \"index\",\n\n /**\n * Current highest index number.\n */\n get: function get() {\n return this.registry.length === 0 ? 0 : this.registry[this.registry.length - 1].options.index;\n }\n }]);\n\n return SheetsRegistry;\n}();\n\n/**\n * This is a global sheets registry. Only DomRenderer will add sheets to it.\n * On the server one should use an own SheetsRegistry instance and add the\n * sheets to it, because you need to make sure to create a new registry for\n * each request in order to not leak sheets across requests.\n */\n\nvar registry = new SheetsRegistry();\n\n/* eslint-disable */\n\n/**\n * Now that `globalThis` is available on most platforms\n * (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis#browser_compatibility)\n * we check for `globalThis` first. `globalThis` is necessary for jss\n * to run in Agoric's secure version of JavaScript (SES). Under SES,\n * `globalThis` exists, but `window`, `self`, and `Function('return\n * this')()` are all undefined for security reasons.\n *\n * https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\n */\nvar globalThis$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' && window.Math === Math ? window : typeof self !== 'undefined' && self.Math === Math ? self : Function('return this')();\n\nvar ns = '2f1acc6c3a606b082e5eef5e54414ffb';\nif (globalThis$1[ns] == null) globalThis$1[ns] = 0; // Bundle may contain multiple JSS versions at the same time. In order to identify\n// the current version with just one short number and use it for classes generation\n// we use a counter. Also it is more accurate, because user can manually reevaluate\n// the module.\n\nvar moduleId = globalThis$1[ns]++;\n\nvar maxRules = 1e10;\n\n/**\n * Returns a function which generates unique class names based on counters.\n * When new generator function is created, rule counter is reseted.\n * We need to reset the rule counter for SSR for each request.\n */\nvar createGenerateId = function createGenerateId(options) {\n if (options === void 0) {\n options = {};\n }\n\n var ruleCounter = 0;\n return function (rule, sheet) {\n ruleCounter += 1;\n\n if (ruleCounter > maxRules) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] You might have a memory leak. Rule counter is at \" + ruleCounter + \".\") : void 0;\n }\n\n var jssId = '';\n var prefix = '';\n\n if (sheet) {\n if (sheet.options.classNamePrefix) {\n prefix = sheet.options.classNamePrefix;\n }\n\n if (sheet.options.jss.id != null) {\n jssId = String(sheet.options.jss.id);\n }\n }\n\n if (options.minify) {\n // Using \"c\" because a number can't be the first char in a class name.\n return \"\" + (prefix || 'c') + moduleId + jssId + ruleCounter;\n }\n\n return prefix + rule.key + \"-\" + moduleId + (jssId ? \"-\" + jssId : '') + \"-\" + ruleCounter;\n };\n};\n\n/**\n * Cache the value from the first time a function is called.\n */\nvar memoize = function memoize(fn) {\n var value;\n return function () {\n if (!value) value = fn();\n return value;\n };\n};\n\n/**\n * Get a style property value.\n */\nvar getPropertyValue = function getPropertyValue(cssRule, prop) {\n try {\n // Support CSSTOM.\n if (cssRule.attributeStyleMap) {\n return cssRule.attributeStyleMap.get(prop);\n }\n\n return cssRule.style.getPropertyValue(prop);\n } catch (err) {\n // IE may throw if property is unknown.\n return '';\n }\n};\n\n/**\n * Set a style property.\n */\nvar setProperty = function setProperty(cssRule, prop, value) {\n try {\n var cssValue = value;\n\n if (Array.isArray(value)) {\n cssValue = toCssValue(value, true);\n\n if (value[value.length - 1] === '!important') {\n cssRule.style.setProperty(prop, cssValue, 'important');\n return true;\n }\n } // Support CSSTOM.\n\n\n if (cssRule.attributeStyleMap) {\n cssRule.attributeStyleMap.set(prop, cssValue);\n } else {\n cssRule.style.setProperty(prop, cssValue);\n }\n } catch (err) {\n // IE may throw if property is unknown.\n return false;\n }\n\n return true;\n};\n\n/**\n * Remove a style property.\n */\nvar removeProperty = function removeProperty(cssRule, prop) {\n try {\n // Support CSSTOM.\n if (cssRule.attributeStyleMap) {\n cssRule.attributeStyleMap.delete(prop);\n } else {\n cssRule.style.removeProperty(prop);\n }\n } catch (err) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] DOMException \\\"\" + err.message + \"\\\" was thrown. Tried to remove property \\\"\" + prop + \"\\\".\") : void 0;\n }\n};\n\n/**\n * Set the selector.\n */\nvar setSelector = function setSelector(cssRule, selectorText) {\n cssRule.selectorText = selectorText; // Return false if setter was not successful.\n // Currently works in chrome only.\n\n return cssRule.selectorText === selectorText;\n};\n/**\n * Gets the `head` element upon the first call and caches it.\n * We assume it can't be null.\n */\n\n\nvar getHead = memoize(function () {\n return document.querySelector('head');\n});\n/**\n * Find attached sheet with an index higher than the passed one.\n */\n\nfunction findHigherSheet(registry, options) {\n for (var i = 0; i < registry.length; i++) {\n var sheet = registry[i];\n\n if (sheet.attached && sheet.options.index > options.index && sheet.options.insertionPoint === options.insertionPoint) {\n return sheet;\n }\n }\n\n return null;\n}\n/**\n * Find attached sheet with the highest index.\n */\n\n\nfunction findHighestSheet(registry, options) {\n for (var i = registry.length - 1; i >= 0; i--) {\n var sheet = registry[i];\n\n if (sheet.attached && sheet.options.insertionPoint === options.insertionPoint) {\n return sheet;\n }\n }\n\n return null;\n}\n/**\n * Find a comment with \"jss\" inside.\n */\n\n\nfunction findCommentNode(text) {\n var head = getHead();\n\n for (var i = 0; i < head.childNodes.length; i++) {\n var node = head.childNodes[i];\n\n if (node.nodeType === 8 && node.nodeValue.trim() === text) {\n return node;\n }\n }\n\n return null;\n}\n\n/**\n * Find a node before which we can insert the sheet.\n */\nfunction findPrevNode(options) {\n var registry$1 = registry.registry;\n\n if (registry$1.length > 0) {\n // Try to insert before the next higher sheet.\n var sheet = findHigherSheet(registry$1, options);\n\n if (sheet && sheet.renderer) {\n return {\n parent: sheet.renderer.element.parentNode,\n node: sheet.renderer.element\n };\n } // Otherwise insert after the last attached.\n\n\n sheet = findHighestSheet(registry$1, options);\n\n if (sheet && sheet.renderer) {\n return {\n parent: sheet.renderer.element.parentNode,\n node: sheet.renderer.element.nextSibling\n };\n }\n } // Try to find a comment placeholder if registry is empty.\n\n\n var insertionPoint = options.insertionPoint;\n\n if (insertionPoint && typeof insertionPoint === 'string') {\n var comment = findCommentNode(insertionPoint);\n\n if (comment) {\n return {\n parent: comment.parentNode,\n node: comment.nextSibling\n };\n } // If user specifies an insertion point and it can't be found in the document -\n // bad specificity issues may appear.\n\n\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Insertion point \\\"\" + insertionPoint + \"\\\" not found.\") : void 0;\n }\n\n return false;\n}\n/**\n * Insert style element into the DOM.\n */\n\n\nfunction insertStyle(style, options) {\n var insertionPoint = options.insertionPoint;\n var nextNode = findPrevNode(options);\n\n if (nextNode !== false && nextNode.parent) {\n nextNode.parent.insertBefore(style, nextNode.node);\n return;\n } // Works with iframes and any node types.\n\n\n if (insertionPoint && typeof insertionPoint.nodeType === 'number') {\n // https://stackoverflow.com/questions/41328728/force-casting-in-flow\n var insertionPointElement = insertionPoint;\n var parentNode = insertionPointElement.parentNode;\n if (parentNode) parentNode.insertBefore(style, insertionPointElement.nextSibling);else process.env.NODE_ENV !== \"production\" ? warning(false, '[JSS] Insertion point is not in the DOM.') : void 0;\n return;\n }\n\n getHead().appendChild(style);\n}\n/**\n * Read jss nonce setting from the page if the user has set it.\n */\n\n\nvar getNonce = memoize(function () {\n var node = document.querySelector('meta[property=\"csp-nonce\"]');\n return node ? node.getAttribute('content') : null;\n});\n\nvar _insertRule = function insertRule(container, rule, index) {\n try {\n if ('insertRule' in container) {\n var c = container;\n c.insertRule(rule, index);\n } // Keyframes rule.\n else if ('appendRule' in container) {\n var _c = container;\n\n _c.appendRule(rule);\n }\n } catch (err) {\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] \" + err.message) : void 0;\n return false;\n }\n\n return container.cssRules[index];\n};\n\nvar getValidRuleInsertionIndex = function getValidRuleInsertionIndex(container, index) {\n var maxIndex = container.cssRules.length; // In case previous insertion fails, passed index might be wrong\n\n if (index === undefined || index > maxIndex) {\n // eslint-disable-next-line no-param-reassign\n return maxIndex;\n }\n\n return index;\n};\n\nvar createStyle = function createStyle() {\n var el = document.createElement('style'); // Without it, IE will have a broken source order specificity if we\n // insert rules after we insert the style tag.\n // It seems to kick-off the source order specificity algorithm.\n\n el.textContent = '\\n';\n return el;\n};\n\nvar DomRenderer =\n/*#__PURE__*/\nfunction () {\n // HTMLStyleElement needs fixing https://github.com/facebook/flow/issues/2696\n // Will be empty if link: true option is not set, because\n // it is only for use together with insertRule API.\n function DomRenderer(sheet) {\n this.getPropertyValue = getPropertyValue;\n this.setProperty = setProperty;\n this.removeProperty = removeProperty;\n this.setSelector = setSelector;\n this.element = void 0;\n this.sheet = void 0;\n this.hasInsertedRules = false;\n this.cssRules = [];\n // There is no sheet when the renderer is used from a standalone StyleRule.\n if (sheet) registry.add(sheet);\n this.sheet = sheet;\n\n var _ref = this.sheet ? this.sheet.options : {},\n media = _ref.media,\n meta = _ref.meta,\n element = _ref.element;\n\n this.element = element || createStyle();\n this.element.setAttribute('data-jss', '');\n if (media) this.element.setAttribute('media', media);\n if (meta) this.element.setAttribute('data-meta', meta);\n var nonce = getNonce();\n if (nonce) this.element.setAttribute('nonce', nonce);\n }\n /**\n * Insert style element into render tree.\n */\n\n\n var _proto = DomRenderer.prototype;\n\n _proto.attach = function attach() {\n // In the case the element node is external and it is already in the DOM.\n if (this.element.parentNode || !this.sheet) return;\n insertStyle(this.element, this.sheet.options); // When rules are inserted using `insertRule` API, after `sheet.detach().attach()`\n // most browsers create a new CSSStyleSheet, except of all IEs.\n\n var deployed = Boolean(this.sheet && this.sheet.deployed);\n\n if (this.hasInsertedRules && deployed) {\n this.hasInsertedRules = false;\n this.deploy();\n }\n }\n /**\n * Remove style element from render tree.\n */\n ;\n\n _proto.detach = function detach() {\n if (!this.sheet) return;\n var parentNode = this.element.parentNode;\n if (parentNode) parentNode.removeChild(this.element); // In the most browsers, rules inserted using insertRule() API will be lost when style element is removed.\n // Though IE will keep them and we need a consistent behavior.\n\n if (this.sheet.options.link) {\n this.cssRules = [];\n this.element.textContent = '\\n';\n }\n }\n /**\n * Inject CSS string into element.\n */\n ;\n\n _proto.deploy = function deploy() {\n var sheet = this.sheet;\n if (!sheet) return;\n\n if (sheet.options.link) {\n this.insertRules(sheet.rules);\n return;\n }\n\n this.element.textContent = \"\\n\" + sheet.toString() + \"\\n\";\n }\n /**\n * Insert RuleList into an element.\n */\n ;\n\n _proto.insertRules = function insertRules(rules, nativeParent) {\n for (var i = 0; i < rules.index.length; i++) {\n this.insertRule(rules.index[i], i, nativeParent);\n }\n }\n /**\n * Insert a rule into element.\n */\n ;\n\n _proto.insertRule = function insertRule(rule, index, nativeParent) {\n if (nativeParent === void 0) {\n nativeParent = this.element.sheet;\n }\n\n if (rule.rules) {\n var parent = rule;\n var latestNativeParent = nativeParent;\n\n if (rule.type === 'conditional' || rule.type === 'keyframes') {\n var _insertionIndex = getValidRuleInsertionIndex(nativeParent, index); // We need to render the container without children first.\n\n\n latestNativeParent = _insertRule(nativeParent, parent.toString({\n children: false\n }), _insertionIndex);\n\n if (latestNativeParent === false) {\n return false;\n }\n\n this.refCssRule(rule, _insertionIndex, latestNativeParent);\n }\n\n this.insertRules(parent.rules, latestNativeParent);\n return latestNativeParent;\n }\n\n var ruleStr = rule.toString();\n if (!ruleStr) return false;\n var insertionIndex = getValidRuleInsertionIndex(nativeParent, index);\n\n var nativeRule = _insertRule(nativeParent, ruleStr, insertionIndex);\n\n if (nativeRule === false) {\n return false;\n }\n\n this.hasInsertedRules = true;\n this.refCssRule(rule, insertionIndex, nativeRule);\n return nativeRule;\n };\n\n _proto.refCssRule = function refCssRule(rule, index, cssRule) {\n rule.renderable = cssRule; // We only want to reference the top level rules, deleteRule API doesn't support removing nested rules\n // like rules inside media queries or keyframes\n\n if (rule.options.parent instanceof StyleSheet) {\n this.cssRules[index] = cssRule;\n }\n }\n /**\n * Delete a rule.\n */\n ;\n\n _proto.deleteRule = function deleteRule(cssRule) {\n var sheet = this.element.sheet;\n var index = this.indexOf(cssRule);\n if (index === -1) return false;\n sheet.deleteRule(index);\n this.cssRules.splice(index, 1);\n return true;\n }\n /**\n * Get index of a CSS Rule.\n */\n ;\n\n _proto.indexOf = function indexOf(cssRule) {\n return this.cssRules.indexOf(cssRule);\n }\n /**\n * Generate a new CSS rule and replace the existing one.\n *\n * Only used for some old browsers because they can't set a selector.\n */\n ;\n\n _proto.replaceRule = function replaceRule(cssRule, rule) {\n var index = this.indexOf(cssRule);\n if (index === -1) return false;\n this.element.sheet.deleteRule(index);\n this.cssRules.splice(index, 1);\n return this.insertRule(rule, index);\n }\n /**\n * Get all rules elements.\n */\n ;\n\n _proto.getRules = function getRules() {\n return this.element.sheet.cssRules;\n };\n\n return DomRenderer;\n}();\n\nvar instanceCounter = 0;\n\nvar Jss =\n/*#__PURE__*/\nfunction () {\n function Jss(options) {\n this.id = instanceCounter++;\n this.version = \"10.6.0\";\n this.plugins = new PluginsRegistry();\n this.options = {\n id: {\n minify: false\n },\n createGenerateId: createGenerateId,\n Renderer: isInBrowser ? DomRenderer : null,\n plugins: []\n };\n this.generateId = createGenerateId({\n minify: false\n });\n\n for (var i = 0; i < plugins.length; i++) {\n this.plugins.use(plugins[i], {\n queue: 'internal'\n });\n }\n\n this.setup(options);\n }\n /**\n * Prepares various options, applies plugins.\n * Should not be used twice on the same instance, because there is no plugins\n * deduplication logic.\n */\n\n\n var _proto = Jss.prototype;\n\n _proto.setup = function setup(options) {\n if (options === void 0) {\n options = {};\n }\n\n if (options.createGenerateId) {\n this.options.createGenerateId = options.createGenerateId;\n }\n\n if (options.id) {\n this.options.id = _extends({}, this.options.id, options.id);\n }\n\n if (options.createGenerateId || options.id) {\n this.generateId = this.options.createGenerateId(this.options.id);\n }\n\n if (options.insertionPoint != null) this.options.insertionPoint = options.insertionPoint;\n\n if ('Renderer' in options) {\n this.options.Renderer = options.Renderer;\n } // eslint-disable-next-line prefer-spread\n\n\n if (options.plugins) this.use.apply(this, options.plugins);\n return this;\n }\n /**\n * Create a Style Sheet.\n */\n ;\n\n _proto.createStyleSheet = function createStyleSheet(styles, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n index = _options.index;\n\n if (typeof index !== 'number') {\n index = registry.index === 0 ? 0 : registry.index + 1;\n }\n\n var sheet = new StyleSheet(styles, _extends({}, options, {\n jss: this,\n generateId: options.generateId || this.generateId,\n insertionPoint: this.options.insertionPoint,\n Renderer: this.options.Renderer,\n index: index\n }));\n this.plugins.onProcessSheet(sheet);\n return sheet;\n }\n /**\n * Detach the Style Sheet and remove it from the registry.\n */\n ;\n\n _proto.removeStyleSheet = function removeStyleSheet(sheet) {\n sheet.detach();\n registry.remove(sheet);\n return this;\n }\n /**\n * Create a rule without a Style Sheet.\n * [Deprecated] will be removed in the next major version.\n */\n ;\n\n _proto.createRule = function createRule$1(name, style, options) {\n if (style === void 0) {\n style = {};\n }\n\n if (options === void 0) {\n options = {};\n }\n\n // Enable rule without name for inline styles.\n if (typeof name === 'object') {\n // $FlowFixMe[incompatible-call]\n return this.createRule(undefined, name, style);\n } // $FlowFixMe[incompatible-type]\n\n\n var ruleOptions = _extends({}, options, {\n name: name,\n jss: this,\n Renderer: this.options.Renderer\n });\n\n if (!ruleOptions.generateId) ruleOptions.generateId = this.generateId;\n if (!ruleOptions.classes) ruleOptions.classes = {};\n if (!ruleOptions.keyframes) ruleOptions.keyframes = {};\n\n var rule = createRule(name, style, ruleOptions);\n\n if (rule) this.plugins.onProcessRule(rule);\n return rule;\n }\n /**\n * Register plugin. Passed function will be invoked with a rule instance.\n */\n ;\n\n _proto.use = function use() {\n var _this = this;\n\n for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {\n plugins[_key] = arguments[_key];\n }\n\n plugins.forEach(function (plugin) {\n _this.plugins.use(plugin);\n });\n return this;\n };\n\n return Jss;\n}();\n\n/**\n * Extracts a styles object with only props that contain function values.\n */\nfunction getDynamicStyles(styles) {\n var to = null;\n\n for (var key in styles) {\n var value = styles[key];\n var type = typeof value;\n\n if (type === 'function') {\n if (!to) to = {};\n to[key] = value;\n } else if (type === 'object' && value !== null && !Array.isArray(value)) {\n var extracted = getDynamicStyles(value);\n\n if (extracted) {\n if (!to) to = {};\n to[key] = extracted;\n }\n }\n }\n\n return to;\n}\n\n/**\n * SheetsManager is like a WeakMap which is designed to count StyleSheet\n * instances and attach/detach automatically.\n */\nvar SheetsManager =\n/*#__PURE__*/\nfunction () {\n function SheetsManager() {\n this.length = 0;\n this.sheets = new WeakMap();\n }\n\n var _proto = SheetsManager.prototype;\n\n _proto.get = function get(key) {\n var entry = this.sheets.get(key);\n return entry && entry.sheet;\n };\n\n _proto.add = function add(key, sheet) {\n if (this.sheets.has(key)) return;\n this.length++;\n this.sheets.set(key, {\n sheet: sheet,\n refs: 0\n });\n };\n\n _proto.manage = function manage(key) {\n var entry = this.sheets.get(key);\n\n if (entry) {\n if (entry.refs === 0) {\n entry.sheet.attach();\n }\n\n entry.refs++;\n return entry.sheet;\n }\n\n warning(false, \"[JSS] SheetsManager: can't find sheet to manage\");\n return undefined;\n };\n\n _proto.unmanage = function unmanage(key) {\n var entry = this.sheets.get(key);\n\n if (entry) {\n if (entry.refs > 0) {\n entry.refs--;\n if (entry.refs === 0) entry.sheet.detach();\n }\n } else {\n warning(false, \"SheetsManager: can't find sheet to unmanage\");\n }\n };\n\n _createClass(SheetsManager, [{\n key: \"size\",\n get: function get() {\n return this.length;\n }\n }]);\n\n return SheetsManager;\n}();\n\n/**\n * A better abstraction over CSS.\n *\n * @copyright Oleg Isonen (Slobodskoi) / Isonen 2014-present\n * @website https://github.com/cssinjs/jss\n * @license MIT\n */\n\n/**\n * Export a constant indicating if this browser has CSSTOM support.\n * https://developers.google.com/web/updates/2018/03/cssom\n */\nvar hasCSSTOMSupport = typeof CSS === 'object' && CSS != null && 'number' in CSS;\n/**\n * Creates a new instance of Jss.\n */\n\nvar create = function create(options) {\n return new Jss(options);\n};\n/**\n * A global Jss instance.\n */\n\nvar jss = create();\n\nexport default jss;\nexport { RuleList, SheetsManager, SheetsRegistry, create, createGenerateId, createRule, getDynamicStyles, hasCSSTOMSupport, registry as sheets, toCssValue };\n","// Used https://github.com/thinkloop/multi-key-cache as inspiration\nvar multiKeyStore = {\n set: function set(cache, key1, key2, value) {\n var subCache = cache.get(key1);\n\n if (!subCache) {\n subCache = new Map();\n cache.set(key1, subCache);\n }\n\n subCache.set(key2, value);\n },\n get: function get(cache, key1, key2) {\n var subCache = cache.get(key1);\n return subCache ? subCache.get(key2) : undefined;\n },\n delete: function _delete(cache, key1, key2) {\n var subCache = cache.get(key1);\n subCache.delete(key2);\n }\n};\nexport default multiKeyStore;","var hasSymbol = typeof Symbol === 'function' && Symbol.for;\nexport default hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__';","import nested from '../ThemeProvider/nested';\n/**\n * This is the list of the style rule name we use as drop in replacement for the built-in\n * pseudo classes (:checked, :disabled, :focused, etc.).\n *\n * Why do they exist in the first place?\n * These classes are used at a specificity of 2.\n * It allows them to override previously definied styles as well as\n * being untouched by simple user overrides.\n */\n\nvar pseudoClasses = ['checked', 'disabled', 'error', 'focused', 'focusVisible', 'required', 'expanded', 'selected']; // Returns a function which generates unique class names based on counters.\n// When new generator function is created, rule counter is reset.\n// We need to reset the rule counter for SSR for each request.\n//\n// It's inspired by\n// https://github.com/cssinjs/jss/blob/4e6a05dd3f7b6572fdd3ab216861d9e446c20331/src/utils/createGenerateClassName.js\n\nexport default function createGenerateClassName() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var _options$disableGloba = options.disableGlobal,\n disableGlobal = _options$disableGloba === void 0 ? false : _options$disableGloba,\n _options$productionPr = options.productionPrefix,\n productionPrefix = _options$productionPr === void 0 ? 'jss' : _options$productionPr,\n _options$seed = options.seed,\n seed = _options$seed === void 0 ? '' : _options$seed;\n var seedPrefix = seed === '' ? '' : \"\".concat(seed, \"-\");\n var ruleCounter = 0;\n\n var getNextCounterId = function getNextCounterId() {\n ruleCounter += 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (ruleCounter >= 1e10) {\n console.warn(['Material-UI: You might have a memory leak.', 'The ruleCounter is not supposed to grow that much.'].join(''));\n }\n }\n\n return ruleCounter;\n };\n\n return function (rule, styleSheet) {\n var name = styleSheet.options.name; // Is a global static MUI style?\n\n if (name && name.indexOf('Mui') === 0 && !styleSheet.options.link && !disableGlobal) {\n // We can use a shorthand class name, we never use the keys to style the components.\n if (pseudoClasses.indexOf(rule.key) !== -1) {\n return \"Mui-\".concat(rule.key);\n }\n\n var prefix = \"\".concat(seedPrefix).concat(name, \"-\").concat(rule.key);\n\n if (!styleSheet.options.theme[nested] || seed !== '') {\n return prefix;\n }\n\n return \"\".concat(prefix, \"-\").concat(getNextCounterId());\n }\n\n if (process.env.NODE_ENV === 'production') {\n return \"\".concat(seedPrefix).concat(productionPrefix).concat(getNextCounterId());\n }\n\n var suffix = \"\".concat(rule.key, \"-\").concat(getNextCounterId()); // Help with debuggability.\n\n if (styleSheet.options.classNamePrefix) {\n return \"\".concat(seedPrefix).concat(styleSheet.options.classNamePrefix, \"-\").concat(suffix);\n }\n\n return \"\".concat(seedPrefix).concat(suffix);\n };\n}","import warning from 'tiny-warning';\nimport { createRule } from 'jss';\n\nvar now = Date.now();\nvar fnValuesNs = \"fnValues\" + now;\nvar fnRuleNs = \"fnStyle\" + ++now;\n\nvar functionPlugin = function functionPlugin() {\n return {\n onCreateRule: function onCreateRule(name, decl, options) {\n if (typeof decl !== 'function') return null;\n var rule = createRule(name, {}, options);\n rule[fnRuleNs] = decl;\n return rule;\n },\n onProcessStyle: function onProcessStyle(style, rule) {\n // We need to extract function values from the declaration, so that we can keep core unaware of them.\n // We need to do that only once.\n // We don't need to extract functions on each style update, since this can happen only once.\n // We don't support function values inside of function rules.\n if (fnValuesNs in rule || fnRuleNs in rule) return style;\n var fnValues = {};\n\n for (var prop in style) {\n var value = style[prop];\n if (typeof value !== 'function') continue;\n delete style[prop];\n fnValues[prop] = value;\n } // $FlowFixMe[prop-missing]\n\n\n rule[fnValuesNs] = fnValues;\n return style;\n },\n onUpdate: function onUpdate(data, rule, sheet, options) {\n var styleRule = rule; // $FlowFixMe[prop-missing]\n\n var fnRule = styleRule[fnRuleNs]; // If we have a style function, the entire rule is dynamic and style object\n // will be returned from that function.\n\n if (fnRule) {\n // Empty object will remove all currently defined props\n // in case function rule returns a falsy value.\n styleRule.style = fnRule(data) || {};\n\n if (process.env.NODE_ENV === 'development') {\n for (var prop in styleRule.style) {\n if (typeof styleRule.style[prop] === 'function') {\n process.env.NODE_ENV !== \"production\" ? warning(false, '[JSS] Function values inside function rules are not supported.') : void 0;\n break;\n }\n }\n }\n } // $FlowFixMe[prop-missing]\n\n\n var fnValues = styleRule[fnValuesNs]; // If we have a fn values map, it is a rule with function values.\n\n if (fnValues) {\n for (var _prop in fnValues) {\n styleRule.prop(_prop, fnValues[_prop](data), options);\n }\n }\n }\n };\n};\n\nexport default functionPlugin;\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport { RuleList } from 'jss';\n\nvar at = '@global';\nvar atPrefix = '@global ';\n\nvar GlobalContainerRule =\n/*#__PURE__*/\nfunction () {\n function GlobalContainerRule(key, styles, options) {\n this.type = 'global';\n this.at = at;\n this.rules = void 0;\n this.options = void 0;\n this.key = void 0;\n this.isProcessed = false;\n this.key = key;\n this.options = options;\n this.rules = new RuleList(_extends({}, options, {\n parent: this\n }));\n\n for (var selector in styles) {\n this.rules.add(selector, styles[selector]);\n }\n\n this.rules.process();\n }\n /**\n * Get a rule.\n */\n\n\n var _proto = GlobalContainerRule.prototype;\n\n _proto.getRule = function getRule(name) {\n return this.rules.get(name);\n }\n /**\n * Create and register rule, run plugins.\n */\n ;\n\n _proto.addRule = function addRule(name, style, options) {\n var rule = this.rules.add(name, style, options);\n if (rule) this.options.jss.plugins.onProcessRule(rule);\n return rule;\n }\n /**\n * Get index of a rule.\n */\n ;\n\n _proto.indexOf = function indexOf(rule) {\n return this.rules.indexOf(rule);\n }\n /**\n * Generates a CSS string.\n */\n ;\n\n _proto.toString = function toString() {\n return this.rules.toString();\n };\n\n return GlobalContainerRule;\n}();\n\nvar GlobalPrefixedRule =\n/*#__PURE__*/\nfunction () {\n function GlobalPrefixedRule(key, style, options) {\n this.type = 'global';\n this.at = at;\n this.options = void 0;\n this.rule = void 0;\n this.isProcessed = false;\n this.key = void 0;\n this.key = key;\n this.options = options;\n var selector = key.substr(atPrefix.length);\n this.rule = options.jss.createRule(selector, style, _extends({}, options, {\n parent: this\n }));\n }\n\n var _proto2 = GlobalPrefixedRule.prototype;\n\n _proto2.toString = function toString(options) {\n return this.rule ? this.rule.toString(options) : '';\n };\n\n return GlobalPrefixedRule;\n}();\n\nvar separatorRegExp = /\\s*,\\s*/g;\n\nfunction addScope(selector, scope) {\n var parts = selector.split(separatorRegExp);\n var scoped = '';\n\n for (var i = 0; i < parts.length; i++) {\n scoped += scope + \" \" + parts[i].trim();\n if (parts[i + 1]) scoped += ', ';\n }\n\n return scoped;\n}\n\nfunction handleNestedGlobalContainerRule(rule, sheet) {\n var options = rule.options,\n style = rule.style;\n var rules = style ? style[at] : null;\n if (!rules) return;\n\n for (var name in rules) {\n sheet.addRule(name, rules[name], _extends({}, options, {\n selector: addScope(name, rule.selector)\n }));\n }\n\n delete style[at];\n}\n\nfunction handlePrefixedGlobalRule(rule, sheet) {\n var options = rule.options,\n style = rule.style;\n\n for (var prop in style) {\n if (prop[0] !== '@' || prop.substr(0, at.length) !== at) continue;\n var selector = addScope(prop.substr(at.length), rule.selector);\n sheet.addRule(selector, style[prop], _extends({}, options, {\n selector: selector\n }));\n delete style[prop];\n }\n}\n/**\n * Convert nested rules to separate, remove them from original styles.\n *\n * @param {Rule} rule\n * @api public\n */\n\n\nfunction jssGlobal() {\n function onCreateRule(name, styles, options) {\n if (!name) return null;\n\n if (name === at) {\n return new GlobalContainerRule(name, styles, options);\n }\n\n if (name[0] === '@' && name.substr(0, atPrefix.length) === atPrefix) {\n return new GlobalPrefixedRule(name, styles, options);\n }\n\n var parent = options.parent;\n\n if (parent) {\n if (parent.type === 'global' || parent.options.parent && parent.options.parent.type === 'global') {\n options.scoped = false;\n }\n }\n\n if (options.scoped === false) {\n options.selector = name;\n }\n\n return null;\n }\n\n function onProcessRule(rule, sheet) {\n if (rule.type !== 'style' || !sheet) return;\n handleNestedGlobalContainerRule(rule, sheet);\n handlePrefixedGlobalRule(rule, sheet);\n }\n\n return {\n onCreateRule: onCreateRule,\n onProcessRule: onProcessRule\n };\n}\n\nexport default jssGlobal;\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport warning from 'tiny-warning';\n\nvar separatorRegExp = /\\s*,\\s*/g;\nvar parentRegExp = /&/g;\nvar refRegExp = /\\$([\\w-]+)/g;\n/**\n * Convert nested rules to separate, remove them from original styles.\n *\n * @param {Rule} rule\n * @api public\n */\n\nfunction jssNested() {\n // Get a function to be used for $ref replacement.\n function getReplaceRef(container, sheet) {\n return function (match, key) {\n var rule = container.getRule(key) || sheet && sheet.getRule(key);\n\n if (rule) {\n rule = rule;\n return rule.selector;\n }\n\n process.env.NODE_ENV !== \"production\" ? warning(false, \"[JSS] Could not find the referenced rule \\\"\" + key + \"\\\" in \\\"\" + (container.options.meta || container.toString()) + \"\\\".\") : void 0;\n return key;\n };\n }\n\n function replaceParentRefs(nestedProp, parentProp) {\n var parentSelectors = parentProp.split(separatorRegExp);\n var nestedSelectors = nestedProp.split(separatorRegExp);\n var result = '';\n\n for (var i = 0; i < parentSelectors.length; i++) {\n var parent = parentSelectors[i];\n\n for (var j = 0; j < nestedSelectors.length; j++) {\n var nested = nestedSelectors[j];\n if (result) result += ', '; // Replace all & by the parent or prefix & with the parent.\n\n result += nested.indexOf('&') !== -1 ? nested.replace(parentRegExp, parent) : parent + \" \" + nested;\n }\n }\n\n return result;\n }\n\n function getOptions(rule, container, prevOptions) {\n // Options has been already created, now we only increase index.\n if (prevOptions) return _extends({}, prevOptions, {\n index: prevOptions.index + 1 // $FlowFixMe[prop-missing]\n\n });\n var nestingLevel = rule.options.nestingLevel;\n nestingLevel = nestingLevel === undefined ? 1 : nestingLevel + 1;\n\n var options = _extends({}, rule.options, {\n nestingLevel: nestingLevel,\n index: container.indexOf(rule) + 1 // We don't need the parent name to be set options for chlid.\n\n });\n\n delete options.name;\n return options;\n }\n\n function onProcessStyle(style, rule, sheet) {\n if (rule.type !== 'style') return style;\n var styleRule = rule;\n var container = styleRule.options.parent;\n var options;\n var replaceRef;\n\n for (var prop in style) {\n var isNested = prop.indexOf('&') !== -1;\n var isNestedConditional = prop[0] === '@';\n if (!isNested && !isNestedConditional) continue;\n options = getOptions(styleRule, container, options);\n\n if (isNested) {\n var selector = replaceParentRefs(prop, styleRule.selector); // Lazily create the ref replacer function just once for\n // all nested rules within the sheet.\n\n if (!replaceRef) replaceRef = getReplaceRef(container, sheet); // Replace all $refs.\n\n selector = selector.replace(refRegExp, replaceRef);\n container.addRule(selector, style[prop], _extends({}, options, {\n selector: selector\n }));\n } else if (isNestedConditional) {\n // Place conditional right after the parent rule to ensure right ordering.\n container.addRule(prop, {}, options) // Flow expects more options but they aren't required\n // And flow doesn't know this will always be a StyleRule which has the addRule method\n // $FlowFixMe[incompatible-use]\n // $FlowFixMe[prop-missing]\n .addRule(styleRule.key, style[prop], {\n selector: styleRule.selector\n });\n }\n\n delete style[prop];\n }\n\n return style;\n }\n\n return {\n onProcessStyle: onProcessStyle\n };\n}\n\nexport default jssNested;\n","/* eslint-disable no-var, prefer-template */\nvar uppercasePattern = /[A-Z]/g\nvar msPattern = /^ms-/\nvar cache = {}\n\nfunction toHyphenLower(match) {\n return '-' + match.toLowerCase()\n}\n\nfunction hyphenateStyleName(name) {\n if (cache.hasOwnProperty(name)) {\n return cache[name]\n }\n\n var hName = name.replace(uppercasePattern, toHyphenLower)\n return (cache[name] = msPattern.test(hName) ? '-' + hName : hName)\n}\n\nexport default hyphenateStyleName\n","import hyphenate from 'hyphenate-style-name';\n\n/**\n * Convert camel cased property names to dash separated.\n *\n * @param {Object} style\n * @return {Object}\n */\n\nfunction convertCase(style) {\n var converted = {};\n\n for (var prop in style) {\n var key = prop.indexOf('--') === 0 ? prop : hyphenate(prop);\n converted[key] = style[prop];\n }\n\n if (style.fallbacks) {\n if (Array.isArray(style.fallbacks)) converted.fallbacks = style.fallbacks.map(convertCase);else converted.fallbacks = convertCase(style.fallbacks);\n }\n\n return converted;\n}\n/**\n * Allow camel cased property names by converting them back to dasherized.\n *\n * @param {Rule} rule\n */\n\n\nfunction camelCase() {\n function onProcessStyle(style) {\n if (Array.isArray(style)) {\n // Handle rules like @font-face, which can have multiple styles in an array\n for (var index = 0; index < style.length; index++) {\n style[index] = convertCase(style[index]);\n }\n\n return style;\n }\n\n return convertCase(style);\n }\n\n function onChangeValue(value, prop, rule) {\n if (prop.indexOf('--') === 0) {\n return value;\n }\n\n var hyphenatedProp = hyphenate(prop); // There was no camel case in place\n\n if (prop === hyphenatedProp) return value;\n rule.prop(hyphenatedProp, value); // Core will ignore that property value we set the proper one above.\n\n return null;\n }\n\n return {\n onProcessStyle: onProcessStyle,\n onChangeValue: onChangeValue\n };\n}\n\nexport default camelCase;\n","import { hasCSSTOMSupport } from 'jss';\n\nvar px = hasCSSTOMSupport && CSS ? CSS.px : 'px';\nvar ms = hasCSSTOMSupport && CSS ? CSS.ms : 'ms';\nvar percent = hasCSSTOMSupport && CSS ? CSS.percent : '%';\n/**\n * Generated jss-plugin-default-unit CSS property units\n *\n * @type object\n */\n\nvar defaultUnits = {\n // Animation properties\n 'animation-delay': ms,\n 'animation-duration': ms,\n // Background properties\n 'background-position': px,\n 'background-position-x': px,\n 'background-position-y': px,\n 'background-size': px,\n // Border Properties\n border: px,\n 'border-bottom': px,\n 'border-bottom-left-radius': px,\n 'border-bottom-right-radius': px,\n 'border-bottom-width': px,\n 'border-left': px,\n 'border-left-width': px,\n 'border-radius': px,\n 'border-right': px,\n 'border-right-width': px,\n 'border-top': px,\n 'border-top-left-radius': px,\n 'border-top-right-radius': px,\n 'border-top-width': px,\n 'border-width': px,\n 'border-block': px,\n 'border-block-end': px,\n 'border-block-end-width': px,\n 'border-block-start': px,\n 'border-block-start-width': px,\n 'border-block-width': px,\n 'border-inline': px,\n 'border-inline-end': px,\n 'border-inline-end-width': px,\n 'border-inline-start': px,\n 'border-inline-start-width': px,\n 'border-inline-width': px,\n 'border-start-start-radius': px,\n 'border-start-end-radius': px,\n 'border-end-start-radius': px,\n 'border-end-end-radius': px,\n // Margin properties\n margin: px,\n 'margin-bottom': px,\n 'margin-left': px,\n 'margin-right': px,\n 'margin-top': px,\n 'margin-block': px,\n 'margin-block-end': px,\n 'margin-block-start': px,\n 'margin-inline': px,\n 'margin-inline-end': px,\n 'margin-inline-start': px,\n // Padding properties\n padding: px,\n 'padding-bottom': px,\n 'padding-left': px,\n 'padding-right': px,\n 'padding-top': px,\n 'padding-block': px,\n 'padding-block-end': px,\n 'padding-block-start': px,\n 'padding-inline': px,\n 'padding-inline-end': px,\n 'padding-inline-start': px,\n // Mask properties\n 'mask-position-x': px,\n 'mask-position-y': px,\n 'mask-size': px,\n // Width and height properties\n height: px,\n width: px,\n 'min-height': px,\n 'max-height': px,\n 'min-width': px,\n 'max-width': px,\n // Position properties\n bottom: px,\n left: px,\n top: px,\n right: px,\n inset: px,\n 'inset-block': px,\n 'inset-block-end': px,\n 'inset-block-start': px,\n 'inset-inline': px,\n 'inset-inline-end': px,\n 'inset-inline-start': px,\n // Shadow properties\n 'box-shadow': px,\n 'text-shadow': px,\n // Column properties\n 'column-gap': px,\n 'column-rule': px,\n 'column-rule-width': px,\n 'column-width': px,\n // Font and text properties\n 'font-size': px,\n 'font-size-delta': px,\n 'letter-spacing': px,\n 'text-decoration-thickness': px,\n 'text-indent': px,\n 'text-stroke': px,\n 'text-stroke-width': px,\n 'word-spacing': px,\n // Motion properties\n motion: px,\n 'motion-offset': px,\n // Outline properties\n outline: px,\n 'outline-offset': px,\n 'outline-width': px,\n // Perspective properties\n perspective: px,\n 'perspective-origin-x': percent,\n 'perspective-origin-y': percent,\n // Transform properties\n 'transform-origin': percent,\n 'transform-origin-x': percent,\n 'transform-origin-y': percent,\n 'transform-origin-z': percent,\n // Transition properties\n 'transition-delay': ms,\n 'transition-duration': ms,\n // Alignment properties\n 'vertical-align': px,\n 'flex-basis': px,\n // Some random properties\n 'shape-margin': px,\n size: px,\n gap: px,\n // Grid properties\n grid: px,\n 'grid-gap': px,\n 'row-gap': px,\n 'grid-row-gap': px,\n 'grid-column-gap': px,\n 'grid-template-rows': px,\n 'grid-template-columns': px,\n 'grid-auto-rows': px,\n 'grid-auto-columns': px,\n // Not existing properties.\n // Used to avoid issues with jss-plugin-expand integration.\n 'box-shadow-x': px,\n 'box-shadow-y': px,\n 'box-shadow-blur': px,\n 'box-shadow-spread': px,\n 'font-line-height': px,\n 'text-shadow-x': px,\n 'text-shadow-y': px,\n 'text-shadow-blur': px\n};\n\n/**\n * Clones the object and adds a camel cased property version.\n */\nfunction addCamelCasedVersion(obj) {\n var regExp = /(-[a-z])/g;\n\n var replace = function replace(str) {\n return str[1].toUpperCase();\n };\n\n var newObj = {};\n\n for (var _key in obj) {\n newObj[_key] = obj[_key];\n newObj[_key.replace(regExp, replace)] = obj[_key];\n }\n\n return newObj;\n}\n\nvar units = addCamelCasedVersion(defaultUnits);\n/**\n * Recursive deep style passing function\n */\n\nfunction iterate(prop, value, options) {\n if (value == null) return value;\n\n if (Array.isArray(value)) {\n for (var i = 0; i < value.length; i++) {\n value[i] = iterate(prop, value[i], options);\n }\n } else if (typeof value === 'object') {\n if (prop === 'fallbacks') {\n for (var innerProp in value) {\n value[innerProp] = iterate(innerProp, value[innerProp], options);\n }\n } else {\n for (var _innerProp in value) {\n value[_innerProp] = iterate(prop + \"-\" + _innerProp, value[_innerProp], options);\n }\n } // eslint-disable-next-line no-restricted-globals\n\n } else if (typeof value === 'number' && isNaN(value) === false) {\n var unit = options[prop] || units[prop]; // Add the unit if available, except for the special case of 0px.\n\n if (unit && !(value === 0 && unit === px)) {\n return typeof unit === 'function' ? unit(value).toString() : \"\" + value + unit;\n }\n\n return value.toString();\n }\n\n return value;\n}\n/**\n * Add unit to numeric values.\n */\n\n\nfunction defaultUnit(options) {\n if (options === void 0) {\n options = {};\n }\n\n var camelCasedOptions = addCamelCasedVersion(options);\n\n function onProcessStyle(style, rule) {\n if (rule.type !== 'style') return style;\n\n for (var prop in style) {\n style[prop] = iterate(prop, style[prop], camelCasedOptions);\n }\n\n return style;\n }\n\n function onChangeValue(value, prop) {\n return iterate(prop, value, camelCasedOptions);\n }\n\n return {\n onProcessStyle: onProcessStyle,\n onChangeValue: onChangeValue\n };\n}\n\nexport default defaultUnit;\n","import isInBrowser from 'is-in-browser';\nimport _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray';\n\n// Export javascript style and css style vendor prefixes.\nvar js = '';\nvar css = '';\nvar vendor = '';\nvar browser = '';\nvar isTouch = isInBrowser && 'ontouchstart' in document.documentElement; // We should not do anything if required serverside.\n\nif (isInBrowser) {\n // Order matters. We need to check Webkit the last one because\n // other vendors use to add Webkit prefixes to some properties\n var jsCssMap = {\n Moz: '-moz-',\n ms: '-ms-',\n O: '-o-',\n Webkit: '-webkit-'\n };\n\n var _document$createEleme = document.createElement('p'),\n style = _document$createEleme.style;\n\n var testProp = 'Transform';\n\n for (var key in jsCssMap) {\n if (key + testProp in style) {\n js = key;\n css = jsCssMap[key];\n break;\n }\n } // Correctly detect the Edge browser.\n\n\n if (js === 'Webkit' && 'msHyphens' in style) {\n js = 'ms';\n css = jsCssMap.ms;\n browser = 'edge';\n } // Correctly detect the Safari browser.\n\n\n if (js === 'Webkit' && '-apple-trailing-word' in style) {\n vendor = 'apple';\n }\n}\n/**\n * Vendor prefix string for the current browser.\n *\n * @type {{js: String, css: String, vendor: String, browser: String}}\n * @api public\n */\n\n\nvar prefix = {\n js: js,\n css: css,\n vendor: vendor,\n browser: browser,\n isTouch: isTouch\n};\n\n/**\n * Test if a keyframe at-rule should be prefixed or not\n *\n * @param {String} vendor prefix string for the current browser.\n * @return {String}\n * @api public\n */\n\nfunction supportedKeyframes(key) {\n // Keyframes is already prefixed. e.g. key = '@-webkit-keyframes a'\n if (key[1] === '-') return key; // No need to prefix IE/Edge. Older browsers will ignore unsupported rules.\n // https://caniuse.com/#search=keyframes\n\n if (prefix.js === 'ms') return key;\n return \"@\" + prefix.css + \"keyframes\" + key.substr(10);\n}\n\n// https://caniuse.com/#search=appearance\n\nvar appearence = {\n noPrefill: ['appearance'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'appearance') return false;\n if (prefix.js === 'ms') return \"-webkit-\" + prop;\n return prefix.css + prop;\n }\n};\n\n// https://caniuse.com/#search=color-adjust\n\nvar colorAdjust = {\n noPrefill: ['color-adjust'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'color-adjust') return false;\n if (prefix.js === 'Webkit') return prefix.css + \"print-\" + prop;\n return prop;\n }\n};\n\nvar regExp = /[-\\s]+(.)?/g;\n/**\n * Replaces the letter with the capital letter\n *\n * @param {String} match\n * @param {String} c\n * @return {String}\n * @api private\n */\n\nfunction toUpper(match, c) {\n return c ? c.toUpperCase() : '';\n}\n/**\n * Convert dash separated strings to camel-cased.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\n\nfunction camelize(str) {\n return str.replace(regExp, toUpper);\n}\n\n/**\n * Convert dash separated strings to pascal cased.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nfunction pascalize(str) {\n return camelize(\"-\" + str);\n}\n\n// but we can use a longhand property instead.\n// https://caniuse.com/#search=mask\n\nvar mask = {\n noPrefill: ['mask'],\n supportedProperty: function supportedProperty(prop, style) {\n if (!/^mask/.test(prop)) return false;\n\n if (prefix.js === 'Webkit') {\n var longhand = 'mask-image';\n\n if (camelize(longhand) in style) {\n return prop;\n }\n\n if (prefix.js + pascalize(longhand) in style) {\n return prefix.css + prop;\n }\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=text-orientation\n\nvar textOrientation = {\n noPrefill: ['text-orientation'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'text-orientation') return false;\n\n if (prefix.vendor === 'apple' && !prefix.isTouch) {\n return prefix.css + prop;\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=transform\n\nvar transform = {\n noPrefill: ['transform'],\n supportedProperty: function supportedProperty(prop, style, options) {\n if (prop !== 'transform') return false;\n\n if (options.transform) {\n return prop;\n }\n\n return prefix.css + prop;\n }\n};\n\n// https://caniuse.com/#search=transition\n\nvar transition = {\n noPrefill: ['transition'],\n supportedProperty: function supportedProperty(prop, style, options) {\n if (prop !== 'transition') return false;\n\n if (options.transition) {\n return prop;\n }\n\n return prefix.css + prop;\n }\n};\n\n// https://caniuse.com/#search=writing-mode\n\nvar writingMode = {\n noPrefill: ['writing-mode'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'writing-mode') return false;\n\n if (prefix.js === 'Webkit' || prefix.js === 'ms' && prefix.browser !== 'edge') {\n return prefix.css + prop;\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=user-select\n\nvar userSelect = {\n noPrefill: ['user-select'],\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'user-select') return false;\n\n if (prefix.js === 'Moz' || prefix.js === 'ms' || prefix.vendor === 'apple') {\n return prefix.css + prop;\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=multicolumn\n// https://github.com/postcss/autoprefixer/issues/491\n// https://github.com/postcss/autoprefixer/issues/177\n\nvar breakPropsOld = {\n supportedProperty: function supportedProperty(prop, style) {\n if (!/^break-/.test(prop)) return false;\n\n if (prefix.js === 'Webkit') {\n var jsProp = \"WebkitColumn\" + pascalize(prop);\n return jsProp in style ? prefix.css + \"column-\" + prop : false;\n }\n\n if (prefix.js === 'Moz') {\n var _jsProp = \"page\" + pascalize(prop);\n\n return _jsProp in style ? \"page-\" + prop : false;\n }\n\n return false;\n }\n};\n\n// See https://github.com/postcss/autoprefixer/issues/324.\n\nvar inlineLogicalOld = {\n supportedProperty: function supportedProperty(prop, style) {\n if (!/^(border|margin|padding)-inline/.test(prop)) return false;\n if (prefix.js === 'Moz') return prop;\n var newProp = prop.replace('-inline', '');\n return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false;\n }\n};\n\n// Camelization is required because we can't test using.\n// CSS syntax for e.g. in FF.\n\nvar unprefixed = {\n supportedProperty: function supportedProperty(prop, style) {\n return camelize(prop) in style ? prop : false;\n }\n};\n\nvar prefixed = {\n supportedProperty: function supportedProperty(prop, style) {\n var pascalized = pascalize(prop); // Return custom CSS variable without prefixing.\n\n if (prop[0] === '-') return prop; // Return already prefixed value without prefixing.\n\n if (prop[0] === '-' && prop[1] === '-') return prop;\n if (prefix.js + pascalized in style) return prefix.css + prop; // Try webkit fallback.\n\n if (prefix.js !== 'Webkit' && \"Webkit\" + pascalized in style) return \"-webkit-\" + prop;\n return false;\n }\n};\n\n// https://caniuse.com/#search=scroll-snap\n\nvar scrollSnap = {\n supportedProperty: function supportedProperty(prop) {\n if (prop.substring(0, 11) !== 'scroll-snap') return false;\n\n if (prefix.js === 'ms') {\n return \"\" + prefix.css + prop;\n }\n\n return prop;\n }\n};\n\n// https://caniuse.com/#search=overscroll-behavior\n\nvar overscrollBehavior = {\n supportedProperty: function supportedProperty(prop) {\n if (prop !== 'overscroll-behavior') return false;\n\n if (prefix.js === 'ms') {\n return prefix.css + \"scroll-chaining\";\n }\n\n return prop;\n }\n};\n\nvar propMap = {\n 'flex-grow': 'flex-positive',\n 'flex-shrink': 'flex-negative',\n 'flex-basis': 'flex-preferred-size',\n 'justify-content': 'flex-pack',\n order: 'flex-order',\n 'align-items': 'flex-align',\n 'align-content': 'flex-line-pack' // 'align-self' is handled by 'align-self' plugin.\n\n}; // Support old flex spec from 2012.\n\nvar flex2012 = {\n supportedProperty: function supportedProperty(prop, style) {\n var newProp = propMap[prop];\n if (!newProp) return false;\n return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false;\n }\n};\n\nvar propMap$1 = {\n flex: 'box-flex',\n 'flex-grow': 'box-flex',\n 'flex-direction': ['box-orient', 'box-direction'],\n order: 'box-ordinal-group',\n 'align-items': 'box-align',\n 'flex-flow': ['box-orient', 'box-direction'],\n 'justify-content': 'box-pack'\n};\nvar propKeys = Object.keys(propMap$1);\n\nvar prefixCss = function prefixCss(p) {\n return prefix.css + p;\n}; // Support old flex spec from 2009.\n\n\nvar flex2009 = {\n supportedProperty: function supportedProperty(prop, style, _ref) {\n var multiple = _ref.multiple;\n\n if (propKeys.indexOf(prop) > -1) {\n var newProp = propMap$1[prop];\n\n if (!Array.isArray(newProp)) {\n return prefix.js + pascalize(newProp) in style ? prefix.css + newProp : false;\n }\n\n if (!multiple) return false;\n\n for (var i = 0; i < newProp.length; i++) {\n if (!(prefix.js + pascalize(newProp[0]) in style)) {\n return false;\n }\n }\n\n return newProp.map(prefixCss);\n }\n\n return false;\n }\n};\n\n// plugins = [\n// ...plugins,\n// breakPropsOld,\n// inlineLogicalOld,\n// unprefixed,\n// prefixed,\n// scrollSnap,\n// flex2012,\n// flex2009\n// ]\n// Plugins without 'noPrefill' value, going last.\n// 'flex-*' plugins should be at the bottom.\n// 'flex2009' going after 'flex2012'.\n// 'prefixed' going after 'unprefixed'\n\nvar plugins = [appearence, colorAdjust, mask, textOrientation, transform, transition, writingMode, userSelect, breakPropsOld, inlineLogicalOld, unprefixed, prefixed, scrollSnap, overscrollBehavior, flex2012, flex2009];\nvar propertyDetectors = plugins.filter(function (p) {\n return p.supportedProperty;\n}).map(function (p) {\n return p.supportedProperty;\n});\nvar noPrefill = plugins.filter(function (p) {\n return p.noPrefill;\n}).reduce(function (a, p) {\n a.push.apply(a, _toConsumableArray(p.noPrefill));\n return a;\n}, []);\n\nvar el;\nvar cache = {};\n\nif (isInBrowser) {\n el = document.createElement('p'); // We test every property on vendor prefix requirement.\n // Once tested, result is cached. It gives us up to 70% perf boost.\n // http://jsperf.com/element-style-object-access-vs-plain-object\n //\n // Prefill cache with known css properties to reduce amount of\n // properties we need to feature test at runtime.\n // http://davidwalsh.name/vendor-prefix\n\n var computed = window.getComputedStyle(document.documentElement, '');\n\n for (var key$1 in computed) {\n // eslint-disable-next-line no-restricted-globals\n if (!isNaN(key$1)) cache[computed[key$1]] = computed[key$1];\n } // Properties that cannot be correctly detected using the\n // cache prefill method.\n\n\n noPrefill.forEach(function (x) {\n return delete cache[x];\n });\n}\n/**\n * Test if a property is supported, returns supported property with vendor\n * prefix if required. Returns `false` if not supported.\n *\n * @param {String} prop dash separated\n * @param {Object} [options]\n * @return {String|Boolean}\n * @api public\n */\n\n\nfunction supportedProperty(prop, options) {\n if (options === void 0) {\n options = {};\n }\n\n // For server-side rendering.\n if (!el) return prop; // Remove cache for benchmark tests or return property from the cache.\n\n if (process.env.NODE_ENV !== 'benchmark' && cache[prop] != null) {\n return cache[prop];\n } // Check if 'transition' or 'transform' natively supported in browser.\n\n\n if (prop === 'transition' || prop === 'transform') {\n options[prop] = prop in el.style;\n } // Find a plugin for current prefix property.\n\n\n for (var i = 0; i < propertyDetectors.length; i++) {\n cache[prop] = propertyDetectors[i](prop, el.style, options); // Break loop, if value found.\n\n if (cache[prop]) break;\n } // Reset styles for current property.\n // Firefox can even throw an error for invalid properties, e.g., \"0\".\n\n\n try {\n el.style[prop] = '';\n } catch (err) {\n return false;\n }\n\n return cache[prop];\n}\n\nvar cache$1 = {};\nvar transitionProperties = {\n transition: 1,\n 'transition-property': 1,\n '-webkit-transition': 1,\n '-webkit-transition-property': 1\n};\nvar transPropsRegExp = /(^\\s*[\\w-]+)|, (\\s*[\\w-]+)(?![^()]*\\))/g;\nvar el$1;\n/**\n * Returns prefixed value transition/transform if needed.\n *\n * @param {String} match\n * @param {String} p1\n * @param {String} p2\n * @return {String}\n * @api private\n */\n\nfunction prefixTransitionCallback(match, p1, p2) {\n if (p1 === 'var') return 'var';\n if (p1 === 'all') return 'all';\n if (p2 === 'all') return ', all';\n var prefixedValue = p1 ? supportedProperty(p1) : \", \" + supportedProperty(p2);\n if (!prefixedValue) return p1 || p2;\n return prefixedValue;\n}\n\nif (isInBrowser) el$1 = document.createElement('p');\n/**\n * Returns prefixed value if needed. Returns `false` if value is not supported.\n *\n * @param {String} property\n * @param {String} value\n * @return {String|Boolean}\n * @api public\n */\n\nfunction supportedValue(property, value) {\n // For server-side rendering.\n var prefixedValue = value;\n if (!el$1 || property === 'content') return value; // It is a string or a number as a string like '1'.\n // We want only prefixable values here.\n // eslint-disable-next-line no-restricted-globals\n\n if (typeof prefixedValue !== 'string' || !isNaN(parseInt(prefixedValue, 10))) {\n return prefixedValue;\n } // Create cache key for current value.\n\n\n var cacheKey = property + prefixedValue; // Remove cache for benchmark tests or return value from cache.\n\n if (process.env.NODE_ENV !== 'benchmark' && cache$1[cacheKey] != null) {\n return cache$1[cacheKey];\n } // IE can even throw an error in some cases, for e.g. style.content = 'bar'.\n\n\n try {\n // Test value as it is.\n el$1.style[property] = prefixedValue;\n } catch (err) {\n // Return false if value not supported.\n cache$1[cacheKey] = false;\n return false;\n } // If 'transition' or 'transition-property' property.\n\n\n if (transitionProperties[property]) {\n prefixedValue = prefixedValue.replace(transPropsRegExp, prefixTransitionCallback);\n } else if (el$1.style[property] === '') {\n // Value with a vendor prefix.\n prefixedValue = prefix.css + prefixedValue; // Hardcode test to convert \"flex\" to \"-ms-flexbox\" for IE10.\n\n if (prefixedValue === '-ms-flex') el$1.style[property] = '-ms-flexbox'; // Test prefixed value.\n\n el$1.style[property] = prefixedValue; // Return false if value not supported.\n\n if (el$1.style[property] === '') {\n cache$1[cacheKey] = false;\n return false;\n }\n } // Reset styles for current property.\n\n\n el$1.style[property] = ''; // Write current value to cache.\n\n cache$1[cacheKey] = prefixedValue;\n return cache$1[cacheKey];\n}\n\nexport { prefix, supportedKeyframes, supportedProperty, supportedValue };\n","import { supportedKeyframes, supportedValue, supportedProperty } from 'css-vendor';\nimport { toCssValue } from 'jss';\n\n/**\n * Add vendor prefix to a property name when needed.\n *\n * @api public\n */\n\nfunction jssVendorPrefixer() {\n function onProcessRule(rule) {\n if (rule.type === 'keyframes') {\n var atRule = rule;\n atRule.at = supportedKeyframes(atRule.at);\n }\n }\n\n function prefixStyle(style) {\n for (var prop in style) {\n var value = style[prop];\n\n if (prop === 'fallbacks' && Array.isArray(value)) {\n style[prop] = value.map(prefixStyle);\n continue;\n }\n\n var changeProp = false;\n var supportedProp = supportedProperty(prop);\n if (supportedProp && supportedProp !== prop) changeProp = true;\n var changeValue = false;\n var supportedValue$1 = supportedValue(supportedProp, toCssValue(value));\n if (supportedValue$1 && supportedValue$1 !== value) changeValue = true;\n\n if (changeProp || changeValue) {\n if (changeProp) delete style[prop];\n style[supportedProp || prop] = supportedValue$1 || value;\n }\n }\n\n return style;\n }\n\n function onProcessStyle(style, rule) {\n if (rule.type !== 'style') return style;\n return prefixStyle(style);\n }\n\n function onChangeValue(value, prop) {\n return supportedValue(prop, toCssValue(value)) || value;\n }\n\n return {\n onProcessRule: onProcessRule,\n onProcessStyle: onProcessStyle,\n onChangeValue: onChangeValue\n };\n}\n\nexport default jssVendorPrefixer;\n","/**\n * Sort props by length.\n */\nfunction jssPropsSort() {\n var sort = function sort(prop0, prop1) {\n if (prop0.length === prop1.length) {\n return prop0 > prop1 ? 1 : -1;\n }\n\n return prop0.length - prop1.length;\n };\n\n return {\n onProcessStyle: function onProcessStyle(style, rule) {\n if (rule.type !== 'style') return style;\n var newStyle = {};\n var props = Object.keys(style).sort(sort);\n\n for (var i = 0; i < props.length; i++) {\n newStyle[props[i]] = style[props[i]];\n }\n\n return newStyle;\n }\n };\n}\n\nexport default jssPropsSort;\n","import functions from 'jss-plugin-rule-value-function';\nimport global from 'jss-plugin-global';\nimport nested from 'jss-plugin-nested';\nimport camelCase from 'jss-plugin-camel-case';\nimport defaultUnit from 'jss-plugin-default-unit';\nimport vendorPrefixer from 'jss-plugin-vendor-prefixer';\nimport propsSort from 'jss-plugin-props-sort'; // Subset of jss-preset-default with only the plugins the Material-UI components are using.\n\nexport default function jssPreset() {\n return {\n plugins: [functions(), global(), nested(), camelCase(), defaultUnit(), // Disable the vendor prefixer server-side, it does nothing.\n // This way, we can get a performance boost.\n // In the documentation, we are using `autoprefixer` to solve this problem.\n typeof window === 'undefined' ? null : vendorPrefixer(), propsSort()]\n };\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport { exactProp } from '@material-ui/utils';\nimport createGenerateClassName from '../createGenerateClassName';\nimport { create } from 'jss';\nimport jssPreset from '../jssPreset'; // Default JSS instance.\n\nvar jss = create(jssPreset()); // Use a singleton or the provided one by the context.\n//\n// The counter-based approach doesn't tolerate any mistake.\n// It's much safer to use the same counter everywhere.\n\nvar generateClassName = createGenerateClassName(); // Exported for test purposes\n\nexport var sheetsManager = new Map();\nvar defaultOptions = {\n disableGeneration: false,\n generateClassName: generateClassName,\n jss: jss,\n sheetsCache: null,\n sheetsManager: sheetsManager,\n sheetsRegistry: null\n};\nexport var StylesContext = React.createContext(defaultOptions);\n\nif (process.env.NODE_ENV !== 'production') {\n StylesContext.displayName = 'StylesContext';\n}\n\nvar injectFirstNode;\nexport default function StylesProvider(props) {\n var children = props.children,\n _props$injectFirst = props.injectFirst,\n injectFirst = _props$injectFirst === void 0 ? false : _props$injectFirst,\n _props$disableGenerat = props.disableGeneration,\n disableGeneration = _props$disableGenerat === void 0 ? false : _props$disableGenerat,\n localOptions = _objectWithoutProperties(props, [\"children\", \"injectFirst\", \"disableGeneration\"]);\n\n var outerOptions = React.useContext(StylesContext);\n\n var context = _extends({}, outerOptions, {\n disableGeneration: disableGeneration\n }, localOptions);\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof window === 'undefined' && !context.sheetsManager) {\n console.error('Material-UI: You need to use the ServerStyleSheets API when rendering on the server.');\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (context.jss.options.insertionPoint && injectFirst) {\n console.error('Material-UI: You cannot use a custom insertionPoint and <StylesContext injectFirst> at the same time.');\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (injectFirst && localOptions.jss) {\n console.error('Material-UI: You cannot use the jss and injectFirst props at the same time.');\n }\n }\n\n if (!context.jss.options.insertionPoint && injectFirst && typeof window !== 'undefined') {\n if (!injectFirstNode) {\n var head = document.head;\n injectFirstNode = document.createComment('mui-inject-first');\n head.insertBefore(injectFirstNode, head.firstChild);\n }\n\n context.jss = create({\n plugins: jssPreset().plugins,\n insertionPoint: injectFirstNode\n });\n }\n\n return /*#__PURE__*/React.createElement(StylesContext.Provider, {\n value: context\n }, children);\n}\nprocess.env.NODE_ENV !== \"production\" ? StylesProvider.propTypes = {\n /**\n * Your component tree.\n */\n children: PropTypes.node.isRequired,\n\n /**\n * You can disable the generation of the styles with this option.\n * It can be useful when traversing the React tree outside of the HTML\n * rendering step on the server.\n * Let's say you are using react-apollo to extract all\n * the queries made by the interface server-side - you can significantly speed up the traversal with this prop.\n */\n disableGeneration: PropTypes.bool,\n\n /**\n * JSS's class name generator.\n */\n generateClassName: PropTypes.func,\n\n /**\n * By default, the styles are injected last in the <head> element of the page.\n * As a result, they gain more specificity than any other style sheet.\n * If you want to override Material-UI's styles, set this prop.\n */\n injectFirst: PropTypes.bool,\n\n /**\n * JSS's instance.\n */\n jss: PropTypes.object,\n\n /**\n * @ignore\n */\n serverGenerateClassName: PropTypes.func,\n\n /**\n * @ignore\n *\n * Beta feature.\n *\n * Cache for the sheets.\n */\n sheetsCache: PropTypes.object,\n\n /**\n * @ignore\n *\n * The sheetsManager is used to deduplicate style sheet injection in the page.\n * It's deduplicating using the (theme, styles) couple.\n * On the server, you should provide a new instance for each request.\n */\n sheetsManager: PropTypes.object,\n\n /**\n * @ignore\n *\n * Collect the sheets.\n */\n sheetsRegistry: PropTypes.object\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n process.env.NODE_ENV !== \"production\" ? StylesProvider.propTypes = exactProp(StylesProvider.propTypes) : void 0;\n}","/* eslint-disable import/prefer-default-export */\n// Global index counter to preserve source order.\n// We create the style sheet during the creation of the component,\n// children are handled after the parents, so the order of style elements would be parent->child.\n// It is a problem though when a parent passes a className\n// which needs to override any child's styles.\n// StyleSheet of the child has a higher specificity, because of the source order.\n// So our solution is to render sheets them in the reverse order child->sheet, so\n// that parent has a higher specificity.\nvar indexCounter = -1e9;\nexport function increment() {\n indexCounter += 1;\n\n if (process.env.NODE_ENV !== 'production') {\n if (indexCounter >= 0) {\n console.warn(['Material-UI: You might have a memory leak.', 'The indexCounter is not supposed to grow that much.'].join('\\n'));\n }\n }\n\n return indexCounter;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport { deepmerge } from '@material-ui/utils';\nimport noopTheme from './noopTheme';\nexport default function getStylesCreator(stylesOrCreator) {\n var themingEnabled = typeof stylesOrCreator === 'function';\n\n if (process.env.NODE_ENV !== 'production') {\n if (_typeof(stylesOrCreator) !== 'object' && !themingEnabled) {\n console.error(['Material-UI: The `styles` argument provided is invalid.', 'You need to provide a function generating the styles or a styles object.'].join('\\n'));\n }\n }\n\n return {\n create: function create(theme, name) {\n var styles;\n\n try {\n styles = themingEnabled ? stylesOrCreator(theme) : stylesOrCreator;\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n if (themingEnabled === true && theme === noopTheme) {\n // TODO: prepend error message/name instead\n console.error(['Material-UI: The `styles` argument provided is invalid.', 'You are providing a function without a theme in the context.', 'One of the parent elements needs to use a ThemeProvider.'].join('\\n'));\n }\n }\n\n throw err;\n }\n\n if (!name || !theme.overrides || !theme.overrides[name]) {\n return styles;\n }\n\n var overrides = theme.overrides[name];\n\n var stylesWithOverrides = _extends({}, styles);\n\n Object.keys(overrides).forEach(function (key) {\n if (process.env.NODE_ENV !== 'production') {\n if (!stylesWithOverrides[key]) {\n console.warn(['Material-UI: You are trying to override a style that does not exist.', \"Fix the `\".concat(key, \"` key of `theme.overrides.\").concat(name, \"`.\")].join('\\n'));\n }\n }\n\n stylesWithOverrides[key] = deepmerge(stylesWithOverrides[key], overrides[key]);\n });\n return stylesWithOverrides;\n },\n options: {}\n };\n}","// We use the same empty object to ref count the styles that don't need a theme object.\nvar noopTheme = {};\nexport default noopTheme;","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport React from 'react';\nimport { getDynamicStyles } from 'jss';\nimport mergeClasses from '../mergeClasses';\nimport multiKeyStore from './multiKeyStore';\nimport useTheme from '../useTheme';\nimport { StylesContext } from '../StylesProvider';\nimport { increment } from './indexCounter';\nimport getStylesCreator from '../getStylesCreator';\nimport noopTheme from '../getStylesCreator/noopTheme';\n\nfunction getClasses(_ref, classes, Component) {\n var state = _ref.state,\n stylesOptions = _ref.stylesOptions;\n\n if (stylesOptions.disableGeneration) {\n return classes || {};\n }\n\n if (!state.cacheClasses) {\n state.cacheClasses = {\n // Cache for the finalized classes value.\n value: null,\n // Cache for the last used classes prop pointer.\n lastProp: null,\n // Cache for the last used rendered classes pointer.\n lastJSS: {}\n };\n } // Tracks if either the rendered classes or classes prop has changed,\n // requiring the generation of a new finalized classes object.\n\n\n var generate = false;\n\n if (state.classes !== state.cacheClasses.lastJSS) {\n state.cacheClasses.lastJSS = state.classes;\n generate = true;\n }\n\n if (classes !== state.cacheClasses.lastProp) {\n state.cacheClasses.lastProp = classes;\n generate = true;\n }\n\n if (generate) {\n state.cacheClasses.value = mergeClasses({\n baseClasses: state.cacheClasses.lastJSS,\n newClasses: classes,\n Component: Component\n });\n }\n\n return state.cacheClasses.value;\n}\n\nfunction attach(_ref2, props) {\n var state = _ref2.state,\n theme = _ref2.theme,\n stylesOptions = _ref2.stylesOptions,\n stylesCreator = _ref2.stylesCreator,\n name = _ref2.name;\n\n if (stylesOptions.disableGeneration) {\n return;\n }\n\n var sheetManager = multiKeyStore.get(stylesOptions.sheetsManager, stylesCreator, theme);\n\n if (!sheetManager) {\n sheetManager = {\n refs: 0,\n staticSheet: null,\n dynamicStyles: null\n };\n multiKeyStore.set(stylesOptions.sheetsManager, stylesCreator, theme, sheetManager);\n }\n\n var options = _extends({}, stylesCreator.options, stylesOptions, {\n theme: theme,\n flip: typeof stylesOptions.flip === 'boolean' ? stylesOptions.flip : theme.direction === 'rtl'\n });\n\n options.generateId = options.serverGenerateClassName || options.generateClassName;\n var sheetsRegistry = stylesOptions.sheetsRegistry;\n\n if (sheetManager.refs === 0) {\n var staticSheet;\n\n if (stylesOptions.sheetsCache) {\n staticSheet = multiKeyStore.get(stylesOptions.sheetsCache, stylesCreator, theme);\n }\n\n var styles = stylesCreator.create(theme, name);\n\n if (!staticSheet) {\n staticSheet = stylesOptions.jss.createStyleSheet(styles, _extends({\n link: false\n }, options));\n staticSheet.attach();\n\n if (stylesOptions.sheetsCache) {\n multiKeyStore.set(stylesOptions.sheetsCache, stylesCreator, theme, staticSheet);\n }\n }\n\n if (sheetsRegistry) {\n sheetsRegistry.add(staticSheet);\n }\n\n sheetManager.staticSheet = staticSheet;\n sheetManager.dynamicStyles = getDynamicStyles(styles);\n }\n\n if (sheetManager.dynamicStyles) {\n var dynamicSheet = stylesOptions.jss.createStyleSheet(sheetManager.dynamicStyles, _extends({\n link: true\n }, options));\n dynamicSheet.update(props);\n dynamicSheet.attach();\n state.dynamicSheet = dynamicSheet;\n state.classes = mergeClasses({\n baseClasses: sheetManager.staticSheet.classes,\n newClasses: dynamicSheet.classes\n });\n\n if (sheetsRegistry) {\n sheetsRegistry.add(dynamicSheet);\n }\n } else {\n state.classes = sheetManager.staticSheet.classes;\n }\n\n sheetManager.refs += 1;\n}\n\nfunction update(_ref3, props) {\n var state = _ref3.state;\n\n if (state.dynamicSheet) {\n state.dynamicSheet.update(props);\n }\n}\n\nfunction detach(_ref4) {\n var state = _ref4.state,\n theme = _ref4.theme,\n stylesOptions = _ref4.stylesOptions,\n stylesCreator = _ref4.stylesCreator;\n\n if (stylesOptions.disableGeneration) {\n return;\n }\n\n var sheetManager = multiKeyStore.get(stylesOptions.sheetsManager, stylesCreator, theme);\n sheetManager.refs -= 1;\n var sheetsRegistry = stylesOptions.sheetsRegistry;\n\n if (sheetManager.refs === 0) {\n multiKeyStore.delete(stylesOptions.sheetsManager, stylesCreator, theme);\n stylesOptions.jss.removeStyleSheet(sheetManager.staticSheet);\n\n if (sheetsRegistry) {\n sheetsRegistry.remove(sheetManager.staticSheet);\n }\n }\n\n if (state.dynamicSheet) {\n stylesOptions.jss.removeStyleSheet(state.dynamicSheet);\n\n if (sheetsRegistry) {\n sheetsRegistry.remove(state.dynamicSheet);\n }\n }\n}\n\nfunction useSynchronousEffect(func, values) {\n var key = React.useRef([]);\n var output; // Store \"generation\" key. Just returns a new object every time\n\n var currentKey = React.useMemo(function () {\n return {};\n }, values); // eslint-disable-line react-hooks/exhaustive-deps\n // \"the first render\", or \"memo dropped the value\"\n\n if (key.current !== currentKey) {\n key.current = currentKey;\n output = func();\n }\n\n React.useEffect(function () {\n return function () {\n if (output) {\n output();\n }\n };\n }, [currentKey] // eslint-disable-line react-hooks/exhaustive-deps\n );\n}\n\nexport default function makeStyles(stylesOrCreator) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n var name = options.name,\n classNamePrefixOption = options.classNamePrefix,\n Component = options.Component,\n _options$defaultTheme = options.defaultTheme,\n defaultTheme = _options$defaultTheme === void 0 ? noopTheme : _options$defaultTheme,\n stylesOptions2 = _objectWithoutProperties(options, [\"name\", \"classNamePrefix\", \"Component\", \"defaultTheme\"]);\n\n var stylesCreator = getStylesCreator(stylesOrCreator);\n var classNamePrefix = name || classNamePrefixOption || 'makeStyles';\n stylesCreator.options = {\n index: increment(),\n name: name,\n meta: classNamePrefix,\n classNamePrefix: classNamePrefix\n };\n\n var useStyles = function useStyles() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var theme = useTheme() || defaultTheme;\n\n var stylesOptions = _extends({}, React.useContext(StylesContext), stylesOptions2);\n\n var instance = React.useRef();\n var shouldUpdate = React.useRef();\n useSynchronousEffect(function () {\n var current = {\n name: name,\n state: {},\n stylesCreator: stylesCreator,\n stylesOptions: stylesOptions,\n theme: theme\n };\n attach(current, props);\n shouldUpdate.current = false;\n instance.current = current;\n return function () {\n detach(current);\n };\n }, [theme, stylesCreator]);\n React.useEffect(function () {\n if (shouldUpdate.current) {\n update(instance.current, props);\n }\n\n shouldUpdate.current = true;\n });\n var classes = getClasses(instance.current, props.classes, Component);\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(classes);\n }\n\n return classes;\n };\n\n return useStyles;\n}","import React from 'react';\nvar ThemeContext = React.createContext(null);\n\nif (process.env.NODE_ENV !== 'production') {\n ThemeContext.displayName = 'ThemeContext';\n}\n\nexport default ThemeContext;","import React from 'react';\nimport ThemeContext from './ThemeContext';\nexport default function useTheme() {\n var theme = React.useContext(ThemeContext);\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(theme);\n }\n\n return theme;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport { getDisplayName } from '@material-ui/utils';\nexport default function mergeClasses() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var baseClasses = options.baseClasses,\n newClasses = options.newClasses,\n Component = options.Component;\n\n if (!newClasses) {\n return baseClasses;\n }\n\n var nextClasses = _extends({}, baseClasses);\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof newClasses === 'string') {\n console.error([\"Material-UI: The value `\".concat(newClasses, \"` \") + \"provided to the classes prop of \".concat(getDisplayName(Component), \" is incorrect.\"), 'You might want to use the className prop instead.'].join('\\n'));\n return baseClasses;\n }\n }\n\n Object.keys(newClasses).forEach(function (key) {\n if (process.env.NODE_ENV !== 'production') {\n if (!baseClasses[key] && newClasses[key]) {\n console.error([\"Material-UI: The key `\".concat(key, \"` \") + \"provided to the classes prop is not implemented in \".concat(getDisplayName(Component), \".\"), \"You can only override one of the following: \".concat(Object.keys(baseClasses).join(','), \".\")].join('\\n'));\n }\n\n if (newClasses[key] && typeof newClasses[key] !== 'string') {\n console.error([\"Material-UI: The key `\".concat(key, \"` \") + \"provided to the classes prop is not valid for \".concat(getDisplayName(Component), \".\"), \"You need to provide a non empty string instead of: \".concat(newClasses[key], \".\")].join('\\n'));\n }\n }\n\n if (newClasses[key]) {\n nextClasses[key] = \"\".concat(baseClasses[key], \" \").concat(newClasses[key]);\n }\n });\n return nextClasses;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n margin: 0\n },\n\n /* Styles applied to the root element if `variant=\"body2\"`. */\n body2: theme.typography.body2,\n\n /* Styles applied to the root element if `variant=\"body1\"`. */\n body1: theme.typography.body1,\n\n /* Styles applied to the root element if `variant=\"caption\"`. */\n caption: theme.typography.caption,\n\n /* Styles applied to the root element if `variant=\"button\"`. */\n button: theme.typography.button,\n\n /* Styles applied to the root element if `variant=\"h1\"`. */\n h1: theme.typography.h1,\n\n /* Styles applied to the root element if `variant=\"h2\"`. */\n h2: theme.typography.h2,\n\n /* Styles applied to the root element if `variant=\"h3\"`. */\n h3: theme.typography.h3,\n\n /* Styles applied to the root element if `variant=\"h4\"`. */\n h4: theme.typography.h4,\n\n /* Styles applied to the root element if `variant=\"h5\"`. */\n h5: theme.typography.h5,\n\n /* Styles applied to the root element if `variant=\"h6\"`. */\n h6: theme.typography.h6,\n\n /* Styles applied to the root element if `variant=\"subtitle1\"`. */\n subtitle1: theme.typography.subtitle1,\n\n /* Styles applied to the root element if `variant=\"subtitle2\"`. */\n subtitle2: theme.typography.subtitle2,\n\n /* Styles applied to the root element if `variant=\"overline\"`. */\n overline: theme.typography.overline,\n\n /* Styles applied to the root element if `variant=\"srOnly\"`. Only accessible to screen readers. */\n srOnly: {\n position: 'absolute',\n height: 1,\n width: 1,\n overflow: 'hidden'\n },\n\n /* Styles applied to the root element if `align=\"left\"`. */\n alignLeft: {\n textAlign: 'left'\n },\n\n /* Styles applied to the root element if `align=\"center\"`. */\n alignCenter: {\n textAlign: 'center'\n },\n\n /* Styles applied to the root element if `align=\"right\"`. */\n alignRight: {\n textAlign: 'right'\n },\n\n /* Styles applied to the root element if `align=\"justify\"`. */\n alignJustify: {\n textAlign: 'justify'\n },\n\n /* Styles applied to the root element if `nowrap={true}`. */\n noWrap: {\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap'\n },\n\n /* Styles applied to the root element if `gutterBottom={true}`. */\n gutterBottom: {\n marginBottom: '0.35em'\n },\n\n /* Styles applied to the root element if `paragraph={true}`. */\n paragraph: {\n marginBottom: 16\n },\n\n /* Styles applied to the root element if `color=\"inherit\"`. */\n colorInherit: {\n color: 'inherit'\n },\n\n /* Styles applied to the root element if `color=\"primary\"`. */\n colorPrimary: {\n color: theme.palette.primary.main\n },\n\n /* Styles applied to the root element if `color=\"secondary\"`. */\n colorSecondary: {\n color: theme.palette.secondary.main\n },\n\n /* Styles applied to the root element if `color=\"textPrimary\"`. */\n colorTextPrimary: {\n color: theme.palette.text.primary\n },\n\n /* Styles applied to the root element if `color=\"textSecondary\"`. */\n colorTextSecondary: {\n color: theme.palette.text.secondary\n },\n\n /* Styles applied to the root element if `color=\"error\"`. */\n colorError: {\n color: theme.palette.error.main\n },\n\n /* Styles applied to the root element if `display=\"inline\"`. */\n displayInline: {\n display: 'inline'\n },\n\n /* Styles applied to the root element if `display=\"block\"`. */\n displayBlock: {\n display: 'block'\n }\n };\n};\nvar defaultVariantMapping = {\n h1: 'h1',\n h2: 'h2',\n h3: 'h3',\n h4: 'h4',\n h5: 'h5',\n h6: 'h6',\n subtitle1: 'h6',\n subtitle2: 'h6',\n body1: 'p',\n body2: 'p'\n};\nvar Typography = /*#__PURE__*/React.forwardRef(function Typography(props, ref) {\n var _props$align = props.align,\n align = _props$align === void 0 ? 'inherit' : _props$align,\n classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'initial' : _props$color,\n component = props.component,\n _props$display = props.display,\n display = _props$display === void 0 ? 'initial' : _props$display,\n _props$gutterBottom = props.gutterBottom,\n gutterBottom = _props$gutterBottom === void 0 ? false : _props$gutterBottom,\n _props$noWrap = props.noWrap,\n noWrap = _props$noWrap === void 0 ? false : _props$noWrap,\n _props$paragraph = props.paragraph,\n paragraph = _props$paragraph === void 0 ? false : _props$paragraph,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'body1' : _props$variant,\n _props$variantMapping = props.variantMapping,\n variantMapping = _props$variantMapping === void 0 ? defaultVariantMapping : _props$variantMapping,\n other = _objectWithoutProperties(props, [\"align\", \"classes\", \"className\", \"color\", \"component\", \"display\", \"gutterBottom\", \"noWrap\", \"paragraph\", \"variant\", \"variantMapping\"]);\n\n var Component = component || (paragraph ? 'p' : variantMapping[variant] || defaultVariantMapping[variant]) || 'span';\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, variant !== 'inherit' && classes[variant], color !== 'initial' && classes[\"color\".concat(capitalize(color))], noWrap && classes.noWrap, gutterBottom && classes.gutterBottom, paragraph && classes.paragraph, align !== 'inherit' && classes[\"align\".concat(capitalize(align))], display !== 'initial' && classes[\"display\".concat(capitalize(display))]),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? Typography.propTypes = {\n /**\n * Set the text-align on the component.\n */\n align: PropTypes.oneOf(['inherit', 'left', 'center', 'right', 'justify']),\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['initial', 'inherit', 'primary', 'secondary', 'textPrimary', 'textSecondary', 'error']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n * Overrides the behavior of the `variantMapping` prop.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * Controls the display type\n */\n display: PropTypes.oneOf(['initial', 'block', 'inline']),\n\n /**\n * If `true`, the text will have a bottom margin.\n */\n gutterBottom: PropTypes.bool,\n\n /**\n * If `true`, the text will not wrap, but instead will truncate with a text overflow ellipsis.\n *\n * Note that text overflow can only happen with block or inline-block level elements\n * (the element needs to have a width in order to overflow).\n */\n noWrap: PropTypes.bool,\n\n /**\n * If `true`, the text will have a bottom margin.\n */\n paragraph: PropTypes.bool,\n\n /**\n * Applies the theme typography styles.\n */\n variant: PropTypes.oneOf(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1', 'subtitle2', 'body1', 'body2', 'caption', 'button', 'overline', 'srOnly', 'inherit']),\n\n /**\n * The component maps the variant prop to a range of different HTML element types.\n * For instance, subtitle1 to `<h6>`.\n * If you wish to change that mapping, you can provide your own.\n * Alternatively, you can use the `component` prop.\n */\n variantMapping: PropTypes.object\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTypography'\n})(Typography);","/* eslint-disable no-restricted-syntax */\nexport default function getThemeProps(params) {\n var theme = params.theme,\n name = params.name,\n props = params.props;\n\n if (!theme || !theme.props || !theme.props[name]) {\n return props;\n } // Resolve default props, code borrow from React source.\n // https://github.com/facebook/react/blob/15a8f031838a553e41c0b66eb1bcf1da8448104d/packages/react/src/ReactElement.js#L221\n\n\n var defaultProps = theme.props[name];\n var propName;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n\n return props;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport capitalize from '../utils/capitalize';\nimport withStyles from '../styles/withStyles';\nimport { darken, lighten } from '../styles/colorManipulator';\nimport useTheme from '../styles/useTheme';\nvar TRANSITION_DURATION = 4; // seconds\n\nexport var styles = function styles(theme) {\n var getColor = function getColor(color) {\n return theme.palette.type === 'light' ? lighten(color, 0.62) : darken(color, 0.5);\n };\n\n var backgroundPrimary = getColor(theme.palette.primary.main);\n var backgroundSecondary = getColor(theme.palette.secondary.main);\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'relative',\n overflow: 'hidden',\n height: 4,\n '@media print': {\n colorAdjust: 'exact'\n }\n },\n\n /* Styles applied to the root and bar2 element if `color=\"primary\"`; bar2 if `variant=\"buffer\"`. */\n colorPrimary: {\n backgroundColor: backgroundPrimary\n },\n\n /* Styles applied to the root and bar2 elements if `color=\"secondary\"`; bar2 if `variant=\"buffer\"`. */\n colorSecondary: {\n backgroundColor: backgroundSecondary\n },\n\n /* Styles applied to the root element if `variant=\"determinate\"`. */\n determinate: {},\n\n /* Styles applied to the root element if `variant=\"indeterminate\"`. */\n indeterminate: {},\n\n /* Styles applied to the root element if `variant=\"buffer\"`. */\n buffer: {\n backgroundColor: 'transparent'\n },\n\n /* Styles applied to the root element if `variant=\"query\"`. */\n query: {\n transform: 'rotate(180deg)'\n },\n\n /* Styles applied to the additional bar element if `variant=\"buffer\"`. */\n dashed: {\n position: 'absolute',\n marginTop: 0,\n height: '100%',\n width: '100%',\n animation: '$buffer 3s infinite linear'\n },\n\n /* Styles applied to the additional bar element if `variant=\"buffer\"` and `color=\"primary\"`. */\n dashedColorPrimary: {\n backgroundImage: \"radial-gradient(\".concat(backgroundPrimary, \" 0%, \").concat(backgroundPrimary, \" 16%, transparent 42%)\"),\n backgroundSize: '10px 10px',\n backgroundPosition: '0 -23px'\n },\n\n /* Styles applied to the additional bar element if `variant=\"buffer\"` and `color=\"secondary\"`. */\n dashedColorSecondary: {\n backgroundImage: \"radial-gradient(\".concat(backgroundSecondary, \" 0%, \").concat(backgroundSecondary, \" 16%, transparent 42%)\"),\n backgroundSize: '10px 10px',\n backgroundPosition: '0 -23px'\n },\n\n /* Styles applied to the layered bar1 and bar2 elements. */\n bar: {\n width: '100%',\n position: 'absolute',\n left: 0,\n bottom: 0,\n top: 0,\n transition: 'transform 0.2s linear',\n transformOrigin: 'left'\n },\n\n /* Styles applied to the bar elements if `color=\"primary\"`; bar2 if `variant` not \"buffer\". */\n barColorPrimary: {\n backgroundColor: theme.palette.primary.main\n },\n\n /* Styles applied to the bar elements if `color=\"secondary\"`; bar2 if `variant` not \"buffer\". */\n barColorSecondary: {\n backgroundColor: theme.palette.secondary.main\n },\n\n /* Styles applied to the bar1 element if `variant=\"indeterminate or query\"`. */\n bar1Indeterminate: {\n width: 'auto',\n animation: '$indeterminate1 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite'\n },\n\n /* Styles applied to the bar1 element if `variant=\"determinate\"`. */\n bar1Determinate: {\n transition: \"transform .\".concat(TRANSITION_DURATION, \"s linear\")\n },\n\n /* Styles applied to the bar1 element if `variant=\"buffer\"`. */\n bar1Buffer: {\n zIndex: 1,\n transition: \"transform .\".concat(TRANSITION_DURATION, \"s linear\")\n },\n\n /* Styles applied to the bar2 element if `variant=\"indeterminate or query\"`. */\n bar2Indeterminate: {\n width: 'auto',\n animation: '$indeterminate2 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite'\n },\n\n /* Styles applied to the bar2 element if `variant=\"buffer\"`. */\n bar2Buffer: {\n transition: \"transform .\".concat(TRANSITION_DURATION, \"s linear\")\n },\n // Legends:\n // || represents the viewport\n // - represents a light background\n // x represents a dark background\n '@keyframes indeterminate1': {\n // |-----|---x-||-----||-----|\n '0%': {\n left: '-35%',\n right: '100%'\n },\n // |-----|-----||-----||xxxx-|\n '60%': {\n left: '100%',\n right: '-90%'\n },\n '100%': {\n left: '100%',\n right: '-90%'\n }\n },\n '@keyframes indeterminate2': {\n // |xxxxx|xxxxx||-----||-----|\n '0%': {\n left: '-200%',\n right: '100%'\n },\n // |-----|-----||-----||-x----|\n '60%': {\n left: '107%',\n right: '-8%'\n },\n '100%': {\n left: '107%',\n right: '-8%'\n }\n },\n '@keyframes buffer': {\n '0%': {\n opacity: 1,\n backgroundPosition: '0 -23px'\n },\n '50%': {\n opacity: 0,\n backgroundPosition: '0 -23px'\n },\n '100%': {\n opacity: 1,\n backgroundPosition: '-200px -23px'\n }\n }\n };\n};\n/**\n * ## ARIA\n *\n * If the progress bar is describing the loading progress of a particular region of a page,\n * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`\n * attribute to `true` on that region until it has finished loading.\n */\n\nvar LinearProgress = /*#__PURE__*/React.forwardRef(function LinearProgress(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'primary' : _props$color,\n value = props.value,\n valueBuffer = props.valueBuffer,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'indeterminate' : _props$variant,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"color\", \"value\", \"valueBuffer\", \"variant\"]);\n\n var theme = useTheme();\n var rootProps = {};\n var inlineStyles = {\n bar1: {},\n bar2: {}\n };\n\n if (variant === 'determinate' || variant === 'buffer') {\n if (value !== undefined) {\n rootProps['aria-valuenow'] = Math.round(value);\n rootProps['aria-valuemin'] = 0;\n rootProps['aria-valuemax'] = 100;\n var transform = value - 100;\n\n if (theme.direction === 'rtl') {\n transform = -transform;\n }\n\n inlineStyles.bar1.transform = \"translateX(\".concat(transform, \"%)\");\n } else if (process.env.NODE_ENV !== 'production') {\n console.error('Material-UI: You need to provide a value prop ' + 'when using the determinate or buffer variant of LinearProgress .');\n }\n }\n\n if (variant === 'buffer') {\n if (valueBuffer !== undefined) {\n var _transform = (valueBuffer || 0) - 100;\n\n if (theme.direction === 'rtl') {\n _transform = -_transform;\n }\n\n inlineStyles.bar2.transform = \"translateX(\".concat(_transform, \"%)\");\n } else if (process.env.NODE_ENV !== 'production') {\n console.error('Material-UI: You need to provide a valueBuffer prop ' + 'when using the buffer variant of LinearProgress.');\n }\n }\n\n return /*#__PURE__*/React.createElement(\"div\", _extends({\n className: clsx(classes.root, classes[\"color\".concat(capitalize(color))], className, {\n 'determinate': classes.determinate,\n 'indeterminate': classes.indeterminate,\n 'buffer': classes.buffer,\n 'query': classes.query\n }[variant]),\n role: \"progressbar\"\n }, rootProps, {\n ref: ref\n }, other), variant === 'buffer' ? /*#__PURE__*/React.createElement(\"div\", {\n className: clsx(classes.dashed, classes[\"dashedColor\".concat(capitalize(color))])\n }) : null, /*#__PURE__*/React.createElement(\"div\", {\n className: clsx(classes.bar, classes[\"barColor\".concat(capitalize(color))], (variant === 'indeterminate' || variant === 'query') && classes.bar1Indeterminate, {\n 'determinate': classes.bar1Determinate,\n 'buffer': classes.bar1Buffer\n }[variant]),\n style: inlineStyles.bar1\n }), variant === 'determinate' ? null : /*#__PURE__*/React.createElement(\"div\", {\n className: clsx(classes.bar, (variant === 'indeterminate' || variant === 'query') && classes.bar2Indeterminate, variant === 'buffer' ? [classes[\"color\".concat(capitalize(color))], classes.bar2Buffer] : classes[\"barColor\".concat(capitalize(color))]),\n style: inlineStyles.bar2\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? LinearProgress.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The value of the progress indicator for the determinate and buffer variants.\n * Value between 0 and 100.\n */\n value: PropTypes.number,\n\n /**\n * The value for the buffer variant.\n * Value between 0 and 100.\n */\n valueBuffer: PropTypes.number,\n\n /**\n * The variant to use.\n * Use indeterminate or query when there is no progress value.\n */\n variant: PropTypes.oneOf(['buffer', 'determinate', 'indeterminate', 'query'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiLinearProgress'\n})(LinearProgress);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport { fade } from '../styles/colorManipulator';\nimport ButtonBase from '../ButtonBase';\nimport capitalize from '../utils/capitalize';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: _extends({}, theme.typography.button, {\n boxSizing: 'border-box',\n minWidth: 64,\n padding: '6px 16px',\n borderRadius: theme.shape.borderRadius,\n color: theme.palette.text.primary,\n transition: theme.transitions.create(['background-color', 'box-shadow', 'border'], {\n duration: theme.transitions.duration.short\n }),\n '&:hover': {\n textDecoration: 'none',\n backgroundColor: fade(theme.palette.text.primary, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n },\n '&$disabled': {\n backgroundColor: 'transparent'\n }\n },\n '&$disabled': {\n color: theme.palette.action.disabled\n }\n }),\n\n /* Styles applied to the span element that wraps the children. */\n label: {\n width: '100%',\n // Ensure the correct width for iOS Safari\n display: 'inherit',\n alignItems: 'inherit',\n justifyContent: 'inherit'\n },\n\n /* Styles applied to the root element if `variant=\"text\"`. */\n text: {\n padding: '6px 8px'\n },\n\n /* Styles applied to the root element if `variant=\"text\"` and `color=\"primary\"`. */\n textPrimary: {\n color: theme.palette.primary.main,\n '&:hover': {\n backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"text\"` and `color=\"secondary\"`. */\n textSecondary: {\n color: theme.palette.secondary.main,\n '&:hover': {\n backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"`. */\n outlined: {\n padding: '5px 15px',\n border: \"1px solid \".concat(theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'),\n '&$disabled': {\n border: \"1px solid \".concat(theme.palette.action.disabledBackground)\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"` and `color=\"primary\"`. */\n outlinedPrimary: {\n color: theme.palette.primary.main,\n border: \"1px solid \".concat(fade(theme.palette.primary.main, 0.5)),\n '&:hover': {\n border: \"1px solid \".concat(theme.palette.primary.main),\n backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"` and `color=\"secondary\"`. */\n outlinedSecondary: {\n color: theme.palette.secondary.main,\n border: \"1px solid \".concat(fade(theme.palette.secondary.main, 0.5)),\n '&:hover': {\n border: \"1px solid \".concat(theme.palette.secondary.main),\n backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n },\n '&$disabled': {\n border: \"1px solid \".concat(theme.palette.action.disabled)\n }\n },\n\n /* Styles applied to the root element if `variant=\"contained\"`. */\n contained: {\n color: theme.palette.getContrastText(theme.palette.grey[300]),\n backgroundColor: theme.palette.grey[300],\n boxShadow: theme.shadows[2],\n '&:hover': {\n backgroundColor: theme.palette.grey.A100,\n boxShadow: theme.shadows[4],\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n boxShadow: theme.shadows[2],\n backgroundColor: theme.palette.grey[300]\n },\n '&$disabled': {\n backgroundColor: theme.palette.action.disabledBackground\n }\n },\n '&$focusVisible': {\n boxShadow: theme.shadows[6]\n },\n '&:active': {\n boxShadow: theme.shadows[8]\n },\n '&$disabled': {\n color: theme.palette.action.disabled,\n boxShadow: theme.shadows[0],\n backgroundColor: theme.palette.action.disabledBackground\n }\n },\n\n /* Styles applied to the root element if `variant=\"contained\"` and `color=\"primary\"`. */\n containedPrimary: {\n color: theme.palette.primary.contrastText,\n backgroundColor: theme.palette.primary.main,\n '&:hover': {\n backgroundColor: theme.palette.primary.dark,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: theme.palette.primary.main\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"contained\"` and `color=\"secondary\"`. */\n containedSecondary: {\n color: theme.palette.secondary.contrastText,\n backgroundColor: theme.palette.secondary.main,\n '&:hover': {\n backgroundColor: theme.palette.secondary.dark,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: theme.palette.secondary.main\n }\n }\n },\n\n /* Styles applied to the root element if `disableElevation={true}`. */\n disableElevation: {\n boxShadow: 'none',\n '&:hover': {\n boxShadow: 'none'\n },\n '&$focusVisible': {\n boxShadow: 'none'\n },\n '&:active': {\n boxShadow: 'none'\n },\n '&$disabled': {\n boxShadow: 'none'\n }\n },\n\n /* Pseudo-class applied to the ButtonBase root element if the button is keyboard focused. */\n focusVisible: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the root element if `color=\"inherit\"`. */\n colorInherit: {\n color: 'inherit',\n borderColor: 'currentColor'\n },\n\n /* Styles applied to the root element if `size=\"small\"` and `variant=\"text\"`. */\n textSizeSmall: {\n padding: '4px 5px',\n fontSize: theme.typography.pxToRem(13)\n },\n\n /* Styles applied to the root element if `size=\"large\"` and `variant=\"text\"`. */\n textSizeLarge: {\n padding: '8px 11px',\n fontSize: theme.typography.pxToRem(15)\n },\n\n /* Styles applied to the root element if `size=\"small\"` and `variant=\"outlined\"`. */\n outlinedSizeSmall: {\n padding: '3px 9px',\n fontSize: theme.typography.pxToRem(13)\n },\n\n /* Styles applied to the root element if `size=\"large\"` and `variant=\"outlined\"`. */\n outlinedSizeLarge: {\n padding: '7px 21px',\n fontSize: theme.typography.pxToRem(15)\n },\n\n /* Styles applied to the root element if `size=\"small\"` and `variant=\"contained\"`. */\n containedSizeSmall: {\n padding: '4px 10px',\n fontSize: theme.typography.pxToRem(13)\n },\n\n /* Styles applied to the root element if `size=\"large\"` and `variant=\"contained\"`. */\n containedSizeLarge: {\n padding: '8px 22px',\n fontSize: theme.typography.pxToRem(15)\n },\n\n /* Styles applied to the root element if `size=\"small\"`. */\n sizeSmall: {},\n\n /* Styles applied to the root element if `size=\"large\"`. */\n sizeLarge: {},\n\n /* Styles applied to the root element if `fullWidth={true}`. */\n fullWidth: {\n width: '100%'\n },\n\n /* Styles applied to the startIcon element if supplied. */\n startIcon: {\n display: 'inherit',\n marginRight: 8,\n marginLeft: -4,\n '&$iconSizeSmall': {\n marginLeft: -2\n }\n },\n\n /* Styles applied to the endIcon element if supplied. */\n endIcon: {\n display: 'inherit',\n marginRight: -4,\n marginLeft: 8,\n '&$iconSizeSmall': {\n marginRight: -2\n }\n },\n\n /* Styles applied to the icon element if supplied and `size=\"small\"`. */\n iconSizeSmall: {\n '& > *:first-child': {\n fontSize: 18\n }\n },\n\n /* Styles applied to the icon element if supplied and `size=\"medium\"`. */\n iconSizeMedium: {\n '& > *:first-child': {\n fontSize: 20\n }\n },\n\n /* Styles applied to the icon element if supplied and `size=\"large\"`. */\n iconSizeLarge: {\n '& > *:first-child': {\n fontSize: 22\n }\n }\n };\n};\nvar Button = /*#__PURE__*/React.forwardRef(function Button(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'default' : _props$color,\n _props$component = props.component,\n component = _props$component === void 0 ? 'button' : _props$component,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$disableElevati = props.disableElevation,\n disableElevation = _props$disableElevati === void 0 ? false : _props$disableElevati,\n _props$disableFocusRi = props.disableFocusRipple,\n disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi,\n endIconProp = props.endIcon,\n focusVisibleClassName = props.focusVisibleClassName,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n _props$size = props.size,\n size = _props$size === void 0 ? 'medium' : _props$size,\n startIconProp = props.startIcon,\n _props$type = props.type,\n type = _props$type === void 0 ? 'button' : _props$type,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'text' : _props$variant,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"color\", \"component\", \"disabled\", \"disableElevation\", \"disableFocusRipple\", \"endIcon\", \"focusVisibleClassName\", \"fullWidth\", \"size\", \"startIcon\", \"type\", \"variant\"]);\n\n var startIcon = startIconProp && /*#__PURE__*/React.createElement(\"span\", {\n className: clsx(classes.startIcon, classes[\"iconSize\".concat(capitalize(size))])\n }, startIconProp);\n var endIcon = endIconProp && /*#__PURE__*/React.createElement(\"span\", {\n className: clsx(classes.endIcon, classes[\"iconSize\".concat(capitalize(size))])\n }, endIconProp);\n return /*#__PURE__*/React.createElement(ButtonBase, _extends({\n className: clsx(classes.root, classes[variant], className, color === 'inherit' ? classes.colorInherit : color !== 'default' && classes[\"\".concat(variant).concat(capitalize(color))], size !== 'medium' && [classes[\"\".concat(variant, \"Size\").concat(capitalize(size))], classes[\"size\".concat(capitalize(size))]], disableElevation && classes.disableElevation, disabled && classes.disabled, fullWidth && classes.fullWidth),\n component: component,\n disabled: disabled,\n focusRipple: !disableFocusRipple,\n focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),\n ref: ref,\n type: type\n }, other), /*#__PURE__*/React.createElement(\"span\", {\n className: classes.label\n }, startIcon, children, endIcon));\n});\nprocess.env.NODE_ENV !== \"production\" ? Button.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the button.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, the button will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, no elevation is used.\n */\n disableElevation: PropTypes.bool,\n\n /**\n * If `true`, the keyboard focus ripple will be disabled.\n */\n disableFocusRipple: PropTypes.bool,\n\n /**\n * If `true`, the ripple effect will be disabled.\n *\n * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure\n * to highlight the element by applying separate styles with the `focusVisibleClassName`.\n */\n disableRipple: PropTypes.bool,\n\n /**\n * Element placed after the children.\n */\n endIcon: PropTypes.node,\n\n /**\n * @ignore\n */\n focusVisibleClassName: PropTypes.string,\n\n /**\n * If `true`, the button will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The URL to link to when the button is clicked.\n * If defined, an `a` element will be used as the root node.\n */\n href: PropTypes.string,\n\n /**\n * The size of the button.\n * `small` is equivalent to the dense button styling.\n */\n size: PropTypes.oneOf(['large', 'medium', 'small']),\n\n /**\n * Element placed before the children.\n */\n startIcon: PropTypes.node,\n\n /**\n * @ignore\n */\n type: PropTypes.oneOfType([PropTypes.oneOf(['button', 'reset', 'submit']), PropTypes.string]),\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['contained', 'outlined', 'text'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiButton'\n})(Button);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport { makeStyles as makeStylesWithoutDefault } from '@material-ui/styles';\nimport defaultTheme from './defaultTheme';\n\nfunction makeStyles(stylesOrCreator) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return makeStylesWithoutDefault(stylesOrCreator, _extends({\n defaultTheme: defaultTheme\n }, options));\n}\n\nexport default makeStyles;","import * as React from 'react';\nimport createSvgIcon from './utils/createSvgIcon';\nexport default createSvgIcon( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z\"\n}), 'Description');","import * as React from 'react';\nimport createSvgIcon from './utils/createSvgIcon';\nexport default createSvgIcon( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2c-3.3.7-4-1.6-4-1.6-.6-1.4-1.4-1.8-1.4-1.8-1-.7.1-.7.1-.7 1.2 0 1.9 1.2 1.9 1.2 1 1.8 2.8 1.3 3.5 1 0-.8.4-1.3.7-1.6-2.7-.3-5.5-1.3-5.5-6 0-1.2.5-2.3 1.3-3.1-.2-.4-.6-1.6 0-3.2 0 0 1-.3 3.4 1.2a11.5 11.5 0 0 1 6 0c2.3-1.5 3.3-1.2 3.3-1.2.6 1.6.2 2.8 0 3.2.9.8 1.3 1.9 1.3 3.2 0 4.6-2.8 5.6-5.5 5.9.5.4.9 1 .9 2.2v3.3c0 .3.1.7.8.6A12 12 0 0 0 12 .3\"\n}), 'GitHub');","import * as React from 'react';\nimport createSvgIcon from './utils/createSvgIcon';\nexport default createSvgIcon( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M9.4 10.5l4.77-8.26C13.47 2.09 12.75 2 12 2c-2.4 0-4.6.85-6.32 2.25l3.66 6.35.06-.1zM21.54 9c-.92-2.92-3.15-5.26-6-6.34L11.88 9h9.66zm.26 1h-7.49l.29.5 4.76 8.25C21 16.97 22 14.61 22 12c0-.69-.07-1.35-.2-2zM8.54 12l-3.9-6.75C3.01 7.03 2 9.39 2 12c0 .69.07 1.35.2 2h7.49l-1.15-2zm-6.08 3c.92 2.92 3.15 5.26 6 6.34L12.12 15H2.46zm11.27 0l-3.9 6.76c.7.15 1.42.24 2.17.24 2.4 0 4.6-.85 6.32-2.25l-3.66-6.35-.93 1.6z\"\n}), 'Camera');","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport withStyles from '../styles/withStyles';\nimport { exactProp } from '@material-ui/utils';\nexport var html = {\n WebkitFontSmoothing: 'antialiased',\n // Antialiasing.\n MozOsxFontSmoothing: 'grayscale',\n // Antialiasing.\n // Change from `box-sizing: content-box` so that `width`\n // is not affected by `padding` or `border`.\n boxSizing: 'border-box'\n};\nexport var body = function body(theme) {\n return _extends({\n color: theme.palette.text.primary\n }, theme.typography.body2, {\n backgroundColor: theme.palette.background.default,\n '@media print': {\n // Save printer ink.\n backgroundColor: theme.palette.common.white\n }\n });\n};\nexport var styles = function styles(theme) {\n return {\n '@global': {\n html: html,\n '*, *::before, *::after': {\n boxSizing: 'inherit'\n },\n 'strong, b': {\n fontWeight: theme.typography.fontWeightBold\n },\n body: _extends({\n margin: 0\n }, body(theme), {\n // Add support for document.body.requestFullScreen().\n // Other elements, if background transparent, are not supported.\n '&::backdrop': {\n backgroundColor: theme.palette.background.default\n }\n })\n }\n };\n};\n/**\n * Kickstart an elegant, consistent, and simple baseline to build upon.\n */\n\nfunction CssBaseline(props) {\n /* eslint-disable no-unused-vars */\n var _props$children = props.children,\n children = _props$children === void 0 ? null : _props$children,\n classes = props.classes;\n /* eslint-enable no-unused-vars */\n\n return /*#__PURE__*/React.createElement(React.Fragment, null, children);\n}\n\nprocess.env.NODE_ENV !== \"production\" ? CssBaseline.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * You can wrap a node.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n CssBaseline['propTypes' + ''] = exactProp(CssBaseline.propTypes);\n}\n\nexport default withStyles(styles, {\n name: 'MuiCssBaseline'\n})(CssBaseline);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nimport Paper from '../Paper';\nexport var styles = function styles(theme) {\n var backgroundColorDefault = theme.palette.type === 'light' ? theme.palette.grey[100] : theme.palette.grey[900];\n return {\n /* Styles applied to the root element. */\n root: {\n display: 'flex',\n flexDirection: 'column',\n width: '100%',\n boxSizing: 'border-box',\n // Prevent padding issue with the Modal and fixed positioned AppBar.\n zIndex: theme.zIndex.appBar,\n flexShrink: 0\n },\n\n /* Styles applied to the root element if `position=\"fixed\"`. */\n positionFixed: {\n position: 'fixed',\n top: 0,\n left: 'auto',\n right: 0,\n '@media print': {\n // Prevent the app bar to be visible on each printed page.\n position: 'absolute'\n }\n },\n\n /* Styles applied to the root element if `position=\"absolute\"`. */\n positionAbsolute: {\n position: 'absolute',\n top: 0,\n left: 'auto',\n right: 0\n },\n\n /* Styles applied to the root element if `position=\"sticky\"`. */\n positionSticky: {\n // ⚠️ sticky is not supported by IE 11.\n position: 'sticky',\n top: 0,\n left: 'auto',\n right: 0\n },\n\n /* Styles applied to the root element if `position=\"static\"`. */\n positionStatic: {\n position: 'static'\n },\n\n /* Styles applied to the root element if `position=\"relative\"`. */\n positionRelative: {\n position: 'relative'\n },\n\n /* Styles applied to the root element if `color=\"default\"`. */\n colorDefault: {\n backgroundColor: backgroundColorDefault,\n color: theme.palette.getContrastText(backgroundColorDefault)\n },\n\n /* Styles applied to the root element if `color=\"primary\"`. */\n colorPrimary: {\n backgroundColor: theme.palette.primary.main,\n color: theme.palette.primary.contrastText\n },\n\n /* Styles applied to the root element if `color=\"secondary\"`. */\n colorSecondary: {\n backgroundColor: theme.palette.secondary.main,\n color: theme.palette.secondary.contrastText\n },\n\n /* Styles applied to the root element if `color=\"inherit\"`. */\n colorInherit: {\n color: 'inherit'\n },\n\n /* Styles applied to the root element if `color=\"transparent\"`. */\n colorTransparent: {\n backgroundColor: 'transparent',\n color: 'inherit'\n }\n };\n};\nvar AppBar = /*#__PURE__*/React.forwardRef(function AppBar(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'primary' : _props$color,\n _props$position = props.position,\n position = _props$position === void 0 ? 'fixed' : _props$position,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"color\", \"position\"]);\n\n return /*#__PURE__*/React.createElement(Paper, _extends({\n square: true,\n component: \"header\",\n elevation: 4,\n className: clsx(classes.root, classes[\"position\".concat(capitalize(position))], classes[\"color\".concat(capitalize(color))], className, position === 'fixed' && 'mui-fixed'),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? AppBar.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary', 'transparent']),\n\n /**\n * The positioning type. The behavior of the different options is described\n * [in the MDN web docs](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning).\n * Note: `sticky` is not universally supported and will fall back to `static` when unavailable.\n */\n position: PropTypes.oneOf(['absolute', 'fixed', 'relative', 'static', 'sticky'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiAppBar'\n})(AppBar);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'relative',\n display: 'flex',\n alignItems: 'center'\n },\n\n /* Styles applied to the root element if `disableGutters={false}`. */\n gutters: _defineProperty({\n paddingLeft: theme.spacing(2),\n paddingRight: theme.spacing(2)\n }, theme.breakpoints.up('sm'), {\n paddingLeft: theme.spacing(3),\n paddingRight: theme.spacing(3)\n }),\n\n /* Styles applied to the root element if `variant=\"regular\"`. */\n regular: theme.mixins.toolbar,\n\n /* Styles applied to the root element if `variant=\"dense\"`. */\n dense: {\n minHeight: 48\n }\n };\n};\nvar Toolbar = /*#__PURE__*/React.forwardRef(function Toolbar(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n _props$disableGutters = props.disableGutters,\n disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'regular' : _props$variant,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"component\", \"disableGutters\", \"variant\"]);\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, classes[variant], className, !disableGutters && classes.gutters),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? Toolbar.propTypes = {\n /**\n * Toolbar children, usually a mixture of `IconButton`, `Button` and `Typography`.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, disables gutter padding.\n */\n disableGutters: PropTypes.bool,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['regular', 'dense'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiToolbar'\n})(Toolbar);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport ButtonBase from '../ButtonBase';\nimport capitalize from '../utils/capitalize';\nimport unsupportedProp from '../utils/unsupportedProp';\nexport var styles = function styles(theme) {\n var _extends2;\n\n return {\n /* Styles applied to the root element. */\n root: _extends({}, theme.typography.button, (_extends2 = {\n maxWidth: 264,\n minWidth: 72,\n position: 'relative',\n boxSizing: 'border-box',\n minHeight: 48,\n flexShrink: 0,\n padding: '6px 12px'\n }, _defineProperty(_extends2, theme.breakpoints.up('sm'), {\n padding: '6px 24px'\n }), _defineProperty(_extends2, \"overflow\", 'hidden'), _defineProperty(_extends2, \"whiteSpace\", 'normal'), _defineProperty(_extends2, \"textAlign\", 'center'), _defineProperty(_extends2, theme.breakpoints.up('sm'), {\n minWidth: 160\n }), _extends2)),\n\n /* Styles applied to the root element if both `icon` and `label` are provided. */\n labelIcon: {\n minHeight: 72,\n paddingTop: 9,\n '& $wrapper > *:first-child': {\n marginBottom: 6\n }\n },\n\n /* Styles applied to the root element if the parent [`Tabs`](/api/tabs/) has `textColor=\"inherit\"`. */\n textColorInherit: {\n color: 'inherit',\n opacity: 0.7,\n '&$selected': {\n opacity: 1\n },\n '&$disabled': {\n opacity: 0.5\n }\n },\n\n /* Styles applied to the root element if the parent [`Tabs`](/api/tabs/) has `textColor=\"primary\"`. */\n textColorPrimary: {\n color: theme.palette.text.secondary,\n '&$selected': {\n color: theme.palette.primary.main\n },\n '&$disabled': {\n color: theme.palette.text.disabled\n }\n },\n\n /* Styles applied to the root element if the parent [`Tabs`](/api/tabs/) has `textColor=\"secondary\"`. */\n textColorSecondary: {\n color: theme.palette.text.secondary,\n '&$selected': {\n color: theme.palette.secondary.main\n },\n '&$disabled': {\n color: theme.palette.text.disabled\n }\n },\n\n /* Pseudo-class applied to the root element if `selected={true}` (controlled by the Tabs component). */\n selected: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}` (controlled by the Tabs component). */\n disabled: {},\n\n /* Styles applied to the root element if `fullWidth={true}` (controlled by the Tabs component). */\n fullWidth: {\n flexShrink: 1,\n flexGrow: 1,\n flexBasis: 0,\n maxWidth: 'none'\n },\n\n /* Styles applied to the root element if `wrapped={true}`. */\n wrapped: {\n fontSize: theme.typography.pxToRem(12),\n lineHeight: 1.5\n },\n\n /* Styles applied to the `icon` and `label`'s wrapper element. */\n wrapper: {\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n width: '100%',\n flexDirection: 'column'\n }\n };\n};\nvar Tab = /*#__PURE__*/React.forwardRef(function Tab(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$disableFocusRi = props.disableFocusRipple,\n disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi,\n fullWidth = props.fullWidth,\n icon = props.icon,\n indicator = props.indicator,\n label = props.label,\n onChange = props.onChange,\n onClick = props.onClick,\n onFocus = props.onFocus,\n selected = props.selected,\n selectionFollowsFocus = props.selectionFollowsFocus,\n _props$textColor = props.textColor,\n textColor = _props$textColor === void 0 ? 'inherit' : _props$textColor,\n value = props.value,\n _props$wrapped = props.wrapped,\n wrapped = _props$wrapped === void 0 ? false : _props$wrapped,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"disabled\", \"disableFocusRipple\", \"fullWidth\", \"icon\", \"indicator\", \"label\", \"onChange\", \"onClick\", \"onFocus\", \"selected\", \"selectionFollowsFocus\", \"textColor\", \"value\", \"wrapped\"]);\n\n var handleClick = function handleClick(event) {\n if (onChange) {\n onChange(event, value);\n }\n\n if (onClick) {\n onClick(event);\n }\n };\n\n var handleFocus = function handleFocus(event) {\n if (selectionFollowsFocus && !selected && onChange) {\n onChange(event, value);\n }\n\n if (onFocus) {\n onFocus(event);\n }\n };\n\n return /*#__PURE__*/React.createElement(ButtonBase, _extends({\n focusRipple: !disableFocusRipple,\n className: clsx(classes.root, classes[\"textColor\".concat(capitalize(textColor))], className, disabled && classes.disabled, selected && classes.selected, label && icon && classes.labelIcon, fullWidth && classes.fullWidth, wrapped && classes.wrapped),\n ref: ref,\n role: \"tab\",\n \"aria-selected\": selected,\n disabled: disabled,\n onClick: handleClick,\n onFocus: handleFocus,\n tabIndex: selected ? 0 : -1\n }, other), /*#__PURE__*/React.createElement(\"span\", {\n className: classes.wrapper\n }, icon, label), indicator);\n});\nprocess.env.NODE_ENV !== \"production\" ? Tab.propTypes = {\n /**\n * This prop isn't supported.\n * Use the `component` prop if you need to change the children structure.\n */\n children: unsupportedProp,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * If `true`, the tab will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the keyboard focus ripple will be disabled.\n */\n disableFocusRipple: PropTypes.bool,\n\n /**\n * If `true`, the ripple effect will be disabled.\n */\n disableRipple: PropTypes.bool,\n\n /**\n * @ignore\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The icon element.\n */\n icon: PropTypes.node,\n\n /**\n * @ignore\n * For server-side rendering consideration, we let the selected tab\n * render the indicator.\n */\n indicator: PropTypes.node,\n\n /**\n * The label element.\n */\n label: PropTypes.node,\n\n /**\n * @ignore\n */\n onChange: PropTypes.func,\n\n /**\n * @ignore\n */\n onClick: PropTypes.func,\n\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n\n /**\n * @ignore\n */\n selected: PropTypes.bool,\n\n /**\n * @ignore\n */\n selectionFollowsFocus: PropTypes.bool,\n\n /**\n * @ignore\n */\n textColor: PropTypes.oneOf(['secondary', 'primary', 'inherit']),\n\n /**\n * You can provide your own value. Otherwise, we fallback to the child position index.\n */\n value: PropTypes.any,\n\n /**\n * Tab labels appear in a single row.\n * They can use a second line if needed.\n */\n wrapped: PropTypes.bool\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTab'\n})(Tab);","export default function formControlState(_ref) {\n var props = _ref.props,\n states = _ref.states,\n muiFormControl = _ref.muiFormControl;\n return states.reduce(function (acc, state) {\n acc[state] = props[state];\n\n if (muiFormControl) {\n if (typeof props[state] === 'undefined') {\n acc[state] = muiFormControl[state];\n }\n }\n\n return acc;\n }, {});\n}","import * as React from 'react';\n/**\n * @ignore - internal component.\n */\n\nvar FormControlContext = React.createContext();\n\nif (process.env.NODE_ENV !== 'production') {\n FormControlContext.displayName = 'FormControlContext';\n}\n\nexport function useFormControl() {\n return React.useContext(FormControlContext);\n}\nexport default FormControlContext;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport debounce from '../utils/debounce';\nimport useForkRef from '../utils/useForkRef';\n\nfunction getStyleValue(computedStyle, property) {\n return parseInt(computedStyle[property], 10) || 0;\n}\n\nvar useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\nvar styles = {\n /* Styles applied to the shadow textarea element. */\n shadow: {\n // Visibility needed to hide the extra text area on iPads\n visibility: 'hidden',\n // Remove from the content flow\n position: 'absolute',\n // Ignore the scrollbar width\n overflow: 'hidden',\n height: 0,\n top: 0,\n left: 0,\n // Create a new layer, increase the isolation of the computed values\n transform: 'translateZ(0)'\n }\n};\nvar TextareaAutosize = /*#__PURE__*/React.forwardRef(function TextareaAutosize(props, ref) {\n var onChange = props.onChange,\n rows = props.rows,\n rowsMax = props.rowsMax,\n _props$rowsMin = props.rowsMin,\n rowsMinProp = _props$rowsMin === void 0 ? 1 : _props$rowsMin,\n style = props.style,\n value = props.value,\n other = _objectWithoutProperties(props, [\"onChange\", \"rows\", \"rowsMax\", \"rowsMin\", \"style\", \"value\"]);\n\n var rowsMin = rows || rowsMinProp;\n\n var _React$useRef = React.useRef(value != null),\n isControlled = _React$useRef.current;\n\n var inputRef = React.useRef(null);\n var handleRef = useForkRef(ref, inputRef);\n var shadowRef = React.useRef(null);\n var renders = React.useRef(0);\n\n var _React$useState = React.useState({}),\n state = _React$useState[0],\n setState = _React$useState[1];\n\n var syncHeight = React.useCallback(function () {\n var input = inputRef.current;\n var computedStyle = window.getComputedStyle(input);\n var inputShallow = shadowRef.current;\n inputShallow.style.width = computedStyle.width;\n inputShallow.value = input.value || props.placeholder || 'x';\n\n if (inputShallow.value.slice(-1) === '\\n') {\n // Certain fonts which overflow the line height will cause the textarea\n // to report a different scrollHeight depending on whether the last line\n // is empty. Make it non-empty to avoid this issue.\n inputShallow.value += ' ';\n }\n\n var boxSizing = computedStyle['box-sizing'];\n var padding = getStyleValue(computedStyle, 'padding-bottom') + getStyleValue(computedStyle, 'padding-top');\n var border = getStyleValue(computedStyle, 'border-bottom-width') + getStyleValue(computedStyle, 'border-top-width'); // The height of the inner content\n\n var innerHeight = inputShallow.scrollHeight - padding; // Measure height of a textarea with a single row\n\n inputShallow.value = 'x';\n var singleRowHeight = inputShallow.scrollHeight - padding; // The height of the outer content\n\n var outerHeight = innerHeight;\n\n if (rowsMin) {\n outerHeight = Math.max(Number(rowsMin) * singleRowHeight, outerHeight);\n }\n\n if (rowsMax) {\n outerHeight = Math.min(Number(rowsMax) * singleRowHeight, outerHeight);\n }\n\n outerHeight = Math.max(outerHeight, singleRowHeight); // Take the box sizing into account for applying this value as a style.\n\n var outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0);\n var overflow = Math.abs(outerHeight - innerHeight) <= 1;\n setState(function (prevState) {\n // Need a large enough difference to update the height.\n // This prevents infinite rendering loop.\n if (renders.current < 20 && (outerHeightStyle > 0 && Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1 || prevState.overflow !== overflow)) {\n renders.current += 1;\n return {\n overflow: overflow,\n outerHeightStyle: outerHeightStyle\n };\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (renders.current === 20) {\n console.error(['Material-UI: Too many re-renders. The layout is unstable.', 'TextareaAutosize limits the number of renders to prevent an infinite loop.'].join('\\n'));\n }\n }\n\n return prevState;\n });\n }, [rowsMax, rowsMin, props.placeholder]);\n React.useEffect(function () {\n var handleResize = debounce(function () {\n renders.current = 0;\n syncHeight();\n });\n window.addEventListener('resize', handleResize);\n return function () {\n handleResize.clear();\n window.removeEventListener('resize', handleResize);\n };\n }, [syncHeight]);\n useEnhancedEffect(function () {\n syncHeight();\n });\n React.useEffect(function () {\n renders.current = 0;\n }, [value]);\n\n var handleChange = function handleChange(event) {\n renders.current = 0;\n\n if (!isControlled) {\n syncHeight();\n }\n\n if (onChange) {\n onChange(event);\n }\n };\n\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"textarea\", _extends({\n value: value,\n onChange: handleChange,\n ref: handleRef // Apply the rows prop to get a \"correct\" first SSR paint\n ,\n rows: rowsMin,\n style: _extends({\n height: state.outerHeightStyle,\n // Need a large enough difference to allow scrolling.\n // This prevents infinite rendering loop.\n overflow: state.overflow ? 'hidden' : null\n }, style)\n }, other)), /*#__PURE__*/React.createElement(\"textarea\", {\n \"aria-hidden\": true,\n className: props.className,\n readOnly: true,\n ref: shadowRef,\n tabIndex: -1,\n style: _extends({}, styles.shadow, style)\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? TextareaAutosize.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * @ignore\n */\n onChange: PropTypes.func,\n\n /**\n * @ignore\n */\n placeholder: PropTypes.string,\n\n /**\n * Use `rowsMin` instead. The prop will be removed in v5.\n *\n * @deprecated\n */\n rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Maximum number of rows to display.\n */\n rowsMax: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Minimum number of rows to display.\n */\n rowsMin: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * @ignore\n */\n style: PropTypes.object,\n\n /**\n * @ignore\n */\n value: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.string), PropTypes.number, PropTypes.string])\n} : void 0;\nexport default TextareaAutosize;","// Supports determination of isControlled().\n// Controlled input accepts its current value as a prop.\n//\n// @see https://facebook.github.io/react/docs/forms.html#controlled-components\n// @param value\n// @returns {boolean} true if string (including '') or number (including zero)\nexport function hasValue(value) {\n return value != null && !(Array.isArray(value) && value.length === 0);\n} // Determine if field is empty or filled.\n// Response determines if label is presented above field or as placeholder.\n//\n// @param obj\n// @param SSR\n// @returns {boolean} False when not present or empty string.\n// True when any number or string with length.\n\nexport function isFilled(obj) {\n var SSR = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n return obj && (hasValue(obj.value) && obj.value !== '' || SSR && hasValue(obj.defaultValue) && obj.defaultValue !== '');\n} // Determine if an Input is adorned on start.\n// It's corresponding to the left with LTR.\n//\n// @param obj\n// @returns {boolean} False when no adornments.\n// True when adorned at the start.\n\nexport function isAdornedStart(obj) {\n return obj.startAdornment;\n}","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\n\n/* eslint-disable jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { refType } from '@material-ui/utils';\nimport formControlState from '../FormControl/formControlState';\nimport FormControlContext, { useFormControl } from '../FormControl/FormControlContext';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nimport useForkRef from '../utils/useForkRef';\nimport TextareaAutosize from '../TextareaAutosize';\nimport { isFilled } from './utils';\nexport var styles = function styles(theme) {\n var light = theme.palette.type === 'light';\n var placeholder = {\n color: 'currentColor',\n opacity: light ? 0.42 : 0.5,\n transition: theme.transitions.create('opacity', {\n duration: theme.transitions.duration.shorter\n })\n };\n var placeholderHidden = {\n opacity: '0 !important'\n };\n var placeholderVisible = {\n opacity: light ? 0.42 : 0.5\n };\n return {\n '@global': {\n '@keyframes mui-auto-fill': {},\n '@keyframes mui-auto-fill-cancel': {}\n },\n\n /* Styles applied to the root element. */\n root: _extends({}, theme.typography.body1, {\n color: theme.palette.text.primary,\n lineHeight: '1.1876em',\n // Reset (19px), match the native input line-height\n boxSizing: 'border-box',\n // Prevent padding issue with fullWidth.\n position: 'relative',\n cursor: 'text',\n display: 'inline-flex',\n alignItems: 'center',\n '&$disabled': {\n color: theme.palette.text.disabled,\n cursor: 'default'\n }\n }),\n\n /* Styles applied to the root element if the component is a descendant of `FormControl`. */\n formControl: {},\n\n /* Styles applied to the root element if the component is focused. */\n focused: {},\n\n /* Styles applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the root element if `startAdornment` is provided. */\n adornedStart: {},\n\n /* Styles applied to the root element if `endAdornment` is provided. */\n adornedEnd: {},\n\n /* Pseudo-class applied to the root element if `error={true}`. */\n error: {},\n\n /* Styles applied to the `input` element if `margin=\"dense\"`. */\n marginDense: {},\n\n /* Styles applied to the root element if `multiline={true}`. */\n multiline: {\n padding: \"\".concat(8 - 2, \"px 0 \").concat(8 - 1, \"px\"),\n '&$marginDense': {\n paddingTop: 4 - 1\n }\n },\n\n /* Styles applied to the root element if the color is secondary. */\n colorSecondary: {},\n\n /* Styles applied to the root element if `fullWidth={true}`. */\n fullWidth: {\n width: '100%'\n },\n\n /* Styles applied to the `input` element. */\n input: {\n font: 'inherit',\n letterSpacing: 'inherit',\n color: 'currentColor',\n padding: \"\".concat(8 - 2, \"px 0 \").concat(8 - 1, \"px\"),\n border: 0,\n boxSizing: 'content-box',\n background: 'none',\n height: '1.1876em',\n // Reset (19px), match the native input line-height\n margin: 0,\n // Reset for Safari\n WebkitTapHighlightColor: 'transparent',\n display: 'block',\n // Make the flex item shrink with Firefox\n minWidth: 0,\n width: '100%',\n // Fix IE 11 width issue\n animationName: 'mui-auto-fill-cancel',\n animationDuration: '10ms',\n '&::-webkit-input-placeholder': placeholder,\n '&::-moz-placeholder': placeholder,\n // Firefox 19+\n '&:-ms-input-placeholder': placeholder,\n // IE 11\n '&::-ms-input-placeholder': placeholder,\n // Edge\n '&:focus': {\n outline: 0\n },\n // Reset Firefox invalid required input style\n '&:invalid': {\n boxShadow: 'none'\n },\n '&::-webkit-search-decoration': {\n // Remove the padding when type=search.\n '-webkit-appearance': 'none'\n },\n // Show and hide the placeholder logic\n 'label[data-shrink=false] + $formControl &': {\n '&::-webkit-input-placeholder': placeholderHidden,\n '&::-moz-placeholder': placeholderHidden,\n // Firefox 19+\n '&:-ms-input-placeholder': placeholderHidden,\n // IE 11\n '&::-ms-input-placeholder': placeholderHidden,\n // Edge\n '&:focus::-webkit-input-placeholder': placeholderVisible,\n '&:focus::-moz-placeholder': placeholderVisible,\n // Firefox 19+\n '&:focus:-ms-input-placeholder': placeholderVisible,\n // IE 11\n '&:focus::-ms-input-placeholder': placeholderVisible // Edge\n\n },\n '&$disabled': {\n opacity: 1 // Reset iOS opacity\n\n },\n '&:-webkit-autofill': {\n animationDuration: '5000s',\n animationName: 'mui-auto-fill'\n }\n },\n\n /* Styles applied to the `input` element if `margin=\"dense\"`. */\n inputMarginDense: {\n paddingTop: 4 - 1\n },\n\n /* Styles applied to the `input` element if `multiline={true}`. */\n inputMultiline: {\n height: 'auto',\n resize: 'none',\n padding: 0\n },\n\n /* Styles applied to the `input` element if `type=\"search\"`. */\n inputTypeSearch: {\n // Improve type search style.\n '-moz-appearance': 'textfield',\n '-webkit-appearance': 'textfield'\n },\n\n /* Styles applied to the `input` element if `startAdornment` is provided. */\n inputAdornedStart: {},\n\n /* Styles applied to the `input` element if `endAdornment` is provided. */\n inputAdornedEnd: {},\n\n /* Styles applied to the `input` element if `hiddenLabel={true}`. */\n inputHiddenLabel: {}\n };\n};\nvar useEnhancedEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;\n/**\n * `InputBase` contains as few styles as possible.\n * It aims to be a simple building block for creating an input.\n * It contains a load of style reset and some state logic.\n */\n\nvar InputBase = /*#__PURE__*/React.forwardRef(function InputBase(props, ref) {\n var ariaDescribedby = props['aria-describedby'],\n autoComplete = props.autoComplete,\n autoFocus = props.autoFocus,\n classes = props.classes,\n className = props.className,\n color = props.color,\n defaultValue = props.defaultValue,\n disabled = props.disabled,\n endAdornment = props.endAdornment,\n error = props.error,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n id = props.id,\n _props$inputComponent = props.inputComponent,\n inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,\n _props$inputProps = props.inputProps,\n inputPropsProp = _props$inputProps === void 0 ? {} : _props$inputProps,\n inputRefProp = props.inputRef,\n margin = props.margin,\n _props$multiline = props.multiline,\n multiline = _props$multiline === void 0 ? false : _props$multiline,\n name = props.name,\n onBlur = props.onBlur,\n onChange = props.onChange,\n onClick = props.onClick,\n onFocus = props.onFocus,\n onKeyDown = props.onKeyDown,\n onKeyUp = props.onKeyUp,\n placeholder = props.placeholder,\n readOnly = props.readOnly,\n renderSuffix = props.renderSuffix,\n rows = props.rows,\n rowsMax = props.rowsMax,\n rowsMin = props.rowsMin,\n startAdornment = props.startAdornment,\n _props$type = props.type,\n type = _props$type === void 0 ? 'text' : _props$type,\n valueProp = props.value,\n other = _objectWithoutProperties(props, [\"aria-describedby\", \"autoComplete\", \"autoFocus\", \"classes\", \"className\", \"color\", \"defaultValue\", \"disabled\", \"endAdornment\", \"error\", \"fullWidth\", \"id\", \"inputComponent\", \"inputProps\", \"inputRef\", \"margin\", \"multiline\", \"name\", \"onBlur\", \"onChange\", \"onClick\", \"onFocus\", \"onKeyDown\", \"onKeyUp\", \"placeholder\", \"readOnly\", \"renderSuffix\", \"rows\", \"rowsMax\", \"rowsMin\", \"startAdornment\", \"type\", \"value\"]);\n\n var value = inputPropsProp.value != null ? inputPropsProp.value : valueProp;\n\n var _React$useRef = React.useRef(value != null),\n isControlled = _React$useRef.current;\n\n var inputRef = React.useRef();\n var handleInputRefWarning = React.useCallback(function (instance) {\n if (process.env.NODE_ENV !== 'production') {\n if (instance && instance.nodeName !== 'INPUT' && !instance.focus) {\n console.error(['Material-UI: You have provided a `inputComponent` to the input component', 'that does not correctly handle the `inputRef` prop.', 'Make sure the `inputRef` prop is called with a HTMLInputElement.'].join('\\n'));\n }\n }\n }, []);\n var handleInputPropsRefProp = useForkRef(inputPropsProp.ref, handleInputRefWarning);\n var handleInputRefProp = useForkRef(inputRefProp, handleInputPropsRefProp);\n var handleInputRef = useForkRef(inputRef, handleInputRefProp);\n\n var _React$useState = React.useState(false),\n focused = _React$useState[0],\n setFocused = _React$useState[1];\n\n var muiFormControl = useFormControl();\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(function () {\n if (muiFormControl) {\n return muiFormControl.registerEffect();\n }\n\n return undefined;\n }, [muiFormControl]);\n }\n\n var fcs = formControlState({\n props: props,\n muiFormControl: muiFormControl,\n states: ['color', 'disabled', 'error', 'hiddenLabel', 'margin', 'required', 'filled']\n });\n fcs.focused = muiFormControl ? muiFormControl.focused : focused; // The blur won't fire when the disabled state is set on a focused input.\n // We need to book keep the focused state manually.\n\n React.useEffect(function () {\n if (!muiFormControl && disabled && focused) {\n setFocused(false);\n\n if (onBlur) {\n onBlur();\n }\n }\n }, [muiFormControl, disabled, focused, onBlur]);\n var onFilled = muiFormControl && muiFormControl.onFilled;\n var onEmpty = muiFormControl && muiFormControl.onEmpty;\n var checkDirty = React.useCallback(function (obj) {\n if (isFilled(obj)) {\n if (onFilled) {\n onFilled();\n }\n } else if (onEmpty) {\n onEmpty();\n }\n }, [onFilled, onEmpty]);\n useEnhancedEffect(function () {\n if (isControlled) {\n checkDirty({\n value: value\n });\n }\n }, [value, checkDirty, isControlled]);\n\n var handleFocus = function handleFocus(event) {\n // Fix a bug with IE 11 where the focus/blur events are triggered\n // while the input is disabled.\n if (fcs.disabled) {\n event.stopPropagation();\n return;\n }\n\n if (onFocus) {\n onFocus(event);\n }\n\n if (inputPropsProp.onFocus) {\n inputPropsProp.onFocus(event);\n }\n\n if (muiFormControl && muiFormControl.onFocus) {\n muiFormControl.onFocus(event);\n } else {\n setFocused(true);\n }\n };\n\n var handleBlur = function handleBlur(event) {\n if (onBlur) {\n onBlur(event);\n }\n\n if (inputPropsProp.onBlur) {\n inputPropsProp.onBlur(event);\n }\n\n if (muiFormControl && muiFormControl.onBlur) {\n muiFormControl.onBlur(event);\n } else {\n setFocused(false);\n }\n };\n\n var handleChange = function handleChange(event) {\n if (!isControlled) {\n var element = event.target || inputRef.current;\n\n if (element == null) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: Expected valid input target. Did you use a custom `inputComponent` and forget to forward refs? See https://material-ui.com/r/input-component-ref-interface for more info.\" : _formatMuiErrorMessage(1));\n }\n\n checkDirty({\n value: element.value\n });\n }\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n if (inputPropsProp.onChange) {\n inputPropsProp.onChange.apply(inputPropsProp, [event].concat(args));\n } // Perform in the willUpdate\n\n\n if (onChange) {\n onChange.apply(void 0, [event].concat(args));\n }\n }; // Check the input state on mount, in case it was filled by the user\n // or auto filled by the browser before the hydration (for SSR).\n\n\n React.useEffect(function () {\n checkDirty(inputRef.current);\n }, []); // eslint-disable-line react-hooks/exhaustive-deps\n\n var handleClick = function handleClick(event) {\n if (inputRef.current && event.currentTarget === event.target) {\n inputRef.current.focus();\n }\n\n if (onClick) {\n onClick(event);\n }\n };\n\n var InputComponent = inputComponent;\n\n var inputProps = _extends({}, inputPropsProp, {\n ref: handleInputRef\n });\n\n if (typeof InputComponent !== 'string') {\n inputProps = _extends({\n // Rename ref to inputRef as we don't know the\n // provided `inputComponent` structure.\n inputRef: handleInputRef,\n type: type\n }, inputProps, {\n ref: null\n });\n } else if (multiline) {\n if (rows && !rowsMax && !rowsMin) {\n InputComponent = 'textarea';\n } else {\n inputProps = _extends({\n rows: rows,\n rowsMax: rowsMax\n }, inputProps);\n InputComponent = TextareaAutosize;\n }\n } else {\n inputProps = _extends({\n type: type\n }, inputProps);\n }\n\n var handleAutoFill = function handleAutoFill(event) {\n // Provide a fake value as Chrome might not let you access it for security reasons.\n checkDirty(event.animationName === 'mui-auto-fill-cancel' ? inputRef.current : {\n value: 'x'\n });\n };\n\n React.useEffect(function () {\n if (muiFormControl) {\n muiFormControl.setAdornedStart(Boolean(startAdornment));\n }\n }, [muiFormControl, startAdornment]);\n return /*#__PURE__*/React.createElement(\"div\", _extends({\n className: clsx(classes.root, classes[\"color\".concat(capitalize(fcs.color || 'primary'))], className, fcs.disabled && classes.disabled, fcs.error && classes.error, fullWidth && classes.fullWidth, fcs.focused && classes.focused, muiFormControl && classes.formControl, multiline && classes.multiline, startAdornment && classes.adornedStart, endAdornment && classes.adornedEnd, fcs.margin === 'dense' && classes.marginDense),\n onClick: handleClick,\n ref: ref\n }, other), startAdornment, /*#__PURE__*/React.createElement(FormControlContext.Provider, {\n value: null\n }, /*#__PURE__*/React.createElement(InputComponent, _extends({\n \"aria-invalid\": fcs.error,\n \"aria-describedby\": ariaDescribedby,\n autoComplete: autoComplete,\n autoFocus: autoFocus,\n defaultValue: defaultValue,\n disabled: fcs.disabled,\n id: id,\n onAnimationStart: handleAutoFill,\n name: name,\n placeholder: placeholder,\n readOnly: readOnly,\n required: fcs.required,\n rows: rows,\n value: value,\n onKeyDown: onKeyDown,\n onKeyUp: onKeyUp\n }, inputProps, {\n className: clsx(classes.input, inputPropsProp.className, fcs.disabled && classes.disabled, multiline && classes.inputMultiline, fcs.hiddenLabel && classes.inputHiddenLabel, startAdornment && classes.inputAdornedStart, endAdornment && classes.inputAdornedEnd, type === 'search' && classes.inputTypeSearch, fcs.margin === 'dense' && classes.inputMarginDense),\n onBlur: handleBlur,\n onChange: handleChange,\n onFocus: handleFocus\n }))), endAdornment, renderSuffix ? renderSuffix(_extends({}, fcs, {\n startAdornment: startAdornment\n })) : null);\n});\nprocess.env.NODE_ENV !== \"production\" ? InputBase.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * @ignore\n */\n 'aria-describedby': PropTypes.string,\n\n /**\n * This prop helps users to fill forms faster, especially on mobile devices.\n * The name can be confusing, as it's more like an autofill.\n * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).\n */\n autoComplete: PropTypes.string,\n\n /**\n * If `true`, the `input` element will be focused during the first mount.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The default `input` element value. Use when the component is not controlled.\n */\n defaultValue: PropTypes.any,\n\n /**\n * If `true`, the `input` element will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * End `InputAdornment` for this component.\n */\n endAdornment: PropTypes.node,\n\n /**\n * If `true`, the input will indicate an error. This is normally obtained via context from\n * FormControl.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the input will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The id of the `input` element.\n */\n id: PropTypes.string,\n\n /**\n * The component used for the `input` element.\n * Either a string to use a HTML element or a component.\n */\n inputComponent: PropTypes.elementType,\n\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n */\n inputProps: PropTypes.object,\n\n /**\n * Pass a ref to the `input` element.\n */\n inputRef: refType,\n\n /**\n * If `dense`, will adjust vertical spacing. This is normally obtained via context from\n * FormControl.\n */\n margin: PropTypes.oneOf(['dense', 'none']),\n\n /**\n * If `true`, a textarea element will be rendered.\n */\n multiline: PropTypes.bool,\n\n /**\n * Name attribute of the `input` element.\n */\n name: PropTypes.string,\n\n /**\n * Callback fired when the input is blurred.\n *\n * Notice that the first argument (event) might be undefined.\n */\n onBlur: PropTypes.func,\n\n /**\n * Callback fired when the value is changed.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (string).\n */\n onChange: PropTypes.func,\n\n /**\n * @ignore\n */\n onClick: PropTypes.func,\n\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n\n /**\n * @ignore\n */\n onKeyDown: PropTypes.func,\n\n /**\n * @ignore\n */\n onKeyUp: PropTypes.func,\n\n /**\n * The short hint displayed in the input before the user enters a value.\n */\n placeholder: PropTypes.string,\n\n /**\n * It prevents the user from changing the value of the field\n * (not from interacting with the field).\n */\n readOnly: PropTypes.bool,\n\n /**\n * @ignore\n */\n renderSuffix: PropTypes.func,\n\n /**\n * If `true`, the `input` element will be required.\n */\n required: PropTypes.bool,\n\n /**\n * Number of rows to display when multiline option is set to true.\n */\n rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Maximum number of rows to display when multiline option is set to true.\n */\n rowsMax: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Minimum number of rows to display when multiline option is set to true.\n */\n rowsMin: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Start `InputAdornment` for this component.\n */\n startAdornment: PropTypes.node,\n\n /**\n * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).\n */\n type: PropTypes.string,\n\n /**\n * The value of the `input` element, required for a controlled component.\n */\n value: PropTypes.any\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiInputBase'\n})(InputBase);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { refType } from '@material-ui/utils';\nimport InputBase from '../InputBase';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n var light = theme.palette.type === 'light';\n var bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'relative'\n },\n\n /* Styles applied to the root element if the component is a descendant of `FormControl`. */\n formControl: {\n 'label + &': {\n marginTop: 16\n }\n },\n\n /* Styles applied to the root element if the component is focused. */\n focused: {},\n\n /* Styles applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the root element if color secondary. */\n colorSecondary: {\n '&$underline:after': {\n borderBottomColor: theme.palette.secondary.main\n }\n },\n\n /* Styles applied to the root element if `disableUnderline={false}`. */\n underline: {\n '&:after': {\n borderBottom: \"2px solid \".concat(theme.palette.primary.main),\n left: 0,\n bottom: 0,\n // Doing the other way around crash on IE 11 \"''\" https://github.com/cssinjs/jss/issues/242\n content: '\"\"',\n position: 'absolute',\n right: 0,\n transform: 'scaleX(0)',\n transition: theme.transitions.create('transform', {\n duration: theme.transitions.duration.shorter,\n easing: theme.transitions.easing.easeOut\n }),\n pointerEvents: 'none' // Transparent to the hover style.\n\n },\n '&$focused:after': {\n transform: 'scaleX(1)'\n },\n '&$error:after': {\n borderBottomColor: theme.palette.error.main,\n transform: 'scaleX(1)' // error is always underlined in red\n\n },\n '&:before': {\n borderBottom: \"1px solid \".concat(bottomLineColor),\n left: 0,\n bottom: 0,\n // Doing the other way around crash on IE 11 \"''\" https://github.com/cssinjs/jss/issues/242\n content: '\"\\\\00a0\"',\n position: 'absolute',\n right: 0,\n transition: theme.transitions.create('border-bottom-color', {\n duration: theme.transitions.duration.shorter\n }),\n pointerEvents: 'none' // Transparent to the hover style.\n\n },\n '&:hover:not($disabled):before': {\n borderBottom: \"2px solid \".concat(theme.palette.text.primary),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n borderBottom: \"1px solid \".concat(bottomLineColor)\n }\n },\n '&$disabled:before': {\n borderBottomStyle: 'dotted'\n }\n },\n\n /* Pseudo-class applied to the root element if `error={true}`. */\n error: {},\n\n /* Styles applied to the `input` element if `margin=\"dense\"`. */\n marginDense: {},\n\n /* Styles applied to the root element if `multiline={true}`. */\n multiline: {},\n\n /* Styles applied to the root element if `fullWidth={true}`. */\n fullWidth: {},\n\n /* Styles applied to the `input` element. */\n input: {},\n\n /* Styles applied to the `input` element if `margin=\"dense\"`. */\n inputMarginDense: {},\n\n /* Styles applied to the `input` element if `multiline={true}`. */\n inputMultiline: {},\n\n /* Styles applied to the `input` element if `type=\"search\"`. */\n inputTypeSearch: {}\n };\n};\nvar Input = /*#__PURE__*/React.forwardRef(function Input(props, ref) {\n var disableUnderline = props.disableUnderline,\n classes = props.classes,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n _props$inputComponent = props.inputComponent,\n inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,\n _props$multiline = props.multiline,\n multiline = _props$multiline === void 0 ? false : _props$multiline,\n _props$type = props.type,\n type = _props$type === void 0 ? 'text' : _props$type,\n other = _objectWithoutProperties(props, [\"disableUnderline\", \"classes\", \"fullWidth\", \"inputComponent\", \"multiline\", \"type\"]);\n\n return /*#__PURE__*/React.createElement(InputBase, _extends({\n classes: _extends({}, classes, {\n root: clsx(classes.root, !disableUnderline && classes.underline),\n underline: null\n }),\n fullWidth: fullWidth,\n inputComponent: inputComponent,\n multiline: multiline,\n ref: ref,\n type: type\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? Input.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * This prop helps users to fill forms faster, especially on mobile devices.\n * The name can be confusing, as it's more like an autofill.\n * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).\n */\n autoComplete: PropTypes.string,\n\n /**\n * If `true`, the `input` element will be focused during the first mount.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The default `input` element value. Use when the component is not controlled.\n */\n defaultValue: PropTypes.any,\n\n /**\n * If `true`, the `input` element will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the input will not have an underline.\n */\n disableUnderline: PropTypes.bool,\n\n /**\n * End `InputAdornment` for this component.\n */\n endAdornment: PropTypes.node,\n\n /**\n * If `true`, the input will indicate an error. This is normally obtained via context from\n * FormControl.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the input will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The id of the `input` element.\n */\n id: PropTypes.string,\n\n /**\n * The component used for the `input` element.\n * Either a string to use a HTML element or a component.\n */\n inputComponent: PropTypes.elementType,\n\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n */\n inputProps: PropTypes.object,\n\n /**\n * Pass a ref to the `input` element.\n */\n inputRef: refType,\n\n /**\n * If `dense`, will adjust vertical spacing. This is normally obtained via context from\n * FormControl.\n */\n margin: PropTypes.oneOf(['dense', 'none']),\n\n /**\n * If `true`, a textarea element will be rendered.\n */\n multiline: PropTypes.bool,\n\n /**\n * Name attribute of the `input` element.\n */\n name: PropTypes.string,\n\n /**\n * Callback fired when the value is changed.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (string).\n */\n onChange: PropTypes.func,\n\n /**\n * The short hint displayed in the input before the user enters a value.\n */\n placeholder: PropTypes.string,\n\n /**\n * It prevents the user from changing the value of the field\n * (not from interacting with the field).\n */\n readOnly: PropTypes.bool,\n\n /**\n * If `true`, the `input` element will be required.\n */\n required: PropTypes.bool,\n\n /**\n * Number of rows to display when multiline option is set to true.\n */\n rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Maximum number of rows to display when multiline option is set to true.\n */\n rowsMax: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Start `InputAdornment` for this component.\n */\n startAdornment: PropTypes.node,\n\n /**\n * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).\n */\n type: PropTypes.string,\n\n /**\n * The value of the `input` element, required for a controlled component.\n */\n value: PropTypes.any\n} : void 0;\nInput.muiName = 'Input';\nexport default withStyles(styles, {\n name: 'MuiInput'\n})(Input);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { refType } from '@material-ui/utils';\nimport InputBase from '../InputBase';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n var light = theme.palette.type === 'light';\n var bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';\n var backgroundColor = light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)';\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'relative',\n backgroundColor: backgroundColor,\n borderTopLeftRadius: theme.shape.borderRadius,\n borderTopRightRadius: theme.shape.borderRadius,\n transition: theme.transitions.create('background-color', {\n duration: theme.transitions.duration.shorter,\n easing: theme.transitions.easing.easeOut\n }),\n '&:hover': {\n backgroundColor: light ? 'rgba(0, 0, 0, 0.13)' : 'rgba(255, 255, 255, 0.13)',\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: backgroundColor\n }\n },\n '&$focused': {\n backgroundColor: light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)'\n },\n '&$disabled': {\n backgroundColor: light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)'\n }\n },\n\n /* Styles applied to the root element if color secondary. */\n colorSecondary: {\n '&$underline:after': {\n borderBottomColor: theme.palette.secondary.main\n }\n },\n\n /* Styles applied to the root element if `disableUnderline={false}`. */\n underline: {\n '&:after': {\n borderBottom: \"2px solid \".concat(theme.palette.primary.main),\n left: 0,\n bottom: 0,\n // Doing the other way around crash on IE 11 \"''\" https://github.com/cssinjs/jss/issues/242\n content: '\"\"',\n position: 'absolute',\n right: 0,\n transform: 'scaleX(0)',\n transition: theme.transitions.create('transform', {\n duration: theme.transitions.duration.shorter,\n easing: theme.transitions.easing.easeOut\n }),\n pointerEvents: 'none' // Transparent to the hover style.\n\n },\n '&$focused:after': {\n transform: 'scaleX(1)'\n },\n '&$error:after': {\n borderBottomColor: theme.palette.error.main,\n transform: 'scaleX(1)' // error is always underlined in red\n\n },\n '&:before': {\n borderBottom: \"1px solid \".concat(bottomLineColor),\n left: 0,\n bottom: 0,\n // Doing the other way around crash on IE 11 \"''\" https://github.com/cssinjs/jss/issues/242\n content: '\"\\\\00a0\"',\n position: 'absolute',\n right: 0,\n transition: theme.transitions.create('border-bottom-color', {\n duration: theme.transitions.duration.shorter\n }),\n pointerEvents: 'none' // Transparent to the hover style.\n\n },\n '&:hover:before': {\n borderBottom: \"1px solid \".concat(theme.palette.text.primary)\n },\n '&$disabled:before': {\n borderBottomStyle: 'dotted'\n }\n },\n\n /* Pseudo-class applied to the root element if the component is focused. */\n focused: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the root element if `startAdornment` is provided. */\n adornedStart: {\n paddingLeft: 12\n },\n\n /* Styles applied to the root element if `endAdornment` is provided. */\n adornedEnd: {\n paddingRight: 12\n },\n\n /* Pseudo-class applied to the root element if `error={true}`. */\n error: {},\n\n /* Styles applied to the `input` element if `margin=\"dense\"`. */\n marginDense: {},\n\n /* Styles applied to the root element if `multiline={true}`. */\n multiline: {\n padding: '27px 12px 10px',\n '&$marginDense': {\n paddingTop: 23,\n paddingBottom: 6\n }\n },\n\n /* Styles applied to the `input` element. */\n input: {\n padding: '27px 12px 10px',\n '&:-webkit-autofill': {\n WebkitBoxShadow: theme.palette.type === 'light' ? null : '0 0 0 100px #266798 inset',\n WebkitTextFillColor: theme.palette.type === 'light' ? null : '#fff',\n caretColor: theme.palette.type === 'light' ? null : '#fff',\n borderTopLeftRadius: 'inherit',\n borderTopRightRadius: 'inherit'\n }\n },\n\n /* Styles applied to the `input` element if `margin=\"dense\"`. */\n inputMarginDense: {\n paddingTop: 23,\n paddingBottom: 6\n },\n\n /* Styles applied to the `input` if in `<FormControl hiddenLabel />`. */\n inputHiddenLabel: {\n paddingTop: 18,\n paddingBottom: 19,\n '&$inputMarginDense': {\n paddingTop: 10,\n paddingBottom: 11\n }\n },\n\n /* Styles applied to the `input` element if `multiline={true}`. */\n inputMultiline: {\n padding: 0\n },\n\n /* Styles applied to the `input` element if `startAdornment` is provided. */\n inputAdornedStart: {\n paddingLeft: 0\n },\n\n /* Styles applied to the `input` element if `endAdornment` is provided. */\n inputAdornedEnd: {\n paddingRight: 0\n }\n };\n};\nvar FilledInput = /*#__PURE__*/React.forwardRef(function FilledInput(props, ref) {\n var disableUnderline = props.disableUnderline,\n classes = props.classes,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n _props$inputComponent = props.inputComponent,\n inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,\n _props$multiline = props.multiline,\n multiline = _props$multiline === void 0 ? false : _props$multiline,\n _props$type = props.type,\n type = _props$type === void 0 ? 'text' : _props$type,\n other = _objectWithoutProperties(props, [\"disableUnderline\", \"classes\", \"fullWidth\", \"inputComponent\", \"multiline\", \"type\"]);\n\n return /*#__PURE__*/React.createElement(InputBase, _extends({\n classes: _extends({}, classes, {\n root: clsx(classes.root, !disableUnderline && classes.underline),\n underline: null\n }),\n fullWidth: fullWidth,\n inputComponent: inputComponent,\n multiline: multiline,\n ref: ref,\n type: type\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? FilledInput.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * This prop helps users to fill forms faster, especially on mobile devices.\n * The name can be confusing, as it's more like an autofill.\n * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).\n */\n autoComplete: PropTypes.string,\n\n /**\n * If `true`, the `input` element will be focused during the first mount.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The default `input` element value. Use when the component is not controlled.\n */\n defaultValue: PropTypes.any,\n\n /**\n * If `true`, the `input` element will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the input will not have an underline.\n */\n disableUnderline: PropTypes.bool,\n\n /**\n * End `InputAdornment` for this component.\n */\n endAdornment: PropTypes.node,\n\n /**\n * If `true`, the input will indicate an error. This is normally obtained via context from\n * FormControl.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the input will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The id of the `input` element.\n */\n id: PropTypes.string,\n\n /**\n * The component used for the `input` element.\n * Either a string to use a HTML element or a component.\n */\n inputComponent: PropTypes.elementType,\n\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n */\n inputProps: PropTypes.object,\n\n /**\n * Pass a ref to the `input` element.\n */\n inputRef: refType,\n\n /**\n * If `dense`, will adjust vertical spacing. This is normally obtained via context from\n * FormControl.\n */\n margin: PropTypes.oneOf(['dense', 'none']),\n\n /**\n * If `true`, a textarea element will be rendered.\n */\n multiline: PropTypes.bool,\n\n /**\n * Name attribute of the `input` element.\n */\n name: PropTypes.string,\n\n /**\n * Callback fired when the value is changed.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (string).\n */\n onChange: PropTypes.func,\n\n /**\n * The short hint displayed in the input before the user enters a value.\n */\n placeholder: PropTypes.string,\n\n /**\n * It prevents the user from changing the value of the field\n * (not from interacting with the field).\n */\n readOnly: PropTypes.bool,\n\n /**\n * If `true`, the `input` element will be required.\n */\n required: PropTypes.bool,\n\n /**\n * Number of rows to display when multiline option is set to true.\n */\n rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Maximum number of rows to display when multiline option is set to true.\n */\n rowsMax: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Start `InputAdornment` for this component.\n */\n startAdornment: PropTypes.node,\n\n /**\n * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).\n */\n type: PropTypes.string,\n\n /**\n * The value of the `input` element, required for a controlled component.\n */\n value: PropTypes.any\n} : void 0;\nFilledInput.muiName = 'Input';\nexport default withStyles(styles, {\n name: 'MuiFilledInput'\n})(FilledInput);","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport useTheme from '../styles/useTheme';\nimport capitalize from '../utils/capitalize';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'absolute',\n bottom: 0,\n right: 0,\n top: -5,\n left: 0,\n margin: 0,\n padding: '0 8px',\n pointerEvents: 'none',\n borderRadius: 'inherit',\n borderStyle: 'solid',\n borderWidth: 1,\n overflow: 'hidden'\n },\n\n /* Styles applied to the legend element when `labelWidth` is provided. */\n legend: {\n textAlign: 'left',\n padding: 0,\n lineHeight: '11px',\n // sync with `height` in `legend` styles\n transition: theme.transitions.create('width', {\n duration: 150,\n easing: theme.transitions.easing.easeOut\n })\n },\n\n /* Styles applied to the legend element. */\n legendLabelled: {\n display: 'block',\n width: 'auto',\n textAlign: 'left',\n padding: 0,\n height: 11,\n // sync with `lineHeight` in `legend` styles\n fontSize: '0.75em',\n visibility: 'hidden',\n maxWidth: 0.01,\n transition: theme.transitions.create('max-width', {\n duration: 50,\n easing: theme.transitions.easing.easeOut\n }),\n '& > span': {\n paddingLeft: 5,\n paddingRight: 5,\n display: 'inline-block'\n }\n },\n\n /* Styles applied to the legend element is notched. */\n legendNotched: {\n maxWidth: 1000,\n transition: theme.transitions.create('max-width', {\n duration: 100,\n easing: theme.transitions.easing.easeOut,\n delay: 50\n })\n }\n };\n};\n/**\n * @ignore - internal component.\n */\n\nvar NotchedOutline = /*#__PURE__*/React.forwardRef(function NotchedOutline(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n label = props.label,\n labelWidthProp = props.labelWidth,\n notched = props.notched,\n style = props.style,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"label\", \"labelWidth\", \"notched\", \"style\"]);\n\n var theme = useTheme();\n var align = theme.direction === 'rtl' ? 'right' : 'left';\n\n if (label !== undefined) {\n return /*#__PURE__*/React.createElement(\"fieldset\", _extends({\n \"aria-hidden\": true,\n className: clsx(classes.root, className),\n ref: ref,\n style: style\n }, other), /*#__PURE__*/React.createElement(\"legend\", {\n className: clsx(classes.legendLabelled, notched && classes.legendNotched)\n }, label ? /*#__PURE__*/React.createElement(\"span\", null, label) : /*#__PURE__*/React.createElement(\"span\", {\n dangerouslySetInnerHTML: {\n __html: '&#8203;'\n }\n })));\n }\n\n var labelWidth = labelWidthProp > 0 ? labelWidthProp * 0.75 + 8 : 0.01;\n return /*#__PURE__*/React.createElement(\"fieldset\", _extends({\n \"aria-hidden\": true,\n style: _extends(_defineProperty({}, \"padding\".concat(capitalize(align)), 8), style),\n className: clsx(classes.root, className),\n ref: ref\n }, other), /*#__PURE__*/React.createElement(\"legend\", {\n className: classes.legend,\n style: {\n // IE 11: fieldset with legend does not render\n // a border radius. This maintains consistency\n // by always having a legend rendered\n width: notched ? labelWidth : 0.01\n }\n }, /*#__PURE__*/React.createElement(\"span\", {\n dangerouslySetInnerHTML: {\n __html: '&#8203;'\n }\n })));\n});\nprocess.env.NODE_ENV !== \"production\" ? NotchedOutline.propTypes = {\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The label.\n */\n label: PropTypes.node,\n\n /**\n * The width of the label.\n */\n labelWidth: PropTypes.number.isRequired,\n\n /**\n * If `true`, the outline is notched to accommodate the label.\n */\n notched: PropTypes.bool.isRequired,\n\n /**\n * @ignore\n */\n style: PropTypes.object\n} : void 0;\nexport default withStyles(styles, {\n name: 'PrivateNotchedOutline'\n})(NotchedOutline);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { refType } from '@material-ui/utils';\nimport InputBase from '../InputBase';\nimport NotchedOutline from './NotchedOutline';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n var borderColor = theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'relative',\n borderRadius: theme.shape.borderRadius,\n '&:hover $notchedOutline': {\n borderColor: theme.palette.text.primary\n },\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n '&:hover $notchedOutline': {\n borderColor: borderColor\n }\n },\n '&$focused $notchedOutline': {\n borderColor: theme.palette.primary.main,\n borderWidth: 2\n },\n '&$error $notchedOutline': {\n borderColor: theme.palette.error.main\n },\n '&$disabled $notchedOutline': {\n borderColor: theme.palette.action.disabled\n }\n },\n\n /* Styles applied to the root element if the color is secondary. */\n colorSecondary: {\n '&$focused $notchedOutline': {\n borderColor: theme.palette.secondary.main\n }\n },\n\n /* Styles applied to the root element if the component is focused. */\n focused: {},\n\n /* Styles applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the root element if `startAdornment` is provided. */\n adornedStart: {\n paddingLeft: 14\n },\n\n /* Styles applied to the root element if `endAdornment` is provided. */\n adornedEnd: {\n paddingRight: 14\n },\n\n /* Pseudo-class applied to the root element if `error={true}`. */\n error: {},\n\n /* Styles applied to the `input` element if `margin=\"dense\"`. */\n marginDense: {},\n\n /* Styles applied to the root element if `multiline={true}`. */\n multiline: {\n padding: '18.5px 14px',\n '&$marginDense': {\n paddingTop: 10.5,\n paddingBottom: 10.5\n }\n },\n\n /* Styles applied to the `NotchedOutline` element. */\n notchedOutline: {\n borderColor: borderColor\n },\n\n /* Styles applied to the `input` element. */\n input: {\n padding: '18.5px 14px',\n '&:-webkit-autofill': {\n WebkitBoxShadow: theme.palette.type === 'light' ? null : '0 0 0 100px #266798 inset',\n WebkitTextFillColor: theme.palette.type === 'light' ? null : '#fff',\n caretColor: theme.palette.type === 'light' ? null : '#fff',\n borderRadius: 'inherit'\n }\n },\n\n /* Styles applied to the `input` element if `margin=\"dense\"`. */\n inputMarginDense: {\n paddingTop: 10.5,\n paddingBottom: 10.5\n },\n\n /* Styles applied to the `input` element if `multiline={true}`. */\n inputMultiline: {\n padding: 0\n },\n\n /* Styles applied to the `input` element if `startAdornment` is provided. */\n inputAdornedStart: {\n paddingLeft: 0\n },\n\n /* Styles applied to the `input` element if `endAdornment` is provided. */\n inputAdornedEnd: {\n paddingRight: 0\n }\n };\n};\nvar OutlinedInput = /*#__PURE__*/React.forwardRef(function OutlinedInput(props, ref) {\n var classes = props.classes,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n _props$inputComponent = props.inputComponent,\n inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,\n label = props.label,\n _props$labelWidth = props.labelWidth,\n labelWidth = _props$labelWidth === void 0 ? 0 : _props$labelWidth,\n _props$multiline = props.multiline,\n multiline = _props$multiline === void 0 ? false : _props$multiline,\n notched = props.notched,\n _props$type = props.type,\n type = _props$type === void 0 ? 'text' : _props$type,\n other = _objectWithoutProperties(props, [\"classes\", \"fullWidth\", \"inputComponent\", \"label\", \"labelWidth\", \"multiline\", \"notched\", \"type\"]);\n\n return /*#__PURE__*/React.createElement(InputBase, _extends({\n renderSuffix: function renderSuffix(state) {\n return /*#__PURE__*/React.createElement(NotchedOutline, {\n className: classes.notchedOutline,\n label: label,\n labelWidth: labelWidth,\n notched: typeof notched !== 'undefined' ? notched : Boolean(state.startAdornment || state.filled || state.focused)\n });\n },\n classes: _extends({}, classes, {\n root: clsx(classes.root, classes.underline),\n notchedOutline: null\n }),\n fullWidth: fullWidth,\n inputComponent: inputComponent,\n multiline: multiline,\n ref: ref,\n type: type\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? OutlinedInput.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * This prop helps users to fill forms faster, especially on mobile devices.\n * The name can be confusing, as it's more like an autofill.\n * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).\n */\n autoComplete: PropTypes.string,\n\n /**\n * If `true`, the `input` element will be focused during the first mount.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The default `input` element value. Use when the component is not controlled.\n */\n defaultValue: PropTypes.any,\n\n /**\n * If `true`, the `input` element will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * End `InputAdornment` for this component.\n */\n endAdornment: PropTypes.node,\n\n /**\n * If `true`, the input will indicate an error. This is normally obtained via context from\n * FormControl.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the input will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The id of the `input` element.\n */\n id: PropTypes.string,\n\n /**\n * The component used for the `input` element.\n * Either a string to use a HTML element or a component.\n */\n inputComponent: PropTypes.elementType,\n\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n */\n inputProps: PropTypes.object,\n\n /**\n * Pass a ref to the `input` element.\n */\n inputRef: refType,\n\n /**\n * The label of the input. It is only used for layout. The actual labelling\n * is handled by `InputLabel`. If specified `labelWidth` is ignored.\n */\n label: PropTypes.node,\n\n /**\n * The width of the label. Is ignored if `label` is provided. Prefer `label`\n * if the input label appears with a strike through.\n */\n labelWidth: PropTypes.number,\n\n /**\n * If `dense`, will adjust vertical spacing. This is normally obtained via context from\n * FormControl.\n */\n margin: PropTypes.oneOf(['dense', 'none']),\n\n /**\n * If `true`, a textarea element will be rendered.\n */\n multiline: PropTypes.bool,\n\n /**\n * Name attribute of the `input` element.\n */\n name: PropTypes.string,\n\n /**\n * If `true`, the outline is notched to accommodate the label.\n */\n notched: PropTypes.bool,\n\n /**\n * Callback fired when the value is changed.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (string).\n */\n onChange: PropTypes.func,\n\n /**\n * The short hint displayed in the input before the user enters a value.\n */\n placeholder: PropTypes.string,\n\n /**\n * It prevents the user from changing the value of the field\n * (not from interacting with the field).\n */\n readOnly: PropTypes.bool,\n\n /**\n * If `true`, the `input` element will be required.\n */\n required: PropTypes.bool,\n\n /**\n * Number of rows to display when multiline option is set to true.\n */\n rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Maximum number of rows to display when multiline option is set to true.\n */\n rowsMax: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Start `InputAdornment` for this component.\n */\n startAdornment: PropTypes.node,\n\n /**\n * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).\n */\n type: PropTypes.string,\n\n /**\n * The value of the `input` element, required for a controlled component.\n */\n value: PropTypes.any\n} : void 0;\nOutlinedInput.muiName = 'Input';\nexport default withStyles(styles, {\n name: 'MuiOutlinedInput'\n})(OutlinedInput);","import * as React from 'react';\nimport FormControlContext from './FormControlContext';\nexport default function useFormControl() {\n return React.useContext(FormControlContext);\n}","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport formControlState from '../FormControl/formControlState';\nimport useFormControl from '../FormControl/useFormControl';\nimport capitalize from '../utils/capitalize';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: _extends({\n color: theme.palette.text.secondary\n }, theme.typography.body1, {\n lineHeight: 1,\n padding: 0,\n '&$focused': {\n color: theme.palette.primary.main\n },\n '&$disabled': {\n color: theme.palette.text.disabled\n },\n '&$error': {\n color: theme.palette.error.main\n }\n }),\n\n /* Styles applied to the root element if the color is secondary. */\n colorSecondary: {\n '&$focused': {\n color: theme.palette.secondary.main\n }\n },\n\n /* Pseudo-class applied to the root element if `focused={true}`. */\n focused: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Pseudo-class applied to the root element if `error={true}`. */\n error: {},\n\n /* Pseudo-class applied to the root element if `filled={true}`. */\n filled: {},\n\n /* Pseudo-class applied to the root element if `required={true}`. */\n required: {},\n\n /* Styles applied to the asterisk element. */\n asterisk: {\n '&$error': {\n color: theme.palette.error.main\n }\n }\n };\n};\nvar FormLabel = /*#__PURE__*/React.forwardRef(function FormLabel(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n color = props.color,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'label' : _props$component,\n disabled = props.disabled,\n error = props.error,\n filled = props.filled,\n focused = props.focused,\n required = props.required,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"color\", \"component\", \"disabled\", \"error\", \"filled\", \"focused\", \"required\"]);\n\n var muiFormControl = useFormControl();\n var fcs = formControlState({\n props: props,\n muiFormControl: muiFormControl,\n states: ['color', 'required', 'focused', 'disabled', 'error', 'filled']\n });\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, classes[\"color\".concat(capitalize(fcs.color || 'primary'))], className, fcs.disabled && classes.disabled, fcs.error && classes.error, fcs.filled && classes.filled, fcs.focused && classes.focused, fcs.required && classes.required),\n ref: ref\n }, other), children, fcs.required && /*#__PURE__*/React.createElement(\"span\", {\n \"aria-hidden\": true,\n className: clsx(classes.asterisk, fcs.error && classes.error)\n }, \"\\u2009\", '*'));\n});\nprocess.env.NODE_ENV !== \"production\" ? FormLabel.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, the label should be displayed in a disabled state.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the label should be displayed in an error state.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the label should use filled classes key.\n */\n filled: PropTypes.bool,\n\n /**\n * If `true`, the input of this label is focused (used by `FormGroup` components).\n */\n focused: PropTypes.bool,\n\n /**\n * If `true`, the label will indicate that the input is required.\n */\n required: PropTypes.bool\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiFormLabel'\n})(FormLabel);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport formControlState from '../FormControl/formControlState';\nimport useFormControl from '../FormControl/useFormControl';\nimport withStyles from '../styles/withStyles';\nimport FormLabel from '../FormLabel';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n display: 'block',\n transformOrigin: 'top left'\n },\n\n /* Pseudo-class applied to the root element if `focused={true}`. */\n focused: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Pseudo-class applied to the root element if `error={true}`. */\n error: {},\n\n /* Pseudo-class applied to the root element if `required={true}`. */\n required: {},\n\n /* Pseudo-class applied to the asterisk element. */\n asterisk: {},\n\n /* Styles applied to the root element if the component is a descendant of `FormControl`. */\n formControl: {\n position: 'absolute',\n left: 0,\n top: 0,\n // slight alteration to spec spacing to match visual spec result\n transform: 'translate(0, 24px) scale(1)'\n },\n\n /* Styles applied to the root element if `margin=\"dense\"`. */\n marginDense: {\n // Compensation for the `Input.inputDense` style.\n transform: 'translate(0, 21px) scale(1)'\n },\n\n /* Styles applied to the `input` element if `shrink={true}`. */\n shrink: {\n transform: 'translate(0, 1.5px) scale(0.75)',\n transformOrigin: 'top left'\n },\n\n /* Styles applied to the `input` element if `disableAnimation={false}`. */\n animated: {\n transition: theme.transitions.create(['color', 'transform'], {\n duration: theme.transitions.duration.shorter,\n easing: theme.transitions.easing.easeOut\n })\n },\n\n /* Styles applied to the root element if `variant=\"filled\"`. */\n filled: {\n // Chrome's autofill feature gives the input field a yellow background.\n // Since the input field is behind the label in the HTML tree,\n // the input field is drawn last and hides the label with an opaque background color.\n // zIndex: 1 will raise the label above opaque background-colors of input.\n zIndex: 1,\n pointerEvents: 'none',\n transform: 'translate(12px, 20px) scale(1)',\n '&$marginDense': {\n transform: 'translate(12px, 17px) scale(1)'\n },\n '&$shrink': {\n transform: 'translate(12px, 10px) scale(0.75)',\n '&$marginDense': {\n transform: 'translate(12px, 7px) scale(0.75)'\n }\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"`. */\n outlined: {\n // see comment above on filled.zIndex\n zIndex: 1,\n pointerEvents: 'none',\n transform: 'translate(14px, 20px) scale(1)',\n '&$marginDense': {\n transform: 'translate(14px, 12px) scale(1)'\n },\n '&$shrink': {\n transform: 'translate(14px, -6px) scale(0.75)'\n }\n }\n };\n};\nvar InputLabel = /*#__PURE__*/React.forwardRef(function InputLabel(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$disableAnimati = props.disableAnimation,\n disableAnimation = _props$disableAnimati === void 0 ? false : _props$disableAnimati,\n margin = props.margin,\n shrinkProp = props.shrink,\n variant = props.variant,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"disableAnimation\", \"margin\", \"shrink\", \"variant\"]);\n\n var muiFormControl = useFormControl();\n var shrink = shrinkProp;\n\n if (typeof shrink === 'undefined' && muiFormControl) {\n shrink = muiFormControl.filled || muiFormControl.focused || muiFormControl.adornedStart;\n }\n\n var fcs = formControlState({\n props: props,\n muiFormControl: muiFormControl,\n states: ['margin', 'variant']\n });\n return /*#__PURE__*/React.createElement(FormLabel, _extends({\n \"data-shrink\": shrink,\n className: clsx(classes.root, className, muiFormControl && classes.formControl, !disableAnimation && classes.animated, shrink && classes.shrink, fcs.margin === 'dense' && classes.marginDense, {\n 'filled': classes.filled,\n 'outlined': classes.outlined\n }[fcs.variant]),\n classes: {\n focused: classes.focused,\n disabled: classes.disabled,\n error: classes.error,\n required: classes.required,\n asterisk: classes.asterisk\n },\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? InputLabel.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The contents of the `InputLabel`.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * If `true`, the transition animation is disabled.\n */\n disableAnimation: PropTypes.bool,\n\n /**\n * If `true`, apply disabled class.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the label will be displayed in an error state.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the input of this label is focused.\n */\n focused: PropTypes.bool,\n\n /**\n * If `dense`, will adjust vertical spacing. This is normally obtained via context from\n * FormControl.\n */\n margin: PropTypes.oneOf(['dense']),\n\n /**\n * if `true`, the label will indicate that the input is required.\n */\n required: PropTypes.bool,\n\n /**\n * If `true`, the label is shrunk.\n */\n shrink: PropTypes.bool,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiInputLabel'\n})(InputLabel);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { isFilled, isAdornedStart } from '../InputBase/utils';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nimport isMuiElement from '../utils/isMuiElement';\nimport FormControlContext from './FormControlContext';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n display: 'inline-flex',\n flexDirection: 'column',\n position: 'relative',\n // Reset fieldset default style.\n minWidth: 0,\n padding: 0,\n margin: 0,\n border: 0,\n verticalAlign: 'top' // Fix alignment issue on Safari.\n\n },\n\n /* Styles applied to the root element if `margin=\"normal\"`. */\n marginNormal: {\n marginTop: 16,\n marginBottom: 8\n },\n\n /* Styles applied to the root element if `margin=\"dense\"`. */\n marginDense: {\n marginTop: 8,\n marginBottom: 4\n },\n\n /* Styles applied to the root element if `fullWidth={true}`. */\n fullWidth: {\n width: '100%'\n }\n};\n/**\n * Provides context such as filled/focused/error/required for form inputs.\n * Relying on the context provides high flexibility and ensures that the state always stays\n * consistent across the children of the `FormControl`.\n * This context is used by the following components:\n *\n * - FormLabel\n * - FormHelperText\n * - Input\n * - InputLabel\n *\n * You can find one composition example below and more going to [the demos](/components/text-fields/#components).\n *\n * ```jsx\n * <FormControl>\n * <InputLabel htmlFor=\"my-input\">Email address</InputLabel>\n * <Input id=\"my-input\" aria-describedby=\"my-helper-text\" />\n * <FormHelperText id=\"my-helper-text\">We'll never share your email.</FormHelperText>\n * </FormControl>\n * ```\n *\n * ⚠️Only one input can be used within a FormControl.\n */\n\nvar FormControl = /*#__PURE__*/React.forwardRef(function FormControl(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'primary' : _props$color,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$error = props.error,\n error = _props$error === void 0 ? false : _props$error,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n visuallyFocused = props.focused,\n _props$hiddenLabel = props.hiddenLabel,\n hiddenLabel = _props$hiddenLabel === void 0 ? false : _props$hiddenLabel,\n _props$margin = props.margin,\n margin = _props$margin === void 0 ? 'none' : _props$margin,\n _props$required = props.required,\n required = _props$required === void 0 ? false : _props$required,\n size = props.size,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'standard' : _props$variant,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"color\", \"component\", \"disabled\", \"error\", \"fullWidth\", \"focused\", \"hiddenLabel\", \"margin\", \"required\", \"size\", \"variant\"]);\n\n var _React$useState = React.useState(function () {\n // We need to iterate through the children and find the Input in order\n // to fully support server-side rendering.\n var initialAdornedStart = false;\n\n if (children) {\n React.Children.forEach(children, function (child) {\n if (!isMuiElement(child, ['Input', 'Select'])) {\n return;\n }\n\n var input = isMuiElement(child, ['Select']) ? child.props.input : child;\n\n if (input && isAdornedStart(input.props)) {\n initialAdornedStart = true;\n }\n });\n }\n\n return initialAdornedStart;\n }),\n adornedStart = _React$useState[0],\n setAdornedStart = _React$useState[1];\n\n var _React$useState2 = React.useState(function () {\n // We need to iterate through the children and find the Input in order\n // to fully support server-side rendering.\n var initialFilled = false;\n\n if (children) {\n React.Children.forEach(children, function (child) {\n if (!isMuiElement(child, ['Input', 'Select'])) {\n return;\n }\n\n if (isFilled(child.props, true)) {\n initialFilled = true;\n }\n });\n }\n\n return initialFilled;\n }),\n filled = _React$useState2[0],\n setFilled = _React$useState2[1];\n\n var _React$useState3 = React.useState(false),\n _focused = _React$useState3[0],\n setFocused = _React$useState3[1];\n\n var focused = visuallyFocused !== undefined ? visuallyFocused : _focused;\n\n if (disabled && focused) {\n setFocused(false);\n }\n\n var registerEffect;\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n var registeredInput = React.useRef(false);\n\n registerEffect = function registerEffect() {\n if (registeredInput.current) {\n console.error(['Material-UI: There are multiple InputBase components inside a FormControl.', 'This is not supported. It might cause infinite rendering loops.', 'Only use one InputBase.'].join('\\n'));\n }\n\n registeredInput.current = true;\n return function () {\n registeredInput.current = false;\n };\n };\n }\n\n var onFilled = React.useCallback(function () {\n setFilled(true);\n }, []);\n var onEmpty = React.useCallback(function () {\n setFilled(false);\n }, []);\n var childContext = {\n adornedStart: adornedStart,\n setAdornedStart: setAdornedStart,\n color: color,\n disabled: disabled,\n error: error,\n filled: filled,\n focused: focused,\n fullWidth: fullWidth,\n hiddenLabel: hiddenLabel,\n margin: (size === 'small' ? 'dense' : undefined) || margin,\n onBlur: function onBlur() {\n setFocused(false);\n },\n onEmpty: onEmpty,\n onFilled: onFilled,\n onFocus: function onFocus() {\n setFocused(true);\n },\n registerEffect: registerEffect,\n required: required,\n variant: variant\n };\n return /*#__PURE__*/React.createElement(FormControlContext.Provider, {\n value: childContext\n }, /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, margin !== 'none' && classes[\"margin\".concat(capitalize(margin))], fullWidth && classes.fullWidth),\n ref: ref\n }, other), children));\n});\nprocess.env.NODE_ENV !== \"production\" ? FormControl.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The contents of the form control.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, the label, input and helper text should be displayed in a disabled state.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the label should be displayed in an error state.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the component will be displayed in focused state.\n */\n focused: PropTypes.bool,\n\n /**\n * If `true`, the component will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * If `true`, the label will be hidden.\n * This is used to increase density for a `FilledInput`.\n * Be sure to add `aria-label` to the `input` element.\n */\n hiddenLabel: PropTypes.bool,\n\n /**\n * If `dense` or `normal`, will adjust vertical spacing of this and contained components.\n */\n margin: PropTypes.oneOf(['dense', 'none', 'normal']),\n\n /**\n * If `true`, the label will indicate that the input is required.\n */\n required: PropTypes.bool,\n\n /**\n * The size of the text field.\n */\n size: PropTypes.oneOf(['medium', 'small']),\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiFormControl'\n})(FormControl);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport formControlState from '../FormControl/formControlState';\nimport useFormControl from '../FormControl/useFormControl';\nimport withStyles from '../styles/withStyles';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: _extends({\n color: theme.palette.text.secondary\n }, theme.typography.caption, {\n textAlign: 'left',\n marginTop: 3,\n margin: 0,\n '&$disabled': {\n color: theme.palette.text.disabled\n },\n '&$error': {\n color: theme.palette.error.main\n }\n }),\n\n /* Pseudo-class applied to the root element if `error={true}`. */\n error: {},\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the root element if `margin=\"dense\"`. */\n marginDense: {\n marginTop: 4\n },\n\n /* Styles applied to the root element if `variant=\"filled\"` or `variant=\"outlined\"`. */\n contained: {\n marginLeft: 14,\n marginRight: 14\n },\n\n /* Pseudo-class applied to the root element if `focused={true}`. */\n focused: {},\n\n /* Pseudo-class applied to the root element if `filled={true}`. */\n filled: {},\n\n /* Pseudo-class applied to the root element if `required={true}`. */\n required: {}\n };\n};\nvar FormHelperText = /*#__PURE__*/React.forwardRef(function FormHelperText(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'p' : _props$component,\n disabled = props.disabled,\n error = props.error,\n filled = props.filled,\n focused = props.focused,\n margin = props.margin,\n required = props.required,\n variant = props.variant,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"component\", \"disabled\", \"error\", \"filled\", \"focused\", \"margin\", \"required\", \"variant\"]);\n\n var muiFormControl = useFormControl();\n var fcs = formControlState({\n props: props,\n muiFormControl: muiFormControl,\n states: ['variant', 'margin', 'disabled', 'error', 'filled', 'focused', 'required']\n });\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, (fcs.variant === 'filled' || fcs.variant === 'outlined') && classes.contained, className, fcs.disabled && classes.disabled, fcs.error && classes.error, fcs.filled && classes.filled, fcs.focused && classes.focused, fcs.required && classes.required, fcs.margin === 'dense' && classes.marginDense),\n ref: ref\n }, other), children === ' ' ?\n /*#__PURE__*/\n // eslint-disable-next-line react/no-danger\n React.createElement(\"span\", {\n dangerouslySetInnerHTML: {\n __html: '&#8203;'\n }\n }) : children);\n});\nprocess.env.NODE_ENV !== \"production\" ? FormHelperText.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the component.\n *\n * If `' '` is provided, the component reserves one line height for displaying a future message.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, the helper text should be displayed in a disabled state.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, helper text should be displayed in an error state.\n */\n error: PropTypes.bool,\n\n /**\n * If `true`, the helper text should use filled classes key.\n */\n filled: PropTypes.bool,\n\n /**\n * If `true`, the helper text should use focused classes key.\n */\n focused: PropTypes.bool,\n\n /**\n * If `dense`, will adjust vertical spacing. This is normally obtained via context from\n * FormControl.\n */\n margin: PropTypes.oneOf(['dense']),\n\n /**\n * If `true`, the helper text should use required classes key.\n */\n required: PropTypes.bool,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiFormHelperText'\n})(FormHelperText);","/**\n * Safe chained function\n *\n * Will only create a new function if needed,\n * otherwise will pass back existing functions or null.\n *\n * @param {function} functions to chain\n * @returns {function|null}\n */\nexport default function createChainedFunction() {\n for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {\n funcs[_key] = arguments[_key];\n }\n\n return funcs.reduce(function (acc, func) {\n if (func == null) {\n return acc;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof func !== 'function') {\n console.error('Material-UI: Invalid Argument Type, must only provide functions, undefined, or null.');\n }\n }\n\n return function chainedFunction() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n acc.apply(this, args);\n func.apply(this, args);\n };\n }, function () {});\n}","import * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport { exactProp, HTMLElementType } from '@material-ui/utils';\nimport setRef from '../utils/setRef';\nimport useForkRef from '../utils/useForkRef';\n\nfunction getContainer(container) {\n container = typeof container === 'function' ? container() : container; // #StrictMode ready\n\n return ReactDOM.findDOMNode(container);\n}\n\nvar useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n/**\n * Portals provide a first-class way to render children into a DOM node\n * that exists outside the DOM hierarchy of the parent component.\n */\n\nvar Portal = /*#__PURE__*/React.forwardRef(function Portal(props, ref) {\n var children = props.children,\n container = props.container,\n _props$disablePortal = props.disablePortal,\n disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,\n onRendered = props.onRendered;\n\n var _React$useState = React.useState(null),\n mountNode = _React$useState[0],\n setMountNode = _React$useState[1];\n\n var handleRef = useForkRef( /*#__PURE__*/React.isValidElement(children) ? children.ref : null, ref);\n useEnhancedEffect(function () {\n if (!disablePortal) {\n setMountNode(getContainer(container) || document.body);\n }\n }, [container, disablePortal]);\n useEnhancedEffect(function () {\n if (mountNode && !disablePortal) {\n setRef(ref, mountNode);\n return function () {\n setRef(ref, null);\n };\n }\n\n return undefined;\n }, [ref, mountNode, disablePortal]);\n useEnhancedEffect(function () {\n if (onRendered && (mountNode || disablePortal)) {\n onRendered();\n }\n }, [onRendered, mountNode, disablePortal]);\n\n if (disablePortal) {\n if ( /*#__PURE__*/React.isValidElement(children)) {\n return /*#__PURE__*/React.cloneElement(children, {\n ref: handleRef\n });\n }\n\n return children;\n }\n\n return mountNode ? /*#__PURE__*/ReactDOM.createPortal(children, mountNode) : mountNode;\n});\nprocess.env.NODE_ENV !== \"production\" ? Portal.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The children to render into the `container`.\n */\n children: PropTypes.node,\n\n /**\n * A HTML element, component instance, or function that returns either.\n * The `container` will have the portal children appended to it.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([HTMLElementType, PropTypes.instanceOf(React.Component), PropTypes.func]),\n\n /**\n * Disable the portal behavior.\n * The children stay within it's parent DOM hierarchy.\n */\n disablePortal: PropTypes.bool,\n\n /**\n * Callback fired once the children has been mounted into the `container`.\n *\n * This prop will be deprecated and removed in v5, the ref can be used instead.\n */\n onRendered: PropTypes.func\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n Portal['propTypes' + ''] = exactProp(Portal.propTypes);\n}\n\nexport default Portal;","// A change of the browser zoom change the scrollbar size.\n// Credit https://github.com/twbs/bootstrap/blob/3ffe3a5d82f6f561b82ff78d82b32a7d14aed558/js/src/modal.js#L512-L519\nexport default function getScrollbarSize() {\n var scrollDiv = document.createElement('div');\n scrollDiv.style.width = '99px';\n scrollDiv.style.height = '99px';\n scrollDiv.style.position = 'absolute';\n scrollDiv.style.top = '-9999px';\n scrollDiv.style.overflow = 'scroll';\n document.body.appendChild(scrollDiv);\n var scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;\n document.body.removeChild(scrollDiv);\n return scrollbarSize;\n}","import _classCallCheck from \"@babel/runtime/helpers/esm/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/esm/createClass\";\nimport _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport getScrollbarSize from '../utils/getScrollbarSize';\nimport ownerDocument from '../utils/ownerDocument';\nimport ownerWindow from '../utils/ownerWindow'; // Is a vertical scrollbar displayed?\n\nfunction isOverflowing(container) {\n var doc = ownerDocument(container);\n\n if (doc.body === container) {\n return ownerWindow(doc).innerWidth > doc.documentElement.clientWidth;\n }\n\n return container.scrollHeight > container.clientHeight;\n}\n\nexport function ariaHidden(node, show) {\n if (show) {\n node.setAttribute('aria-hidden', 'true');\n } else {\n node.removeAttribute('aria-hidden');\n }\n}\n\nfunction getPaddingRight(node) {\n return parseInt(window.getComputedStyle(node)['padding-right'], 10) || 0;\n}\n\nfunction ariaHiddenSiblings(container, mountNode, currentNode) {\n var nodesToExclude = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];\n var show = arguments.length > 4 ? arguments[4] : undefined;\n var blacklist = [mountNode, currentNode].concat(_toConsumableArray(nodesToExclude));\n var blacklistTagNames = ['TEMPLATE', 'SCRIPT', 'STYLE'];\n [].forEach.call(container.children, function (node) {\n if (node.nodeType === 1 && blacklist.indexOf(node) === -1 && blacklistTagNames.indexOf(node.tagName) === -1) {\n ariaHidden(node, show);\n }\n });\n}\n\nfunction findIndexOf(containerInfo, callback) {\n var idx = -1;\n containerInfo.some(function (item, index) {\n if (callback(item)) {\n idx = index;\n return true;\n }\n\n return false;\n });\n return idx;\n}\n\nfunction handleContainer(containerInfo, props) {\n var restoreStyle = [];\n var restorePaddings = [];\n var container = containerInfo.container;\n var fixedNodes;\n\n if (!props.disableScrollLock) {\n if (isOverflowing(container)) {\n // Compute the size before applying overflow hidden to avoid any scroll jumps.\n var scrollbarSize = getScrollbarSize();\n restoreStyle.push({\n value: container.style.paddingRight,\n key: 'padding-right',\n el: container\n }); // Use computed style, here to get the real padding to add our scrollbar width.\n\n container.style['padding-right'] = \"\".concat(getPaddingRight(container) + scrollbarSize, \"px\"); // .mui-fixed is a global helper.\n\n fixedNodes = ownerDocument(container).querySelectorAll('.mui-fixed');\n [].forEach.call(fixedNodes, function (node) {\n restorePaddings.push(node.style.paddingRight);\n node.style.paddingRight = \"\".concat(getPaddingRight(node) + scrollbarSize, \"px\");\n });\n } // Improve Gatsby support\n // https://css-tricks.com/snippets/css/force-vertical-scrollbar/\n\n\n var parent = container.parentElement;\n var scrollContainer = parent.nodeName === 'HTML' && window.getComputedStyle(parent)['overflow-y'] === 'scroll' ? parent : container; // Block the scroll even if no scrollbar is visible to account for mobile keyboard\n // screensize shrink.\n\n restoreStyle.push({\n value: scrollContainer.style.overflow,\n key: 'overflow',\n el: scrollContainer\n });\n scrollContainer.style.overflow = 'hidden';\n }\n\n var restore = function restore() {\n if (fixedNodes) {\n [].forEach.call(fixedNodes, function (node, i) {\n if (restorePaddings[i]) {\n node.style.paddingRight = restorePaddings[i];\n } else {\n node.style.removeProperty('padding-right');\n }\n });\n }\n\n restoreStyle.forEach(function (_ref) {\n var value = _ref.value,\n el = _ref.el,\n key = _ref.key;\n\n if (value) {\n el.style.setProperty(key, value);\n } else {\n el.style.removeProperty(key);\n }\n });\n };\n\n return restore;\n}\n\nfunction getHiddenSiblings(container) {\n var hiddenSiblings = [];\n [].forEach.call(container.children, function (node) {\n if (node.getAttribute && node.getAttribute('aria-hidden') === 'true') {\n hiddenSiblings.push(node);\n }\n });\n return hiddenSiblings;\n}\n/**\n * @ignore - do not document.\n *\n * Proper state management for containers and the modals in those containers.\n * Simplified, but inspired by react-overlay's ModalManager class.\n * Used by the Modal to ensure proper styling of containers.\n */\n\n\nvar ModalManager = /*#__PURE__*/function () {\n function ModalManager() {\n _classCallCheck(this, ModalManager);\n\n // this.modals[modalIndex] = modal\n this.modals = []; // this.containers[containerIndex] = {\n // modals: [],\n // container,\n // restore: null,\n // }\n\n this.containers = [];\n }\n\n _createClass(ModalManager, [{\n key: \"add\",\n value: function add(modal, container) {\n var modalIndex = this.modals.indexOf(modal);\n\n if (modalIndex !== -1) {\n return modalIndex;\n }\n\n modalIndex = this.modals.length;\n this.modals.push(modal); // If the modal we are adding is already in the DOM.\n\n if (modal.modalRef) {\n ariaHidden(modal.modalRef, false);\n }\n\n var hiddenSiblingNodes = getHiddenSiblings(container);\n ariaHiddenSiblings(container, modal.mountNode, modal.modalRef, hiddenSiblingNodes, true);\n var containerIndex = findIndexOf(this.containers, function (item) {\n return item.container === container;\n });\n\n if (containerIndex !== -1) {\n this.containers[containerIndex].modals.push(modal);\n return modalIndex;\n }\n\n this.containers.push({\n modals: [modal],\n container: container,\n restore: null,\n hiddenSiblingNodes: hiddenSiblingNodes\n });\n return modalIndex;\n }\n }, {\n key: \"mount\",\n value: function mount(modal, props) {\n var containerIndex = findIndexOf(this.containers, function (item) {\n return item.modals.indexOf(modal) !== -1;\n });\n var containerInfo = this.containers[containerIndex];\n\n if (!containerInfo.restore) {\n containerInfo.restore = handleContainer(containerInfo, props);\n }\n }\n }, {\n key: \"remove\",\n value: function remove(modal) {\n var modalIndex = this.modals.indexOf(modal);\n\n if (modalIndex === -1) {\n return modalIndex;\n }\n\n var containerIndex = findIndexOf(this.containers, function (item) {\n return item.modals.indexOf(modal) !== -1;\n });\n var containerInfo = this.containers[containerIndex];\n containerInfo.modals.splice(containerInfo.modals.indexOf(modal), 1);\n this.modals.splice(modalIndex, 1); // If that was the last modal in a container, clean up the container.\n\n if (containerInfo.modals.length === 0) {\n // The modal might be closed before it had the chance to be mounted in the DOM.\n if (containerInfo.restore) {\n containerInfo.restore();\n }\n\n if (modal.modalRef) {\n // In case the modal wasn't in the DOM yet.\n ariaHidden(modal.modalRef, true);\n }\n\n ariaHiddenSiblings(containerInfo.container, modal.mountNode, modal.modalRef, containerInfo.hiddenSiblingNodes, false);\n this.containers.splice(containerIndex, 1);\n } else {\n // Otherwise make sure the next top modal is visible to a screen reader.\n var nextTop = containerInfo.modals[containerInfo.modals.length - 1]; // as soon as a modal is adding its modalRef is undefined. it can't set\n // aria-hidden because the dom element doesn't exist either\n // when modal was unmounted before modalRef gets null\n\n if (nextTop.modalRef) {\n ariaHidden(nextTop.modalRef, false);\n }\n }\n\n return modalIndex;\n }\n }, {\n key: \"isTopModal\",\n value: function isTopModal(modal) {\n return this.modals.length > 0 && this.modals[this.modals.length - 1] === modal;\n }\n }]);\n\n return ModalManager;\n}();\n\nexport { ModalManager as default };","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex, camelcase */\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport ownerDocument from '../utils/ownerDocument';\nimport useForkRef from '../utils/useForkRef';\nimport { exactProp } from '@material-ui/utils';\n/**\n * Utility component that locks focus inside the component.\n */\n\nfunction Unstable_TrapFocus(props) {\n var children = props.children,\n _props$disableAutoFoc = props.disableAutoFocus,\n disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,\n _props$disableEnforce = props.disableEnforceFocus,\n disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce,\n _props$disableRestore = props.disableRestoreFocus,\n disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore,\n getDoc = props.getDoc,\n isEnabled = props.isEnabled,\n open = props.open;\n var ignoreNextEnforceFocus = React.useRef();\n var sentinelStart = React.useRef(null);\n var sentinelEnd = React.useRef(null);\n var nodeToRestore = React.useRef();\n var rootRef = React.useRef(null); // can be removed once we drop support for non ref forwarding class components\n\n var handleOwnRef = React.useCallback(function (instance) {\n // #StrictMode ready\n rootRef.current = ReactDOM.findDOMNode(instance);\n }, []);\n var handleRef = useForkRef(children.ref, handleOwnRef);\n var prevOpenRef = React.useRef();\n React.useEffect(function () {\n prevOpenRef.current = open;\n }, [open]);\n\n if (!prevOpenRef.current && open && typeof window !== 'undefined') {\n // WARNING: Potentially unsafe in concurrent mode.\n // The way the read on `nodeToRestore` is setup could make this actually safe.\n // Say we render `open={false}` -> `open={true}` but never commit.\n // We have now written a state that wasn't committed. But no committed effect\n // will read this wrong value. We only read from `nodeToRestore` in effects\n // that were committed on `open={true}`\n // WARNING: Prevents the instance from being garbage collected. Should only\n // hold a weak ref.\n nodeToRestore.current = getDoc().activeElement;\n }\n\n React.useEffect(function () {\n if (!open) {\n return;\n }\n\n var doc = ownerDocument(rootRef.current); // We might render an empty child.\n\n if (!disableAutoFocus && rootRef.current && !rootRef.current.contains(doc.activeElement)) {\n if (!rootRef.current.hasAttribute('tabIndex')) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(['Material-UI: The modal content node does not accept focus.', 'For the benefit of assistive technologies, ' + 'the tabIndex of the node is being set to \"-1\".'].join('\\n'));\n }\n\n rootRef.current.setAttribute('tabIndex', -1);\n }\n\n rootRef.current.focus();\n }\n\n var contain = function contain() {\n var rootElement = rootRef.current; // Cleanup functions are executed lazily in React 17.\n // Contain can be called between the component being unmounted and its cleanup function being run.\n\n if (rootElement === null) {\n return;\n }\n\n if (!doc.hasFocus() || disableEnforceFocus || !isEnabled() || ignoreNextEnforceFocus.current) {\n ignoreNextEnforceFocus.current = false;\n return;\n }\n\n if (rootRef.current && !rootRef.current.contains(doc.activeElement)) {\n rootRef.current.focus();\n }\n };\n\n var loopFocus = function loopFocus(event) {\n // 9 = Tab\n if (disableEnforceFocus || !isEnabled() || event.keyCode !== 9) {\n return;\n } // Make sure the next tab starts from the right place.\n\n\n if (doc.activeElement === rootRef.current) {\n // We need to ignore the next contain as\n // it will try to move the focus back to the rootRef element.\n ignoreNextEnforceFocus.current = true;\n\n if (event.shiftKey) {\n sentinelEnd.current.focus();\n } else {\n sentinelStart.current.focus();\n }\n }\n };\n\n doc.addEventListener('focus', contain, true);\n doc.addEventListener('keydown', loopFocus, true); // With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area\n // e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561.\n //\n // The whatwg spec defines how the browser should behave but does not explicitly mention any events:\n // https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule.\n\n var interval = setInterval(function () {\n contain();\n }, 50);\n return function () {\n clearInterval(interval);\n doc.removeEventListener('focus', contain, true);\n doc.removeEventListener('keydown', loopFocus, true); // restoreLastFocus()\n\n if (!disableRestoreFocus) {\n // In IE 11 it is possible for document.activeElement to be null resulting\n // in nodeToRestore.current being null.\n // Not all elements in IE 11 have a focus method.\n // Once IE 11 support is dropped the focus() call can be unconditional.\n if (nodeToRestore.current && nodeToRestore.current.focus) {\n nodeToRestore.current.focus();\n }\n\n nodeToRestore.current = null;\n }\n };\n }, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open]);\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"div\", {\n tabIndex: 0,\n ref: sentinelStart,\n \"data-test\": \"sentinelStart\"\n }), /*#__PURE__*/React.cloneElement(children, {\n ref: handleRef\n }), /*#__PURE__*/React.createElement(\"div\", {\n tabIndex: 0,\n ref: sentinelEnd,\n \"data-test\": \"sentinelEnd\"\n }));\n}\n\nprocess.env.NODE_ENV !== \"production\" ? Unstable_TrapFocus.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A single child content element.\n */\n children: PropTypes.node,\n\n /**\n * If `true`, the trap focus will not automatically shift focus to itself when it opens, and\n * replace it to the last focused element when it closes.\n * This also works correctly with any trap focus children that have the `disableAutoFocus` prop.\n *\n * Generally this should never be set to `true` as it makes the trap focus less\n * accessible to assistive technologies, like screen readers.\n */\n disableAutoFocus: PropTypes.bool,\n\n /**\n * If `true`, the trap focus will not prevent focus from leaving the trap focus while open.\n *\n * Generally this should never be set to `true` as it makes the trap focus less\n * accessible to assistive technologies, like screen readers.\n */\n disableEnforceFocus: PropTypes.bool,\n\n /**\n * If `true`, the trap focus will not restore focus to previously focused element once\n * trap focus is hidden.\n */\n disableRestoreFocus: PropTypes.bool,\n\n /**\n * Return the document to consider.\n * We use it to implement the restore focus between different browser documents.\n */\n getDoc: PropTypes.func.isRequired,\n\n /**\n * Do we still want to enforce the focus?\n * This prop helps nesting TrapFocus elements.\n */\n isEnabled: PropTypes.func.isRequired,\n\n /**\n * If `true`, focus will be locked.\n */\n open: PropTypes.bool.isRequired\n} : void 0;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n Unstable_TrapFocus['propTypes' + ''] = exactProp(Unstable_TrapFocus.propTypes);\n}\n\nexport default Unstable_TrapFocus;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n zIndex: -1,\n position: 'fixed',\n right: 0,\n bottom: 0,\n top: 0,\n left: 0,\n backgroundColor: 'rgba(0, 0, 0, 0.5)',\n WebkitTapHighlightColor: 'transparent'\n },\n\n /* Styles applied to the root element if `invisible={true}`. */\n invisible: {\n backgroundColor: 'transparent'\n }\n};\n/**\n * @ignore - internal component.\n */\n\nvar SimpleBackdrop = /*#__PURE__*/React.forwardRef(function SimpleBackdrop(props, ref) {\n var _props$invisible = props.invisible,\n invisible = _props$invisible === void 0 ? false : _props$invisible,\n open = props.open,\n other = _objectWithoutProperties(props, [\"invisible\", \"open\"]);\n\n return open ? /*#__PURE__*/React.createElement(\"div\", _extends({\n \"aria-hidden\": true,\n ref: ref\n }, other, {\n style: _extends({}, styles.root, invisible ? styles.invisible : {}, other.style)\n })) : null;\n});\nprocess.env.NODE_ENV !== \"production\" ? SimpleBackdrop.propTypes = {\n /**\n * If `true`, the backdrop is invisible.\n * It can be used when rendering a popover or a custom select component.\n */\n invisible: PropTypes.bool,\n\n /**\n * If `true`, the backdrop is open.\n */\n open: PropTypes.bool.isRequired\n} : void 0;\nexport default SimpleBackdrop;","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport { getThemeProps, useTheme } from '@material-ui/styles';\nimport { elementAcceptingRef, HTMLElementType } from '@material-ui/utils';\nimport ownerDocument from '../utils/ownerDocument';\nimport Portal from '../Portal';\nimport createChainedFunction from '../utils/createChainedFunction';\nimport useForkRef from '../utils/useForkRef';\nimport useEventCallback from '../utils/useEventCallback';\nimport zIndex from '../styles/zIndex';\nimport ModalManager, { ariaHidden } from './ModalManager';\nimport TrapFocus from '../Unstable_TrapFocus';\nimport SimpleBackdrop from './SimpleBackdrop';\n\nfunction getContainer(container) {\n container = typeof container === 'function' ? container() : container;\n return ReactDOM.findDOMNode(container);\n}\n\nfunction getHasTransition(props) {\n return props.children ? props.children.props.hasOwnProperty('in') : false;\n} // A modal manager used to track and manage the state of open Modals.\n// Modals don't open on the server so this won't conflict with concurrent requests.\n\n\nvar defaultManager = new ModalManager();\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'fixed',\n zIndex: theme.zIndex.modal,\n right: 0,\n bottom: 0,\n top: 0,\n left: 0\n },\n\n /* Styles applied to the root element if the `Modal` has exited. */\n hidden: {\n visibility: 'hidden'\n }\n };\n};\n/**\n * Modal is a lower-level construct that is leveraged by the following components:\n *\n * - [Dialog](/api/dialog/)\n * - [Drawer](/api/drawer/)\n * - [Menu](/api/menu/)\n * - [Popover](/api/popover/)\n *\n * If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component\n * rather than directly using Modal.\n *\n * This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).\n */\n\nvar Modal = /*#__PURE__*/React.forwardRef(function Modal(inProps, ref) {\n var theme = useTheme();\n var props = getThemeProps({\n name: 'MuiModal',\n props: _extends({}, inProps),\n theme: theme\n });\n\n var _props$BackdropCompon = props.BackdropComponent,\n BackdropComponent = _props$BackdropCompon === void 0 ? SimpleBackdrop : _props$BackdropCompon,\n BackdropProps = props.BackdropProps,\n children = props.children,\n _props$closeAfterTran = props.closeAfterTransition,\n closeAfterTransition = _props$closeAfterTran === void 0 ? false : _props$closeAfterTran,\n container = props.container,\n _props$disableAutoFoc = props.disableAutoFocus,\n disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,\n _props$disableBackdro = props.disableBackdropClick,\n disableBackdropClick = _props$disableBackdro === void 0 ? false : _props$disableBackdro,\n _props$disableEnforce = props.disableEnforceFocus,\n disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce,\n _props$disableEscapeK = props.disableEscapeKeyDown,\n disableEscapeKeyDown = _props$disableEscapeK === void 0 ? false : _props$disableEscapeK,\n _props$disablePortal = props.disablePortal,\n disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,\n _props$disableRestore = props.disableRestoreFocus,\n disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore,\n _props$disableScrollL = props.disableScrollLock,\n disableScrollLock = _props$disableScrollL === void 0 ? false : _props$disableScrollL,\n _props$hideBackdrop = props.hideBackdrop,\n hideBackdrop = _props$hideBackdrop === void 0 ? false : _props$hideBackdrop,\n _props$keepMounted = props.keepMounted,\n keepMounted = _props$keepMounted === void 0 ? false : _props$keepMounted,\n _props$manager = props.manager,\n manager = _props$manager === void 0 ? defaultManager : _props$manager,\n onBackdropClick = props.onBackdropClick,\n onClose = props.onClose,\n onEscapeKeyDown = props.onEscapeKeyDown,\n onRendered = props.onRendered,\n open = props.open,\n other = _objectWithoutProperties(props, [\"BackdropComponent\", \"BackdropProps\", \"children\", \"closeAfterTransition\", \"container\", \"disableAutoFocus\", \"disableBackdropClick\", \"disableEnforceFocus\", \"disableEscapeKeyDown\", \"disablePortal\", \"disableRestoreFocus\", \"disableScrollLock\", \"hideBackdrop\", \"keepMounted\", \"manager\", \"onBackdropClick\", \"onClose\", \"onEscapeKeyDown\", \"onRendered\", \"open\"]);\n\n var _React$useState = React.useState(true),\n exited = _React$useState[0],\n setExited = _React$useState[1];\n\n var modal = React.useRef({});\n var mountNodeRef = React.useRef(null);\n var modalRef = React.useRef(null);\n var handleRef = useForkRef(modalRef, ref);\n var hasTransition = getHasTransition(props);\n\n var getDoc = function getDoc() {\n return ownerDocument(mountNodeRef.current);\n };\n\n var getModal = function getModal() {\n modal.current.modalRef = modalRef.current;\n modal.current.mountNode = mountNodeRef.current;\n return modal.current;\n };\n\n var handleMounted = function handleMounted() {\n manager.mount(getModal(), {\n disableScrollLock: disableScrollLock\n }); // Fix a bug on Chrome where the scroll isn't initially 0.\n\n modalRef.current.scrollTop = 0;\n };\n\n var handleOpen = useEventCallback(function () {\n var resolvedContainer = getContainer(container) || getDoc().body;\n manager.add(getModal(), resolvedContainer); // The element was already mounted.\n\n if (modalRef.current) {\n handleMounted();\n }\n });\n var isTopModal = React.useCallback(function () {\n return manager.isTopModal(getModal());\n }, [manager]);\n var handlePortalRef = useEventCallback(function (node) {\n mountNodeRef.current = node;\n\n if (!node) {\n return;\n }\n\n if (onRendered) {\n onRendered();\n }\n\n if (open && isTopModal()) {\n handleMounted();\n } else {\n ariaHidden(modalRef.current, true);\n }\n });\n var handleClose = React.useCallback(function () {\n manager.remove(getModal());\n }, [manager]);\n React.useEffect(function () {\n return function () {\n handleClose();\n };\n }, [handleClose]);\n React.useEffect(function () {\n if (open) {\n handleOpen();\n } else if (!hasTransition || !closeAfterTransition) {\n handleClose();\n }\n }, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);\n\n if (!keepMounted && !open && (!hasTransition || exited)) {\n return null;\n }\n\n var handleEnter = function handleEnter() {\n setExited(false);\n };\n\n var handleExited = function handleExited() {\n setExited(true);\n\n if (closeAfterTransition) {\n handleClose();\n }\n };\n\n var handleBackdropClick = function handleBackdropClick(event) {\n if (event.target !== event.currentTarget) {\n return;\n }\n\n if (onBackdropClick) {\n onBackdropClick(event);\n }\n\n if (!disableBackdropClick && onClose) {\n onClose(event, 'backdropClick');\n }\n };\n\n var handleKeyDown = function handleKeyDown(event) {\n // The handler doesn't take event.defaultPrevented into account:\n //\n // event.preventDefault() is meant to stop default behaviours like\n // clicking a checkbox to check it, hitting a button to submit a form,\n // and hitting left arrow to move the cursor in a text input etc.\n // Only special HTML elements have these default behaviors.\n if (event.key !== 'Escape' || !isTopModal()) {\n return;\n }\n\n if (onEscapeKeyDown) {\n onEscapeKeyDown(event);\n }\n\n if (!disableEscapeKeyDown) {\n // Swallow the event, in case someone is listening for the escape key on the body.\n event.stopPropagation();\n\n if (onClose) {\n onClose(event, 'escapeKeyDown');\n }\n }\n };\n\n var inlineStyle = styles(theme || {\n zIndex: zIndex\n });\n var childProps = {};\n\n if (children.props.tabIndex === undefined) {\n childProps.tabIndex = children.props.tabIndex || '-1';\n } // It's a Transition like component\n\n\n if (hasTransition) {\n childProps.onEnter = createChainedFunction(handleEnter, children.props.onEnter);\n childProps.onExited = createChainedFunction(handleExited, children.props.onExited);\n }\n\n return /*#__PURE__*/React.createElement(Portal, {\n ref: handlePortalRef,\n container: container,\n disablePortal: disablePortal\n }, /*#__PURE__*/React.createElement(\"div\", _extends({\n ref: handleRef,\n onKeyDown: handleKeyDown,\n role: \"presentation\"\n }, other, {\n style: _extends({}, inlineStyle.root, !open && exited ? inlineStyle.hidden : {}, other.style)\n }), hideBackdrop ? null : /*#__PURE__*/React.createElement(BackdropComponent, _extends({\n open: open,\n onClick: handleBackdropClick\n }, BackdropProps)), /*#__PURE__*/React.createElement(TrapFocus, {\n disableEnforceFocus: disableEnforceFocus,\n disableAutoFocus: disableAutoFocus,\n disableRestoreFocus: disableRestoreFocus,\n getDoc: getDoc,\n isEnabled: isTopModal,\n open: open\n }, /*#__PURE__*/React.cloneElement(children, childProps))));\n});\nprocess.env.NODE_ENV !== \"production\" ? Modal.propTypes = {\n /**\n * A backdrop component. This prop enables custom backdrop rendering.\n */\n BackdropComponent: PropTypes.elementType,\n\n /**\n * Props applied to the [`Backdrop`](/api/backdrop/) element.\n */\n BackdropProps: PropTypes.object,\n\n /**\n * A single child content element.\n */\n children: elementAcceptingRef.isRequired,\n\n /**\n * When set to true the Modal waits until a nested Transition is completed before closing.\n */\n closeAfterTransition: PropTypes.bool,\n\n /**\n * A HTML element, component instance, or function that returns either.\n * The `container` will have the portal children appended to it.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([HTMLElementType, PropTypes.instanceOf(React.Component), PropTypes.func]),\n\n /**\n * If `true`, the modal will not automatically shift focus to itself when it opens, and\n * replace it to the last focused element when it closes.\n * This also works correctly with any modal children that have the `disableAutoFocus` prop.\n *\n * Generally this should never be set to `true` as it makes the modal less\n * accessible to assistive technologies, like screen readers.\n */\n disableAutoFocus: PropTypes.bool,\n\n /**\n * If `true`, clicking the backdrop will not fire `onClose`.\n */\n disableBackdropClick: PropTypes.bool,\n\n /**\n * If `true`, the modal will not prevent focus from leaving the modal while open.\n *\n * Generally this should never be set to `true` as it makes the modal less\n * accessible to assistive technologies, like screen readers.\n */\n disableEnforceFocus: PropTypes.bool,\n\n /**\n * If `true`, hitting escape will not fire `onClose`.\n */\n disableEscapeKeyDown: PropTypes.bool,\n\n /**\n * Disable the portal behavior.\n * The children stay within it's parent DOM hierarchy.\n */\n disablePortal: PropTypes.bool,\n\n /**\n * If `true`, the modal will not restore focus to previously focused element once\n * modal is hidden.\n */\n disableRestoreFocus: PropTypes.bool,\n\n /**\n * Disable the scroll lock behavior.\n */\n disableScrollLock: PropTypes.bool,\n\n /**\n * If `true`, the backdrop is not rendered.\n */\n hideBackdrop: PropTypes.bool,\n\n /**\n * Always keep the children in the DOM.\n * This prop can be useful in SEO situation or\n * when you want to maximize the responsiveness of the Modal.\n */\n keepMounted: PropTypes.bool,\n\n /**\n * @ignore\n */\n manager: PropTypes.object,\n\n /**\n * Callback fired when the backdrop is clicked.\n */\n onBackdropClick: PropTypes.func,\n\n /**\n * Callback fired when the component requests to be closed.\n * The `reason` parameter can optionally be used to control the response to `onClose`.\n *\n * @param {object} event The event source of the callback.\n * @param {string} reason Can be: `\"escapeKeyDown\"`, `\"backdropClick\"`.\n */\n onClose: PropTypes.func,\n\n /**\n * Callback fired when the escape key is pressed,\n * `disableEscapeKeyDown` is false and the modal is in focus.\n */\n onEscapeKeyDown: PropTypes.func,\n\n /**\n * Callback fired once the children has been mounted into the `container`.\n * It signals that the `open={true}` prop took effect.\n *\n * This prop will be deprecated and removed in v5, the ref can be used instead.\n */\n onRendered: PropTypes.func,\n\n /**\n * If `true`, the modal is open.\n */\n open: PropTypes.bool.isRequired\n} : void 0;\nexport default Modal;","export default {\n disabled: false\n};","import _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _inheritsLoose from \"@babel/runtime/helpers/esm/inheritsLoose\";\nimport PropTypes from 'prop-types';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport config from './config';\nimport { timeoutsShape } from './utils/PropTypes';\nimport TransitionGroupContext from './TransitionGroupContext';\nexport var UNMOUNTED = 'unmounted';\nexport var EXITED = 'exited';\nexport var ENTERING = 'entering';\nexport var ENTERED = 'entered';\nexport var EXITING = 'exiting';\n/**\n * The Transition component lets you describe a transition from one component\n * state to another _over time_ with a simple declarative API. Most commonly\n * it's used to animate the mounting and unmounting of a component, but can also\n * be used to describe in-place transition states as well.\n *\n * ---\n *\n * **Note**: `Transition` is a platform-agnostic base component. If you're using\n * transitions in CSS, you'll probably want to use\n * [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition)\n * instead. It inherits all the features of `Transition`, but contains\n * additional features necessary to play nice with CSS transitions (hence the\n * name of the component).\n *\n * ---\n *\n * By default the `Transition` component does not alter the behavior of the\n * component it renders, it only tracks \"enter\" and \"exit\" states for the\n * components. It's up to you to give meaning and effect to those states. For\n * example we can add styles to a component when it enters or exits:\n *\n * ```jsx\n * import { Transition } from 'react-transition-group';\n *\n * const duration = 300;\n *\n * const defaultStyle = {\n * transition: `opacity ${duration}ms ease-in-out`,\n * opacity: 0,\n * }\n *\n * const transitionStyles = {\n * entering: { opacity: 1 },\n * entered: { opacity: 1 },\n * exiting: { opacity: 0 },\n * exited: { opacity: 0 },\n * };\n *\n * const Fade = ({ in: inProp }) => (\n * <Transition in={inProp} timeout={duration}>\n * {state => (\n * <div style={{\n * ...defaultStyle,\n * ...transitionStyles[state]\n * }}>\n * I'm a fade Transition!\n * </div>\n * )}\n * </Transition>\n * );\n * ```\n *\n * There are 4 main states a Transition can be in:\n * - `'entering'`\n * - `'entered'`\n * - `'exiting'`\n * - `'exited'`\n *\n * Transition state is toggled via the `in` prop. When `true` the component\n * begins the \"Enter\" stage. During this stage, the component will shift from\n * its current transition state, to `'entering'` for the duration of the\n * transition and then to the `'entered'` stage once it's complete. Let's take\n * the following example (we'll use the\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook):\n *\n * ```jsx\n * function App() {\n * const [inProp, setInProp] = useState(false);\n * return (\n * <div>\n * <Transition in={inProp} timeout={500}>\n * {state => (\n * // ...\n * )}\n * </Transition>\n * <button onClick={() => setInProp(true)}>\n * Click to Enter\n * </button>\n * </div>\n * );\n * }\n * ```\n *\n * When the button is clicked the component will shift to the `'entering'` state\n * and stay there for 500ms (the value of `timeout`) before it finally switches\n * to `'entered'`.\n *\n * When `in` is `false` the same thing happens except the state moves from\n * `'exiting'` to `'exited'`.\n */\n\nvar Transition = /*#__PURE__*/function (_React$Component) {\n _inheritsLoose(Transition, _React$Component);\n\n function Transition(props, context) {\n var _this;\n\n _this = _React$Component.call(this, props, context) || this;\n var parentGroup = context; // In the context of a TransitionGroup all enters are really appears\n\n var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear;\n var initialStatus;\n _this.appearStatus = null;\n\n if (props.in) {\n if (appear) {\n initialStatus = EXITED;\n _this.appearStatus = ENTERING;\n } else {\n initialStatus = ENTERED;\n }\n } else {\n if (props.unmountOnExit || props.mountOnEnter) {\n initialStatus = UNMOUNTED;\n } else {\n initialStatus = EXITED;\n }\n }\n\n _this.state = {\n status: initialStatus\n };\n _this.nextCallback = null;\n return _this;\n }\n\n Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) {\n var nextIn = _ref.in;\n\n if (nextIn && prevState.status === UNMOUNTED) {\n return {\n status: EXITED\n };\n }\n\n return null;\n } // getSnapshotBeforeUpdate(prevProps) {\n // let nextStatus = null\n // if (prevProps !== this.props) {\n // const { status } = this.state\n // if (this.props.in) {\n // if (status !== ENTERING && status !== ENTERED) {\n // nextStatus = ENTERING\n // }\n // } else {\n // if (status === ENTERING || status === ENTERED) {\n // nextStatus = EXITING\n // }\n // }\n // }\n // return { nextStatus }\n // }\n ;\n\n var _proto = Transition.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this.updateStatus(true, this.appearStatus);\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps) {\n var nextStatus = null;\n\n if (prevProps !== this.props) {\n var status = this.state.status;\n\n if (this.props.in) {\n if (status !== ENTERING && status !== ENTERED) {\n nextStatus = ENTERING;\n }\n } else {\n if (status === ENTERING || status === ENTERED) {\n nextStatus = EXITING;\n }\n }\n }\n\n this.updateStatus(false, nextStatus);\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n this.cancelNextCallback();\n };\n\n _proto.getTimeouts = function getTimeouts() {\n var timeout = this.props.timeout;\n var exit, enter, appear;\n exit = enter = appear = timeout;\n\n if (timeout != null && typeof timeout !== 'number') {\n exit = timeout.exit;\n enter = timeout.enter; // TODO: remove fallback for next major\n\n appear = timeout.appear !== undefined ? timeout.appear : enter;\n }\n\n return {\n exit: exit,\n enter: enter,\n appear: appear\n };\n };\n\n _proto.updateStatus = function updateStatus(mounting, nextStatus) {\n if (mounting === void 0) {\n mounting = false;\n }\n\n if (nextStatus !== null) {\n // nextStatus will always be ENTERING or EXITING.\n this.cancelNextCallback();\n\n if (nextStatus === ENTERING) {\n this.performEnter(mounting);\n } else {\n this.performExit();\n }\n } else if (this.props.unmountOnExit && this.state.status === EXITED) {\n this.setState({\n status: UNMOUNTED\n });\n }\n };\n\n _proto.performEnter = function performEnter(mounting) {\n var _this2 = this;\n\n var enter = this.props.enter;\n var appearing = this.context ? this.context.isMounting : mounting;\n\n var _ref2 = this.props.nodeRef ? [appearing] : [ReactDOM.findDOMNode(this), appearing],\n maybeNode = _ref2[0],\n maybeAppearing = _ref2[1];\n\n var timeouts = this.getTimeouts();\n var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED\n // if we are mounting and running this it means appear _must_ be set\n\n if (!mounting && !enter || config.disabled) {\n this.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode);\n });\n return;\n }\n\n this.props.onEnter(maybeNode, maybeAppearing);\n this.safeSetState({\n status: ENTERING\n }, function () {\n _this2.props.onEntering(maybeNode, maybeAppearing);\n\n _this2.onTransitionEnd(enterTimeout, function () {\n _this2.safeSetState({\n status: ENTERED\n }, function () {\n _this2.props.onEntered(maybeNode, maybeAppearing);\n });\n });\n });\n };\n\n _proto.performExit = function performExit() {\n var _this3 = this;\n\n var exit = this.props.exit;\n var timeouts = this.getTimeouts();\n var maybeNode = this.props.nodeRef ? undefined : ReactDOM.findDOMNode(this); // no exit animation skip right to EXITED\n\n if (!exit || config.disabled) {\n this.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n return;\n }\n\n this.props.onExit(maybeNode);\n this.safeSetState({\n status: EXITING\n }, function () {\n _this3.props.onExiting(maybeNode);\n\n _this3.onTransitionEnd(timeouts.exit, function () {\n _this3.safeSetState({\n status: EXITED\n }, function () {\n _this3.props.onExited(maybeNode);\n });\n });\n });\n };\n\n _proto.cancelNextCallback = function cancelNextCallback() {\n if (this.nextCallback !== null) {\n this.nextCallback.cancel();\n this.nextCallback = null;\n }\n };\n\n _proto.safeSetState = function safeSetState(nextState, callback) {\n // This shouldn't be necessary, but there are weird race conditions with\n // setState callbacks and unmounting in testing, so always make sure that\n // we can cancel any pending setState callbacks after we unmount.\n callback = this.setNextCallback(callback);\n this.setState(nextState, callback);\n };\n\n _proto.setNextCallback = function setNextCallback(callback) {\n var _this4 = this;\n\n var active = true;\n\n this.nextCallback = function (event) {\n if (active) {\n active = false;\n _this4.nextCallback = null;\n callback(event);\n }\n };\n\n this.nextCallback.cancel = function () {\n active = false;\n };\n\n return this.nextCallback;\n };\n\n _proto.onTransitionEnd = function onTransitionEnd(timeout, handler) {\n this.setNextCallback(handler);\n var node = this.props.nodeRef ? this.props.nodeRef.current : ReactDOM.findDOMNode(this);\n var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener;\n\n if (!node || doesNotHaveTimeoutOrListener) {\n setTimeout(this.nextCallback, 0);\n return;\n }\n\n if (this.props.addEndListener) {\n var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback],\n maybeNode = _ref3[0],\n maybeNextCallback = _ref3[1];\n\n this.props.addEndListener(maybeNode, maybeNextCallback);\n }\n\n if (timeout != null) {\n setTimeout(this.nextCallback, timeout);\n }\n };\n\n _proto.render = function render() {\n var status = this.state.status;\n\n if (status === UNMOUNTED) {\n return null;\n }\n\n var _this$props = this.props,\n children = _this$props.children,\n _in = _this$props.in,\n _mountOnEnter = _this$props.mountOnEnter,\n _unmountOnExit = _this$props.unmountOnExit,\n _appear = _this$props.appear,\n _enter = _this$props.enter,\n _exit = _this$props.exit,\n _timeout = _this$props.timeout,\n _addEndListener = _this$props.addEndListener,\n _onEnter = _this$props.onEnter,\n _onEntering = _this$props.onEntering,\n _onEntered = _this$props.onEntered,\n _onExit = _this$props.onExit,\n _onExiting = _this$props.onExiting,\n _onExited = _this$props.onExited,\n _nodeRef = _this$props.nodeRef,\n childProps = _objectWithoutPropertiesLoose(_this$props, [\"children\", \"in\", \"mountOnEnter\", \"unmountOnExit\", \"appear\", \"enter\", \"exit\", \"timeout\", \"addEndListener\", \"onEnter\", \"onEntering\", \"onEntered\", \"onExit\", \"onExiting\", \"onExited\", \"nodeRef\"]);\n\n return (\n /*#__PURE__*/\n // allows for nested Transitions\n React.createElement(TransitionGroupContext.Provider, {\n value: null\n }, typeof children === 'function' ? children(status, childProps) : React.cloneElement(React.Children.only(children), childProps))\n );\n };\n\n return Transition;\n}(React.Component);\n\nTransition.contextType = TransitionGroupContext;\nTransition.propTypes = process.env.NODE_ENV !== \"production\" ? {\n /**\n * A React reference to DOM element that need to transition:\n * https://stackoverflow.com/a/51127130/4671932\n *\n * - When `nodeRef` prop is used, `node` is not passed to callback functions\n * (e.g. `onEnter`) because user already has direct access to the node.\n * - When changing `key` prop of `Transition` in a `TransitionGroup` a new\n * `nodeRef` need to be provided to `Transition` with changed `key` prop\n * (see\n * [test/CSSTransition-test.js](https://github.com/reactjs/react-transition-group/blob/13435f897b3ab71f6e19d724f145596f5910581c/test/CSSTransition-test.js#L362-L437)).\n */\n nodeRef: PropTypes.shape({\n current: typeof Element === 'undefined' ? PropTypes.any : PropTypes.instanceOf(Element)\n }),\n\n /**\n * A `function` child can be used instead of a React element. This function is\n * called with the current transition status (`'entering'`, `'entered'`,\n * `'exiting'`, `'exited'`), which can be used to apply context\n * specific props to a component.\n *\n * ```jsx\n * <Transition in={this.state.in} timeout={150}>\n * {state => (\n * <MyComponent className={`fade fade-${state}`} />\n * )}\n * </Transition>\n * ```\n */\n children: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.element.isRequired]).isRequired,\n\n /**\n * Show the component; triggers the enter or exit states\n */\n in: PropTypes.bool,\n\n /**\n * By default the child component is mounted immediately along with\n * the parent `Transition` component. If you want to \"lazy mount\" the component on the\n * first `in={true}` you can set `mountOnEnter`. After the first enter transition the component will stay\n * mounted, even on \"exited\", unless you also specify `unmountOnExit`.\n */\n mountOnEnter: PropTypes.bool,\n\n /**\n * By default the child component stays mounted after it reaches the `'exited'` state.\n * Set `unmountOnExit` if you'd prefer to unmount the component after it finishes exiting.\n */\n unmountOnExit: PropTypes.bool,\n\n /**\n * By default the child component does not perform the enter transition when\n * it first mounts, regardless of the value of `in`. If you want this\n * behavior, set both `appear` and `in` to `true`.\n *\n * > **Note**: there are no special appear states like `appearing`/`appeared`, this prop\n * > only adds an additional enter transition. However, in the\n * > `<CSSTransition>` component that first enter transition does result in\n * > additional `.appear-*` classes, that way you can choose to style it\n * > differently.\n */\n appear: PropTypes.bool,\n\n /**\n * Enable or disable enter transitions.\n */\n enter: PropTypes.bool,\n\n /**\n * Enable or disable exit transitions.\n */\n exit: PropTypes.bool,\n\n /**\n * The duration of the transition, in milliseconds.\n * Required unless `addEndListener` is provided.\n *\n * You may specify a single timeout for all transitions:\n *\n * ```jsx\n * timeout={500}\n * ```\n *\n * or individually:\n *\n * ```jsx\n * timeout={{\n * appear: 500,\n * enter: 300,\n * exit: 500,\n * }}\n * ```\n *\n * - `appear` defaults to the value of `enter`\n * - `enter` defaults to `0`\n * - `exit` defaults to `0`\n *\n * @type {number | { enter?: number, exit?: number, appear?: number }}\n */\n timeout: function timeout(props) {\n var pt = timeoutsShape;\n if (!props.addEndListener) pt = pt.isRequired;\n\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return pt.apply(void 0, [props].concat(args));\n },\n\n /**\n * Add a custom transition end trigger. Called with the transitioning\n * DOM node and a `done` callback. Allows for more fine grained transition end\n * logic. Timeouts are still used as a fallback if provided.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * ```jsx\n * addEndListener={(node, done) => {\n * // use the css transitionend event to mark the finish of a transition\n * node.addEventListener('transitionend', done, false);\n * }}\n * ```\n */\n addEndListener: PropTypes.func,\n\n /**\n * Callback fired before the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEnter: PropTypes.func,\n\n /**\n * Callback fired after the \"entering\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool)\n */\n onEntering: PropTypes.func,\n\n /**\n * Callback fired after the \"entered\" status is applied. An extra parameter\n * `isAppearing` is supplied to indicate if the enter stage is occurring on the initial mount\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement, isAppearing: bool) -> void\n */\n onEntered: PropTypes.func,\n\n /**\n * Callback fired before the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExit: PropTypes.func,\n\n /**\n * Callback fired after the \"exiting\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed.\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExiting: PropTypes.func,\n\n /**\n * Callback fired after the \"exited\" status is applied.\n *\n * **Note**: when `nodeRef` prop is passed, `node` is not passed\n *\n * @type Function(node: HtmlElement) -> void\n */\n onExited: PropTypes.func\n} : {}; // Name the function so it is clearer in the documentation\n\nfunction noop() {}\n\nTransition.defaultProps = {\n in: false,\n mountOnEnter: false,\n unmountOnExit: false,\n appear: false,\n enter: true,\n exit: true,\n onEnter: noop,\n onEntering: noop,\n onEntered: noop,\n onExit: noop,\n onExiting: noop,\n onExited: noop\n};\nTransition.UNMOUNTED = UNMOUNTED;\nTransition.EXITED = EXITED;\nTransition.ENTERING = ENTERING;\nTransition.ENTERED = ENTERED;\nTransition.EXITING = EXITING;\nexport default Transition;","export var reflow = function reflow(node) {\n return node.scrollTop;\n};\nexport function getTransitionProps(props, options) {\n var timeout = props.timeout,\n _props$style = props.style,\n style = _props$style === void 0 ? {} : _props$style;\n return {\n duration: style.transitionDuration || typeof timeout === 'number' ? timeout : timeout[options.mode] || 0,\n delay: style.transitionDelay\n };\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { Transition } from 'react-transition-group';\nimport useTheme from '../styles/useTheme';\nimport { reflow, getTransitionProps } from '../transitions/utils';\nimport useForkRef from '../utils/useForkRef';\n\nfunction getScale(value) {\n return \"scale(\".concat(value, \", \").concat(Math.pow(value, 2), \")\");\n}\n\nvar styles = {\n entering: {\n opacity: 1,\n transform: getScale(1)\n },\n entered: {\n opacity: 1,\n transform: 'none'\n }\n};\n/**\n * The Grow transition is used by the [Tooltip](/components/tooltips/) and\n * [Popover](/components/popover/) components.\n * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.\n */\n\nvar Grow = /*#__PURE__*/React.forwardRef(function Grow(props, ref) {\n var children = props.children,\n _props$disableStrictM = props.disableStrictModeCompat,\n disableStrictModeCompat = _props$disableStrictM === void 0 ? false : _props$disableStrictM,\n inProp = props.in,\n onEnter = props.onEnter,\n onEntered = props.onEntered,\n onEntering = props.onEntering,\n onExit = props.onExit,\n onExited = props.onExited,\n onExiting = props.onExiting,\n style = props.style,\n _props$timeout = props.timeout,\n timeout = _props$timeout === void 0 ? 'auto' : _props$timeout,\n _props$TransitionComp = props.TransitionComponent,\n TransitionComponent = _props$TransitionComp === void 0 ? Transition : _props$TransitionComp,\n other = _objectWithoutProperties(props, [\"children\", \"disableStrictModeCompat\", \"in\", \"onEnter\", \"onEntered\", \"onEntering\", \"onExit\", \"onExited\", \"onExiting\", \"style\", \"timeout\", \"TransitionComponent\"]);\n\n var timer = React.useRef();\n var autoTimeout = React.useRef();\n var theme = useTheme();\n var enableStrictModeCompat = theme.unstable_strictMode && !disableStrictModeCompat;\n var nodeRef = React.useRef(null);\n var foreignRef = useForkRef(children.ref, ref);\n var handleRef = useForkRef(enableStrictModeCompat ? nodeRef : undefined, foreignRef);\n\n var normalizedTransitionCallback = function normalizedTransitionCallback(callback) {\n return function (nodeOrAppearing, maybeAppearing) {\n if (callback) {\n var _ref = enableStrictModeCompat ? [nodeRef.current, nodeOrAppearing] : [nodeOrAppearing, maybeAppearing],\n _ref2 = _slicedToArray(_ref, 2),\n node = _ref2[0],\n isAppearing = _ref2[1]; // onEnterXxx and onExitXxx callbacks have a different arguments.length value.\n\n\n if (isAppearing === undefined) {\n callback(node);\n } else {\n callback(node, isAppearing);\n }\n }\n };\n };\n\n var handleEntering = normalizedTransitionCallback(onEntering);\n var handleEnter = normalizedTransitionCallback(function (node, isAppearing) {\n reflow(node); // So the animation always start from the start.\n\n var _getTransitionProps = getTransitionProps({\n style: style,\n timeout: timeout\n }, {\n mode: 'enter'\n }),\n transitionDuration = _getTransitionProps.duration,\n delay = _getTransitionProps.delay;\n\n var duration;\n\n if (timeout === 'auto') {\n duration = theme.transitions.getAutoHeightDuration(node.clientHeight);\n autoTimeout.current = duration;\n } else {\n duration = transitionDuration;\n }\n\n node.style.transition = [theme.transitions.create('opacity', {\n duration: duration,\n delay: delay\n }), theme.transitions.create('transform', {\n duration: duration * 0.666,\n delay: delay\n })].join(',');\n\n if (onEnter) {\n onEnter(node, isAppearing);\n }\n });\n var handleEntered = normalizedTransitionCallback(onEntered);\n var handleExiting = normalizedTransitionCallback(onExiting);\n var handleExit = normalizedTransitionCallback(function (node) {\n var _getTransitionProps2 = getTransitionProps({\n style: style,\n timeout: timeout\n }, {\n mode: 'exit'\n }),\n transitionDuration = _getTransitionProps2.duration,\n delay = _getTransitionProps2.delay;\n\n var duration;\n\n if (timeout === 'auto') {\n duration = theme.transitions.getAutoHeightDuration(node.clientHeight);\n autoTimeout.current = duration;\n } else {\n duration = transitionDuration;\n }\n\n node.style.transition = [theme.transitions.create('opacity', {\n duration: duration,\n delay: delay\n }), theme.transitions.create('transform', {\n duration: duration * 0.666,\n delay: delay || duration * 0.333\n })].join(',');\n node.style.opacity = '0';\n node.style.transform = getScale(0.75);\n\n if (onExit) {\n onExit(node);\n }\n });\n var handleExited = normalizedTransitionCallback(onExited);\n\n var addEndListener = function addEndListener(nodeOrNext, maybeNext) {\n var next = enableStrictModeCompat ? nodeOrNext : maybeNext;\n\n if (timeout === 'auto') {\n timer.current = setTimeout(next, autoTimeout.current || 0);\n }\n };\n\n React.useEffect(function () {\n return function () {\n clearTimeout(timer.current);\n };\n }, []);\n return /*#__PURE__*/React.createElement(TransitionComponent, _extends({\n appear: true,\n in: inProp,\n nodeRef: enableStrictModeCompat ? nodeRef : undefined,\n onEnter: handleEnter,\n onEntered: handleEntered,\n onEntering: handleEntering,\n onExit: handleExit,\n onExited: handleExited,\n onExiting: handleExiting,\n addEndListener: addEndListener,\n timeout: timeout === 'auto' ? null : timeout\n }, other), function (state, childProps) {\n return /*#__PURE__*/React.cloneElement(children, _extends({\n style: _extends({\n opacity: 0,\n transform: getScale(0.75),\n visibility: state === 'exited' && !inProp ? 'hidden' : undefined\n }, styles[state], style, children.props.style),\n ref: handleRef\n }, childProps));\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Grow.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A single child content element.\n */\n children: PropTypes.element,\n\n /**\n * Enable this prop if you encounter 'Function components cannot be given refs',\n * use `unstable_createStrictModeTheme`,\n * and can't forward the ref in the child component.\n */\n disableStrictModeCompat: PropTypes.bool,\n\n /**\n * If `true`, show the component; triggers the enter or exit animation.\n */\n in: PropTypes.bool,\n\n /**\n * @ignore\n */\n onEnter: PropTypes.func,\n\n /**\n * @ignore\n */\n onEntered: PropTypes.func,\n\n /**\n * @ignore\n */\n onEntering: PropTypes.func,\n\n /**\n * @ignore\n */\n onExit: PropTypes.func,\n\n /**\n * @ignore\n */\n onExited: PropTypes.func,\n\n /**\n * @ignore\n */\n onExiting: PropTypes.func,\n\n /**\n * @ignore\n */\n style: PropTypes.object,\n\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n *\n * Set to 'auto' to automatically calculate transition time based on height.\n */\n timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })])\n} : void 0;\nGrow.muiSupportAuto = true;\nexport default Grow;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport * as ReactDOM from 'react-dom';\nimport { chainPropTypes, elementTypeAcceptingRef, refType, HTMLElementType } from '@material-ui/utils';\nimport debounce from '../utils/debounce';\nimport clsx from 'clsx';\nimport ownerDocument from '../utils/ownerDocument';\nimport ownerWindow from '../utils/ownerWindow';\nimport createChainedFunction from '../utils/createChainedFunction';\nimport withStyles from '../styles/withStyles';\nimport Modal from '../Modal';\nimport Grow from '../Grow';\nimport Paper from '../Paper';\nexport function getOffsetTop(rect, vertical) {\n var offset = 0;\n\n if (typeof vertical === 'number') {\n offset = vertical;\n } else if (vertical === 'center') {\n offset = rect.height / 2;\n } else if (vertical === 'bottom') {\n offset = rect.height;\n }\n\n return offset;\n}\nexport function getOffsetLeft(rect, horizontal) {\n var offset = 0;\n\n if (typeof horizontal === 'number') {\n offset = horizontal;\n } else if (horizontal === 'center') {\n offset = rect.width / 2;\n } else if (horizontal === 'right') {\n offset = rect.width;\n }\n\n return offset;\n}\n\nfunction getTransformOriginValue(transformOrigin) {\n return [transformOrigin.horizontal, transformOrigin.vertical].map(function (n) {\n return typeof n === 'number' ? \"\".concat(n, \"px\") : n;\n }).join(' ');\n} // Sum the scrollTop between two elements.\n\n\nfunction getScrollParent(parent, child) {\n var element = child;\n var scrollTop = 0;\n\n while (element && element !== parent) {\n element = element.parentElement;\n scrollTop += element.scrollTop;\n }\n\n return scrollTop;\n}\n\nfunction getAnchorEl(anchorEl) {\n return typeof anchorEl === 'function' ? anchorEl() : anchorEl;\n}\n\nexport var styles = {\n /* Styles applied to the root element. */\n root: {},\n\n /* Styles applied to the `Paper` component. */\n paper: {\n position: 'absolute',\n overflowY: 'auto',\n overflowX: 'hidden',\n // So we see the popover when it's empty.\n // It's most likely on issue on userland.\n minWidth: 16,\n minHeight: 16,\n maxWidth: 'calc(100% - 32px)',\n maxHeight: 'calc(100% - 32px)',\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0\n }\n};\nvar Popover = /*#__PURE__*/React.forwardRef(function Popover(props, ref) {\n var action = props.action,\n anchorEl = props.anchorEl,\n _props$anchorOrigin = props.anchorOrigin,\n anchorOrigin = _props$anchorOrigin === void 0 ? {\n vertical: 'top',\n horizontal: 'left'\n } : _props$anchorOrigin,\n anchorPosition = props.anchorPosition,\n _props$anchorReferenc = props.anchorReference,\n anchorReference = _props$anchorReferenc === void 0 ? 'anchorEl' : _props$anchorReferenc,\n children = props.children,\n classes = props.classes,\n className = props.className,\n containerProp = props.container,\n _props$elevation = props.elevation,\n elevation = _props$elevation === void 0 ? 8 : _props$elevation,\n getContentAnchorEl = props.getContentAnchorEl,\n _props$marginThreshol = props.marginThreshold,\n marginThreshold = _props$marginThreshol === void 0 ? 16 : _props$marginThreshol,\n onEnter = props.onEnter,\n onEntered = props.onEntered,\n onEntering = props.onEntering,\n onExit = props.onExit,\n onExited = props.onExited,\n onExiting = props.onExiting,\n open = props.open,\n _props$PaperProps = props.PaperProps,\n PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps,\n _props$transformOrigi = props.transformOrigin,\n transformOrigin = _props$transformOrigi === void 0 ? {\n vertical: 'top',\n horizontal: 'left'\n } : _props$transformOrigi,\n _props$TransitionComp = props.TransitionComponent,\n TransitionComponent = _props$TransitionComp === void 0 ? Grow : _props$TransitionComp,\n _props$transitionDura = props.transitionDuration,\n transitionDurationProp = _props$transitionDura === void 0 ? 'auto' : _props$transitionDura,\n _props$TransitionProp = props.TransitionProps,\n TransitionProps = _props$TransitionProp === void 0 ? {} : _props$TransitionProp,\n other = _objectWithoutProperties(props, [\"action\", \"anchorEl\", \"anchorOrigin\", \"anchorPosition\", \"anchorReference\", \"children\", \"classes\", \"className\", \"container\", \"elevation\", \"getContentAnchorEl\", \"marginThreshold\", \"onEnter\", \"onEntered\", \"onEntering\", \"onExit\", \"onExited\", \"onExiting\", \"open\", \"PaperProps\", \"transformOrigin\", \"TransitionComponent\", \"transitionDuration\", \"TransitionProps\"]);\n\n var paperRef = React.useRef(); // Returns the top/left offset of the position\n // to attach to on the anchor element (or body if none is provided)\n\n var getAnchorOffset = React.useCallback(function (contentAnchorOffset) {\n if (anchorReference === 'anchorPosition') {\n if (process.env.NODE_ENV !== 'production') {\n if (!anchorPosition) {\n console.error('Material-UI: You need to provide a `anchorPosition` prop when using ' + '<Popover anchorReference=\"anchorPosition\" />.');\n }\n }\n\n return anchorPosition;\n }\n\n var resolvedAnchorEl = getAnchorEl(anchorEl); // If an anchor element wasn't provided, just use the parent body element of this Popover\n\n var anchorElement = resolvedAnchorEl && resolvedAnchorEl.nodeType === 1 ? resolvedAnchorEl : ownerDocument(paperRef.current).body;\n var anchorRect = anchorElement.getBoundingClientRect();\n\n if (process.env.NODE_ENV !== 'production') {\n var box = anchorElement.getBoundingClientRect();\n\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n console.warn(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n }\n\n var anchorVertical = contentAnchorOffset === 0 ? anchorOrigin.vertical : 'center';\n return {\n top: anchorRect.top + getOffsetTop(anchorRect, anchorVertical),\n left: anchorRect.left + getOffsetLeft(anchorRect, anchorOrigin.horizontal)\n };\n }, [anchorEl, anchorOrigin.horizontal, anchorOrigin.vertical, anchorPosition, anchorReference]); // Returns the vertical offset of inner content to anchor the transform on if provided\n\n var getContentAnchorOffset = React.useCallback(function (element) {\n var contentAnchorOffset = 0;\n\n if (getContentAnchorEl && anchorReference === 'anchorEl') {\n var contentAnchorEl = getContentAnchorEl(element);\n\n if (contentAnchorEl && element.contains(contentAnchorEl)) {\n var scrollTop = getScrollParent(element, contentAnchorEl);\n contentAnchorOffset = contentAnchorEl.offsetTop + contentAnchorEl.clientHeight / 2 - scrollTop || 0;\n } // != the default value\n\n\n if (process.env.NODE_ENV !== 'production') {\n if (anchorOrigin.vertical !== 'top') {\n console.error(['Material-UI: You can not change the default `anchorOrigin.vertical` value ', 'when also providing the `getContentAnchorEl` prop to the popover component.', 'Only use one of the two props.', 'Set `getContentAnchorEl` to `null | undefined`' + ' or leave `anchorOrigin.vertical` unchanged.'].join('\\n'));\n }\n }\n }\n\n return contentAnchorOffset;\n }, [anchorOrigin.vertical, anchorReference, getContentAnchorEl]); // Return the base transform origin using the element\n // and taking the content anchor offset into account if in use\n\n var getTransformOrigin = React.useCallback(function (elemRect) {\n var contentAnchorOffset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return {\n vertical: getOffsetTop(elemRect, transformOrigin.vertical) + contentAnchorOffset,\n horizontal: getOffsetLeft(elemRect, transformOrigin.horizontal)\n };\n }, [transformOrigin.horizontal, transformOrigin.vertical]);\n var getPositioningStyle = React.useCallback(function (element) {\n // Check if the parent has requested anchoring on an inner content node\n var contentAnchorOffset = getContentAnchorOffset(element);\n var elemRect = {\n width: element.offsetWidth,\n height: element.offsetHeight\n }; // Get the transform origin point on the element itself\n\n var elemTransformOrigin = getTransformOrigin(elemRect, contentAnchorOffset);\n\n if (anchorReference === 'none') {\n return {\n top: null,\n left: null,\n transformOrigin: getTransformOriginValue(elemTransformOrigin)\n };\n } // Get the offset of of the anchoring element\n\n\n var anchorOffset = getAnchorOffset(contentAnchorOffset); // Calculate element positioning\n\n var top = anchorOffset.top - elemTransformOrigin.vertical;\n var left = anchorOffset.left - elemTransformOrigin.horizontal;\n var bottom = top + elemRect.height;\n var right = left + elemRect.width; // Use the parent window of the anchorEl if provided\n\n var containerWindow = ownerWindow(getAnchorEl(anchorEl)); // Window thresholds taking required margin into account\n\n var heightThreshold = containerWindow.innerHeight - marginThreshold;\n var widthThreshold = containerWindow.innerWidth - marginThreshold; // Check if the vertical axis needs shifting\n\n if (top < marginThreshold) {\n var diff = top - marginThreshold;\n top -= diff;\n elemTransformOrigin.vertical += diff;\n } else if (bottom > heightThreshold) {\n var _diff = bottom - heightThreshold;\n\n top -= _diff;\n elemTransformOrigin.vertical += _diff;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (elemRect.height > heightThreshold && elemRect.height && heightThreshold) {\n console.error(['Material-UI: The popover component is too tall.', \"Some part of it can not be seen on the screen (\".concat(elemRect.height - heightThreshold, \"px).\"), 'Please consider adding a `max-height` to improve the user-experience.'].join('\\n'));\n }\n } // Check if the horizontal axis needs shifting\n\n\n if (left < marginThreshold) {\n var _diff2 = left - marginThreshold;\n\n left -= _diff2;\n elemTransformOrigin.horizontal += _diff2;\n } else if (right > widthThreshold) {\n var _diff3 = right - widthThreshold;\n\n left -= _diff3;\n elemTransformOrigin.horizontal += _diff3;\n }\n\n return {\n top: \"\".concat(Math.round(top), \"px\"),\n left: \"\".concat(Math.round(left), \"px\"),\n transformOrigin: getTransformOriginValue(elemTransformOrigin)\n };\n }, [anchorEl, anchorReference, getAnchorOffset, getContentAnchorOffset, getTransformOrigin, marginThreshold]);\n var setPositioningStyles = React.useCallback(function () {\n var element = paperRef.current;\n\n if (!element) {\n return;\n }\n\n var positioning = getPositioningStyle(element);\n\n if (positioning.top !== null) {\n element.style.top = positioning.top;\n }\n\n if (positioning.left !== null) {\n element.style.left = positioning.left;\n }\n\n element.style.transformOrigin = positioning.transformOrigin;\n }, [getPositioningStyle]);\n\n var handleEntering = function handleEntering(element, isAppearing) {\n if (onEntering) {\n onEntering(element, isAppearing);\n }\n\n setPositioningStyles();\n };\n\n var handlePaperRef = React.useCallback(function (instance) {\n // #StrictMode ready\n paperRef.current = ReactDOM.findDOMNode(instance);\n }, []);\n React.useEffect(function () {\n if (open) {\n setPositioningStyles();\n }\n });\n React.useImperativeHandle(action, function () {\n return open ? {\n updatePosition: function updatePosition() {\n setPositioningStyles();\n }\n } : null;\n }, [open, setPositioningStyles]);\n React.useEffect(function () {\n if (!open) {\n return undefined;\n }\n\n var handleResize = debounce(function () {\n setPositioningStyles();\n });\n window.addEventListener('resize', handleResize);\n return function () {\n handleResize.clear();\n window.removeEventListener('resize', handleResize);\n };\n }, [open, setPositioningStyles]);\n var transitionDuration = transitionDurationProp;\n\n if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {\n transitionDuration = undefined;\n } // If the container prop is provided, use that\n // If the anchorEl prop is provided, use its parent body element as the container\n // If neither are provided let the Modal take care of choosing the container\n\n\n var container = containerProp || (anchorEl ? ownerDocument(getAnchorEl(anchorEl)).body : undefined);\n return /*#__PURE__*/React.createElement(Modal, _extends({\n container: container,\n open: open,\n ref: ref,\n BackdropProps: {\n invisible: true\n },\n className: clsx(classes.root, className)\n }, other), /*#__PURE__*/React.createElement(TransitionComponent, _extends({\n appear: true,\n in: open,\n onEnter: onEnter,\n onEntered: onEntered,\n onExit: onExit,\n onExited: onExited,\n onExiting: onExiting,\n timeout: transitionDuration\n }, TransitionProps, {\n onEntering: createChainedFunction(handleEntering, TransitionProps.onEntering)\n }), /*#__PURE__*/React.createElement(Paper, _extends({\n elevation: elevation,\n ref: handlePaperRef\n }, PaperProps, {\n className: clsx(classes.paper, PaperProps.className)\n }), children)));\n});\nprocess.env.NODE_ENV !== \"production\" ? Popover.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A ref for imperative actions.\n * It currently only supports updatePosition() action.\n */\n action: refType,\n\n /**\n * A HTML element, or a function that returns it.\n * It's used to set the position of the popover.\n */\n anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.func]), function (props) {\n if (props.open && (!props.anchorReference || props.anchorReference === 'anchorEl')) {\n var resolvedAnchorEl = getAnchorEl(props.anchorEl);\n\n if (resolvedAnchorEl && resolvedAnchorEl.nodeType === 1) {\n var box = resolvedAnchorEl.getBoundingClientRect();\n\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n return new Error(['Material-UI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n } else {\n return new Error(['Material-UI: The `anchorEl` prop provided to the component is invalid.', \"It should be an Element instance but it's `\".concat(resolvedAnchorEl, \"` instead.\")].join('\\n'));\n }\n }\n\n return null;\n }),\n\n /**\n * This is the point on the anchor where the popover's\n * `anchorEl` will attach to. This is not used when the\n * anchorReference is 'anchorPosition'.\n *\n * Options:\n * vertical: [top, center, bottom];\n * horizontal: [left, center, right].\n */\n anchorOrigin: PropTypes.shape({\n horizontal: PropTypes.oneOfType([PropTypes.oneOf(['center', 'left', 'right']), PropTypes.number]).isRequired,\n vertical: PropTypes.oneOfType([PropTypes.oneOf(['bottom', 'center', 'top']), PropTypes.number]).isRequired\n }),\n\n /**\n * This is the position that may be used\n * to set the position of the popover.\n * The coordinates are relative to\n * the application's client area.\n */\n anchorPosition: PropTypes.shape({\n left: PropTypes.number.isRequired,\n top: PropTypes.number.isRequired\n }),\n\n /**\n * This determines which anchor prop to refer to to set\n * the position of the popover.\n */\n anchorReference: PropTypes.oneOf(['anchorEl', 'anchorPosition', 'none']),\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * A HTML element, component instance, or function that returns either.\n * The `container` will passed to the Modal component.\n *\n * By default, it uses the body of the anchorEl's top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([HTMLElementType, PropTypes.instanceOf(React.Component), PropTypes.func]),\n\n /**\n * The elevation of the popover.\n */\n elevation: PropTypes.number,\n\n /**\n * This function is called in order to retrieve the content anchor element.\n * It's the opposite of the `anchorEl` prop.\n * The content anchor element should be an element inside the popover.\n * It's used to correctly scroll and set the position of the popover.\n * The positioning strategy tries to make the content anchor element just above the\n * anchor element.\n */\n getContentAnchorEl: PropTypes.func,\n\n /**\n * Specifies how close to the edge of the window the popover can appear.\n */\n marginThreshold: PropTypes.number,\n\n /**\n * Callback fired when the component requests to be closed.\n */\n onClose: PropTypes.func,\n\n /**\n * Callback fired before the component is entering.\n */\n onEnter: PropTypes.func,\n\n /**\n * Callback fired when the component has entered.\n */\n onEntered: PropTypes.func,\n\n /**\n * Callback fired when the component is entering.\n */\n onEntering: PropTypes.func,\n\n /**\n * Callback fired before the component is exiting.\n */\n onExit: PropTypes.func,\n\n /**\n * Callback fired when the component has exited.\n */\n onExited: PropTypes.func,\n\n /**\n * Callback fired when the component is exiting.\n */\n onExiting: PropTypes.func,\n\n /**\n * If `true`, the popover is visible.\n */\n open: PropTypes.bool.isRequired,\n\n /**\n * Props applied to the [`Paper`](/api/paper/) element.\n */\n PaperProps: PropTypes\n /* @typescript-to-proptypes-ignore */\n .shape({\n component: elementTypeAcceptingRef\n }),\n\n /**\n * This is the point on the popover which\n * will attach to the anchor's origin.\n *\n * Options:\n * vertical: [top, center, bottom, x(px)];\n * horizontal: [left, center, right, x(px)].\n */\n transformOrigin: PropTypes.shape({\n horizontal: PropTypes.oneOfType([PropTypes.oneOf(['center', 'left', 'right']), PropTypes.number]).isRequired,\n vertical: PropTypes.oneOfType([PropTypes.oneOf(['bottom', 'center', 'top']), PropTypes.number]).isRequired\n }),\n\n /**\n * The component used for the transition.\n * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.\n */\n TransitionComponent: PropTypes.elementType,\n\n /**\n * Set to 'auto' to automatically calculate transition time based on height.\n */\n transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })]),\n\n /**\n * Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element.\n */\n TransitionProps: PropTypes.object\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiPopover'\n})(Popover);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport ListContext from './ListContext';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n listStyle: 'none',\n margin: 0,\n padding: 0,\n position: 'relative'\n },\n\n /* Styles applied to the root element if `disablePadding={false}`. */\n padding: {\n paddingTop: 8,\n paddingBottom: 8\n },\n\n /* Styles applied to the root element if dense. */\n dense: {},\n\n /* Styles applied to the root element if a `subheader` is provided. */\n subheader: {\n paddingTop: 0\n }\n};\nvar List = /*#__PURE__*/React.forwardRef(function List(props, ref) {\n var children = props.children,\n classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'ul' : _props$component,\n _props$dense = props.dense,\n dense = _props$dense === void 0 ? false : _props$dense,\n _props$disablePadding = props.disablePadding,\n disablePadding = _props$disablePadding === void 0 ? false : _props$disablePadding,\n subheader = props.subheader,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"className\", \"component\", \"dense\", \"disablePadding\", \"subheader\"]);\n\n var context = React.useMemo(function () {\n return {\n dense: dense\n };\n }, [dense]);\n return /*#__PURE__*/React.createElement(ListContext.Provider, {\n value: context\n }, /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, dense && classes.dense, !disablePadding && classes.padding, subheader && classes.subheader),\n ref: ref\n }, other), subheader, children));\n});\nprocess.env.NODE_ENV !== \"production\" ? List.propTypes = {\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, compact vertical padding designed for keyboard and mouse input will be used for\n * the list and list items.\n * The prop is available to descendant components as the `dense` context.\n */\n dense: PropTypes.bool,\n\n /**\n * If `true`, vertical padding will be removed from the list.\n */\n disablePadding: PropTypes.bool,\n\n /**\n * The content of the subheader, normally `ListSubheader`.\n */\n subheader: PropTypes.node\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiList'\n})(List);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport * as ReactDOM from 'react-dom';\nimport ownerDocument from '../utils/ownerDocument';\nimport List from '../List';\nimport getScrollbarSize from '../utils/getScrollbarSize';\nimport useForkRef from '../utils/useForkRef';\n\nfunction nextItem(list, item, disableListWrap) {\n if (list === item) {\n return list.firstChild;\n }\n\n if (item && item.nextElementSibling) {\n return item.nextElementSibling;\n }\n\n return disableListWrap ? null : list.firstChild;\n}\n\nfunction previousItem(list, item, disableListWrap) {\n if (list === item) {\n return disableListWrap ? list.firstChild : list.lastChild;\n }\n\n if (item && item.previousElementSibling) {\n return item.previousElementSibling;\n }\n\n return disableListWrap ? null : list.lastChild;\n}\n\nfunction textCriteriaMatches(nextFocus, textCriteria) {\n if (textCriteria === undefined) {\n return true;\n }\n\n var text = nextFocus.innerText;\n\n if (text === undefined) {\n // jsdom doesn't support innerText\n text = nextFocus.textContent;\n }\n\n text = text.trim().toLowerCase();\n\n if (text.length === 0) {\n return false;\n }\n\n if (textCriteria.repeating) {\n return text[0] === textCriteria.keys[0];\n }\n\n return text.indexOf(textCriteria.keys.join('')) === 0;\n}\n\nfunction moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, traversalFunction, textCriteria) {\n var wrappedOnce = false;\n var nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);\n\n while (nextFocus) {\n // Prevent infinite loop.\n if (nextFocus === list.firstChild) {\n if (wrappedOnce) {\n return;\n }\n\n wrappedOnce = true;\n } // Same logic as useAutocomplete.js\n\n\n var nextFocusDisabled = disabledItemsFocusable ? false : nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';\n\n if (!nextFocus.hasAttribute('tabindex') || !textCriteriaMatches(nextFocus, textCriteria) || nextFocusDisabled) {\n // Move to the next element.\n nextFocus = traversalFunction(list, nextFocus, disableListWrap);\n } else {\n nextFocus.focus();\n return;\n }\n }\n}\n\nvar useEnhancedEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;\n/**\n * A permanently displayed menu following https://www.w3.org/TR/wai-aria-practices/#menubutton.\n * It's exposed to help customization of the [`Menu`](/api/menu/) component. If you\n * use it separately you need to move focus into the component manually. Once\n * the focus is placed inside the component it is fully keyboard accessible.\n */\n\nvar MenuList = /*#__PURE__*/React.forwardRef(function MenuList(props, ref) {\n var actions = props.actions,\n _props$autoFocus = props.autoFocus,\n autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,\n _props$autoFocusItem = props.autoFocusItem,\n autoFocusItem = _props$autoFocusItem === void 0 ? false : _props$autoFocusItem,\n children = props.children,\n className = props.className,\n _props$disabledItemsF = props.disabledItemsFocusable,\n disabledItemsFocusable = _props$disabledItemsF === void 0 ? false : _props$disabledItemsF,\n _props$disableListWra = props.disableListWrap,\n disableListWrap = _props$disableListWra === void 0 ? false : _props$disableListWra,\n onKeyDown = props.onKeyDown,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'selectedMenu' : _props$variant,\n other = _objectWithoutProperties(props, [\"actions\", \"autoFocus\", \"autoFocusItem\", \"children\", \"className\", \"disabledItemsFocusable\", \"disableListWrap\", \"onKeyDown\", \"variant\"]);\n\n var listRef = React.useRef(null);\n var textCriteriaRef = React.useRef({\n keys: [],\n repeating: true,\n previousKeyMatched: true,\n lastTime: null\n });\n useEnhancedEffect(function () {\n if (autoFocus) {\n listRef.current.focus();\n }\n }, [autoFocus]);\n React.useImperativeHandle(actions, function () {\n return {\n adjustStyleForScrollbar: function adjustStyleForScrollbar(containerElement, theme) {\n // Let's ignore that piece of logic if users are already overriding the width\n // of the menu.\n var noExplicitWidth = !listRef.current.style.width;\n\n if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {\n var scrollbarSize = \"\".concat(getScrollbarSize(true), \"px\");\n listRef.current.style[theme.direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] = scrollbarSize;\n listRef.current.style.width = \"calc(100% + \".concat(scrollbarSize, \")\");\n }\n\n return listRef.current;\n }\n };\n }, []);\n\n var handleKeyDown = function handleKeyDown(event) {\n var list = listRef.current;\n var key = event.key;\n /**\n * @type {Element} - will always be defined since we are in a keydown handler\n * attached to an element. A keydown event is either dispatched to the activeElement\n * or document.body or document.documentElement. Only the first case will\n * trigger this specific handler.\n */\n\n var currentFocus = ownerDocument(list).activeElement;\n\n if (key === 'ArrowDown') {\n // Prevent scroll of the page\n event.preventDefault();\n moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);\n } else if (key === 'ArrowUp') {\n event.preventDefault();\n moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);\n } else if (key === 'Home') {\n event.preventDefault();\n moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);\n } else if (key === 'End') {\n event.preventDefault();\n moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);\n } else if (key.length === 1) {\n var criteria = textCriteriaRef.current;\n var lowerKey = key.toLowerCase();\n var currTime = performance.now();\n\n if (criteria.keys.length > 0) {\n // Reset\n if (currTime - criteria.lastTime > 500) {\n criteria.keys = [];\n criteria.repeating = true;\n criteria.previousKeyMatched = true;\n } else if (criteria.repeating && lowerKey !== criteria.keys[0]) {\n criteria.repeating = false;\n }\n }\n\n criteria.lastTime = currTime;\n criteria.keys.push(lowerKey);\n var keepFocusOnCurrent = currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);\n\n if (criteria.previousKeyMatched && (keepFocusOnCurrent || moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))) {\n event.preventDefault();\n } else {\n criteria.previousKeyMatched = false;\n }\n }\n\n if (onKeyDown) {\n onKeyDown(event);\n }\n };\n\n var handleOwnRef = React.useCallback(function (instance) {\n // #StrictMode ready\n listRef.current = ReactDOM.findDOMNode(instance);\n }, []);\n var handleRef = useForkRef(handleOwnRef, ref);\n /**\n * the index of the item should receive focus\n * in a `variant=\"selectedMenu\"` it's the first `selected` item\n * otherwise it's the very first item.\n */\n\n var activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead\n // to check if there is a `selected` item. We're looking for the last `selected`\n // item and use the first valid item as a fallback\n\n React.Children.forEach(children, function (child, index) {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n return;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"Material-UI: The Menu component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n\n if (!child.props.disabled) {\n if (variant === 'selectedMenu' && child.props.selected) {\n activeItemIndex = index;\n } else if (activeItemIndex === -1) {\n activeItemIndex = index;\n }\n }\n });\n var items = React.Children.map(children, function (child, index) {\n if (index === activeItemIndex) {\n var newChildProps = {};\n\n if (autoFocusItem) {\n newChildProps.autoFocus = true;\n }\n\n if (child.props.tabIndex === undefined && variant === 'selectedMenu') {\n newChildProps.tabIndex = 0;\n }\n\n return /*#__PURE__*/React.cloneElement(child, newChildProps);\n }\n\n return child;\n });\n return /*#__PURE__*/React.createElement(List, _extends({\n role: \"menu\",\n ref: handleRef,\n className: className,\n onKeyDown: handleKeyDown,\n tabIndex: autoFocus ? 0 : -1\n }, other), items);\n});\nprocess.env.NODE_ENV !== \"production\" ? MenuList.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * If `true`, will focus the `[role=\"menu\"]` container and move into tab order.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * If `true`, will focus the first menuitem if `variant=\"menu\"` or selected item\n * if `variant=\"selectedMenu\"`.\n */\n autoFocusItem: PropTypes.bool,\n\n /**\n * MenuList contents, normally `MenuItem`s.\n */\n children: PropTypes.node,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * If `true`, will allow focus on disabled items.\n */\n disabledItemsFocusable: PropTypes.bool,\n\n /**\n * If `true`, the menu items will not wrap focus.\n */\n disableListWrap: PropTypes.bool,\n\n /**\n * @ignore\n */\n onKeyDown: PropTypes.func,\n\n /**\n * The variant to use. Use `menu` to prevent selected items from impacting the initial focus\n * and the vertical alignment relative to the anchor element.\n */\n variant: PropTypes.oneOf(['menu', 'selectedMenu'])\n} : void 0;\nexport default MenuList;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { HTMLElementType } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nimport Popover from '../Popover';\nimport MenuList from '../MenuList';\nimport * as ReactDOM from 'react-dom';\nimport setRef from '../utils/setRef';\nimport useTheme from '../styles/useTheme';\nvar RTL_ORIGIN = {\n vertical: 'top',\n horizontal: 'right'\n};\nvar LTR_ORIGIN = {\n vertical: 'top',\n horizontal: 'left'\n};\nexport var styles = {\n /* Styles applied to the `Paper` component. */\n paper: {\n // specZ: The maximum height of a simple menu should be one or more rows less than the view\n // height. This ensures a tapable area outside of the simple menu with which to dismiss\n // the menu.\n maxHeight: 'calc(100% - 96px)',\n // Add iOS momentum scrolling.\n WebkitOverflowScrolling: 'touch'\n },\n\n /* Styles applied to the `List` component via `MenuList`. */\n list: {\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0\n }\n};\nvar Menu = /*#__PURE__*/React.forwardRef(function Menu(props, ref) {\n var _props$autoFocus = props.autoFocus,\n autoFocus = _props$autoFocus === void 0 ? true : _props$autoFocus,\n children = props.children,\n classes = props.classes,\n _props$disableAutoFoc = props.disableAutoFocusItem,\n disableAutoFocusItem = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,\n _props$MenuListProps = props.MenuListProps,\n MenuListProps = _props$MenuListProps === void 0 ? {} : _props$MenuListProps,\n onClose = props.onClose,\n onEntering = props.onEntering,\n open = props.open,\n _props$PaperProps = props.PaperProps,\n PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps,\n PopoverClasses = props.PopoverClasses,\n _props$transitionDura = props.transitionDuration,\n transitionDuration = _props$transitionDura === void 0 ? 'auto' : _props$transitionDura,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'selectedMenu' : _props$variant,\n other = _objectWithoutProperties(props, [\"autoFocus\", \"children\", \"classes\", \"disableAutoFocusItem\", \"MenuListProps\", \"onClose\", \"onEntering\", \"open\", \"PaperProps\", \"PopoverClasses\", \"transitionDuration\", \"variant\"]);\n\n var theme = useTheme();\n var autoFocusItem = autoFocus && !disableAutoFocusItem && open;\n var menuListActionsRef = React.useRef(null);\n var contentAnchorRef = React.useRef(null);\n\n var getContentAnchorEl = function getContentAnchorEl() {\n return contentAnchorRef.current;\n };\n\n var handleEntering = function handleEntering(element, isAppearing) {\n if (menuListActionsRef.current) {\n menuListActionsRef.current.adjustStyleForScrollbar(element, theme);\n }\n\n if (onEntering) {\n onEntering(element, isAppearing);\n }\n };\n\n var handleListKeyDown = function handleListKeyDown(event) {\n if (event.key === 'Tab') {\n event.preventDefault();\n\n if (onClose) {\n onClose(event, 'tabKeyDown');\n }\n }\n };\n /**\n * the index of the item should receive focus\n * in a `variant=\"selectedMenu\"` it's the first `selected` item\n * otherwise it's the very first item.\n */\n\n\n var activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead\n // to check if there is a `selected` item. We're looking for the last `selected`\n // item and use the first valid item as a fallback\n\n React.Children.map(children, function (child, index) {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n return;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"Material-UI: The Menu component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n\n if (!child.props.disabled) {\n if (variant !== \"menu\" && child.props.selected) {\n activeItemIndex = index;\n } else if (activeItemIndex === -1) {\n activeItemIndex = index;\n }\n }\n });\n var items = React.Children.map(children, function (child, index) {\n if (index === activeItemIndex) {\n return /*#__PURE__*/React.cloneElement(child, {\n ref: function ref(instance) {\n // #StrictMode ready\n contentAnchorRef.current = ReactDOM.findDOMNode(instance);\n setRef(child.ref, instance);\n }\n });\n }\n\n return child;\n });\n return /*#__PURE__*/React.createElement(Popover, _extends({\n getContentAnchorEl: getContentAnchorEl,\n classes: PopoverClasses,\n onClose: onClose,\n onEntering: handleEntering,\n anchorOrigin: theme.direction === 'rtl' ? RTL_ORIGIN : LTR_ORIGIN,\n transformOrigin: theme.direction === 'rtl' ? RTL_ORIGIN : LTR_ORIGIN,\n PaperProps: _extends({}, PaperProps, {\n classes: _extends({}, PaperProps.classes, {\n root: classes.paper\n })\n }),\n open: open,\n ref: ref,\n transitionDuration: transitionDuration\n }, other), /*#__PURE__*/React.createElement(MenuList, _extends({\n onKeyDown: handleListKeyDown,\n actions: menuListActionsRef,\n autoFocus: autoFocus && (activeItemIndex === -1 || disableAutoFocusItem),\n autoFocusItem: autoFocusItem,\n variant: variant\n }, MenuListProps, {\n className: clsx(classes.list, MenuListProps.className)\n }), items));\n});\nprocess.env.NODE_ENV !== \"production\" ? Menu.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * A HTML element, or a function that returns it.\n * It's used to set the position of the menu.\n */\n anchorEl: PropTypes\n /* @typescript-to-proptypes-ignore */\n .oneOfType([HTMLElementType, PropTypes.func]),\n\n /**\n * If `true` (Default) will focus the `[role=\"menu\"]` if no focusable child is found. Disabled\n * children are not focusable. If you set this prop to `false` focus will be placed\n * on the parent modal container. This has severe accessibility implications\n * and should only be considered if you manage focus otherwise.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * Menu contents, normally `MenuItem`s.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * When opening the menu will not focus the active item but the `[role=\"menu\"]`\n * unless `autoFocus` is also set to `false`. Not using the default means not\n * following WAI-ARIA authoring practices. Please be considerate about possible\n * accessibility implications.\n */\n disableAutoFocusItem: PropTypes.bool,\n\n /**\n * Props applied to the [`MenuList`](/api/menu-list/) element.\n */\n MenuListProps: PropTypes.object,\n\n /**\n * Callback fired when the component requests to be closed.\n *\n * @param {object} event The event source of the callback.\n * @param {string} reason Can be: `\"escapeKeyDown\"`, `\"backdropClick\"`, `\"tabKeyDown\"`.\n */\n onClose: PropTypes.func,\n\n /**\n * Callback fired before the Menu enters.\n */\n onEnter: PropTypes.func,\n\n /**\n * Callback fired when the Menu has entered.\n */\n onEntered: PropTypes.func,\n\n /**\n * Callback fired when the Menu is entering.\n */\n onEntering: PropTypes.func,\n\n /**\n * Callback fired before the Menu exits.\n */\n onExit: PropTypes.func,\n\n /**\n * Callback fired when the Menu has exited.\n */\n onExited: PropTypes.func,\n\n /**\n * Callback fired when the Menu is exiting.\n */\n onExiting: PropTypes.func,\n\n /**\n * If `true`, the menu is visible.\n */\n open: PropTypes.bool.isRequired,\n\n /**\n * @ignore\n */\n PaperProps: PropTypes.object,\n\n /**\n * `classes` prop applied to the [`Popover`](/api/popover/) element.\n */\n PopoverClasses: PropTypes.object,\n\n /**\n * The length of the transition in `ms`, or 'auto'\n */\n transitionDuration: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })]),\n\n /**\n * The variant to use. Use `menu` to prevent selected items from impacting the initial focus\n * and the vertical alignment relative to the anchor element.\n */\n variant: PropTypes.oneOf(['menu', 'selectedMenu'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiMenu'\n})(Menu);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _typeof from \"@babel/runtime/helpers/esm/typeof\";\nimport { formatMuiErrorMessage as _formatMuiErrorMessage } from \"@material-ui/utils\";\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport ownerDocument from '../utils/ownerDocument';\nimport capitalize from '../utils/capitalize';\nimport { refType } from '@material-ui/utils';\nimport Menu from '../Menu/Menu';\nimport { isFilled } from '../InputBase/utils';\nimport useForkRef from '../utils/useForkRef';\nimport useControlled from '../utils/useControlled';\n\nfunction areEqualValues(a, b) {\n if (_typeof(b) === 'object' && b !== null) {\n return a === b;\n }\n\n return String(a) === String(b);\n}\n\nfunction isEmpty(display) {\n return display == null || typeof display === 'string' && !display.trim();\n}\n/**\n * @ignore - internal component.\n */\n\n\nvar SelectInput = /*#__PURE__*/React.forwardRef(function SelectInput(props, ref) {\n var ariaLabel = props['aria-label'],\n autoFocus = props.autoFocus,\n autoWidth = props.autoWidth,\n children = props.children,\n classes = props.classes,\n className = props.className,\n defaultValue = props.defaultValue,\n disabled = props.disabled,\n displayEmpty = props.displayEmpty,\n IconComponent = props.IconComponent,\n inputRefProp = props.inputRef,\n labelId = props.labelId,\n _props$MenuProps = props.MenuProps,\n MenuProps = _props$MenuProps === void 0 ? {} : _props$MenuProps,\n multiple = props.multiple,\n name = props.name,\n onBlur = props.onBlur,\n onChange = props.onChange,\n onClose = props.onClose,\n onFocus = props.onFocus,\n onOpen = props.onOpen,\n openProp = props.open,\n readOnly = props.readOnly,\n renderValue = props.renderValue,\n _props$SelectDisplayP = props.SelectDisplayProps,\n SelectDisplayProps = _props$SelectDisplayP === void 0 ? {} : _props$SelectDisplayP,\n tabIndexProp = props.tabIndex,\n type = props.type,\n valueProp = props.value,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'standard' : _props$variant,\n other = _objectWithoutProperties(props, [\"aria-label\", \"autoFocus\", \"autoWidth\", \"children\", \"classes\", \"className\", \"defaultValue\", \"disabled\", \"displayEmpty\", \"IconComponent\", \"inputRef\", \"labelId\", \"MenuProps\", \"multiple\", \"name\", \"onBlur\", \"onChange\", \"onClose\", \"onFocus\", \"onOpen\", \"open\", \"readOnly\", \"renderValue\", \"SelectDisplayProps\", \"tabIndex\", \"type\", \"value\", \"variant\"]);\n\n var _useControlled = useControlled({\n controlled: valueProp,\n default: defaultValue,\n name: 'Select'\n }),\n _useControlled2 = _slicedToArray(_useControlled, 2),\n value = _useControlled2[0],\n setValue = _useControlled2[1];\n\n var inputRef = React.useRef(null);\n\n var _React$useState = React.useState(null),\n displayNode = _React$useState[0],\n setDisplayNode = _React$useState[1];\n\n var _React$useRef = React.useRef(openProp != null),\n isOpenControlled = _React$useRef.current;\n\n var _React$useState2 = React.useState(),\n menuMinWidthState = _React$useState2[0],\n setMenuMinWidthState = _React$useState2[1];\n\n var _React$useState3 = React.useState(false),\n openState = _React$useState3[0],\n setOpenState = _React$useState3[1];\n\n var handleRef = useForkRef(ref, inputRefProp);\n React.useImperativeHandle(handleRef, function () {\n return {\n focus: function focus() {\n displayNode.focus();\n },\n node: inputRef.current,\n value: value\n };\n }, [displayNode, value]);\n React.useEffect(function () {\n if (autoFocus && displayNode) {\n displayNode.focus();\n }\n }, [autoFocus, displayNode]);\n React.useEffect(function () {\n if (displayNode) {\n var label = ownerDocument(displayNode).getElementById(labelId);\n\n if (label) {\n var handler = function handler() {\n if (getSelection().isCollapsed) {\n displayNode.focus();\n }\n };\n\n label.addEventListener('click', handler);\n return function () {\n label.removeEventListener('click', handler);\n };\n }\n }\n\n return undefined;\n }, [labelId, displayNode]);\n\n var update = function update(open, event) {\n if (open) {\n if (onOpen) {\n onOpen(event);\n }\n } else if (onClose) {\n onClose(event);\n }\n\n if (!isOpenControlled) {\n setMenuMinWidthState(autoWidth ? null : displayNode.clientWidth);\n setOpenState(open);\n }\n };\n\n var handleMouseDown = function handleMouseDown(event) {\n // Ignore everything but left-click\n if (event.button !== 0) {\n return;\n } // Hijack the default focus behavior.\n\n\n event.preventDefault();\n displayNode.focus();\n update(true, event);\n };\n\n var handleClose = function handleClose(event) {\n update(false, event);\n };\n\n var childrenArray = React.Children.toArray(children); // Support autofill.\n\n var handleChange = function handleChange(event) {\n var index = childrenArray.map(function (child) {\n return child.props.value;\n }).indexOf(event.target.value);\n\n if (index === -1) {\n return;\n }\n\n var child = childrenArray[index];\n setValue(child.props.value);\n\n if (onChange) {\n onChange(event, child);\n }\n };\n\n var handleItemClick = function handleItemClick(child) {\n return function (event) {\n if (!multiple) {\n update(false, event);\n }\n\n var newValue;\n\n if (multiple) {\n newValue = Array.isArray(value) ? value.slice() : [];\n var itemIndex = value.indexOf(child.props.value);\n\n if (itemIndex === -1) {\n newValue.push(child.props.value);\n } else {\n newValue.splice(itemIndex, 1);\n }\n } else {\n newValue = child.props.value;\n }\n\n if (child.props.onClick) {\n child.props.onClick(event);\n }\n\n if (value === newValue) {\n return;\n }\n\n setValue(newValue);\n\n if (onChange) {\n event.persist(); // Preact support, target is read only property on a native event.\n\n Object.defineProperty(event, 'target', {\n writable: true,\n value: {\n value: newValue,\n name: name\n }\n });\n onChange(event, child);\n }\n };\n };\n\n var handleKeyDown = function handleKeyDown(event) {\n if (!readOnly) {\n var validKeys = [' ', 'ArrowUp', 'ArrowDown', // The native select doesn't respond to enter on MacOS, but it's recommended by\n // https://www.w3.org/TR/wai-aria-practices/examples/listbox/listbox-collapsible.html\n 'Enter'];\n\n if (validKeys.indexOf(event.key) !== -1) {\n event.preventDefault();\n update(true, event);\n }\n }\n };\n\n var open = displayNode !== null && (isOpenControlled ? openProp : openState);\n\n var handleBlur = function handleBlur(event) {\n // if open event.stopImmediatePropagation\n if (!open && onBlur) {\n event.persist(); // Preact support, target is read only property on a native event.\n\n Object.defineProperty(event, 'target', {\n writable: true,\n value: {\n value: value,\n name: name\n }\n });\n onBlur(event);\n }\n };\n\n delete other['aria-invalid'];\n var display;\n var displaySingle;\n var displayMultiple = [];\n var computeDisplay = false;\n var foundMatch = false; // No need to display any value if the field is empty.\n\n if (isFilled({\n value: value\n }) || displayEmpty) {\n if (renderValue) {\n display = renderValue(value);\n } else {\n computeDisplay = true;\n }\n }\n\n var items = childrenArray.map(function (child) {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n return null;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"Material-UI: The Select component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n\n var selected;\n\n if (multiple) {\n if (!Array.isArray(value)) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? \"Material-UI: The `value` prop must be an array when using the `Select` component with `multiple`.\" : _formatMuiErrorMessage(2));\n }\n\n selected = value.some(function (v) {\n return areEqualValues(v, child.props.value);\n });\n\n if (selected && computeDisplay) {\n displayMultiple.push(child.props.children);\n }\n } else {\n selected = areEqualValues(value, child.props.value);\n\n if (selected && computeDisplay) {\n displaySingle = child.props.children;\n }\n }\n\n if (selected) {\n foundMatch = true;\n }\n\n return /*#__PURE__*/React.cloneElement(child, {\n 'aria-selected': selected ? 'true' : undefined,\n onClick: handleItemClick(child),\n onKeyUp: function onKeyUp(event) {\n if (event.key === ' ') {\n // otherwise our MenuItems dispatches a click event\n // it's not behavior of the native <option> and causes\n // the select to close immediately since we open on space keydown\n event.preventDefault();\n }\n\n if (child.props.onKeyUp) {\n child.props.onKeyUp(event);\n }\n },\n role: 'option',\n selected: selected,\n value: undefined,\n // The value is most likely not a valid HTML attribute.\n 'data-value': child.props.value // Instead, we provide it as a data attribute.\n\n });\n });\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(function () {\n if (!foundMatch && !multiple && value !== '') {\n var values = childrenArray.map(function (child) {\n return child.props.value;\n });\n console.warn([\"Material-UI: You have provided an out-of-range value `\".concat(value, \"` for the select \").concat(name ? \"(name=\\\"\".concat(name, \"\\\") \") : '', \"component.\"), \"Consider providing a value that matches one of the available options or ''.\", \"The available values are \".concat(values.filter(function (x) {\n return x != null;\n }).map(function (x) {\n return \"`\".concat(x, \"`\");\n }).join(', ') || '\"\"', \".\")].join('\\n'));\n }\n }, [foundMatch, childrenArray, multiple, name, value]);\n }\n\n if (computeDisplay) {\n display = multiple ? displayMultiple.join(', ') : displaySingle;\n } // Avoid performing a layout computation in the render method.\n\n\n var menuMinWidth = menuMinWidthState;\n\n if (!autoWidth && isOpenControlled && displayNode) {\n menuMinWidth = displayNode.clientWidth;\n }\n\n var tabIndex;\n\n if (typeof tabIndexProp !== 'undefined') {\n tabIndex = tabIndexProp;\n } else {\n tabIndex = disabled ? null : 0;\n }\n\n var buttonId = SelectDisplayProps.id || (name ? \"mui-component-select-\".concat(name) : undefined);\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"div\", _extends({\n className: clsx(classes.root, // TODO v5: merge root and select\n classes.select, classes.selectMenu, classes[variant], className, disabled && classes.disabled),\n ref: setDisplayNode,\n tabIndex: tabIndex,\n role: \"button\",\n \"aria-disabled\": disabled ? 'true' : undefined,\n \"aria-expanded\": open ? 'true' : undefined,\n \"aria-haspopup\": \"listbox\",\n \"aria-label\": ariaLabel,\n \"aria-labelledby\": [labelId, buttonId].filter(Boolean).join(' ') || undefined,\n onKeyDown: handleKeyDown,\n onMouseDown: disabled || readOnly ? null : handleMouseDown,\n onBlur: handleBlur,\n onFocus: onFocus\n }, SelectDisplayProps, {\n // The id is required for proper a11y\n id: buttonId\n }), isEmpty(display) ?\n /*#__PURE__*/\n // eslint-disable-next-line react/no-danger\n React.createElement(\"span\", {\n dangerouslySetInnerHTML: {\n __html: '&#8203;'\n }\n }) : display), /*#__PURE__*/React.createElement(\"input\", _extends({\n value: Array.isArray(value) ? value.join(',') : value,\n name: name,\n ref: inputRef,\n \"aria-hidden\": true,\n onChange: handleChange,\n tabIndex: -1,\n className: classes.nativeInput,\n autoFocus: autoFocus\n }, other)), /*#__PURE__*/React.createElement(IconComponent, {\n className: clsx(classes.icon, classes[\"icon\".concat(capitalize(variant))], open && classes.iconOpen, disabled && classes.disabled)\n }), /*#__PURE__*/React.createElement(Menu, _extends({\n id: \"menu-\".concat(name || ''),\n anchorEl: displayNode,\n open: open,\n onClose: handleClose\n }, MenuProps, {\n MenuListProps: _extends({\n 'aria-labelledby': labelId,\n role: 'listbox',\n disableListWrap: true\n }, MenuProps.MenuListProps),\n PaperProps: _extends({}, MenuProps.PaperProps, {\n style: _extends({\n minWidth: menuMinWidth\n }, MenuProps.PaperProps != null ? MenuProps.PaperProps.style : null)\n })\n }), items));\n});\nprocess.env.NODE_ENV !== \"production\" ? SelectInput.propTypes = {\n /**\n * @ignore\n */\n 'aria-label': PropTypes.string,\n\n /**\n * @ignore\n */\n autoFocus: PropTypes.bool,\n\n /**\n * If `true`, the width of the popover will automatically be set according to the items inside the\n * menu, otherwise it will be at least the width of the select input.\n */\n autoWidth: PropTypes.bool,\n\n /**\n * The option elements to populate the select with.\n * Can be some `<MenuItem>` elements.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * The CSS class name of the select element.\n */\n className: PropTypes.string,\n\n /**\n * The default element value. Use when the component is not controlled.\n */\n defaultValue: PropTypes.any,\n\n /**\n * If `true`, the select will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the selected item is displayed even if its value is empty.\n */\n displayEmpty: PropTypes.bool,\n\n /**\n * The icon that displays the arrow.\n */\n IconComponent: PropTypes.elementType.isRequired,\n\n /**\n * Imperative handle implementing `{ value: T, node: HTMLElement, focus(): void }`\n * Equivalent to `ref`\n */\n inputRef: refType,\n\n /**\n * The ID of an element that acts as an additional label. The Select will\n * be labelled by the additional label and the selected value.\n */\n labelId: PropTypes.string,\n\n /**\n * Props applied to the [`Menu`](/api/menu/) element.\n */\n MenuProps: PropTypes.object,\n\n /**\n * If `true`, `value` must be an array and the menu will support multiple selections.\n */\n multiple: PropTypes.bool,\n\n /**\n * Name attribute of the `select` or hidden `input` element.\n */\n name: PropTypes.string,\n\n /**\n * @ignore\n */\n onBlur: PropTypes.func,\n\n /**\n * Callback function fired when a menu item is selected.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (any).\n * @param {object} [child] The react element that was selected.\n */\n onChange: PropTypes.func,\n\n /**\n * Callback fired when the component requests to be closed.\n * Use in controlled mode (see open).\n *\n * @param {object} event The event source of the callback.\n */\n onClose: PropTypes.func,\n\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n\n /**\n * Callback fired when the component requests to be opened.\n * Use in controlled mode (see open).\n *\n * @param {object} event The event source of the callback.\n */\n onOpen: PropTypes.func,\n\n /**\n * Control `select` open state.\n */\n open: PropTypes.bool,\n\n /**\n * @ignore\n */\n readOnly: PropTypes.bool,\n\n /**\n * Render the selected value.\n *\n * @param {any} value The `value` provided to the component.\n * @returns {ReactNode}\n */\n renderValue: PropTypes.func,\n\n /**\n * Props applied to the clickable div element.\n */\n SelectDisplayProps: PropTypes.object,\n\n /**\n * @ignore\n */\n tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * @ignore\n */\n type: PropTypes.any,\n\n /**\n * The input value.\n */\n value: PropTypes.any,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])\n} : void 0;\nexport default SelectInput;","/* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */\nimport * as React from 'react';\nexport default function useControlled(_ref) {\n var controlled = _ref.controlled,\n defaultProp = _ref.default,\n name = _ref.name,\n _ref$state = _ref.state,\n state = _ref$state === void 0 ? 'value' : _ref$state;\n\n var _React$useRef = React.useRef(controlled !== undefined),\n isControlled = _React$useRef.current;\n\n var _React$useState = React.useState(defaultProp),\n valueState = _React$useState[0],\n setValue = _React$useState[1];\n\n var value = isControlled ? controlled : valueState;\n\n if (process.env.NODE_ENV !== 'production') {\n React.useEffect(function () {\n if (isControlled !== (controlled !== undefined)) {\n console.error([\"Material-UI: A component is changing the \".concat(isControlled ? '' : 'un', \"controlled \").concat(state, \" state of \").concat(name, \" to be \").concat(isControlled ? 'un' : '', \"controlled.\"), 'Elements should not switch from uncontrolled to controlled (or vice versa).', \"Decide between using a controlled or uncontrolled \".concat(name, \" \") + 'element for the lifetime of the component.', \"The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.\", 'More info: https://fb.me/react-controlled-components'].join('\\n'));\n }\n }, [controlled]);\n\n var _React$useRef2 = React.useRef(defaultProp),\n defaultValue = _React$useRef2.current;\n\n React.useEffect(function () {\n if (!isControlled && defaultValue !== defaultProp) {\n console.error([\"Material-UI: A component is changing the default \".concat(state, \" state of an uncontrolled \").concat(name, \" after being initialized. \") + \"To suppress this warning opt to use a controlled \".concat(name, \".\")].join('\\n'));\n }\n }, [JSON.stringify(defaultProp)]);\n }\n\n var setValueIfUncontrolled = React.useCallback(function (newValue) {\n if (!isControlled) {\n setValue(newValue);\n }\n }, []);\n return [value, setValueIfUncontrolled];\n}","import * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n/**\n * @ignore - internal component.\n */\n\nexport default createSvgIcon( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M7 10l5 5 5-5z\"\n}), 'ArrowDropDown');","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { refType } from '@material-ui/utils';\nimport capitalize from '../utils/capitalize';\n/**\n * @ignore - internal component.\n */\n\nvar NativeSelectInput = /*#__PURE__*/React.forwardRef(function NativeSelectInput(props, ref) {\n var classes = props.classes,\n className = props.className,\n disabled = props.disabled,\n IconComponent = props.IconComponent,\n inputRef = props.inputRef,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'standard' : _props$variant,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"disabled\", \"IconComponent\", \"inputRef\", \"variant\"]);\n\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"select\", _extends({\n className: clsx(classes.root, // TODO v5: merge root and select\n classes.select, classes[variant], className, disabled && classes.disabled),\n disabled: disabled,\n ref: inputRef || ref\n }, other)), props.multiple ? null : /*#__PURE__*/React.createElement(IconComponent, {\n className: clsx(classes.icon, classes[\"icon\".concat(capitalize(variant))], disabled && classes.disabled)\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? NativeSelectInput.propTypes = {\n /**\n * The option elements to populate the select with.\n * Can be some `<option>` elements.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * The CSS class name of the select element.\n */\n className: PropTypes.string,\n\n /**\n * If `true`, the select will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * The icon that displays the arrow.\n */\n IconComponent: PropTypes.elementType.isRequired,\n\n /**\n * Use that prop to pass a ref to the native select element.\n * @deprecated\n */\n inputRef: refType,\n\n /**\n * @ignore\n */\n multiple: PropTypes.bool,\n\n /**\n * Name attribute of the `select` or hidden `input` element.\n */\n name: PropTypes.string,\n\n /**\n * Callback function fired when a menu item is selected.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (string).\n */\n onChange: PropTypes.func,\n\n /**\n * The input value.\n */\n value: PropTypes.any,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])\n} : void 0;\nexport default NativeSelectInput;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport NativeSelectInput from './NativeSelectInput';\nimport withStyles from '../styles/withStyles';\nimport formControlState from '../FormControl/formControlState';\nimport useFormControl from '../FormControl/useFormControl';\nimport ArrowDropDownIcon from '../internal/svg-icons/ArrowDropDown';\nimport Input from '../Input';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the select component `root` class. */\n root: {},\n\n /* Styles applied to the select component `select` class. */\n select: {\n '-moz-appearance': 'none',\n // Reset\n '-webkit-appearance': 'none',\n // Reset\n // When interacting quickly, the text can end up selected.\n // Native select can't be selected either.\n userSelect: 'none',\n borderRadius: 0,\n // Reset\n minWidth: 16,\n // So it doesn't collapse.\n cursor: 'pointer',\n '&:focus': {\n // Show that it's not an text input\n backgroundColor: theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.05)' : 'rgba(255, 255, 255, 0.05)',\n borderRadius: 0 // Reset Chrome style\n\n },\n // Remove IE 11 arrow\n '&::-ms-expand': {\n display: 'none'\n },\n '&$disabled': {\n cursor: 'default'\n },\n '&[multiple]': {\n height: 'auto'\n },\n '&:not([multiple]) option, &:not([multiple]) optgroup': {\n backgroundColor: theme.palette.background.paper\n },\n '&&': {\n paddingRight: 24\n }\n },\n\n /* Styles applied to the select component if `variant=\"filled\"`. */\n filled: {\n '&&': {\n paddingRight: 32\n }\n },\n\n /* Styles applied to the select component if `variant=\"outlined\"`. */\n outlined: {\n borderRadius: theme.shape.borderRadius,\n '&&': {\n paddingRight: 32\n }\n },\n\n /* Styles applied to the select component `selectMenu` class. */\n selectMenu: {\n height: 'auto',\n // Resets for multpile select with chips\n minHeight: '1.1876em',\n // Required for select\\text-field height consistency\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n overflow: 'hidden'\n },\n\n /* Pseudo-class applied to the select component `disabled` class. */\n disabled: {},\n\n /* Styles applied to the icon component. */\n icon: {\n // We use a position absolute over a flexbox in order to forward the pointer events\n // to the input and to support wrapping tags..\n position: 'absolute',\n right: 0,\n top: 'calc(50% - 12px)',\n // Center vertically\n pointerEvents: 'none',\n // Don't block pointer events on the select under the icon.\n color: theme.palette.action.active,\n '&$disabled': {\n color: theme.palette.action.disabled\n }\n },\n\n /* Styles applied to the icon component if the popup is open. */\n iconOpen: {\n transform: 'rotate(180deg)'\n },\n\n /* Styles applied to the icon component if `variant=\"filled\"`. */\n iconFilled: {\n right: 7\n },\n\n /* Styles applied to the icon component if `variant=\"outlined\"`. */\n iconOutlined: {\n right: 7\n },\n\n /* Styles applied to the underlying native input component. */\n nativeInput: {\n bottom: 0,\n left: 0,\n position: 'absolute',\n opacity: 0,\n pointerEvents: 'none',\n width: '100%'\n }\n };\n};\nvar defaultInput = /*#__PURE__*/React.createElement(Input, null);\n/**\n * An alternative to `<Select native />` with a much smaller bundle size footprint.\n */\n\nvar NativeSelect = /*#__PURE__*/React.forwardRef(function NativeSelect(props, ref) {\n var children = props.children,\n classes = props.classes,\n _props$IconComponent = props.IconComponent,\n IconComponent = _props$IconComponent === void 0 ? ArrowDropDownIcon : _props$IconComponent,\n _props$input = props.input,\n input = _props$input === void 0 ? defaultInput : _props$input,\n inputProps = props.inputProps,\n variant = props.variant,\n other = _objectWithoutProperties(props, [\"children\", \"classes\", \"IconComponent\", \"input\", \"inputProps\", \"variant\"]);\n\n var muiFormControl = useFormControl();\n var fcs = formControlState({\n props: props,\n muiFormControl: muiFormControl,\n states: ['variant']\n });\n return /*#__PURE__*/React.cloneElement(input, _extends({\n // Most of the logic is implemented in `NativeSelectInput`.\n // The `Select` component is a simple API wrapper to expose something better to play with.\n inputComponent: NativeSelectInput,\n inputProps: _extends({\n children: children,\n classes: classes,\n IconComponent: IconComponent,\n variant: fcs.variant,\n type: undefined\n }, inputProps, input ? input.props.inputProps : {}),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? NativeSelect.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The option elements to populate the select with.\n * Can be some `<option>` elements.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * The icon that displays the arrow.\n */\n IconComponent: PropTypes.elementType,\n\n /**\n * An `Input` element; does not have to be a material-ui specific `Input`.\n */\n input: PropTypes.element,\n\n /**\n * Attributes applied to the `select` element.\n */\n inputProps: PropTypes.object,\n\n /**\n * Callback function fired when a menu item is selected.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (string).\n */\n onChange: PropTypes.func,\n\n /**\n * The input value. The DOM API casts this to a string.\n */\n value: PropTypes.any,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])\n} : void 0;\nNativeSelect.muiName = 'Select';\nexport default withStyles(styles, {\n name: 'MuiNativeSelect'\n})(NativeSelect);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { mergeClasses } from '@material-ui/styles';\nimport SelectInput from './SelectInput';\nimport formControlState from '../FormControl/formControlState';\nimport useFormControl from '../FormControl/useFormControl';\nimport withStyles from '../styles/withStyles';\nimport ArrowDropDownIcon from '../internal/svg-icons/ArrowDropDown';\nimport Input from '../Input';\nimport { styles as nativeSelectStyles } from '../NativeSelect/NativeSelect';\nimport NativeSelectInput from '../NativeSelect/NativeSelectInput';\nimport FilledInput from '../FilledInput';\nimport OutlinedInput from '../OutlinedInput';\nexport var styles = nativeSelectStyles;\n\nvar _ref = /*#__PURE__*/React.createElement(Input, null);\n\nvar _ref2 = /*#__PURE__*/React.createElement(FilledInput, null);\n\nvar Select = /*#__PURE__*/React.forwardRef(function Select(props, ref) {\n var _props$autoWidth = props.autoWidth,\n autoWidth = _props$autoWidth === void 0 ? false : _props$autoWidth,\n children = props.children,\n classes = props.classes,\n _props$displayEmpty = props.displayEmpty,\n displayEmpty = _props$displayEmpty === void 0 ? false : _props$displayEmpty,\n _props$IconComponent = props.IconComponent,\n IconComponent = _props$IconComponent === void 0 ? ArrowDropDownIcon : _props$IconComponent,\n id = props.id,\n input = props.input,\n inputProps = props.inputProps,\n label = props.label,\n labelId = props.labelId,\n _props$labelWidth = props.labelWidth,\n labelWidth = _props$labelWidth === void 0 ? 0 : _props$labelWidth,\n MenuProps = props.MenuProps,\n _props$multiple = props.multiple,\n multiple = _props$multiple === void 0 ? false : _props$multiple,\n _props$native = props.native,\n native = _props$native === void 0 ? false : _props$native,\n onClose = props.onClose,\n onOpen = props.onOpen,\n open = props.open,\n renderValue = props.renderValue,\n SelectDisplayProps = props.SelectDisplayProps,\n _props$variant = props.variant,\n variantProps = _props$variant === void 0 ? 'standard' : _props$variant,\n other = _objectWithoutProperties(props, [\"autoWidth\", \"children\", \"classes\", \"displayEmpty\", \"IconComponent\", \"id\", \"input\", \"inputProps\", \"label\", \"labelId\", \"labelWidth\", \"MenuProps\", \"multiple\", \"native\", \"onClose\", \"onOpen\", \"open\", \"renderValue\", \"SelectDisplayProps\", \"variant\"]);\n\n var inputComponent = native ? NativeSelectInput : SelectInput;\n var muiFormControl = useFormControl();\n var fcs = formControlState({\n props: props,\n muiFormControl: muiFormControl,\n states: ['variant']\n });\n var variant = fcs.variant || variantProps;\n var InputComponent = input || {\n standard: _ref,\n outlined: /*#__PURE__*/React.createElement(OutlinedInput, {\n label: label,\n labelWidth: labelWidth\n }),\n filled: _ref2\n }[variant];\n return /*#__PURE__*/React.cloneElement(InputComponent, _extends({\n // Most of the logic is implemented in `SelectInput`.\n // The `Select` component is a simple API wrapper to expose something better to play with.\n inputComponent: inputComponent,\n inputProps: _extends({\n children: children,\n IconComponent: IconComponent,\n variant: variant,\n type: undefined,\n // We render a select. We can ignore the type provided by the `Input`.\n multiple: multiple\n }, native ? {\n id: id\n } : {\n autoWidth: autoWidth,\n displayEmpty: displayEmpty,\n labelId: labelId,\n MenuProps: MenuProps,\n onClose: onClose,\n onOpen: onOpen,\n open: open,\n renderValue: renderValue,\n SelectDisplayProps: _extends({\n id: id\n }, SelectDisplayProps)\n }, inputProps, {\n classes: inputProps ? mergeClasses({\n baseClasses: classes,\n newClasses: inputProps.classes,\n Component: Select\n }) : classes\n }, input ? input.props.inputProps : {}),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? Select.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * If `true`, the width of the popover will automatically be set according to the items inside the\n * menu, otherwise it will be at least the width of the select input.\n */\n autoWidth: PropTypes.bool,\n\n /**\n * The option elements to populate the select with.\n * Can be some `MenuItem` when `native` is false and `option` when `native` is true.\n *\n * ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * The default element value. Use when the component is not controlled.\n */\n defaultValue: PropTypes.any,\n\n /**\n * If `true`, a value is displayed even if no items are selected.\n *\n * In order to display a meaningful value, a function should be passed to the `renderValue` prop which returns the value to be displayed when no items are selected.\n * You can only use it when the `native` prop is `false` (default).\n */\n displayEmpty: PropTypes.bool,\n\n /**\n * The icon that displays the arrow.\n */\n IconComponent: PropTypes.elementType,\n\n /**\n * The `id` of the wrapper element or the `select` element when `native`.\n */\n id: PropTypes.string,\n\n /**\n * An `Input` element; does not have to be a material-ui specific `Input`.\n */\n input: PropTypes.element,\n\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n * When `native` is `true`, the attributes are applied on the `select` element.\n */\n inputProps: PropTypes.object,\n\n /**\n * See [OutlinedInput#label](/api/outlined-input/#props)\n */\n label: PropTypes.node,\n\n /**\n * The ID of an element that acts as an additional label. The Select will\n * be labelled by the additional label and the selected value.\n */\n labelId: PropTypes.string,\n\n /**\n * See [OutlinedInput#label](/api/outlined-input/#props)\n */\n labelWidth: PropTypes.number,\n\n /**\n * Props applied to the [`Menu`](/api/menu/) element.\n */\n MenuProps: PropTypes.object,\n\n /**\n * If `true`, `value` must be an array and the menu will support multiple selections.\n */\n multiple: PropTypes.bool,\n\n /**\n * If `true`, the component will be using a native `select` element.\n */\n native: PropTypes.bool,\n\n /**\n * Callback function fired when a menu item is selected.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (any).\n * @param {object} [child] The react element that was selected when `native` is `false` (default).\n */\n onChange: PropTypes.func,\n\n /**\n * Callback fired when the component requests to be closed.\n * Use in controlled mode (see open).\n *\n * @param {object} event The event source of the callback.\n */\n onClose: PropTypes.func,\n\n /**\n * Callback fired when the component requests to be opened.\n * Use in controlled mode (see open).\n *\n * @param {object} event The event source of the callback.\n */\n onOpen: PropTypes.func,\n\n /**\n * Control `select` open state.\n * You can only use it when the `native` prop is `false` (default).\n */\n open: PropTypes.bool,\n\n /**\n * Render the selected value.\n * You can only use it when the `native` prop is `false` (default).\n *\n * @param {any} value The `value` provided to the component.\n * @returns {ReactNode}\n */\n renderValue: PropTypes.func,\n\n /**\n * Props applied to the clickable div element.\n */\n SelectDisplayProps: PropTypes.object,\n\n /**\n * The input value. Providing an empty string will select no options.\n * This prop is required when the `native` prop is `false` (default).\n * Set to an empty string `''` if you don't want any of the available options to be selected.\n *\n * If the value is an object it must have reference equality with the option in order to be selected.\n * If the value is not an object, the string representation must match with the string representation of the option in order to be selected.\n */\n value: PropTypes.any,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])\n} : void 0;\nSelect.muiName = 'Select';\nexport default withStyles(styles, {\n name: 'MuiSelect'\n})(Select);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { refType } from '@material-ui/utils';\nimport Input from '../Input';\nimport FilledInput from '../FilledInput';\nimport OutlinedInput from '../OutlinedInput';\nimport InputLabel from '../InputLabel';\nimport FormControl from '../FormControl';\nimport FormHelperText from '../FormHelperText';\nimport Select from '../Select';\nimport withStyles from '../styles/withStyles';\nvar variantComponent = {\n standard: Input,\n filled: FilledInput,\n outlined: OutlinedInput\n};\nexport var styles = {\n /* Styles applied to the root element. */\n root: {}\n};\n/**\n * The `TextField` is a convenience wrapper for the most common cases (80%).\n * It cannot be all things to all people, otherwise the API would grow out of control.\n *\n * ## Advanced Configuration\n *\n * It's important to understand that the text field is a simple abstraction\n * on top of the following components:\n *\n * - [FormControl](/api/form-control/)\n * - [InputLabel](/api/input-label/)\n * - [FilledInput](/api/filled-input/)\n * - [OutlinedInput](/api/outlined-input/)\n * - [Input](/api/input/)\n * - [FormHelperText](/api/form-helper-text/)\n *\n * If you wish to alter the props applied to the `input` element, you can do so as follows:\n *\n * ```jsx\n * const inputProps = {\n * step: 300,\n * };\n *\n * return <TextField id=\"time\" type=\"time\" inputProps={inputProps} />;\n * ```\n *\n * For advanced cases, please look at the source of TextField by clicking on the\n * \"Edit this page\" button above. Consider either:\n *\n * - using the upper case props for passing values directly to the components\n * - using the underlying components directly as shown in the demos\n */\n\nvar TextField = /*#__PURE__*/React.forwardRef(function TextField(props, ref) {\n var autoComplete = props.autoComplete,\n _props$autoFocus = props.autoFocus,\n autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,\n children = props.children,\n classes = props.classes,\n className = props.className,\n _props$color = props.color,\n color = _props$color === void 0 ? 'primary' : _props$color,\n defaultValue = props.defaultValue,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$error = props.error,\n error = _props$error === void 0 ? false : _props$error,\n FormHelperTextProps = props.FormHelperTextProps,\n _props$fullWidth = props.fullWidth,\n fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,\n helperText = props.helperText,\n hiddenLabel = props.hiddenLabel,\n id = props.id,\n InputLabelProps = props.InputLabelProps,\n inputProps = props.inputProps,\n InputProps = props.InputProps,\n inputRef = props.inputRef,\n label = props.label,\n _props$multiline = props.multiline,\n multiline = _props$multiline === void 0 ? false : _props$multiline,\n name = props.name,\n onBlur = props.onBlur,\n onChange = props.onChange,\n onFocus = props.onFocus,\n placeholder = props.placeholder,\n _props$required = props.required,\n required = _props$required === void 0 ? false : _props$required,\n rows = props.rows,\n rowsMax = props.rowsMax,\n _props$select = props.select,\n select = _props$select === void 0 ? false : _props$select,\n SelectProps = props.SelectProps,\n type = props.type,\n value = props.value,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'standard' : _props$variant,\n other = _objectWithoutProperties(props, [\"autoComplete\", \"autoFocus\", \"children\", \"classes\", \"className\", \"color\", \"defaultValue\", \"disabled\", \"error\", \"FormHelperTextProps\", \"fullWidth\", \"helperText\", \"hiddenLabel\", \"id\", \"InputLabelProps\", \"inputProps\", \"InputProps\", \"inputRef\", \"label\", \"multiline\", \"name\", \"onBlur\", \"onChange\", \"onFocus\", \"placeholder\", \"required\", \"rows\", \"rowsMax\", \"select\", \"SelectProps\", \"type\", \"value\", \"variant\"]);\n\n if (process.env.NODE_ENV !== 'production') {\n if (select && !children) {\n console.error('Material-UI: `children` must be passed when using the `TextField` component with `select`.');\n }\n }\n\n var InputMore = {};\n\n if (variant === 'outlined') {\n if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {\n InputMore.notched = InputLabelProps.shrink;\n }\n\n if (label) {\n var _InputLabelProps$requ;\n\n var displayRequired = (_InputLabelProps$requ = InputLabelProps === null || InputLabelProps === void 0 ? void 0 : InputLabelProps.required) !== null && _InputLabelProps$requ !== void 0 ? _InputLabelProps$requ : required;\n InputMore.label = /*#__PURE__*/React.createElement(React.Fragment, null, label, displayRequired && \"\\xA0*\");\n }\n }\n\n if (select) {\n // unset defaults from textbox inputs\n if (!SelectProps || !SelectProps.native) {\n InputMore.id = undefined;\n }\n\n InputMore['aria-describedby'] = undefined;\n }\n\n var helperTextId = helperText && id ? \"\".concat(id, \"-helper-text\") : undefined;\n var inputLabelId = label && id ? \"\".concat(id, \"-label\") : undefined;\n var InputComponent = variantComponent[variant];\n var InputElement = /*#__PURE__*/React.createElement(InputComponent, _extends({\n \"aria-describedby\": helperTextId,\n autoComplete: autoComplete,\n autoFocus: autoFocus,\n defaultValue: defaultValue,\n fullWidth: fullWidth,\n multiline: multiline,\n name: name,\n rows: rows,\n rowsMax: rowsMax,\n type: type,\n value: value,\n id: id,\n inputRef: inputRef,\n onBlur: onBlur,\n onChange: onChange,\n onFocus: onFocus,\n placeholder: placeholder,\n inputProps: inputProps\n }, InputMore, InputProps));\n return /*#__PURE__*/React.createElement(FormControl, _extends({\n className: clsx(classes.root, className),\n disabled: disabled,\n error: error,\n fullWidth: fullWidth,\n hiddenLabel: hiddenLabel,\n ref: ref,\n required: required,\n color: color,\n variant: variant\n }, other), label && /*#__PURE__*/React.createElement(InputLabel, _extends({\n htmlFor: id,\n id: inputLabelId\n }, InputLabelProps), label), select ? /*#__PURE__*/React.createElement(Select, _extends({\n \"aria-describedby\": helperTextId,\n id: id,\n labelId: inputLabelId,\n value: value,\n input: InputElement\n }, SelectProps), children) : InputElement, helperText && /*#__PURE__*/React.createElement(FormHelperText, _extends({\n id: helperTextId\n }, FormHelperTextProps), helperText));\n});\nprocess.env.NODE_ENV !== \"production\" ? TextField.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * This prop helps users to fill forms faster, especially on mobile devices.\n * The name can be confusing, as it's more like an autofill.\n * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).\n */\n autoComplete: PropTypes.string,\n\n /**\n * If `true`, the `input` element will be focused during the first mount.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * @ignore\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * The default value of the `input` element.\n */\n defaultValue: PropTypes.any,\n\n /**\n * If `true`, the `input` element will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the label will be displayed in an error state.\n */\n error: PropTypes.bool,\n\n /**\n * Props applied to the [`FormHelperText`](/api/form-helper-text/) element.\n */\n FormHelperTextProps: PropTypes.object,\n\n /**\n * If `true`, the input will take up the full width of its container.\n */\n fullWidth: PropTypes.bool,\n\n /**\n * The helper text content.\n */\n helperText: PropTypes.node,\n\n /**\n * @ignore\n */\n hiddenLabel: PropTypes.bool,\n\n /**\n * The id of the `input` element.\n * Use this prop to make `label` and `helperText` accessible for screen readers.\n */\n id: PropTypes.string,\n\n /**\n * Props applied to the [`InputLabel`](/api/input-label/) element.\n */\n InputLabelProps: PropTypes.object,\n\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n */\n inputProps: PropTypes.object,\n\n /**\n * Props applied to the Input element.\n * It will be a [`FilledInput`](/api/filled-input/),\n * [`OutlinedInput`](/api/outlined-input/) or [`Input`](/api/input/)\n * component depending on the `variant` prop value.\n */\n InputProps: PropTypes.object,\n\n /**\n * Pass a ref to the `input` element.\n */\n inputRef: refType,\n\n /**\n * The label content.\n */\n label: PropTypes.node,\n\n /**\n * If `dense` or `normal`, will adjust vertical spacing of this and contained components.\n */\n margin: PropTypes.oneOf(['dense', 'none', 'normal']),\n\n /**\n * If `true`, a textarea element will be rendered instead of an input.\n */\n multiline: PropTypes.bool,\n\n /**\n * Name attribute of the `input` element.\n */\n name: PropTypes.string,\n\n /**\n * @ignore\n */\n onBlur: PropTypes.func,\n\n /**\n * Callback fired when the value is changed.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (string).\n */\n onChange: PropTypes.func,\n\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n\n /**\n * The short hint displayed in the input before the user enters a value.\n */\n placeholder: PropTypes.string,\n\n /**\n * If `true`, the label is displayed as required and the `input` element` will be required.\n */\n required: PropTypes.bool,\n\n /**\n * Number of rows to display when multiline option is set to true.\n */\n rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Maximum number of rows to display when multiline option is set to true.\n */\n rowsMax: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n\n /**\n * Render a [`Select`](/api/select/) element while passing the Input element to `Select` as `input` parameter.\n * If this option is set you must pass the options of the select as children.\n */\n select: PropTypes.bool,\n\n /**\n * Props applied to the [`Select`](/api/select/) element.\n */\n SelectProps: PropTypes.object,\n\n /**\n * The size of the text field.\n */\n size: PropTypes.oneOf(['medium', 'small']),\n\n /**\n * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).\n */\n type: PropTypes.string,\n\n /**\n * The value of the `input` element, required for a controlled component.\n */\n value: PropTypes.any,\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTextField'\n})(TextField);","import _toConsumableArray from \"@babel/runtime/helpers/esm/toConsumableArray\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport PropTypes from 'prop-types';\nimport merge from './merge';\n\nfunction omit(input, fields) {\n var output = {};\n Object.keys(input).forEach(function (prop) {\n if (fields.indexOf(prop) === -1) {\n output[prop] = input[prop];\n }\n });\n return output;\n}\n\nfunction css(styleFunction) {\n var newStyleFunction = function newStyleFunction(props) {\n var output = styleFunction(props);\n\n if (props.css) {\n return _extends({}, merge(output, styleFunction(_extends({\n theme: props.theme\n }, props.css))), omit(props.css, [styleFunction.filterProps]));\n }\n\n return output;\n };\n\n newStyleFunction.propTypes = process.env.NODE_ENV !== 'production' ? _extends({}, styleFunction.propTypes, {\n css: PropTypes.object\n }) : {};\n newStyleFunction.filterProps = ['css'].concat(_toConsumableArray(styleFunction.filterProps));\n return newStyleFunction;\n}\n\nexport default css;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport merge from './merge';\n\nfunction compose() {\n for (var _len = arguments.length, styles = new Array(_len), _key = 0; _key < _len; _key++) {\n styles[_key] = arguments[_key];\n }\n\n var fn = function fn(props) {\n return styles.reduce(function (acc, style) {\n var output = style(props);\n\n if (output) {\n return merge(acc, output);\n }\n\n return acc;\n }, {});\n }; // Alternative approach that doesn't yield any performance gain.\n // const handlers = styles.reduce((acc, style) => {\n // style.filterProps.forEach(prop => {\n // acc[prop] = style;\n // });\n // return acc;\n // }, {});\n // const fn = props => {\n // return Object.keys(props).reduce((acc, prop) => {\n // if (handlers[prop]) {\n // return merge(acc, handlers[prop](props));\n // }\n // return acc;\n // }, {});\n // };\n\n\n fn.propTypes = process.env.NODE_ENV !== 'production' ? styles.reduce(function (acc, style) {\n return _extends(acc, style.propTypes);\n }, {}) : {};\n fn.filterProps = styles.reduce(function (acc, style) {\n return acc.concat(style.filterProps);\n }, []);\n return fn;\n}\n\nexport default compose;","import _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport responsivePropType from './responsivePropType';\nimport { handleBreakpoints } from './breakpoints';\n\nfunction getPath(obj, path) {\n if (!path || typeof path !== 'string') {\n return null;\n }\n\n return path.split('.').reduce(function (acc, item) {\n return acc && acc[item] ? acc[item] : null;\n }, obj);\n}\n\nfunction style(options) {\n var prop = options.prop,\n _options$cssProperty = options.cssProperty,\n cssProperty = _options$cssProperty === void 0 ? options.prop : _options$cssProperty,\n themeKey = options.themeKey,\n transform = options.transform;\n\n var fn = function fn(props) {\n if (props[prop] == null) {\n return null;\n }\n\n var propValue = props[prop];\n var theme = props.theme;\n var themeMapping = getPath(theme, themeKey) || {};\n\n var styleFromPropValue = function styleFromPropValue(propValueFinal) {\n var value;\n\n if (typeof themeMapping === 'function') {\n value = themeMapping(propValueFinal);\n } else if (Array.isArray(themeMapping)) {\n value = themeMapping[propValueFinal] || propValueFinal;\n } else {\n value = getPath(themeMapping, propValueFinal) || propValueFinal;\n\n if (transform) {\n value = transform(value);\n }\n }\n\n if (cssProperty === false) {\n return value;\n }\n\n return _defineProperty({}, cssProperty, value);\n };\n\n return handleBreakpoints(props, propValue, styleFromPropValue);\n };\n\n fn.propTypes = process.env.NODE_ENV !== 'production' ? _defineProperty({}, prop, responsivePropType) : {};\n fn.filterProps = [prop];\n return fn;\n}\n\nexport default style;","import style from './style';\nimport compose from './compose';\n\nfunction getBorder(value) {\n if (typeof value !== 'number') {\n return value;\n }\n\n return \"\".concat(value, \"px solid\");\n}\n\nexport var border = style({\n prop: 'border',\n themeKey: 'borders',\n transform: getBorder\n});\nexport var borderTop = style({\n prop: 'borderTop',\n themeKey: 'borders',\n transform: getBorder\n});\nexport var borderRight = style({\n prop: 'borderRight',\n themeKey: 'borders',\n transform: getBorder\n});\nexport var borderBottom = style({\n prop: 'borderBottom',\n themeKey: 'borders',\n transform: getBorder\n});\nexport var borderLeft = style({\n prop: 'borderLeft',\n themeKey: 'borders',\n transform: getBorder\n});\nexport var borderColor = style({\n prop: 'borderColor',\n themeKey: 'palette'\n});\nexport var borderRadius = style({\n prop: 'borderRadius',\n themeKey: 'shape'\n});\nvar borders = compose(border, borderTop, borderRight, borderBottom, borderLeft, borderColor, borderRadius);\nexport default borders;","import style from './style';\nimport compose from './compose';\nexport var displayPrint = style({\n prop: 'displayPrint',\n cssProperty: false,\n transform: function transform(value) {\n return {\n '@media print': {\n display: value\n }\n };\n }\n});\nexport var displayRaw = style({\n prop: 'display'\n});\nexport var overflow = style({\n prop: 'overflow'\n});\nexport var textOverflow = style({\n prop: 'textOverflow'\n});\nexport var visibility = style({\n prop: 'visibility'\n});\nexport var whiteSpace = style({\n prop: 'whiteSpace'\n});\nexport default compose(displayPrint, displayRaw, overflow, textOverflow, visibility, whiteSpace);","import style from './style';\nimport compose from './compose';\nexport var flexBasis = style({\n prop: 'flexBasis'\n});\nexport var flexDirection = style({\n prop: 'flexDirection'\n});\nexport var flexWrap = style({\n prop: 'flexWrap'\n});\nexport var justifyContent = style({\n prop: 'justifyContent'\n});\nexport var alignItems = style({\n prop: 'alignItems'\n});\nexport var alignContent = style({\n prop: 'alignContent'\n});\nexport var order = style({\n prop: 'order'\n});\nexport var flex = style({\n prop: 'flex'\n});\nexport var flexGrow = style({\n prop: 'flexGrow'\n});\nexport var flexShrink = style({\n prop: 'flexShrink'\n});\nexport var alignSelf = style({\n prop: 'alignSelf'\n});\nexport var justifyItems = style({\n prop: 'justifyItems'\n});\nexport var justifySelf = style({\n prop: 'justifySelf'\n});\nvar flexbox = compose(flexBasis, flexDirection, flexWrap, justifyContent, alignItems, alignContent, order, flex, flexGrow, flexShrink, alignSelf, justifyItems, justifySelf);\nexport default flexbox;","import style from './style';\nimport compose from './compose';\nexport var gridGap = style({\n prop: 'gridGap'\n});\nexport var gridColumnGap = style({\n prop: 'gridColumnGap'\n});\nexport var gridRowGap = style({\n prop: 'gridRowGap'\n});\nexport var gridColumn = style({\n prop: 'gridColumn'\n});\nexport var gridRow = style({\n prop: 'gridRow'\n});\nexport var gridAutoFlow = style({\n prop: 'gridAutoFlow'\n});\nexport var gridAutoColumns = style({\n prop: 'gridAutoColumns'\n});\nexport var gridAutoRows = style({\n prop: 'gridAutoRows'\n});\nexport var gridTemplateColumns = style({\n prop: 'gridTemplateColumns'\n});\nexport var gridTemplateRows = style({\n prop: 'gridTemplateRows'\n});\nexport var gridTemplateAreas = style({\n prop: 'gridTemplateAreas'\n});\nexport var gridArea = style({\n prop: 'gridArea'\n});\nvar grid = compose(gridGap, gridColumnGap, gridRowGap, gridColumn, gridRow, gridAutoFlow, gridAutoColumns, gridAutoRows, gridTemplateColumns, gridTemplateRows, gridTemplateAreas, gridArea);\nexport default grid;","import style from './style';\nimport compose from './compose';\nexport var position = style({\n prop: 'position'\n});\nexport var zIndex = style({\n prop: 'zIndex',\n themeKey: 'zIndex'\n});\nexport var top = style({\n prop: 'top'\n});\nexport var right = style({\n prop: 'right'\n});\nexport var bottom = style({\n prop: 'bottom'\n});\nexport var left = style({\n prop: 'left'\n});\nexport default compose(position, zIndex, top, right, bottom, left);","import style from './style';\nimport compose from './compose';\nexport var color = style({\n prop: 'color',\n themeKey: 'palette'\n});\nexport var bgcolor = style({\n prop: 'bgcolor',\n cssProperty: 'backgroundColor',\n themeKey: 'palette'\n});\nvar palette = compose(color, bgcolor);\nexport default palette;","import style from './style';\nvar boxShadow = style({\n prop: 'boxShadow',\n themeKey: 'shadows'\n});\nexport default boxShadow;","import style from './style';\nimport compose from './compose';\n\nfunction transform(value) {\n return value <= 1 ? \"\".concat(value * 100, \"%\") : value;\n}\n\nexport var width = style({\n prop: 'width',\n transform: transform\n});\nexport var maxWidth = style({\n prop: 'maxWidth',\n transform: transform\n});\nexport var minWidth = style({\n prop: 'minWidth',\n transform: transform\n});\nexport var height = style({\n prop: 'height',\n transform: transform\n});\nexport var maxHeight = style({\n prop: 'maxHeight',\n transform: transform\n});\nexport var minHeight = style({\n prop: 'minHeight',\n transform: transform\n});\nexport var sizeWidth = style({\n prop: 'size',\n cssProperty: 'width',\n transform: transform\n});\nexport var sizeHeight = style({\n prop: 'size',\n cssProperty: 'height',\n transform: transform\n});\nexport var boxSizing = style({\n prop: 'boxSizing'\n});\nvar sizing = compose(width, maxWidth, minWidth, height, maxHeight, minHeight, boxSizing);\nexport default sizing;","import style from './style';\nimport compose from './compose';\nexport var fontFamily = style({\n prop: 'fontFamily',\n themeKey: 'typography'\n});\nexport var fontSize = style({\n prop: 'fontSize',\n themeKey: 'typography'\n});\nexport var fontStyle = style({\n prop: 'fontStyle',\n themeKey: 'typography'\n});\nexport var fontWeight = style({\n prop: 'fontWeight',\n themeKey: 'typography'\n});\nexport var letterSpacing = style({\n prop: 'letterSpacing'\n});\nexport var lineHeight = style({\n prop: 'lineHeight'\n});\nexport var textAlign = style({\n prop: 'textAlign'\n});\nvar typography = compose(fontFamily, fontSize, fontStyle, fontWeight, letterSpacing, lineHeight, textAlign);\nexport default typography;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport React from 'react';\nimport clsx from 'clsx';\nimport PropTypes from 'prop-types';\nimport { chainPropTypes, getDisplayName } from '@material-ui/utils';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport makeStyles from '../makeStyles';\n\nfunction omit(input, fields) {\n var output = {};\n Object.keys(input).forEach(function (prop) {\n if (fields.indexOf(prop) === -1) {\n output[prop] = input[prop];\n }\n });\n return output;\n} // styled-components's API removes the mapping between components and styles.\n// Using components as a low-level styling construct can be simpler.\n\n\nexport default function styled(Component) {\n var componentCreator = function componentCreator(style) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n var name = options.name,\n stylesOptions = _objectWithoutProperties(options, [\"name\"]);\n\n if (process.env.NODE_ENV !== 'production' && Component === undefined) {\n throw new Error(['You are calling styled(Component)(style) with an undefined component.', 'You may have forgotten to import it.'].join('\\n'));\n }\n\n var classNamePrefix = name;\n\n if (process.env.NODE_ENV !== 'production') {\n if (!name) {\n // Provide a better DX outside production.\n var displayName = getDisplayName(Component);\n\n if (displayName !== undefined) {\n classNamePrefix = displayName;\n }\n }\n }\n\n var stylesOrCreator = typeof style === 'function' ? function (theme) {\n return {\n root: function root(props) {\n return style(_extends({\n theme: theme\n }, props));\n }\n };\n } : {\n root: style\n };\n var useStyles = makeStyles(stylesOrCreator, _extends({\n Component: Component,\n name: name || Component.displayName,\n classNamePrefix: classNamePrefix\n }, stylesOptions));\n var filterProps;\n var propTypes = {};\n\n if (style.filterProps) {\n filterProps = style.filterProps;\n delete style.filterProps;\n }\n /* eslint-disable react/forbid-foreign-prop-types */\n\n\n if (style.propTypes) {\n propTypes = style.propTypes;\n delete style.propTypes;\n }\n /* eslint-enable react/forbid-foreign-prop-types */\n\n\n var StyledComponent = /*#__PURE__*/React.forwardRef(function StyledComponent(props, ref) {\n var children = props.children,\n classNameProp = props.className,\n clone = props.clone,\n ComponentProp = props.component,\n other = _objectWithoutProperties(props, [\"children\", \"className\", \"clone\", \"component\"]);\n\n var classes = useStyles(props);\n var className = clsx(classes.root, classNameProp);\n var spread = other;\n\n if (filterProps) {\n spread = omit(spread, filterProps);\n }\n\n if (clone) {\n return /*#__PURE__*/React.cloneElement(children, _extends({\n className: clsx(children.props.className, className)\n }, spread));\n }\n\n if (typeof children === 'function') {\n return children(_extends({\n className: className\n }, spread));\n }\n\n var FinalComponent = ComponentProp || Component;\n return /*#__PURE__*/React.createElement(FinalComponent, _extends({\n ref: ref,\n className: className\n }, spread), children);\n });\n process.env.NODE_ENV !== \"production\" ? StyledComponent.propTypes = _extends({\n /**\n * A render function or node.\n */\n children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * If `true`, the component will recycle it's children HTML element.\n * It's using `React.cloneElement` internally.\n *\n * This prop will be deprecated and removed in v5\n */\n clone: chainPropTypes(PropTypes.bool, function (props) {\n if (props.clone && props.component) {\n return new Error('You can not use the clone and component prop at the same time.');\n }\n\n return null;\n }),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType\n }, propTypes) : void 0;\n\n if (process.env.NODE_ENV !== 'production') {\n StyledComponent.displayName = \"Styled(\".concat(classNamePrefix, \")\");\n }\n\n hoistNonReactStatics(StyledComponent, Component);\n return StyledComponent;\n };\n\n return componentCreator;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport { styled as styledWithoutDefault } from '@material-ui/styles';\nimport defaultTheme from './defaultTheme';\n\nvar styled = function styled(Component) {\n var componentCreator = styledWithoutDefault(Component);\n return function (style, options) {\n return componentCreator(style, _extends({\n defaultTheme: defaultTheme\n }, options));\n };\n};\n\nexport default styled;","import { borders, compose, display, flexbox, grid, palette, positions, shadows, sizing, spacing, typography, css } from '@material-ui/system';\nimport styled from '../styles/styled';\nexport var styleFunction = css(compose(borders, display, flexbox, grid, positions, palette, shadows, sizing, spacing, typography));\n/**\n * @ignore - do not document.\n */\n\nvar Box = styled('div')(styleFunction, {\n name: 'MuiBox'\n});\nexport default Box;","// Source from https://github.com/alitaheri/normalize-scroll-left\nvar cachedType;\n/**\n * Based on the jquery plugin https://github.com/othree/jquery.rtl-scroll-type\n *\n * Types of scrollLeft, assuming scrollWidth=100 and direction is rtl.\n *\n * Type | <- Most Left | Most Right -> | Initial\n * ---------------- | ------------ | ------------- | -------\n * default | 0 | 100 | 100\n * negative (spec*) | -100 | 0 | 0\n * reverse | 100 | 0 | 0\n *\n * Edge 85: default\n * Safari 14: negative\n * Chrome 85: negative\n * Firefox 81: negative\n * IE 11: reverse\n *\n * spec* https://drafts.csswg.org/cssom-view/#dom-window-scroll\n */\n\nexport function detectScrollType() {\n if (cachedType) {\n return cachedType;\n }\n\n var dummy = document.createElement('div');\n var container = document.createElement('div');\n container.style.width = '10px';\n container.style.height = '1px';\n dummy.appendChild(container);\n dummy.dir = 'rtl';\n dummy.style.fontSize = '14px';\n dummy.style.width = '4px';\n dummy.style.height = '1px';\n dummy.style.position = 'absolute';\n dummy.style.top = '-1000px';\n dummy.style.overflow = 'scroll';\n document.body.appendChild(dummy);\n cachedType = 'reverse';\n\n if (dummy.scrollLeft > 0) {\n cachedType = 'default';\n } else {\n dummy.scrollLeft = 1;\n\n if (dummy.scrollLeft === 0) {\n cachedType = 'negative';\n }\n }\n\n document.body.removeChild(dummy);\n return cachedType;\n} // Based on https://stackoverflow.com/a/24394376\n\nexport function getNormalizedScrollLeft(element, direction) {\n var scrollLeft = element.scrollLeft; // Perform the calculations only when direction is rtl to avoid messing up the ltr bahavior\n\n if (direction !== 'rtl') {\n return scrollLeft;\n }\n\n var type = detectScrollType();\n\n switch (type) {\n case 'negative':\n return element.scrollWidth - element.clientWidth + scrollLeft;\n\n case 'reverse':\n return element.scrollWidth - element.clientWidth - scrollLeft;\n\n default:\n return scrollLeft;\n }\n}","function easeInOutSin(time) {\n return (1 + Math.sin(Math.PI * time - Math.PI / 2)) / 2;\n}\n\nexport default function animate(property, element, to) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var cb = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : function () {};\n var _options$ease = options.ease,\n ease = _options$ease === void 0 ? easeInOutSin : _options$ease,\n _options$duration = options.duration,\n duration = _options$duration === void 0 ? 300 : _options$duration;\n var start = null;\n var from = element[property];\n var cancelled = false;\n\n var cancel = function cancel() {\n cancelled = true;\n };\n\n var step = function step(timestamp) {\n if (cancelled) {\n cb(new Error('Animation cancelled'));\n return;\n }\n\n if (start === null) {\n start = timestamp;\n }\n\n var time = Math.min(1, (timestamp - start) / duration);\n element[property] = ease(time) * (to - from) + from;\n\n if (time >= 1) {\n requestAnimationFrame(function () {\n cb(null);\n });\n return;\n }\n\n requestAnimationFrame(step);\n };\n\n if (from === to) {\n cb(new Error('Element already at target position'));\n return cancel;\n }\n\n requestAnimationFrame(step);\n return cancel;\n}","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport debounce from '../utils/debounce';\nvar styles = {\n width: 99,\n height: 99,\n position: 'absolute',\n top: -9999,\n overflow: 'scroll'\n};\n/**\n * @ignore - internal component.\n * The component originates from https://github.com/STORIS/react-scrollbar-size.\n * It has been moved into the core in order to minimize the bundle size.\n */\n\nexport default function ScrollbarSize(props) {\n var onChange = props.onChange,\n other = _objectWithoutProperties(props, [\"onChange\"]);\n\n var scrollbarHeight = React.useRef();\n var nodeRef = React.useRef(null);\n\n var setMeasurements = function setMeasurements() {\n scrollbarHeight.current = nodeRef.current.offsetHeight - nodeRef.current.clientHeight;\n };\n\n React.useEffect(function () {\n var handleResize = debounce(function () {\n var prevHeight = scrollbarHeight.current;\n setMeasurements();\n\n if (prevHeight !== scrollbarHeight.current) {\n onChange(scrollbarHeight.current);\n }\n });\n window.addEventListener('resize', handleResize);\n return function () {\n handleResize.clear();\n window.removeEventListener('resize', handleResize);\n };\n }, [onChange]);\n React.useEffect(function () {\n setMeasurements();\n onChange(scrollbarHeight.current);\n }, [onChange]);\n return /*#__PURE__*/React.createElement(\"div\", _extends({\n style: styles,\n ref: nodeRef\n }, other));\n}\nprocess.env.NODE_ENV !== \"production\" ? ScrollbarSize.propTypes = {\n onChange: PropTypes.func.isRequired\n} : void 0;","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport capitalize from '../utils/capitalize';\nexport var styles = function styles(theme) {\n return {\n root: {\n position: 'absolute',\n height: 2,\n bottom: 0,\n width: '100%',\n transition: theme.transitions.create()\n },\n colorPrimary: {\n backgroundColor: theme.palette.primary.main\n },\n colorSecondary: {\n backgroundColor: theme.palette.secondary.main\n },\n vertical: {\n height: '100%',\n width: 2,\n right: 0\n }\n };\n};\n/**\n * @ignore - internal component.\n */\n\nvar TabIndicator = /*#__PURE__*/React.forwardRef(function TabIndicator(props, ref) {\n var classes = props.classes,\n className = props.className,\n color = props.color,\n orientation = props.orientation,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"color\", \"orientation\"]);\n\n return /*#__PURE__*/React.createElement(\"span\", _extends({\n className: clsx(classes.root, classes[\"color\".concat(capitalize(color))], className, orientation === 'vertical' && classes.vertical),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? TabIndicator.propTypes = {\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * @ignore\n * The color of the tab indicator.\n */\n color: PropTypes.oneOf(['primary', 'secondary']).isRequired,\n\n /**\n * The tabs orientation (layout flow direction).\n */\n orientation: PropTypes.oneOf(['horizontal', 'vertical']).isRequired\n} : void 0;\nexport default withStyles(styles, {\n name: 'PrivateTabIndicator'\n})(TabIndicator);","import * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n/**\n * @ignore - internal component.\n */\n\nexport default createSvgIcon( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z\"\n}), 'KeyboardArrowLeft');","import * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n/**\n * @ignore - internal component.\n */\n\nexport default createSvgIcon( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z\"\n}), 'KeyboardArrowRight');","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\n\n/* eslint-disable jsx-a11y/aria-role */\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport KeyboardArrowLeft from '../internal/svg-icons/KeyboardArrowLeft';\nimport KeyboardArrowRight from '../internal/svg-icons/KeyboardArrowRight';\nimport withStyles from '../styles/withStyles';\nimport ButtonBase from '../ButtonBase';\nexport var styles = {\n /* Styles applied to the root element. */\n root: {\n width: 40,\n flexShrink: 0,\n opacity: 0.8,\n '&$disabled': {\n opacity: 0\n }\n },\n\n /* Styles applied to the root element if `orientation=\"vertical\"`. */\n vertical: {\n width: '100%',\n height: 40,\n '& svg': {\n transform: 'rotate(90deg)'\n }\n },\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {}\n};\n\nvar _ref = /*#__PURE__*/React.createElement(KeyboardArrowLeft, {\n fontSize: \"small\"\n});\n\nvar _ref2 = /*#__PURE__*/React.createElement(KeyboardArrowRight, {\n fontSize: \"small\"\n});\n\nvar TabScrollButton = /*#__PURE__*/React.forwardRef(function TabScrollButton(props, ref) {\n var classes = props.classes,\n classNameProp = props.className,\n direction = props.direction,\n orientation = props.orientation,\n disabled = props.disabled,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"direction\", \"orientation\", \"disabled\"]);\n\n return /*#__PURE__*/React.createElement(ButtonBase, _extends({\n component: \"div\",\n className: clsx(classes.root, classNameProp, disabled && classes.disabled, orientation === 'vertical' && classes.vertical),\n ref: ref,\n role: null,\n tabIndex: null\n }, other), direction === 'left' ? _ref : _ref2);\n});\nprocess.env.NODE_ENV !== \"production\" ? TabScrollButton.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * Which direction should the button indicate?\n */\n direction: PropTypes.oneOf(['left', 'right']).isRequired,\n\n /**\n * If `true`, the element will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * The tabs orientation (layout flow direction).\n */\n orientation: PropTypes.oneOf(['horizontal', 'vertical']).isRequired\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTabScrollButton'\n})(TabScrollButton);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport * as React from 'react';\nimport { isFragment } from 'react-is';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { refType } from '@material-ui/utils';\nimport debounce from '../utils/debounce';\nimport ownerWindow from '../utils/ownerWindow';\nimport { getNormalizedScrollLeft, detectScrollType } from '../utils/scrollLeft';\nimport animate from '../internal/animate';\nimport ScrollbarSize from './ScrollbarSize';\nimport withStyles from '../styles/withStyles';\nimport TabIndicator from './TabIndicator';\nimport TabScrollButton from '../TabScrollButton';\nimport useEventCallback from '../utils/useEventCallback';\nimport useTheme from '../styles/useTheme';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n overflow: 'hidden',\n minHeight: 48,\n WebkitOverflowScrolling: 'touch',\n // Add iOS momentum scrolling.\n display: 'flex'\n },\n\n /* Styles applied to the root element if `orientation=\"vertical\"`. */\n vertical: {\n flexDirection: 'column'\n },\n\n /* Styles applied to the flex container element. */\n flexContainer: {\n display: 'flex'\n },\n\n /* Styles applied to the flex container element if `orientation=\"vertical\"`. */\n flexContainerVertical: {\n flexDirection: 'column'\n },\n\n /* Styles applied to the flex container element if `centered={true}` & `!variant=\"scrollable\"`. */\n centered: {\n justifyContent: 'center'\n },\n\n /* Styles applied to the tablist element. */\n scroller: {\n position: 'relative',\n display: 'inline-block',\n flex: '1 1 auto',\n whiteSpace: 'nowrap'\n },\n\n /* Styles applied to the tablist element if `!variant=\"scrollable\"`\b\b\b. */\n fixed: {\n overflowX: 'hidden',\n width: '100%'\n },\n\n /* Styles applied to the tablist element if `variant=\"scrollable\"`. */\n scrollable: {\n overflowX: 'scroll',\n // Hide dimensionless scrollbar on MacOS\n scrollbarWidth: 'none',\n // Firefox\n '&::-webkit-scrollbar': {\n display: 'none' // Safari + Chrome\n\n }\n },\n\n /* Styles applied to the `ScrollButtonComponent` component. */\n scrollButtons: {},\n\n /* Styles applied to the `ScrollButtonComponent` component if `scrollButtons=\"auto\"` or scrollButtons=\"desktop\"`. */\n scrollButtonsDesktop: _defineProperty({}, theme.breakpoints.down('xs'), {\n display: 'none'\n }),\n\n /* Styles applied to the `TabIndicator` component. */\n indicator: {}\n };\n};\nvar Tabs = /*#__PURE__*/React.forwardRef(function Tabs(props, ref) {\n var ariaLabel = props['aria-label'],\n ariaLabelledBy = props['aria-labelledby'],\n action = props.action,\n _props$centered = props.centered,\n centered = _props$centered === void 0 ? false : _props$centered,\n childrenProp = props.children,\n classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n _props$indicatorColor = props.indicatorColor,\n indicatorColor = _props$indicatorColor === void 0 ? 'secondary' : _props$indicatorColor,\n onChange = props.onChange,\n _props$orientation = props.orientation,\n orientation = _props$orientation === void 0 ? 'horizontal' : _props$orientation,\n _props$ScrollButtonCo = props.ScrollButtonComponent,\n ScrollButtonComponent = _props$ScrollButtonCo === void 0 ? TabScrollButton : _props$ScrollButtonCo,\n _props$scrollButtons = props.scrollButtons,\n scrollButtons = _props$scrollButtons === void 0 ? 'auto' : _props$scrollButtons,\n selectionFollowsFocus = props.selectionFollowsFocus,\n _props$TabIndicatorPr = props.TabIndicatorProps,\n TabIndicatorProps = _props$TabIndicatorPr === void 0 ? {} : _props$TabIndicatorPr,\n TabScrollButtonProps = props.TabScrollButtonProps,\n _props$textColor = props.textColor,\n textColor = _props$textColor === void 0 ? 'inherit' : _props$textColor,\n value = props.value,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'standard' : _props$variant,\n other = _objectWithoutProperties(props, [\"aria-label\", \"aria-labelledby\", \"action\", \"centered\", \"children\", \"classes\", \"className\", \"component\", \"indicatorColor\", \"onChange\", \"orientation\", \"ScrollButtonComponent\", \"scrollButtons\", \"selectionFollowsFocus\", \"TabIndicatorProps\", \"TabScrollButtonProps\", \"textColor\", \"value\", \"variant\"]);\n\n var theme = useTheme();\n var scrollable = variant === 'scrollable';\n var isRtl = theme.direction === 'rtl';\n var vertical = orientation === 'vertical';\n var scrollStart = vertical ? 'scrollTop' : 'scrollLeft';\n var start = vertical ? 'top' : 'left';\n var end = vertical ? 'bottom' : 'right';\n var clientSize = vertical ? 'clientHeight' : 'clientWidth';\n var size = vertical ? 'height' : 'width';\n\n if (process.env.NODE_ENV !== 'production') {\n if (centered && scrollable) {\n console.error('Material-UI: You can not use the `centered={true}` and `variant=\"scrollable\"` properties ' + 'at the same time on a `Tabs` component.');\n }\n }\n\n var _React$useState = React.useState(false),\n mounted = _React$useState[0],\n setMounted = _React$useState[1];\n\n var _React$useState2 = React.useState({}),\n indicatorStyle = _React$useState2[0],\n setIndicatorStyle = _React$useState2[1];\n\n var _React$useState3 = React.useState({\n start: false,\n end: false\n }),\n displayScroll = _React$useState3[0],\n setDisplayScroll = _React$useState3[1];\n\n var _React$useState4 = React.useState({\n overflow: 'hidden',\n marginBottom: null\n }),\n scrollerStyle = _React$useState4[0],\n setScrollerStyle = _React$useState4[1];\n\n var valueToIndex = new Map();\n var tabsRef = React.useRef(null);\n var tabListRef = React.useRef(null);\n\n var getTabsMeta = function getTabsMeta() {\n var tabsNode = tabsRef.current;\n var tabsMeta;\n\n if (tabsNode) {\n var rect = tabsNode.getBoundingClientRect(); // create a new object with ClientRect class props + scrollLeft\n\n tabsMeta = {\n clientWidth: tabsNode.clientWidth,\n scrollLeft: tabsNode.scrollLeft,\n scrollTop: tabsNode.scrollTop,\n scrollLeftNormalized: getNormalizedScrollLeft(tabsNode, theme.direction),\n scrollWidth: tabsNode.scrollWidth,\n top: rect.top,\n bottom: rect.bottom,\n left: rect.left,\n right: rect.right\n };\n }\n\n var tabMeta;\n\n if (tabsNode && value !== false) {\n var _children = tabListRef.current.children;\n\n if (_children.length > 0) {\n var tab = _children[valueToIndex.get(value)];\n\n if (process.env.NODE_ENV !== 'production') {\n if (!tab) {\n console.error([\"Material-UI: The value provided to the Tabs component is invalid.\", \"None of the Tabs' children match with `\".concat(value, \"`.\"), valueToIndex.keys ? \"You can provide one of the following values: \".concat(Array.from(valueToIndex.keys()).join(', '), \".\") : null].join('\\n'));\n }\n }\n\n tabMeta = tab ? tab.getBoundingClientRect() : null;\n }\n }\n\n return {\n tabsMeta: tabsMeta,\n tabMeta: tabMeta\n };\n };\n\n var updateIndicatorState = useEventCallback(function () {\n var _newIndicatorStyle;\n\n var _getTabsMeta = getTabsMeta(),\n tabsMeta = _getTabsMeta.tabsMeta,\n tabMeta = _getTabsMeta.tabMeta;\n\n var startValue = 0;\n\n if (tabMeta && tabsMeta) {\n if (vertical) {\n startValue = tabMeta.top - tabsMeta.top + tabsMeta.scrollTop;\n } else {\n var correction = isRtl ? tabsMeta.scrollLeftNormalized + tabsMeta.clientWidth - tabsMeta.scrollWidth : tabsMeta.scrollLeft;\n startValue = tabMeta.left - tabsMeta.left + correction;\n }\n }\n\n var newIndicatorStyle = (_newIndicatorStyle = {}, _defineProperty(_newIndicatorStyle, start, startValue), _defineProperty(_newIndicatorStyle, size, tabMeta ? tabMeta[size] : 0), _newIndicatorStyle);\n\n if (isNaN(indicatorStyle[start]) || isNaN(indicatorStyle[size])) {\n setIndicatorStyle(newIndicatorStyle);\n } else {\n var dStart = Math.abs(indicatorStyle[start] - newIndicatorStyle[start]);\n var dSize = Math.abs(indicatorStyle[size] - newIndicatorStyle[size]);\n\n if (dStart >= 1 || dSize >= 1) {\n setIndicatorStyle(newIndicatorStyle);\n }\n }\n });\n\n var scroll = function scroll(scrollValue) {\n animate(scrollStart, tabsRef.current, scrollValue);\n };\n\n var moveTabsScroll = function moveTabsScroll(delta) {\n var scrollValue = tabsRef.current[scrollStart];\n\n if (vertical) {\n scrollValue += delta;\n } else {\n scrollValue += delta * (isRtl ? -1 : 1); // Fix for Edge\n\n scrollValue *= isRtl && detectScrollType() === 'reverse' ? -1 : 1;\n }\n\n scroll(scrollValue);\n };\n\n var handleStartScrollClick = function handleStartScrollClick() {\n moveTabsScroll(-tabsRef.current[clientSize]);\n };\n\n var handleEndScrollClick = function handleEndScrollClick() {\n moveTabsScroll(tabsRef.current[clientSize]);\n };\n\n var handleScrollbarSizeChange = React.useCallback(function (scrollbarHeight) {\n setScrollerStyle({\n overflow: null,\n marginBottom: -scrollbarHeight\n });\n }, []);\n\n var getConditionalElements = function getConditionalElements() {\n var conditionalElements = {};\n conditionalElements.scrollbarSizeListener = scrollable ? /*#__PURE__*/React.createElement(ScrollbarSize, {\n className: classes.scrollable,\n onChange: handleScrollbarSizeChange\n }) : null;\n var scrollButtonsActive = displayScroll.start || displayScroll.end;\n var showScrollButtons = scrollable && (scrollButtons === 'auto' && scrollButtonsActive || scrollButtons === 'desktop' || scrollButtons === 'on');\n conditionalElements.scrollButtonStart = showScrollButtons ? /*#__PURE__*/React.createElement(ScrollButtonComponent, _extends({\n orientation: orientation,\n direction: isRtl ? 'right' : 'left',\n onClick: handleStartScrollClick,\n disabled: !displayScroll.start,\n className: clsx(classes.scrollButtons, scrollButtons !== 'on' && classes.scrollButtonsDesktop)\n }, TabScrollButtonProps)) : null;\n conditionalElements.scrollButtonEnd = showScrollButtons ? /*#__PURE__*/React.createElement(ScrollButtonComponent, _extends({\n orientation: orientation,\n direction: isRtl ? 'left' : 'right',\n onClick: handleEndScrollClick,\n disabled: !displayScroll.end,\n className: clsx(classes.scrollButtons, scrollButtons !== 'on' && classes.scrollButtonsDesktop)\n }, TabScrollButtonProps)) : null;\n return conditionalElements;\n };\n\n var scrollSelectedIntoView = useEventCallback(function () {\n var _getTabsMeta2 = getTabsMeta(),\n tabsMeta = _getTabsMeta2.tabsMeta,\n tabMeta = _getTabsMeta2.tabMeta;\n\n if (!tabMeta || !tabsMeta) {\n return;\n }\n\n if (tabMeta[start] < tabsMeta[start]) {\n // left side of button is out of view\n var nextScrollStart = tabsMeta[scrollStart] + (tabMeta[start] - tabsMeta[start]);\n scroll(nextScrollStart);\n } else if (tabMeta[end] > tabsMeta[end]) {\n // right side of button is out of view\n var _nextScrollStart = tabsMeta[scrollStart] + (tabMeta[end] - tabsMeta[end]);\n\n scroll(_nextScrollStart);\n }\n });\n var updateScrollButtonState = useEventCallback(function () {\n if (scrollable && scrollButtons !== 'off') {\n var _tabsRef$current = tabsRef.current,\n scrollTop = _tabsRef$current.scrollTop,\n scrollHeight = _tabsRef$current.scrollHeight,\n clientHeight = _tabsRef$current.clientHeight,\n scrollWidth = _tabsRef$current.scrollWidth,\n clientWidth = _tabsRef$current.clientWidth;\n var showStartScroll;\n var showEndScroll;\n\n if (vertical) {\n showStartScroll = scrollTop > 1;\n showEndScroll = scrollTop < scrollHeight - clientHeight - 1;\n } else {\n var scrollLeft = getNormalizedScrollLeft(tabsRef.current, theme.direction); // use 1 for the potential rounding error with browser zooms.\n\n showStartScroll = isRtl ? scrollLeft < scrollWidth - clientWidth - 1 : scrollLeft > 1;\n showEndScroll = !isRtl ? scrollLeft < scrollWidth - clientWidth - 1 : scrollLeft > 1;\n }\n\n if (showStartScroll !== displayScroll.start || showEndScroll !== displayScroll.end) {\n setDisplayScroll({\n start: showStartScroll,\n end: showEndScroll\n });\n }\n }\n });\n React.useEffect(function () {\n var handleResize = debounce(function () {\n updateIndicatorState();\n updateScrollButtonState();\n });\n var win = ownerWindow(tabsRef.current);\n win.addEventListener('resize', handleResize);\n return function () {\n handleResize.clear();\n win.removeEventListener('resize', handleResize);\n };\n }, [updateIndicatorState, updateScrollButtonState]);\n var handleTabsScroll = React.useCallback(debounce(function () {\n updateScrollButtonState();\n }));\n React.useEffect(function () {\n return function () {\n handleTabsScroll.clear();\n };\n }, [handleTabsScroll]);\n React.useEffect(function () {\n setMounted(true);\n }, []);\n React.useEffect(function () {\n updateIndicatorState();\n updateScrollButtonState();\n });\n React.useEffect(function () {\n scrollSelectedIntoView();\n }, [scrollSelectedIntoView, indicatorStyle]);\n React.useImperativeHandle(action, function () {\n return {\n updateIndicator: updateIndicatorState,\n updateScrollButtons: updateScrollButtonState\n };\n }, [updateIndicatorState, updateScrollButtonState]);\n var indicator = /*#__PURE__*/React.createElement(TabIndicator, _extends({\n className: classes.indicator,\n orientation: orientation,\n color: indicatorColor\n }, TabIndicatorProps, {\n style: _extends({}, indicatorStyle, TabIndicatorProps.style)\n }));\n var childIndex = 0;\n var children = React.Children.map(childrenProp, function (child) {\n if (! /*#__PURE__*/React.isValidElement(child)) {\n return null;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (isFragment(child)) {\n console.error([\"Material-UI: The Tabs component doesn't accept a Fragment as a child.\", 'Consider providing an array instead.'].join('\\n'));\n }\n }\n\n var childValue = child.props.value === undefined ? childIndex : child.props.value;\n valueToIndex.set(childValue, childIndex);\n var selected = childValue === value;\n childIndex += 1;\n return /*#__PURE__*/React.cloneElement(child, {\n fullWidth: variant === 'fullWidth',\n indicator: selected && !mounted && indicator,\n selected: selected,\n selectionFollowsFocus: selectionFollowsFocus,\n onChange: onChange,\n textColor: textColor,\n value: childValue\n });\n });\n\n var handleKeyDown = function handleKeyDown(event) {\n var target = event.target; // Keyboard navigation assumes that [role=\"tab\"] are siblings\n // though we might warn in the future about nested, interactive elements\n // as a a11y violation\n\n var role = target.getAttribute('role');\n\n if (role !== 'tab') {\n return;\n }\n\n var newFocusTarget = null;\n var previousItemKey = orientation !== \"vertical\" ? 'ArrowLeft' : 'ArrowUp';\n var nextItemKey = orientation !== \"vertical\" ? 'ArrowRight' : 'ArrowDown';\n\n if (orientation !== \"vertical\" && theme.direction === 'rtl') {\n // swap previousItemKey with nextItemKey\n previousItemKey = 'ArrowRight';\n nextItemKey = 'ArrowLeft';\n }\n\n switch (event.key) {\n case previousItemKey:\n newFocusTarget = target.previousElementSibling || tabListRef.current.lastChild;\n break;\n\n case nextItemKey:\n newFocusTarget = target.nextElementSibling || tabListRef.current.firstChild;\n break;\n\n case 'Home':\n newFocusTarget = tabListRef.current.firstChild;\n break;\n\n case 'End':\n newFocusTarget = tabListRef.current.lastChild;\n break;\n\n default:\n break;\n }\n\n if (newFocusTarget !== null) {\n newFocusTarget.focus();\n event.preventDefault();\n }\n };\n\n var conditionalElements = getConditionalElements();\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, className, vertical && classes.vertical),\n ref: ref\n }, other), conditionalElements.scrollButtonStart, conditionalElements.scrollbarSizeListener, /*#__PURE__*/React.createElement(\"div\", {\n className: clsx(classes.scroller, scrollable ? classes.scrollable : classes.fixed),\n style: scrollerStyle,\n ref: tabsRef,\n onScroll: handleTabsScroll\n }, /*#__PURE__*/React.createElement(\"div\", {\n \"aria-label\": ariaLabel,\n \"aria-labelledby\": ariaLabelledBy,\n className: clsx(classes.flexContainer, vertical && classes.flexContainerVertical, centered && !scrollable && classes.centered),\n onKeyDown: handleKeyDown,\n ref: tabListRef,\n role: \"tablist\"\n }, children), mounted && indicator), conditionalElements.scrollButtonEnd);\n});\nprocess.env.NODE_ENV !== \"production\" ? Tabs.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * Callback fired when the component mounts.\n * This is useful when you want to trigger an action programmatically.\n * It supports two actions: `updateIndicator()` and `updateScrollButtons()`\n *\n * @param {object} actions This object contains all possible actions\n * that can be triggered programmatically.\n */\n action: refType,\n\n /**\n * The label for the Tabs as a string.\n */\n 'aria-label': PropTypes.string,\n\n /**\n * An id or list of ids separated by a space that label the Tabs.\n */\n 'aria-labelledby': PropTypes.string,\n\n /**\n * If `true`, the tabs will be centered.\n * This property is intended for large views.\n */\n centered: PropTypes.bool,\n\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * Determines the color of the indicator.\n */\n indicatorColor: PropTypes.oneOf(['primary', 'secondary']),\n\n /**\n * Callback fired when the value changes.\n *\n * @param {object} event The event source of the callback\n * @param {any} value We default to the index of the child (number)\n */\n onChange: PropTypes.func,\n\n /**\n * The tabs orientation (layout flow direction).\n */\n orientation: PropTypes.oneOf(['horizontal', 'vertical']),\n\n /**\n * The component used to render the scroll buttons.\n */\n ScrollButtonComponent: PropTypes.elementType,\n\n /**\n * Determine behavior of scroll buttons when tabs are set to scroll:\n *\n * - `auto` will only present them when not all the items are visible.\n * - `desktop` will only present them on medium and larger viewports.\n * - `on` will always present them.\n * - `off` will never present them.\n */\n scrollButtons: PropTypes.oneOf(['auto', 'desktop', 'off', 'on']),\n\n /**\n * If `true` the selected tab changes on focus. Otherwise it only\n * changes on activation.\n */\n selectionFollowsFocus: PropTypes.bool,\n\n /**\n * Props applied to the tab indicator element.\n */\n TabIndicatorProps: PropTypes.object,\n\n /**\n * Props applied to the [`TabScrollButton`](/api/tab-scroll-button/) element.\n */\n TabScrollButtonProps: PropTypes.object,\n\n /**\n * Determines the color of the `Tab`.\n */\n textColor: PropTypes.oneOf(['inherit', 'primary', 'secondary']),\n\n /**\n * The value of the currently selected `Tab`.\n * If you don't want any selected `Tab`, you can set this property to `false`.\n */\n value: PropTypes.any,\n\n /**\n * Determines additional display behavior of the tabs:\n *\n * - `scrollable` will invoke scrolling properties and allow for horizontally\n * scrolling (or swiping) of the tab bar.\n * -`fullWidth` will make the tabs grow to use all the available space,\n * which should be used for small views, like on mobile.\n * - `standard` will render the default state.\n */\n variant: PropTypes.oneOf(['fullWidth', 'scrollable', 'standard'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiTabs'\n})(Tabs);","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nimport ButtonBase from '../ButtonBase';\nimport isMuiElement from '../utils/isMuiElement';\nimport useForkRef from '../utils/useForkRef';\nimport ListContext from '../List/ListContext';\nimport * as ReactDOM from 'react-dom';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */\n root: {\n display: 'flex',\n justifyContent: 'flex-start',\n alignItems: 'center',\n position: 'relative',\n textDecoration: 'none',\n width: '100%',\n boxSizing: 'border-box',\n textAlign: 'left',\n paddingTop: 8,\n paddingBottom: 8,\n '&$focusVisible': {\n backgroundColor: theme.palette.action.selected\n },\n '&$selected, &$selected:hover': {\n backgroundColor: theme.palette.action.selected\n },\n '&$disabled': {\n opacity: 0.5\n }\n },\n\n /* Styles applied to the `container` element if `children` includes `ListItemSecondaryAction`. */\n container: {\n position: 'relative'\n },\n\n /* Pseudo-class applied to the `component`'s `focusVisibleClassName` prop if `button={true}`. */\n focusVisible: {},\n\n /* Styles applied to the `component` element if dense. */\n dense: {\n paddingTop: 4,\n paddingBottom: 4\n },\n\n /* Styles applied to the `component` element if `alignItems=\"flex-start\"`. */\n alignItemsFlexStart: {\n alignItems: 'flex-start'\n },\n\n /* Pseudo-class applied to the inner `component` element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the inner `component` element if `divider={true}`. */\n divider: {\n borderBottom: \"1px solid \".concat(theme.palette.divider),\n backgroundClip: 'padding-box'\n },\n\n /* Styles applied to the inner `component` element if `disableGutters={false}`. */\n gutters: {\n paddingLeft: 16,\n paddingRight: 16\n },\n\n /* Styles applied to the inner `component` element if `button={true}`. */\n button: {\n transition: theme.transitions.create('background-color', {\n duration: theme.transitions.duration.shortest\n }),\n '&:hover': {\n textDecoration: 'none',\n backgroundColor: theme.palette.action.hover,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n }\n },\n\n /* Styles applied to the `component` element if `children` includes `ListItemSecondaryAction`. */\n secondaryAction: {\n // Add some space to avoid collision as `ListItemSecondaryAction`\n // is absolutely positioned.\n paddingRight: 48\n },\n\n /* Pseudo-class applied to the root element if `selected={true}`. */\n selected: {}\n };\n};\nvar useEnhancedEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;\n/**\n * Uses an additional container component if `ListItemSecondaryAction` is the last child.\n */\n\nvar ListItem = /*#__PURE__*/React.forwardRef(function ListItem(props, ref) {\n var _props$alignItems = props.alignItems,\n alignItems = _props$alignItems === void 0 ? 'center' : _props$alignItems,\n _props$autoFocus = props.autoFocus,\n autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,\n _props$button = props.button,\n button = _props$button === void 0 ? false : _props$button,\n childrenProp = props.children,\n classes = props.classes,\n className = props.className,\n componentProp = props.component,\n _props$ContainerCompo = props.ContainerComponent,\n ContainerComponent = _props$ContainerCompo === void 0 ? 'li' : _props$ContainerCompo,\n _props$ContainerProps = props.ContainerProps;\n _props$ContainerProps = _props$ContainerProps === void 0 ? {} : _props$ContainerProps;\n\n var ContainerClassName = _props$ContainerProps.className,\n ContainerProps = _objectWithoutProperties(_props$ContainerProps, [\"className\"]),\n _props$dense = props.dense,\n dense = _props$dense === void 0 ? false : _props$dense,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n _props$disableGutters = props.disableGutters,\n disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters,\n _props$divider = props.divider,\n divider = _props$divider === void 0 ? false : _props$divider,\n focusVisibleClassName = props.focusVisibleClassName,\n _props$selected = props.selected,\n selected = _props$selected === void 0 ? false : _props$selected,\n other = _objectWithoutProperties(props, [\"alignItems\", \"autoFocus\", \"button\", \"children\", \"classes\", \"className\", \"component\", \"ContainerComponent\", \"ContainerProps\", \"dense\", \"disabled\", \"disableGutters\", \"divider\", \"focusVisibleClassName\", \"selected\"]);\n\n var context = React.useContext(ListContext);\n var childContext = {\n dense: dense || context.dense || false,\n alignItems: alignItems\n };\n var listItemRef = React.useRef(null);\n useEnhancedEffect(function () {\n if (autoFocus) {\n if (listItemRef.current) {\n listItemRef.current.focus();\n } else if (process.env.NODE_ENV !== 'production') {\n console.error('Material-UI: Unable to set focus to a ListItem whose component has not been rendered.');\n }\n }\n }, [autoFocus]);\n var children = React.Children.toArray(childrenProp);\n var hasSecondaryAction = children.length && isMuiElement(children[children.length - 1], ['ListItemSecondaryAction']);\n var handleOwnRef = React.useCallback(function (instance) {\n // #StrictMode ready\n listItemRef.current = ReactDOM.findDOMNode(instance);\n }, []);\n var handleRef = useForkRef(handleOwnRef, ref);\n\n var componentProps = _extends({\n className: clsx(classes.root, className, childContext.dense && classes.dense, !disableGutters && classes.gutters, divider && classes.divider, disabled && classes.disabled, button && classes.button, alignItems !== \"center\" && classes.alignItemsFlexStart, hasSecondaryAction && classes.secondaryAction, selected && classes.selected),\n disabled: disabled\n }, other);\n\n var Component = componentProp || 'li';\n\n if (button) {\n componentProps.component = componentProp || 'div';\n componentProps.focusVisibleClassName = clsx(classes.focusVisible, focusVisibleClassName);\n Component = ButtonBase;\n }\n\n if (hasSecondaryAction) {\n // Use div by default.\n Component = !componentProps.component && !componentProp ? 'div' : Component; // Avoid nesting of li > li.\n\n if (ContainerComponent === 'li') {\n if (Component === 'li') {\n Component = 'div';\n } else if (componentProps.component === 'li') {\n componentProps.component = 'div';\n }\n }\n\n return /*#__PURE__*/React.createElement(ListContext.Provider, {\n value: childContext\n }, /*#__PURE__*/React.createElement(ContainerComponent, _extends({\n className: clsx(classes.container, ContainerClassName),\n ref: handleRef\n }, ContainerProps), /*#__PURE__*/React.createElement(Component, componentProps, children), children.pop()));\n }\n\n return /*#__PURE__*/React.createElement(ListContext.Provider, {\n value: childContext\n }, /*#__PURE__*/React.createElement(Component, _extends({\n ref: handleRef\n }, componentProps), children));\n});\nprocess.env.NODE_ENV !== \"production\" ? ListItem.propTypes = {\n /**\n * Defines the `align-items` style property.\n */\n alignItems: PropTypes.oneOf(['flex-start', 'center']),\n\n /**\n * If `true`, the list item will be focused during the first mount.\n * Focus will also be triggered if the value changes from false to true.\n */\n autoFocus: PropTypes.bool,\n\n /**\n * If `true`, the list item will be a button (using `ButtonBase`). Props intended\n * for `ButtonBase` can then be applied to `ListItem`.\n */\n button: PropTypes.bool,\n\n /**\n * The content of the component. If a `ListItemSecondaryAction` is used it must\n * be the last child.\n */\n children: chainPropTypes(PropTypes.node, function (props) {\n var children = React.Children.toArray(props.children); // React.Children.toArray(props.children).findLastIndex(isListItemSecondaryAction)\n\n var secondaryActionIndex = -1;\n\n for (var i = children.length - 1; i >= 0; i -= 1) {\n var child = children[i];\n\n if (isMuiElement(child, ['ListItemSecondaryAction'])) {\n secondaryActionIndex = i;\n break;\n }\n } // is ListItemSecondaryAction the last child of ListItem\n\n\n if (secondaryActionIndex !== -1 && secondaryActionIndex !== children.length - 1) {\n return new Error('Material-UI: You used an element after ListItemSecondaryAction. ' + 'For ListItem to detect that it has a secondary action ' + 'you must pass it as the last child to ListItem.');\n }\n\n return null;\n }),\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n * By default, it's a `li` when `button` is `false` and a `div` when `button` is `true`.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * The container component used when a `ListItemSecondaryAction` is the last child.\n */\n ContainerComponent: PropTypes.elementType,\n\n /**\n * Props applied to the container component if used.\n */\n ContainerProps: PropTypes.object,\n\n /**\n * If `true`, compact vertical padding designed for keyboard and mouse input will be used.\n */\n dense: PropTypes.bool,\n\n /**\n * If `true`, the list item will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the left and right padding is removed.\n */\n disableGutters: PropTypes.bool,\n\n /**\n * If `true`, a 1px light border is added to the bottom of the list item.\n */\n divider: PropTypes.bool,\n\n /**\n * @ignore\n */\n focusVisibleClassName: PropTypes.string,\n\n /**\n * Use to apply selected styling.\n */\n selected: PropTypes.bool\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiListItem'\n})(ListItem);","import _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport _defineProperty from \"@babel/runtime/helpers/esm/defineProperty\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport withStyles from '../styles/withStyles';\nimport ListItem from '../ListItem';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: _extends({}, theme.typography.body1, _defineProperty({\n minHeight: 48,\n paddingTop: 6,\n paddingBottom: 6,\n boxSizing: 'border-box',\n width: 'auto',\n overflow: 'hidden',\n whiteSpace: 'nowrap'\n }, theme.breakpoints.up('sm'), {\n minHeight: 'auto'\n })),\n // TODO v5: remove\n\n /* Styles applied to the root element if `disableGutters={false}`. */\n gutters: {},\n\n /* Styles applied to the root element if `selected={true}`. */\n selected: {},\n\n /* Styles applied to the root element if dense. */\n dense: _extends({}, theme.typography.body2, {\n minHeight: 'auto'\n })\n };\n};\nvar MenuItem = /*#__PURE__*/React.forwardRef(function MenuItem(props, ref) {\n var classes = props.classes,\n className = props.className,\n _props$component = props.component,\n component = _props$component === void 0 ? 'li' : _props$component,\n _props$disableGutters = props.disableGutters,\n disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters,\n ListItemClasses = props.ListItemClasses,\n _props$role = props.role,\n role = _props$role === void 0 ? 'menuitem' : _props$role,\n selected = props.selected,\n tabIndexProp = props.tabIndex,\n other = _objectWithoutProperties(props, [\"classes\", \"className\", \"component\", \"disableGutters\", \"ListItemClasses\", \"role\", \"selected\", \"tabIndex\"]);\n\n var tabIndex;\n\n if (!props.disabled) {\n tabIndex = tabIndexProp !== undefined ? tabIndexProp : -1;\n }\n\n return /*#__PURE__*/React.createElement(ListItem, _extends({\n button: true,\n role: role,\n tabIndex: tabIndex,\n component: component,\n selected: selected,\n disableGutters: disableGutters,\n classes: _extends({\n dense: classes.dense\n }, ListItemClasses),\n className: clsx(classes.root, className, selected && classes.selected, !disableGutters && classes.gutters),\n ref: ref\n }, other));\n});\nprocess.env.NODE_ENV !== \"production\" ? MenuItem.propTypes = {\n /**\n * Menu item contents.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object.isRequired,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * If `true`, compact vertical padding designed for keyboard and mouse input will be used.\n */\n dense: PropTypes.bool,\n\n /**\n * @ignore\n */\n disabled: PropTypes.bool,\n\n /**\n * If `true`, the left and right padding is removed.\n */\n disableGutters: PropTypes.bool,\n\n /**\n * `classes` prop applied to the [`ListItem`](/api/list-item/) element.\n */\n ListItemClasses: PropTypes.object,\n\n /**\n * @ignore\n */\n role: PropTypes.string,\n\n /**\n * @ignore\n */\n selected: PropTypes.bool,\n\n /**\n * @ignore\n */\n tabIndex: PropTypes.number\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiMenuItem'\n})(MenuItem);","import * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n/**\n * @ignore - internal component.\n */\n\nexport default createSvgIcon( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z\"\n}), 'Cancel');","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport CancelIcon from '../internal/svg-icons/Cancel';\nimport withStyles from '../styles/withStyles';\nimport { emphasize, fade } from '../styles/colorManipulator';\nimport useForkRef from '../utils/useForkRef';\nimport unsupportedProp from '../utils/unsupportedProp';\nimport capitalize from '../utils/capitalize';\nimport ButtonBase from '../ButtonBase';\nexport var styles = function styles(theme) {\n var backgroundColor = theme.palette.type === 'light' ? theme.palette.grey[300] : theme.palette.grey[700];\n var deleteIconColor = fade(theme.palette.text.primary, 0.26);\n return {\n /* Styles applied to the root element. */\n root: {\n fontFamily: theme.typography.fontFamily,\n fontSize: theme.typography.pxToRem(13),\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n height: 32,\n color: theme.palette.getContrastText(backgroundColor),\n backgroundColor: backgroundColor,\n borderRadius: 32 / 2,\n whiteSpace: 'nowrap',\n transition: theme.transitions.create(['background-color', 'box-shadow']),\n // label will inherit this from root, then `clickable` class overrides this for both\n cursor: 'default',\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0,\n textDecoration: 'none',\n border: 'none',\n // Remove `button` border\n padding: 0,\n // Remove `button` padding\n verticalAlign: 'middle',\n boxSizing: 'border-box',\n '&$disabled': {\n opacity: 0.5,\n pointerEvents: 'none'\n },\n '& $avatar': {\n marginLeft: 5,\n marginRight: -6,\n width: 24,\n height: 24,\n color: theme.palette.type === 'light' ? theme.palette.grey[700] : theme.palette.grey[300],\n fontSize: theme.typography.pxToRem(12)\n },\n '& $avatarColorPrimary': {\n color: theme.palette.primary.contrastText,\n backgroundColor: theme.palette.primary.dark\n },\n '& $avatarColorSecondary': {\n color: theme.palette.secondary.contrastText,\n backgroundColor: theme.palette.secondary.dark\n },\n '& $avatarSmall': {\n marginLeft: 4,\n marginRight: -4,\n width: 18,\n height: 18,\n fontSize: theme.typography.pxToRem(10)\n }\n },\n\n /* Styles applied to the root element if `size=\"small\"`. */\n sizeSmall: {\n height: 24\n },\n\n /* Styles applied to the root element if `color=\"primary\"`. */\n colorPrimary: {\n backgroundColor: theme.palette.primary.main,\n color: theme.palette.primary.contrastText\n },\n\n /* Styles applied to the root element if `color=\"secondary\"`. */\n colorSecondary: {\n backgroundColor: theme.palette.secondary.main,\n color: theme.palette.secondary.contrastText\n },\n\n /* Pseudo-class applied to the root element if `disabled={true}`. */\n disabled: {},\n\n /* Styles applied to the root element if `onClick` is defined or `clickable={true}`. */\n clickable: {\n userSelect: 'none',\n WebkitTapHighlightColor: 'transparent',\n cursor: 'pointer',\n '&:hover, &:focus': {\n backgroundColor: emphasize(backgroundColor, 0.08)\n },\n '&:active': {\n boxShadow: theme.shadows[1]\n }\n },\n\n /* Styles applied to the root element if `onClick` and `color=\"primary\"` is defined or `clickable={true}`. */\n clickableColorPrimary: {\n '&:hover, &:focus': {\n backgroundColor: emphasize(theme.palette.primary.main, 0.08)\n }\n },\n\n /* Styles applied to the root element if `onClick` and `color=\"secondary\"` is defined or `clickable={true}`. */\n clickableColorSecondary: {\n '&:hover, &:focus': {\n backgroundColor: emphasize(theme.palette.secondary.main, 0.08)\n }\n },\n\n /* Styles applied to the root element if `onDelete` is defined. */\n deletable: {\n '&:focus': {\n backgroundColor: emphasize(backgroundColor, 0.08)\n }\n },\n\n /* Styles applied to the root element if `onDelete` and `color=\"primary\"` is defined. */\n deletableColorPrimary: {\n '&:focus': {\n backgroundColor: emphasize(theme.palette.primary.main, 0.2)\n }\n },\n\n /* Styles applied to the root element if `onDelete` and `color=\"secondary\"` is defined. */\n deletableColorSecondary: {\n '&:focus': {\n backgroundColor: emphasize(theme.palette.secondary.main, 0.2)\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"`. */\n outlined: {\n backgroundColor: 'transparent',\n border: \"1px solid \".concat(theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'),\n '$clickable&:hover, $clickable&:focus, $deletable&:focus': {\n backgroundColor: fade(theme.palette.text.primary, theme.palette.action.hoverOpacity)\n },\n '& $avatar': {\n marginLeft: 4\n },\n '& $avatarSmall': {\n marginLeft: 2\n },\n '& $icon': {\n marginLeft: 4\n },\n '& $iconSmall': {\n marginLeft: 2\n },\n '& $deleteIcon': {\n marginRight: 5\n },\n '& $deleteIconSmall': {\n marginRight: 3\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"` and `color=\"primary\"`. */\n outlinedPrimary: {\n color: theme.palette.primary.main,\n border: \"1px solid \".concat(theme.palette.primary.main),\n '$clickable&:hover, $clickable&:focus, $deletable&:focus': {\n backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity)\n }\n },\n\n /* Styles applied to the root element if `variant=\"outlined\"` and `color=\"secondary\"`. */\n outlinedSecondary: {\n color: theme.palette.secondary.main,\n border: \"1px solid \".concat(theme.palette.secondary.main),\n '$clickable&:hover, $clickable&:focus, $deletable&:focus': {\n backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity)\n }\n },\n // TODO v5: remove\n\n /* Styles applied to the `avatar` element. */\n avatar: {},\n\n /* Styles applied to the `avatar` element if `size=\"small\"`. */\n avatarSmall: {},\n\n /* Styles applied to the `avatar` element if `color=\"primary\"`. */\n avatarColorPrimary: {},\n\n /* Styles applied to the `avatar` element if `color=\"secondary\"`. */\n avatarColorSecondary: {},\n\n /* Styles applied to the `icon` element. */\n icon: {\n color: theme.palette.type === 'light' ? theme.palette.grey[700] : theme.palette.grey[300],\n marginLeft: 5,\n marginRight: -6\n },\n\n /* Styles applied to the `icon` element if `size=\"small\"`. */\n iconSmall: {\n width: 18,\n height: 18,\n marginLeft: 4,\n marginRight: -4\n },\n\n /* Styles applied to the `icon` element if `color=\"primary\"`. */\n iconColorPrimary: {\n color: 'inherit'\n },\n\n /* Styles applied to the `icon` element if `color=\"secondary\"`. */\n iconColorSecondary: {\n color: 'inherit'\n },\n\n /* Styles applied to the label `span` element. */\n label: {\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n paddingLeft: 12,\n paddingRight: 12,\n whiteSpace: 'nowrap'\n },\n\n /* Styles applied to the label `span` element if `size=\"small\"`. */\n labelSmall: {\n paddingLeft: 8,\n paddingRight: 8\n },\n\n /* Styles applied to the `deleteIcon` element. */\n deleteIcon: {\n WebkitTapHighlightColor: 'transparent',\n color: deleteIconColor,\n height: 22,\n width: 22,\n cursor: 'pointer',\n margin: '0 5px 0 -6px',\n '&:hover': {\n color: fade(deleteIconColor, 0.4)\n }\n },\n\n /* Styles applied to the `deleteIcon` element if `size=\"small\"`. */\n deleteIconSmall: {\n height: 16,\n width: 16,\n marginRight: 4,\n marginLeft: -4\n },\n\n /* Styles applied to the deleteIcon element if `color=\"primary\"` and `variant=\"default\"`. */\n deleteIconColorPrimary: {\n color: fade(theme.palette.primary.contrastText, 0.7),\n '&:hover, &:active': {\n color: theme.palette.primary.contrastText\n }\n },\n\n /* Styles applied to the deleteIcon element if `color=\"secondary\"` and `variant=\"default\"`. */\n deleteIconColorSecondary: {\n color: fade(theme.palette.secondary.contrastText, 0.7),\n '&:hover, &:active': {\n color: theme.palette.secondary.contrastText\n }\n },\n\n /* Styles applied to the deleteIcon element if `color=\"primary\"` and `variant=\"outlined\"`. */\n deleteIconOutlinedColorPrimary: {\n color: fade(theme.palette.primary.main, 0.7),\n '&:hover, &:active': {\n color: theme.palette.primary.main\n }\n },\n\n /* Styles applied to the deleteIcon element if `color=\"secondary\"` and `variant=\"outlined\"`. */\n deleteIconOutlinedColorSecondary: {\n color: fade(theme.palette.secondary.main, 0.7),\n '&:hover, &:active': {\n color: theme.palette.secondary.main\n }\n }\n };\n};\n\nfunction isDeleteKeyboardEvent(keyboardEvent) {\n return keyboardEvent.key === 'Backspace' || keyboardEvent.key === 'Delete';\n}\n/**\n * Chips represent complex entities in small blocks, such as a contact.\n */\n\n\nvar Chip = /*#__PURE__*/React.forwardRef(function Chip(props, ref) {\n var avatarProp = props.avatar,\n classes = props.classes,\n className = props.className,\n clickableProp = props.clickable,\n _props$color = props.color,\n color = _props$color === void 0 ? 'default' : _props$color,\n ComponentProp = props.component,\n deleteIconProp = props.deleteIcon,\n _props$disabled = props.disabled,\n disabled = _props$disabled === void 0 ? false : _props$disabled,\n iconProp = props.icon,\n label = props.label,\n onClick = props.onClick,\n onDelete = props.onDelete,\n onKeyDown = props.onKeyDown,\n onKeyUp = props.onKeyUp,\n _props$size = props.size,\n size = _props$size === void 0 ? 'medium' : _props$size,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'default' : _props$variant,\n other = _objectWithoutProperties(props, [\"avatar\", \"classes\", \"className\", \"clickable\", \"color\", \"component\", \"deleteIcon\", \"disabled\", \"icon\", \"label\", \"onClick\", \"onDelete\", \"onKeyDown\", \"onKeyUp\", \"size\", \"variant\"]);\n\n var chipRef = React.useRef(null);\n var handleRef = useForkRef(chipRef, ref);\n\n var handleDeleteIconClick = function handleDeleteIconClick(event) {\n // Stop the event from bubbling up to the `Chip`\n event.stopPropagation();\n\n if (onDelete) {\n onDelete(event);\n }\n };\n\n var handleKeyDown = function handleKeyDown(event) {\n // Ignore events from children of `Chip`.\n if (event.currentTarget === event.target && isDeleteKeyboardEvent(event)) {\n // will be handled in keyUp, otherwise some browsers\n // might init navigation\n event.preventDefault();\n }\n\n if (onKeyDown) {\n onKeyDown(event);\n }\n };\n\n var handleKeyUp = function handleKeyUp(event) {\n // Ignore events from children of `Chip`.\n if (event.currentTarget === event.target) {\n if (onDelete && isDeleteKeyboardEvent(event)) {\n onDelete(event);\n } else if (event.key === 'Escape' && chipRef.current) {\n chipRef.current.blur();\n }\n }\n\n if (onKeyUp) {\n onKeyUp(event);\n }\n };\n\n var clickable = clickableProp !== false && onClick ? true : clickableProp;\n var small = size === 'small';\n var Component = ComponentProp || (clickable ? ButtonBase : 'div');\n var moreProps = Component === ButtonBase ? {\n component: 'div'\n } : {};\n var deleteIcon = null;\n\n if (onDelete) {\n var customClasses = clsx(color !== 'default' && (variant === \"default\" ? classes[\"deleteIconColor\".concat(capitalize(color))] : classes[\"deleteIconOutlinedColor\".concat(capitalize(color))]), small && classes.deleteIconSmall);\n deleteIcon = deleteIconProp && /*#__PURE__*/React.isValidElement(deleteIconProp) ? /*#__PURE__*/React.cloneElement(deleteIconProp, {\n className: clsx(deleteIconProp.props.className, classes.deleteIcon, customClasses),\n onClick: handleDeleteIconClick\n }) : /*#__PURE__*/React.createElement(CancelIcon, {\n className: clsx(classes.deleteIcon, customClasses),\n onClick: handleDeleteIconClick\n });\n }\n\n var avatar = null;\n\n if (avatarProp && /*#__PURE__*/React.isValidElement(avatarProp)) {\n avatar = /*#__PURE__*/React.cloneElement(avatarProp, {\n className: clsx(classes.avatar, avatarProp.props.className, small && classes.avatarSmall, color !== 'default' && classes[\"avatarColor\".concat(capitalize(color))])\n });\n }\n\n var icon = null;\n\n if (iconProp && /*#__PURE__*/React.isValidElement(iconProp)) {\n icon = /*#__PURE__*/React.cloneElement(iconProp, {\n className: clsx(classes.icon, iconProp.props.className, small && classes.iconSmall, color !== 'default' && classes[\"iconColor\".concat(capitalize(color))])\n });\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (avatar && icon) {\n console.error('Material-UI: The Chip component can not handle the avatar ' + 'and the icon prop at the same time. Pick one.');\n }\n }\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n role: clickable || onDelete ? 'button' : undefined,\n className: clsx(classes.root, className, color !== 'default' && [classes[\"color\".concat(capitalize(color))], clickable && classes[\"clickableColor\".concat(capitalize(color))], onDelete && classes[\"deletableColor\".concat(capitalize(color))]], variant !== \"default\" && [classes.outlined, {\n 'primary': classes.outlinedPrimary,\n 'secondary': classes.outlinedSecondary\n }[color]], disabled && classes.disabled, small && classes.sizeSmall, clickable && classes.clickable, onDelete && classes.deletable),\n \"aria-disabled\": disabled ? true : undefined,\n tabIndex: clickable || onDelete ? 0 : undefined,\n onClick: onClick,\n onKeyDown: handleKeyDown,\n onKeyUp: handleKeyUp,\n ref: handleRef\n }, moreProps, other), avatar || icon, /*#__PURE__*/React.createElement(\"span\", {\n className: clsx(classes.label, small && classes.labelSmall)\n }, label), deleteIcon);\n});\nprocess.env.NODE_ENV !== \"production\" ? Chip.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * Avatar element.\n */\n avatar: PropTypes.element,\n\n /**\n * This prop isn't supported.\n * Use the `component` prop if you need to change the children structure.\n */\n children: unsupportedProp,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: PropTypes.object,\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * If `true`, the chip will appear clickable, and will raise when pressed,\n * even if the onClick prop is not defined.\n * If false, the chip will not be clickable, even if onClick prop is defined.\n * This can be used, for example,\n * along with the component prop to indicate an anchor Chip is clickable.\n */\n clickable: PropTypes.bool,\n\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n */\n color: PropTypes.oneOf(['default', 'primary', 'secondary']),\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * Override the default delete icon element. Shown only if `onDelete` is set.\n */\n deleteIcon: PropTypes.element,\n\n /**\n * If `true`, the chip should be displayed in a disabled state.\n */\n disabled: PropTypes.bool,\n\n /**\n * Icon element.\n */\n icon: PropTypes.element,\n\n /**\n * The content of the label.\n */\n label: PropTypes.node,\n\n /**\n * @ignore\n */\n onClick: PropTypes.func,\n\n /**\n * Callback function fired when the delete icon is clicked.\n * If set, the delete icon will be shown.\n */\n onDelete: PropTypes.func,\n\n /**\n * @ignore\n */\n onKeyDown: PropTypes.func,\n\n /**\n * @ignore\n */\n onKeyUp: PropTypes.func,\n\n /**\n * The size of the chip.\n */\n size: PropTypes.oneOf(['medium', 'small']),\n\n /**\n * The variant to use.\n */\n variant: PropTypes.oneOf(['default', 'outlined'])\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiChip'\n})(Chip);","import * as React from 'react';\nimport createSvgIcon from '../../utils/createSvgIcon';\n/**\n * @ignore - internal component.\n */\n\nexport default createSvgIcon( /*#__PURE__*/React.createElement(\"path\", {\n d: \"M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z\"\n}), 'Person');","import _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutProperties from \"@babel/runtime/helpers/esm/objectWithoutProperties\";\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport { chainPropTypes } from '@material-ui/utils';\nimport withStyles from '../styles/withStyles';\nimport Person from '../internal/svg-icons/Person';\nexport var styles = function styles(theme) {\n return {\n /* Styles applied to the root element. */\n root: {\n position: 'relative',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n flexShrink: 0,\n width: 40,\n height: 40,\n fontFamily: theme.typography.fontFamily,\n fontSize: theme.typography.pxToRem(20),\n lineHeight: 1,\n borderRadius: '50%',\n overflow: 'hidden',\n userSelect: 'none'\n },\n\n /* Styles applied to the root element if not `src` or `srcSet`. */\n colorDefault: {\n color: theme.palette.background.default,\n backgroundColor: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[600]\n },\n\n /* Styles applied to the root element if `variant=\"circle\"`. */\n circle: {},\n\n /* Styles applied to the root element if `variant=\"circular\"`. */\n circular: {},\n\n /* Styles applied to the root element if `variant=\"rounded\"`. */\n rounded: {\n borderRadius: theme.shape.borderRadius\n },\n\n /* Styles applied to the root element if `variant=\"square\"`. */\n square: {\n borderRadius: 0\n },\n\n /* Styles applied to the img element if either `src` or `srcSet` is defined. */\n img: {\n width: '100%',\n height: '100%',\n textAlign: 'center',\n // Handle non-square image. The property isn't supported by IE 11.\n objectFit: 'cover',\n // Hide alt text.\n color: 'transparent',\n // Hide the image broken icon, only works on Chrome.\n textIndent: 10000\n },\n\n /* Styles applied to the fallback icon */\n fallback: {\n width: '75%',\n height: '75%'\n }\n };\n};\n\nfunction useLoaded(_ref) {\n var src = _ref.src,\n srcSet = _ref.srcSet;\n\n var _React$useState = React.useState(false),\n loaded = _React$useState[0],\n setLoaded = _React$useState[1];\n\n React.useEffect(function () {\n if (!src && !srcSet) {\n return undefined;\n }\n\n setLoaded(false);\n var active = true;\n var image = new Image();\n image.src = src;\n image.srcSet = srcSet;\n\n image.onload = function () {\n if (!active) {\n return;\n }\n\n setLoaded('loaded');\n };\n\n image.onerror = function () {\n if (!active) {\n return;\n }\n\n setLoaded('error');\n };\n\n return function () {\n active = false;\n };\n }, [src, srcSet]);\n return loaded;\n}\n\nvar Avatar = /*#__PURE__*/React.forwardRef(function Avatar(props, ref) {\n var alt = props.alt,\n childrenProp = props.children,\n classes = props.classes,\n className = props.className,\n _props$component = props.component,\n Component = _props$component === void 0 ? 'div' : _props$component,\n imgProps = props.imgProps,\n sizes = props.sizes,\n src = props.src,\n srcSet = props.srcSet,\n _props$variant = props.variant,\n variant = _props$variant === void 0 ? 'circle' : _props$variant,\n other = _objectWithoutProperties(props, [\"alt\", \"children\", \"classes\", \"className\", \"component\", \"imgProps\", \"sizes\", \"src\", \"srcSet\", \"variant\"]);\n\n var children = null; // Use a hook instead of onError on the img element to support server-side rendering.\n\n var loaded = useLoaded({\n src: src,\n srcSet: srcSet\n });\n var hasImg = src || srcSet;\n var hasImgNotFailing = hasImg && loaded !== 'error';\n\n if (hasImgNotFailing) {\n children = /*#__PURE__*/React.createElement(\"img\", _extends({\n alt: alt,\n src: src,\n srcSet: srcSet,\n sizes: sizes,\n className: classes.img\n }, imgProps));\n } else if (childrenProp != null) {\n children = childrenProp;\n } else if (hasImg && alt) {\n children = alt[0];\n } else {\n children = /*#__PURE__*/React.createElement(Person, {\n className: classes.fallback\n });\n }\n\n return /*#__PURE__*/React.createElement(Component, _extends({\n className: clsx(classes.root, classes.system, classes[variant], className, !hasImgNotFailing && classes.colorDefault),\n ref: ref\n }, other), children);\n});\nprocess.env.NODE_ENV !== \"production\" ? Avatar.propTypes = {\n // ----------------------------- Warning --------------------------------\n // | These PropTypes are generated from the TypeScript type definitions |\n // | To update them edit the d.ts file and run \"yarn proptypes\" |\n // ----------------------------------------------------------------------\n\n /**\n * Used in combination with `src` or `srcSet` to\n * provide an alt attribute for the rendered `img` element.\n */\n alt: PropTypes.string,\n\n /**\n * Used to render icon or text elements inside the Avatar if `src` is not set.\n * This can be an element, or just a string.\n */\n children: PropTypes.node,\n\n /**\n * Override or extend the styles applied to the component.\n * See [CSS API](#css) below for more details.\n */\n classes: chainPropTypes(PropTypes.object, function (props) {\n var classes = props.classes;\n\n if (classes == null) {\n return null;\n }\n\n if (classes.circle != null && // 2 classnames? one from withStyles the other must be custom\n classes.circle.split(' ').length > 1) {\n throw new Error(\"Material-UI: The `circle` class was deprecated. Use `circular` instead.\");\n }\n\n return null;\n }),\n\n /**\n * @ignore\n */\n className: PropTypes.string,\n\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes\n /* @typescript-to-proptypes-ignore */\n .elementType,\n\n /**\n * Attributes applied to the `img` element if the component is used to display an image.\n * It can be used to listen for the loading error event.\n */\n imgProps: PropTypes.object,\n\n /**\n * The `sizes` attribute for the `img` element.\n */\n sizes: PropTypes.string,\n\n /**\n * The `src` attribute for the `img` element.\n */\n src: PropTypes.string,\n\n /**\n * The `srcSet` attribute for the `img` element.\n * Use this attribute for responsive image display.\n */\n srcSet: PropTypes.string,\n\n /**\n * The shape of the avatar.\n */\n variant: chainPropTypes(PropTypes.oneOf(['circle', 'circular', 'rounded', 'square']), function (props) {\n var variant = props.variant;\n\n if (variant === 'circle') {\n throw new Error('Material-UI: `variant=\"circle\"` was deprecated. Use `variant=\"circular\"` instead.');\n }\n\n return null;\n })\n} : void 0;\nexport default withStyles(styles, {\n name: 'MuiAvatar'\n})(Avatar);","import _slicedToArray from \"@babel/runtime/helpers/esm/slicedToArray\";\nimport responsivePropType from './responsivePropType';\nimport { handleBreakpoints } from './breakpoints';\nimport merge from './merge';\nimport memoize from './memoize';\nvar properties = {\n m: 'margin',\n p: 'padding'\n};\nvar directions = {\n t: 'Top',\n r: 'Right',\n b: 'Bottom',\n l: 'Left',\n x: ['Left', 'Right'],\n y: ['Top', 'Bottom']\n};\nvar aliases = {\n marginX: 'mx',\n marginY: 'my',\n paddingX: 'px',\n paddingY: 'py'\n}; // memoize() impact:\n// From 300,000 ops/sec\n// To 350,000 ops/sec\n\nvar getCssProperties = memoize(function (prop) {\n // It's not a shorthand notation.\n if (prop.length > 2) {\n if (aliases[prop]) {\n prop = aliases[prop];\n } else {\n return [prop];\n }\n }\n\n var _prop$split = prop.split(''),\n _prop$split2 = _slicedToArray(_prop$split, 2),\n a = _prop$split2[0],\n b = _prop$split2[1];\n\n var property = properties[a];\n var direction = directions[b] || '';\n return Array.isArray(direction) ? direction.map(function (dir) {\n return property + dir;\n }) : [property + direction];\n});\nvar spacingKeys = ['m', 'mt', 'mr', 'mb', 'ml', 'mx', 'my', 'p', 'pt', 'pr', 'pb', 'pl', 'px', 'py', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'paddingX', 'paddingY'];\nexport function createUnarySpacing(theme) {\n var themeSpacing = theme.spacing || 8;\n\n if (typeof themeSpacing === 'number') {\n return function (abs) {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof abs !== 'number') {\n console.error(\"Material-UI: Expected spacing argument to be a number, got \".concat(abs, \".\"));\n }\n }\n\n return themeSpacing * abs;\n };\n }\n\n if (Array.isArray(themeSpacing)) {\n return function (abs) {\n if (process.env.NODE_ENV !== 'production') {\n if (abs > themeSpacing.length - 1) {\n console.error([\"Material-UI: The value provided (\".concat(abs, \") overflows.\"), \"The supported values are: \".concat(JSON.stringify(themeSpacing), \".\"), \"\".concat(abs, \" > \").concat(themeSpacing.length - 1, \", you need to add the missing values.\")].join('\\n'));\n }\n }\n\n return themeSpacing[abs];\n };\n }\n\n if (typeof themeSpacing === 'function') {\n return themeSpacing;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n console.error([\"Material-UI: The `theme.spacing` value (\".concat(themeSpacing, \") is invalid.\"), 'It should be a number, an array or a function.'].join('\\n'));\n }\n\n return function () {\n return undefined;\n };\n}\n\nfunction getValue(transformer, propValue) {\n if (typeof propValue === 'string' || propValue == null) {\n return propValue;\n }\n\n var abs = Math.abs(propValue);\n var transformed = transformer(abs);\n\n if (propValue >= 0) {\n return transformed;\n }\n\n if (typeof transformed === 'number') {\n return -transformed;\n }\n\n return \"-\".concat(transformed);\n}\n\nfunction getStyleFromPropValue(cssProperties, transformer) {\n return function (propValue) {\n return cssProperties.reduce(function (acc, cssProperty) {\n acc[cssProperty] = getValue(transformer, propValue);\n return acc;\n }, {});\n };\n}\n\nfunction spacing(props) {\n var theme = props.theme;\n var transformer = createUnarySpacing(theme);\n return Object.keys(props).map(function (prop) {\n // Using a hash computation over an array iteration could be faster, but with only 28 items,\n // it's doesn't worth the bundle size.\n if (spacingKeys.indexOf(prop) === -1) {\n return null;\n }\n\n var cssProperties = getCssProperties(prop);\n var styleFromPropValue = getStyleFromPropValue(cssProperties, transformer);\n var propValue = props[prop];\n return handleBreakpoints(props, propValue, styleFromPropValue);\n }).reduce(merge, {});\n}\n\nspacing.propTypes = process.env.NODE_ENV !== 'production' ? spacingKeys.reduce(function (obj, key) {\n obj[key] = responsivePropType;\n return obj;\n}, {}) : {};\nspacing.filterProps = spacingKeys;\nexport default spacing;","export default function memoize(fn) {\n var cache = {};\n return function (arg) {\n if (cache[arg] === undefined) {\n cache[arg] = fn(arg);\n }\n\n return cache[arg];\n };\n}"],"sourceRoot":""}